Merge "Suppress all new Enterprise CTS tests." into lmp-dev
diff --git a/apps/CtsVerifier/AndroidManifest.xml b/apps/CtsVerifier/AndroidManifest.xml
index 9f83d92..4297a74 100644
--- a/apps/CtsVerifier/AndroidManifest.xml
+++ b/apps/CtsVerifier/AndroidManifest.xml
@@ -107,6 +107,8 @@
                 <category android:name="android.cts.intent.category.MANUAL_TEST" />
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_device_admin" />
+            <meta-data android:name="test_excluded_features"
+                       android:value="android.hardware.type.television:android.software.leanback" />
         </activity>
 
         <receiver android:name=".admin.TestDeviceAdminReceiver"
@@ -443,6 +445,8 @@
                 <category android:name="android.cts.intent.category.MANUAL_TEST" />
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_security" />
+            <meta-data android:name="test_excluded_features"
+                       android:value="android.hardware.type.television:android.software.leanback" />
         </activity>
 
         <activity android:name=".streamquality.StreamingVideoActivity"
@@ -776,18 +780,6 @@
                        android:value="android.hardware.sensor.compass" />
         </activity>
 
-        <activity android:name=".sensors.SensorValueAccuracyActivity"
-                  android:label="@string/snsr_val_acc_test"
-                  android:screenOrientation="locked">
-            <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" />
-            <meta-data android:name="test_required_features"
-                       android:value="android.hardware.sensor.accelerometer" />
-        </activity>
-
         <!-- TODO: enable when a full set of verifications can be implemented -->
         <!--activity android:name=".sensors.RotationVectorTestActivity"
                   android:label="@string/snsr_rot_vec_test"
@@ -883,6 +875,8 @@
                 <category android:name="android.cts.intent.category.MANUAL_TEST" />
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_location" />
+            <meta-data android:name="test_excluded_features"
+                       android:value="android.hardware.type.television:android.software.leanback" />
         </activity>
         <activity android:name=".location.LocationModeBatterySavingTestActivity"
                 android:label="@string/location_mode_battery_saving_test">
@@ -899,6 +893,8 @@
                 <category android:name="android.cts.intent.category.MANUAL_TEST" />
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_location" />
+            <meta-data android:name="test_excluded_features"
+                       android:value="android.hardware.type.television:android.software.leanback" />
         </activity>
 
         <activity android:name=".camera.formats.CameraFormatsActivity"
@@ -1010,6 +1006,8 @@
                 <category android:name="android.cts.intent.category.MANUAL_TEST" />
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_sensors" />
+            <meta-data android:name="test_excluded_features"
+                       android:value="android.hardware.type.television:android.software.leanback" />
         </activity>
 
         <activity android:name=".p2p.P2pTestListActivity"
@@ -1149,6 +1147,8 @@
                 <category android:name="android.cts.intent.category.MANUAL_TEST" />
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_sensors" />
+            <meta-data android:name="test_excluded_features"
+                       android:value="android.hardware.type.television:android.software.leanback" />
         </activity>
 
         <activity
@@ -1164,6 +1164,8 @@
             <meta-data
                 android:name="test_category"
                 android:value="@string/test_category_sensors" />
+            <meta-data android:name="test_excluded_features"
+                       android:value="android.hardware.type.television:android.software.leanback" />
         </activity>
 
         <receiver android:name=".widget.WidgetCtsProvider">
@@ -1239,6 +1241,15 @@
                  android:label="@string/projection_service_name"
                  android:process=":projectionservice" />
 
+        <activity android:name=".managedprovisioning.DeviceOwnerTestActivity"
+                android:label="@string/provisioning_device_owner">
+            <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_managed_provisioning" />
+        </activity>
+
 
         <activity android:name=".managedprovisioning.ByodFlowTestActivity"
                 android:launchMode="singleTask"
diff --git a/apps/CtsVerifier/assets/scripts/execute_power_tests.py b/apps/CtsVerifier/assets/scripts/execute_power_tests.py
index e1b11c2..d1c2dac 100755
--- a/apps/CtsVerifier/assets/scripts/execute_power_tests.py
+++ b/apps/CtsVerifier/assets/scripts/execute_power_tests.py
@@ -369,10 +369,8 @@
                         f.write( "%.4f\n"%m)
                     self.setUsbEnabled(True, verbose = False)
                     print("Saving raw data files to device...")
-                    self.executeLocal("adb shell mkdir -p %s/ctsVerifierData/sensor_power_test_data"
-                                      % self._external_storage, False)
-                    self.executeLocal("adb push %s %s/ctsVerifierData/sensor_power_test_data/." %
-                                      (f.name, self._external_storage))
+                    self.executeLocal("adb shell mkdir -p %s" % self._external_storage, False)
+                    self.executeLocal("adb push %s %s/." % (f.name, self._external_storage))
                     self.setUsbEnabled(False, verbose = False)
             self.reportErrorIf(not measurements, "No measurements could be taken for %s" % sensor)
             avg = sum(measurements) / len(measurements)
diff --git a/apps/CtsVerifier/res/values/strings.xml b/apps/CtsVerifier/res/values/strings.xml
index 2cae77b..bb755cd 100644
--- a/apps/CtsVerifier/res/values/strings.xml
+++ b/apps/CtsVerifier/res/values/strings.xml
@@ -541,10 +541,13 @@
     <string name="snsr_mag_m_test">Magnetic Field Measurement Tests</string>
     <string name="snsr_mag_verify_norm">Verifying the Norm...</string>
     <string name="snsr_mag_verify_std_dev">Verifying the Standard Deviation...</string>
+    <string name="snsr_mag_verify_calibrated_uncalibrated">Verifying the relationship between
+        calibrated and uncalibrated measurements...</string>
     <string name="snsr_mag_calibration_description">Please calibrate the Magnetometer by moving
         it in 8 shapes in different orientations.</string>
     <string name="snsr_mag_calibration_complete">When done, leave the device in a flat surface, far
         from all metallic objects (if the test does not pass, try re-running it outdoors).</string>
+    <string name="snsr_mag_measurement">-&gt; (%1$.2f, %2$.2f, %3$.2f) : %4$.2f uT</string>
 
     <!-- Sensor Value Accuracy -->
     <string name="snsr_val_acc_test">Sensor Value Accuracy Tests</string>
@@ -1244,4 +1247,13 @@
     <string name="provisioning_byod_profile_deleted">Work profile deleted.</string>
     <string name="provisioning_byod_disabled">Device provisioning is not enabled.</string>
     <string name="provisioning_byod_go">Go</string>
+
+    <!-- Strings for DeviceOwnerProvisioningTest -->
+    <string name="provisioning_device_owner">Device Owner Provisioning</string>
+    <string name="device_owner_provisioning_tests">Device Owner provisioning tests</string>
+    <string name="device_owner_provisioning_tests_info">The device owner provisioning tests verify that setting up a corporate owned device can only be done on a factory reset device.</string>
+    <string name="device_owner_provisioning_category">Device Owner Provisioning</string>
+    <string name="device_owner_negative_test">Device owner negative test</string>
+    <string name="device_owner_negative_test_info">Device owner provisioning should only work on new or factory reset devices. Please click on the "Start provisioning" button and verify that you get a warning dialog telling you that the device is already set up. If that is the case, this test has passed.</string>
+    <string name="start_device_owner_provisioning_button">Start provisioning</string>
 </resources>
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/ManifestTestListAdapter.java b/apps/CtsVerifier/src/com/android/cts/verifier/ManifestTestListAdapter.java
index 1f19cbe..2f42e81 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/ManifestTestListAdapter.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/ManifestTestListAdapter.java
@@ -67,6 +67,14 @@
  *             <meta-data android:name="test_required_features" android:value="android.hardware.sensor.accelerometer" />
  *         </pre>
  *     </li>
+ *     <li>OPTIONAL: Add a meta data attribute to indicate features such that, if any present, the
+ *         test gets excluded from being shown. If the device has any of the excluded features then
+ *         the test will not appear in the test list. Use a colon (:) to specify multiple features
+ *         to exclude for the test. Note that the colon means "or" in this case.
+ *         <pre>
+ *             <meta-data android:name="test_excluded_features" android:value="android.hardware.type.television" />
+ *         </pre>
+ *     </li>
  *
  * </ol>
  */
@@ -78,6 +86,8 @@
 
     private static final String TEST_REQUIRED_FEATURES_META_DATA = "test_required_features";
 
+    private static final String TEST_EXCLUDED_FEATURES_META_DATA = "test_excluded_features";
+
     private Context mContext;
 
     private String mTestParent;
@@ -152,7 +162,9 @@
             String testName = info.activityInfo.name;
             Intent intent = getActivityIntent(info.activityInfo);
             String[] requiredFeatures = getRequiredFeatures(info.activityInfo.metaData);
-            TestListItem item = TestListItem.newTest(title, testName, intent, requiredFeatures);
+            String[] excludedFeatures = getExcludedFeatures(info.activityInfo.metaData);
+            TestListItem item = TestListItem.newTest(title, testName, intent,
+                                                     requiredFeatures, excludedFeatures);
 
             String testCategory = getTestCategory(mContext, info.activityInfo.metaData);
             addTestToCategory(testsByCategory, testCategory, item);
@@ -190,6 +202,19 @@
         }
     }
 
+    static String[] getExcludedFeatures(Bundle metaData) {
+        if (metaData == null) {
+            return null;
+        } else {
+            String value = metaData.getString(TEST_EXCLUDED_FEATURES_META_DATA);
+            if (value == null) {
+                return null;
+            } else {
+                return value.split(":");
+            }
+        }
+    }
+
     static String getTitle(Context context, ActivityInfo activityInfo) {
         if (activityInfo.labelRes != 0) {
             return context.getString(activityInfo.labelRes);
@@ -216,22 +241,39 @@
         tests.add(item);
     }
 
-    List<TestListItem> filterTests(List<TestListItem> tests) {
-        List<TestListItem> filteredTests = new ArrayList<TestListItem>(tests);
-        PackageManager packageManager = mContext.getPackageManager();
-        Iterator<TestListItem> iterator = filteredTests.iterator();
-        while (iterator.hasNext()) {
-            TestListItem item = iterator.next();
-            String[] requiredFeatures = item.requiredFeatures;
-            if (requiredFeatures != null) {
-                for (int i = 0; i < requiredFeatures.length; i++) {
-                    if (!packageManager.hasSystemFeature(requiredFeatures[i])) {
-                        iterator.remove();
-                        break;
-                    }
+    private boolean hasAnyFeature(String[] features) {
+        if (features != null) {
+            PackageManager packageManager = mContext.getPackageManager();
+            for (String feature : features) {
+                if (packageManager.hasSystemFeature(feature)) {
+                    return true;
                 }
             }
         }
+        return false;
+    }
+
+    private boolean hasAllFeatures(String[] features) {
+        if (features != null) {
+            PackageManager packageManager = mContext.getPackageManager();
+            for (String feature : features) {
+                if (!packageManager.hasSystemFeature(feature)) {
+                    return false;
+                }
+            }
+        }
+        return true;
+    }
+
+    List<TestListItem> filterTests(List<TestListItem> tests) {
+        List<TestListItem> filteredTests = new ArrayList<TestListItem>();
+        for (TestListItem test : tests) {
+            String[] excludedFeatures = test.excludedFeatures;
+            String[] requiredFeatures = test.requiredFeatures;
+            if (!hasAnyFeature(excludedFeatures) && hasAllFeatures(requiredFeatures)) {
+                filteredTests.add(test);
+            }
+        }
         return filteredTests;
     }
 }
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/TestListAdapter.java b/apps/CtsVerifier/src/com/android/cts/verifier/TestListAdapter.java
index 2cc79fb..0d9985c 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/TestListAdapter.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/TestListAdapter.java
@@ -83,14 +83,29 @@
         /** Features necessary to run this test. */
         final String[] requiredFeatures;
 
+        /** Features such that, if any present, the test gets excluded from being shown. */
+        final String[] excludedFeatures;
+
+        public static TestListItem newTest(Context context, int titleResId, String testName,
+                Intent intent, String[] requiredFeatures, String[] excludedFeatures) {
+            return newTest(context.getString(titleResId), testName, intent,
+                           requiredFeatures, excludedFeatures);
+        }
+
         public static TestListItem newTest(Context context, int titleResId, String testName,
                 Intent intent, String[] requiredFeatures) {
-            return newTest(context.getString(titleResId), testName, intent, requiredFeatures);
+            return newTest(context.getString(titleResId), testName, intent,
+                           requiredFeatures, null);
+        }
+
+        public static TestListItem newTest(String title, String testName, Intent intent,
+                String[] requiredFeatures, String[] excludedFeatures) {
+            return new TestListItem(title, testName, intent, requiredFeatures, excludedFeatures);
         }
 
         public static TestListItem newTest(String title, String testName, Intent intent,
                 String[] requiredFeatures) {
-            return new TestListItem(title, testName, intent, requiredFeatures);
+            return new TestListItem(title, testName, intent, requiredFeatures, null);
         }
 
         public static TestListItem newCategory(Context context, int titleResId) {
@@ -98,15 +113,16 @@
         }
 
         public static TestListItem newCategory(String title) {
-            return new TestListItem(title, null, null, null);
+            return new TestListItem(title, null, null, null, null);
         }
 
         private TestListItem(String title, String testName, Intent intent,
-                String[] requiredFeatures) {
+                String[] requiredFeatures, String[] excludedFeatures) {
             this.title = title;
             this.testName = testName;
             this.intent = intent;
             this.requiredFeatures = requiredFeatures;
+            this.excludedFeatures = excludedFeatures;
         }
 
         boolean isTest() {
@@ -366,4 +382,4 @@
 
         }
     }
-}
\ No newline at end of file
+}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/camera/fov/PhotoCaptureActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/camera/fov/PhotoCaptureActivity.java
index 05013ed..d71dca2 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/camera/fov/PhotoCaptureActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/camera/fov/PhotoCaptureActivity.java
@@ -30,6 +30,7 @@
 import android.os.PowerManager;
 import android.os.PowerManager.WakeLock;
 import android.util.Log;
+import android.view.Surface;
 import android.view.SurfaceHolder;
 import android.view.SurfaceView;
 import android.view.View;
@@ -426,6 +427,7 @@
 
     private void startPreview() {
         if (mCameraInitialized && mCamera != null) {
+            setCameraDisplayOrientation(this, mCameraId, mCamera);
             mCamera.startPreview();
             mPreviewActive = true;
         }
@@ -501,4 +503,29 @@
         }
         return result;
     }
+
+    public static void setCameraDisplayOrientation(Activity activity,
+            int cameraId, android.hardware.Camera camera) {
+        android.hardware.Camera.CameraInfo info =
+                new android.hardware.Camera.CameraInfo();
+        android.hardware.Camera.getCameraInfo(cameraId, info);
+        int rotation = activity.getWindowManager().getDefaultDisplay()
+                .getRotation();
+        int degrees = 0;
+        switch (rotation) {
+            case Surface.ROTATION_0: degrees = 0; break;
+            case Surface.ROTATION_90: degrees = 90; break;
+            case Surface.ROTATION_180: degrees = 180; break;
+            case Surface.ROTATION_270: degrees = 270; break;
+        }
+
+        int result;
+        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
+            result = (info.orientation + degrees) % 360;
+            result = (360 - result) % 360;  // compensate the mirror
+        } else {  // back-facing
+            result = (info.orientation - degrees + 360) % 360;
+        }
+        camera.setDisplayOrientation(result);
+    }
 }
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerTestActivity.java
new file mode 100644
index 0000000..7cb3825
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerTestActivity.java
@@ -0,0 +1,93 @@
+package com.android.cts.verifier.managedprovisioning;
+
+import android.app.AlertDialog;
+import android.app.admin.DevicePolicyManager;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.DialogInterface;
+import android.content.Intent;
+import android.database.DataSetObserver;
+import android.os.Bundle;
+import android.provider.Settings;
+import android.util.Log;
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.View.OnClickListener;
+import android.widget.ArrayAdapter;
+import android.widget.ListView;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.android.cts.verifier.ArrayTestListAdapter;
+import com.android.cts.verifier.IntentDrivenTestActivity;
+import com.android.cts.verifier.IntentDrivenTestActivity.ButtonInfo;
+import com.android.cts.verifier.IntentDrivenTestActivity.TestInfo;
+import com.android.cts.verifier.PassFailButtons;
+import com.android.cts.verifier.R;
+import com.android.cts.verifier.TestListAdapter.TestListItem;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Activity that lists all device owner provisioning tests.
+ */
+public class DeviceOwnerTestActivity extends PassFailButtons.TestListActivity {
+
+    private static final String ACTION_PROVISION_MANAGED_DEVICE
+        = "com.android.managedprovisioning.ACTION_PROVISION_MANAGED_DEVICE";
+    private static final Intent PROVISION_DEVICE_INTENT =
+            new Intent(ACTION_PROVISION_MANAGED_DEVICE);
+
+    private static final String DEVICE_OWNER_NEGATIVE_TEST = "DEVICE_OWNER_PROVISIONING_NEGATIVE";
+    private static final TestInfo DEVICE_OWNER_NEGATIVE_TEST_INFO = new TestInfo(
+                    DEVICE_OWNER_NEGATIVE_TEST,
+                    R.string.device_owner_negative_test,
+                    R.string.device_owner_negative_test_info,
+                    new ButtonInfo(
+                            R.string.start_device_owner_provisioning_button,
+                            PROVISION_DEVICE_INTENT));
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.pass_fail_list);
+        setInfoResources(R.string.device_owner_provisioning_tests,
+                R.string.device_owner_provisioning_tests_info, 0);
+        setPassFailButtonClickListeners();
+
+        final ArrayTestListAdapter adapter = new ArrayTestListAdapter(this);
+        adapter.add(TestListItem.newCategory(this, R.string.device_owner_provisioning_category));
+
+        Intent startTestIntent = new Intent(this, IntentDrivenTestActivity.class)
+                    .putExtra(IntentDrivenTestActivity.EXTRA_ID,
+                            DEVICE_OWNER_NEGATIVE_TEST_INFO.getTestId())
+                    .putExtra(IntentDrivenTestActivity.EXTRA_TITLE,
+                            DEVICE_OWNER_NEGATIVE_TEST_INFO.getTitle())
+                    .putExtra(IntentDrivenTestActivity.EXTRA_INFO,
+                            DEVICE_OWNER_NEGATIVE_TEST_INFO.getInfoText())
+                    .putExtra(IntentDrivenTestActivity.EXTRA_BUTTONS,
+                            DEVICE_OWNER_NEGATIVE_TEST_INFO.getButtons());
+
+
+        adapter.add(TestListItem.newTest(this, DEVICE_OWNER_NEGATIVE_TEST_INFO.getTitle(),
+                DEVICE_OWNER_NEGATIVE_TEST_INFO.getTestId(), startTestIntent, null));
+
+        adapter.registerDataSetObserver(new DataSetObserver() {
+            @Override
+            public void onChanged() {
+                updatePassButton();
+            }
+        });
+
+        setTestListAdapter(adapter);
+    }
+
+    /**
+     * Enable Pass Button when the all tests passed.
+     */
+    private void updatePassButton() {
+        getPassButton().setEnabled(mAdapter.allTestsPassed());
+    }
+}
+
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/GyroscopeMeasurementTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/GyroscopeMeasurementTestActivity.java
index 13a695c..ac63780 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/GyroscopeMeasurementTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/GyroscopeMeasurementTestActivity.java
@@ -22,6 +22,7 @@
 
 import android.hardware.Sensor;
 import android.hardware.SensorManager;
+import android.hardware.cts.helpers.SensorCalibratedUncalibratedVerifier;
 import android.hardware.cts.helpers.TestSensorEnvironment;
 import android.hardware.cts.helpers.sensoroperations.TestSensorOperation;
 import android.hardware.cts.helpers.sensorverification.GyroscopeIntegrationVerification;
@@ -32,8 +33,10 @@
  * Semi-automated test that focuses on characteristics associated with Gyroscope measurements.
  */
 public class GyroscopeMeasurementTestActivity extends SensorCtsVerifierTestActivity {
+    private static final float THRESHOLD_CALIBRATED_UNCALIBRATED_RAD_SEC = 0.01f;
     private static final float THRESHOLD_AXIS_UNDER_ROTATION_DEG = 10.0f;
     private static final float THRESHOLD_AXIS_UNDER_NO_ROTATION_DEG = 50.0f;
+
     private static final int ROTATE_360_DEG = 360;
     private static final int ROTATION_COLLECTION_SEC = 10;
 
@@ -59,6 +62,7 @@
         closeGlSurfaceView();
     }
 
+    @SuppressWarnings("unused")
     public String testDeviceStatic() throws Throwable {
         return verifyMeasurements(
                 R.string.snsr_gyro_device_static,
@@ -66,31 +70,72 @@
                 0 /* expectationDeg */);
     }
 
+    @SuppressWarnings("unused")
     public String testRotateClockwise() throws Throwable {
         return verifyMeasurements(R.string.snsr_gyro_rotate_device, Z_AXIS, -ROTATE_360_DEG);
     }
 
+    @SuppressWarnings("unused")
     public String testRotateCounterClockwise() throws Throwable {
         return verifyMeasurements(R.string.snsr_gyro_rotate_device, Z_AXIS, ROTATE_360_DEG);
     }
 
+    @SuppressWarnings("unused")
     public String testRotateRightSide() throws Throwable {
         return verifyMeasurements(R.string.snsr_gyro_rotate_device, Y_AXIS, ROTATE_360_DEG);
     }
 
+    @SuppressWarnings("unused")
     public String testRotateLeftSide() throws Throwable {
         return verifyMeasurements(R.string.snsr_gyro_rotate_device, Y_AXIS, -ROTATE_360_DEG);
     }
 
+    @SuppressWarnings("unused")
     public String testRotateTopSide() throws Throwable {
         return verifyMeasurements(R.string.snsr_gyro_rotate_device, X_AXIS, -ROTATE_360_DEG);
     }
 
+    @SuppressWarnings("unused")
     public String testRotateBottomSide() throws Throwable {
         return verifyMeasurements(R.string.snsr_gyro_rotate_device, X_AXIS, ROTATE_360_DEG);
     }
 
     /**
+     * Verifies that the relationship between readings from calibrated and their corresponding
+     * uncalibrated sensors comply to the following equation:
+     *      calibrated = uncalibrated - bias
+     */
+    @SuppressWarnings("unused")
+    public String testCalibratedAndUncalibrated() throws Throwable {
+        setRendererRotation(Z_AXIS, false);
+
+        SensorTestLogger logger = getTestLogger();
+        logger.logInstructions(R.string.snsr_keep_device_rotating_clockwise);
+        waitForUserToBegin();
+        logger.logWaitForSound();
+
+        TestSensorEnvironment calibratedEnvironment = new TestSensorEnvironment(
+                getApplicationContext(),
+                Sensor.TYPE_GYROSCOPE,
+                SensorManager.SENSOR_DELAY_FASTEST);
+        TestSensorEnvironment uncalibratedEnvironment = new TestSensorEnvironment(
+                getApplicationContext(),
+                Sensor.TYPE_GYROSCOPE_UNCALIBRATED,
+                SensorManager.SENSOR_DELAY_FASTEST);
+        SensorCalibratedUncalibratedVerifier verifier = new SensorCalibratedUncalibratedVerifier(
+                calibratedEnvironment,
+                uncalibratedEnvironment,
+                THRESHOLD_CALIBRATED_UNCALIBRATED_RAD_SEC);
+
+        try {
+            verifier.execute();
+        } finally {
+            playSound();
+        }
+        return null;
+    }
+
+    /**
      * This test verifies that the Gyroscope measures the appropriate angular position.
      *
      * The test takes a set of samples from the sensor under test and calculates the angular
@@ -100,8 +145,9 @@
      */
     private String verifyMeasurements(int instructionsResId, int rotationAxis, int expectationDeg)
             throws Throwable {
-        SensorTestLogger logger = getTestLogger();
         setRendererRotation(rotationAxis, expectationDeg >= 0);
+
+        SensorTestLogger logger = getTestLogger();
         logger.logInstructions(instructionsResId);
         waitForUserToBegin();
         logger.logWaitForSound();
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/MagneticFieldMeasurementTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/MagneticFieldMeasurementTestActivity.java
index c2a9207..bd18a95 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/MagneticFieldMeasurementTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/MagneticFieldMeasurementTestActivity.java
@@ -19,11 +19,12 @@
 import com.android.cts.verifier.R;
 import com.android.cts.verifier.sensors.base.SensorCtsVerifierTestActivity;
 
-import android.graphics.Color;
 import android.hardware.Sensor;
 import android.hardware.SensorEvent;
 import android.hardware.SensorEventListener2;
 import android.hardware.SensorManager;
+import android.hardware.cts.helpers.SensorCalibratedUncalibratedVerifier;
+import android.hardware.cts.helpers.SensorCtsHelper;
 import android.hardware.cts.helpers.TestSensorEnvironment;
 import android.hardware.cts.helpers.TestSensorEventListener;
 import android.hardware.cts.helpers.TestSensorManager;
@@ -38,6 +39,8 @@
  * disturbances.
  */
 public class MagneticFieldMeasurementTestActivity extends SensorCtsVerifierTestActivity {
+    private static final float THRESHOLD_CALIBRATED_UNCALIBRATED_UT = 3f;
+
     public MagneticFieldMeasurementTestActivity() {
         super(MagneticFieldMeasurementTestActivity.class);
     }
@@ -47,50 +50,6 @@
         calibrateMagnetometer();
     }
 
-    public String testNorm() throws Throwable {
-        appendText(R.string.snsr_mag_verify_norm);
-        return verifyNorm();
-    }
-
-    public String testStandardDeviation() throws Throwable {
-        appendText(R.string.snsr_mag_verify_std_dev);
-        return verifyStandardDeviation();
-    }
-
-    private void calibrateMagnetometer() {
-        SensorEventListener2 listener = new SensorEventListener2() {
-            @Override
-            public void onSensorChanged(SensorEvent event) {
-                float values[] = event.values;
-                clearText();
-                appendText(R.string.snsr_mag_calibration_description);
-                appendText(String.format("->  (%.2f, %.2f, %.2f) uT", values[0], values[1],
-                        values[2]), Color.GRAY);
-
-                // TODO: automate finding out when the magnetometer is calibrated
-                appendText(R.string.snsr_mag_calibration_complete);
-            }
-
-            @Override
-            public void onAccuracyChanged(Sensor sensor, int accuracy) {}
-
-            @Override
-            public void onFlushCompleted(Sensor sensor) {}
-        };
-
-        TestSensorEnvironment environment = new TestSensorEnvironment(
-                getApplicationContext(),
-                Sensor.TYPE_MAGNETIC_FIELD,
-                SensorManager.SENSOR_DELAY_NORMAL);
-        TestSensorManager magnetometer = new TestSensorManager(environment);
-        try {
-            magnetometer.registerListener(new TestSensorEventListener(listener));
-            waitForUser();
-        } finally {
-            magnetometer.unregisterListener();
-        }
-    }
-
     /**
      * This test verifies that the Norm of the sensor data is close to the expected reference value.
      * The units of the reference value are dependent on the type of sensor.
@@ -111,7 +70,10 @@
      * - the values representing the expectation of the test
      * - the values sampled from the sensor
      */
-    private String verifyNorm() throws Throwable {
+    @SuppressWarnings("unused")
+    public String testNorm() throws Throwable {
+        getTestLogger().logMessage(R.string.snsr_mag_verify_norm);
+
         TestSensorEnvironment environment = new TestSensorEnvironment(
                 getApplicationContext(),
                 Sensor.TYPE_MAGNETIC_FIELD,
@@ -153,16 +115,93 @@
      * Additionally, the device's debug output (adb logcat) dumps the set of values associated with
      * the failure to help track down the issue.
      */
-    private String verifyStandardDeviation() throws Throwable {
+    @SuppressWarnings("unused")
+    public String testStandardDeviation() throws Throwable {
+        getTestLogger().logMessage(R.string.snsr_mag_verify_std_dev);
+
         TestSensorEnvironment environment = new TestSensorEnvironment(
                 getApplicationContext(),
                 Sensor.TYPE_MAGNETIC_FIELD,
                 SensorManager.SENSOR_DELAY_FASTEST);
         TestSensorOperation verifyStdDev =
                 new TestSensorOperation(environment, 100 /* event count */);
+
         verifyStdDev.addVerification(new StandardDeviationVerification(
                 new float[]{2f, 2f, 2f} /* uT */));
         verifyStdDev.execute();
         return null;
     }
+
+    /**
+     * Verifies that the relationship between readings from calibrated and their corresponding
+     * uncalibrated sensors comply to the following equation:
+     *      calibrated = uncalibrated - bias
+     */
+    @SuppressWarnings("unused")
+    public String testCalibratedAndUncalibrated() throws Throwable {
+        getTestLogger().logMessage(R.string.snsr_mag_verify_calibrated_uncalibrated);
+
+        TestSensorEnvironment calibratedEnvironment = new TestSensorEnvironment(
+                getApplicationContext(),
+                Sensor.TYPE_MAGNETIC_FIELD,
+                SensorManager.SENSOR_DELAY_FASTEST);
+        TestSensorEnvironment uncalibratedEnvironment = new TestSensorEnvironment(
+                getApplicationContext(),
+                Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED,
+                SensorManager.SENSOR_DELAY_FASTEST);
+        SensorCalibratedUncalibratedVerifier verifier = new SensorCalibratedUncalibratedVerifier(
+                calibratedEnvironment,
+                uncalibratedEnvironment,
+                THRESHOLD_CALIBRATED_UNCALIBRATED_UT);
+
+        try {
+            verifier.execute();
+        } finally {
+            playSound();
+        }
+        return null;
+    }
+
+    /**
+     * A routine to help operators calibrate the magnetometer.
+     */
+    private void calibrateMagnetometer() {
+        SensorEventListener2 listener = new SensorEventListener2() {
+            @Override
+            public void onSensorChanged(SensorEvent event) {
+                clearText();
+
+                float values[] = event.values;
+                SensorTestLogger logger = getTestLogger();
+                logger.logInstructions(R.string.snsr_mag_calibration_description);
+                logger.logMessage(
+                        R.string.snsr_mag_measurement,
+                        values[0],
+                        values[1],
+                        values[2],
+                        SensorCtsHelper.getMagnitude(values));
+
+                // TODO: automate finding out when the magnetometer is calibrated
+                logger.logInstructions(R.string.snsr_mag_calibration_complete);
+            }
+
+            @Override
+            public void onAccuracyChanged(Sensor sensor, int accuracy) {}
+
+            @Override
+            public void onFlushCompleted(Sensor sensor) {}
+        };
+
+        TestSensorEnvironment environment = new TestSensorEnvironment(
+                getApplicationContext(),
+                Sensor.TYPE_MAGNETIC_FIELD,
+                SensorManager.SENSOR_DELAY_NORMAL);
+        TestSensorManager magnetometer = new TestSensorManager(environment);
+        try {
+            magnetometer.registerListener(new TestSensorEventListener(listener));
+            waitForUserToContinue();
+        } finally {
+            magnetometer.unregisterListener();
+        }
+    }
 }
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/SensorSynchronizationTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/SensorSynchronizationTestActivity.java
index b5ffc2a..1dd5984 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/SensorSynchronizationTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/SensorSynchronizationTestActivity.java
@@ -14,7 +14,6 @@
 import android.hardware.SensorManager;
 import android.hardware.cts.helpers.TestSensorEvent;
 import android.os.Build;
-import android.os.SystemClock;
 
 import java.util.ArrayList;
 import java.util.List;
@@ -161,7 +160,7 @@
 
     @Override
     public void onSensorChanged(SensorEvent sensorEvent) {
-        mSensorEvents.add(new TestSensorEvent(sensorEvent, SystemClock.elapsedRealtimeNanos()));
+        mSensorEvents.add(new TestSensorEvent(sensorEvent));
     }
 
     @Override
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/SensorValueAccuracyActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/SensorValueAccuracyActivity.java
deleted file mode 100644
index b6d7cd6..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/SensorValueAccuracyActivity.java
+++ /dev/null
@@ -1,282 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.cts.verifier.sensors;
-
-import com.android.cts.verifier.R;
-import com.android.cts.verifier.sensors.base.SensorCtsVerifierTestActivity;
-
-import junit.framework.Assert;
-
-import android.content.Context;
-import android.hardware.Sensor;
-import android.hardware.SensorEvent;
-import android.hardware.SensorEventListener;
-import android.hardware.SensorManager;
-import android.hardware.cts.helpers.SensorNotSupportedException;
-import android.hardware.cts.helpers.TestSensorEnvironment;
-import android.hardware.cts.helpers.TestSensorEvent;
-import android.hardware.cts.helpers.sensoroperations.TestSensorOperation;
-import android.hardware.cts.helpers.sensorverification.ISensorVerification;
-import android.hardware.cts.helpers.sensorverification.MagnitudeVerification;
-import android.os.SystemClock;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.TimeUnit;
-
-/**
- * Activity that verifies sensor event quality. Sensors will be verified with different requested
- * data rates. Also sensor events will be verified while other sensors are also active.
- */
-public class SensorValueAccuracyActivity
-        extends SensorCtsVerifierTestActivity
-        implements SensorEventListener {
-    public SensorValueAccuracyActivity() {
-        super(SensorValueAccuracyActivity.class);
-    }
-
-    private static final int EVENTS_TO_COLLECT = 100;
-    private static final int SENSOR_RATE = SensorManager.SENSOR_DELAY_FASTEST;
-
-    private static final float MAGNETIC_FIELD_CALIBRATED_UNCALIBRATED_THRESHOLD_UT = 3f;
-    private static final float GYROSCOPE_CALIBRATED_UNCALIBRATED_THRESHOLD_RAD_SEC = 0.01f;
-
-    private static final float RANGE_ATMOSPHERIC_PRESSURE = 35f;
-    private static final float AMBIENT_TEMPERATURE_AVERAGE = 22.5f;
-    private static final float AMBIENT_TEMPERATURE_THRESHOLD = 7.5f;
-
-    private SensorManager mSensorManager;
-
-    private final List<TestSensorEvent> mSensorEvents = new ArrayList<TestSensorEvent>();
-
-    @Override
-    protected void activitySetUp() {
-        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
-    }
-
-    // TODO: move tests without interaction to CTS
-    public String testPressure() throws Throwable {
-        return verifySensorNorm(
-                Sensor.TYPE_PRESSURE,
-                R.string.snsr_no_interaction,
-                SensorManager.PRESSURE_STANDARD_ATMOSPHERE,
-                RANGE_ATMOSPHERIC_PRESSURE);
-    }
-
-    public String testAmbientTemperature() throws Throwable {
-        return verifySensorNorm(
-                Sensor.TYPE_AMBIENT_TEMPERATURE,
-                R.string.snsr_no_interaction,
-                AMBIENT_TEMPERATURE_AVERAGE,
-                AMBIENT_TEMPERATURE_THRESHOLD);
-    }
-
-    // TODO: add support for proximity and light to test operations and add test cases here
-
-    // TODO: remove from here, refactor and merge with gyroscope and magnetic field tests
-    public String testMagneticFieldCalibratedUncalibrated() throws Throwable {
-        return verifyCalibratedUncalibrated(
-                Sensor.TYPE_MAGNETIC_FIELD,
-                Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED,
-                MAGNETIC_FIELD_CALIBRATED_UNCALIBRATED_THRESHOLD_UT);
-    }
-
-    public String testGyroscopeCalibratedUncalibrated() throws Throwable {
-        getTestLogger().logInstructions(R.string.snsr_keep_device_rotating_clockwise);
-        return verifyCalibratedUncalibrated(
-                Sensor.TYPE_GYROSCOPE,
-                Sensor.TYPE_GYROSCOPE_UNCALIBRATED,
-                GYROSCOPE_CALIBRATED_UNCALIBRATED_THRESHOLD_RAD_SEC);
-    }
-
-    /**
-     * Validates the norm of a sensor.
-     */
-    // TODO: fix up EventOrdering, EventGap and timestamp>0 Verifications so they can be added to
-    // this test
-    private String verifySensorNorm(
-            int sensorType,
-            int instructionsResId,
-            float expectedNorm,
-            float threshold) {
-        getTestLogger().logInstructions(instructionsResId);
-        waitForUserToBegin();
-
-        TestSensorEnvironment environment =
-                new TestSensorEnvironment(getApplicationContext(), sensorType, SENSOR_RATE);
-        TestSensorOperation verifyNormOperation =
-                new TestSensorOperation(environment, EVENTS_TO_COLLECT);
-
-        // TODO: add event ordering and timestamp > 0 verifications
-        ISensorVerification magnitudeVerification =
-                new MagnitudeVerification(expectedNorm, threshold);
-        verifyNormOperation.addVerification(magnitudeVerification);
-
-        verifyNormOperation.execute();
-        return null;
-    }
-
-    /**
-     * Verifies that the relationship between readings from calibrated and their corresponding
-     * uncalibrated sensors comply to the following equation:
-     *      calibrated = uncalibrated - bias
-     *
-     * NOTES:
-     * Currently given that timestamps might not be synchronized, the verification attempts to
-     * 'match' events from both sensors by aligning them to (time delta mean) / 2.
-     *
-     * @param calibratedSensorType The type of the calibrated sensor to verify.
-     * @param uncalibratedSensorType The type of the uncalibrated sensor to verify.
-     * @param threshold The threshold to consider the difference between the equation as
-     *                            acceptable.
-     */
-    // TODO: find a better synchronization mechanism
-    // TODO: revisit the need of a tolerance once a better synchronization mechanism is available
-    // TODO: refactor this function into a Sensor Test Operation / Verification
-    private String verifyCalibratedUncalibrated(
-            int calibratedSensorType,
-            int uncalibratedSensorType,
-            float threshold) throws Throwable {
-        SensorTestLogger logger = getTestLogger();
-        logger.logInstructions(R.string.snsr_no_interaction);
-        waitForUserToBegin();
-
-        Sensor calibratedSensor = mSensorManager.getDefaultSensor(calibratedSensorType);
-        if (calibratedSensor == null) {
-            throw new SensorNotSupportedException(calibratedSensorType);
-        }
-        Sensor uncalibratedSensor = mSensorManager.getDefaultSensor(uncalibratedSensorType);
-        if (uncalibratedSensor == null) {
-            throw new SensorNotSupportedException(uncalibratedSensorType);
-        }
-
-        // collect the required events
-        final long timeout = TimeUnit.SECONDS.toMillis(10);
-        startDataCollection(calibratedSensor);
-        startDataCollection(uncalibratedSensor);
-        logger.logWaitForSound();
-        Thread.sleep(timeout);
-        stopDataCollection();
-
-        // create a set of readings for verification
-        float[] calibratedValues = new float[3];
-        long calibratedTimestamp = 0;
-        long timestampDeltaSum = 0;
-        int calibratedEventCount = 0;
-        int uncalibratedEventCount = 0;
-        ArrayList<CalibratedUncalibratedReading> readings =
-                new ArrayList<CalibratedUncalibratedReading>();
-        for (TestSensorEvent event : mSensorEvents) {
-            if (event.sensor.getType() == calibratedSensorType) {
-                calibratedValues = event.values.clone();
-                calibratedTimestamp = event.receivedTimestamp;
-                ++calibratedEventCount;
-            } else if (event.sensor.getType() == uncalibratedSensorType) {
-                float[] uncalibratedValues = event.values.clone();
-                long timestampDelta = event.receivedTimestamp - calibratedTimestamp;
-                timestampDeltaSum += timestampDelta;
-                ++uncalibratedEventCount;
-
-                CalibratedUncalibratedReading reading = new CalibratedUncalibratedReading(
-                        calibratedValues,
-                        uncalibratedValues,
-                        timestampDelta);
-                readings.add(reading);
-            }
-            // TODO: use delayed asserts to log on else clause
-        }
-
-        // verify readings that are under a timestamp synchronization threshold
-        String calibratedEventsMessage = String.format(
-                "Calibrated (%s) events expected. Found=%d.",
-                calibratedSensor.getName(),
-                calibratedEventCount);
-        Assert.assertTrue(calibratedEventsMessage, calibratedEventCount > 0);
-
-        String uncalibratedEventsMessage = String.format(
-                "Uncalibrated (%s) events expected. Found=%d.",
-                uncalibratedSensor.getName(),
-                uncalibratedEventCount);
-        Assert.assertTrue(uncalibratedEventsMessage, uncalibratedEventCount > 0);
-
-        long timestampDeltaMean = timestampDeltaSum / readings.size();
-        long timestampTolerance = timestampDeltaMean / 2;
-        int verifiedEventsCount = 0;
-        for (CalibratedUncalibratedReading reading : readings) {
-            if (reading.timestampDelta < timestampTolerance) {
-                for (int i = 0; i < 3; ++i) {
-                    float calibrated = reading.calibratedValues[i];
-                    float uncalibrated = reading.uncalibratedValues[i];
-                    float bias = reading.uncalibratedValues[i + 3];
-                    String message = String.format(
-                            "Calibrated (%s) and Uncalibrated (%s) sensor readings are expected to"
-                                    + " satisfy: calibrated = uncalibrated - bias. Axis=%d,"
-                                    + " Calibrated=%s, Uncalibrated=%s, Bias=%s, Threshold=%s",
-                            calibratedSensor.getName(),
-                            uncalibratedSensor.getName(),
-                            i,
-                            calibrated,
-                            uncalibrated,
-                            bias,
-                            threshold);
-                    Assert.assertEquals(message, calibrated, uncalibrated - bias, threshold);
-                }
-                ++verifiedEventsCount;
-            }
-        }
-
-        playSound();
-        String eventsFoundMessage = String.format(
-                "At least one uncalibrated event expected to be verified. Found=%d.",
-                verifiedEventsCount);
-        Assert.assertTrue(eventsFoundMessage, verifiedEventsCount > 0);
-        return eventsFoundMessage;
-    }
-
-    private void startDataCollection(Sensor sensorUnderTest) throws Throwable {
-        mSensorEvents.clear();
-        mSensorManager.registerListener(this, sensorUnderTest, SENSOR_RATE);
-    }
-
-    private void stopDataCollection() {
-        mSensorManager.unregisterListener(this);
-    }
-
-    @Override
-    public void onSensorChanged(SensorEvent sensorEvent) {
-        mSensorEvents.add(new TestSensorEvent(sensorEvent, SystemClock.elapsedRealtimeNanos()));
-    }
-
-    @Override
-    public void onAccuracyChanged(Sensor sensor, int accuracy) {
-    }
-
-    private class CalibratedUncalibratedReading {
-        public final float[] calibratedValues;
-        public final float[] uncalibratedValues;
-        public final long timestampDelta;
-
-        public CalibratedUncalibratedReading(
-                float[] calibratedValues,
-                float[] uncalibratedValues,
-                long timestampDelta) {
-            this.calibratedValues = calibratedValues;
-            this.uncalibratedValues = uncalibratedValues;
-            this.timestampDelta = timestampDelta;
-        }
-    }
-}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/BaseSensorTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/BaseSensorTestActivity.java
index 068869f..d1c06cb 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/BaseSensorTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/BaseSensorTestActivity.java
@@ -349,6 +349,9 @@
         });
     }
 
+    /**
+     * Plays a (default) sound as a notification for the operator.
+     */
     protected void playSound() {
         MediaPlayer player = MediaPlayer.create(this, Settings.System.DEFAULT_NOTIFICATION_URI);
         if (player == null) {
@@ -366,11 +369,18 @@
         }
     }
 
+    /**
+     * Makes the device vibrate for the given amount of time.
+     */
     protected void vibrate(int timeInMs) {
         Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
         vibrator.vibrate(timeInMs);
     }
 
+    /**
+     * Makes the device vibrate following the given pattern.
+     * See {@link Vibrator#vibrate(long[], int)} for more information.
+     */
     protected void vibrate(long[] pattern) {
         Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
         vibrator.vibrate(pattern, -1);
@@ -519,8 +529,6 @@
             textAppender.append();
         }
 
-        // TODO: add methods to log failures in activity setup/cleanup
-
         public void logInstructions(int instructionsResId, Object ... params) {
             TextAppender textAppender = new TextAppender(R.layout.snsr_instruction);
             textAppender.setText(getString(instructionsResId, params));
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/SensorCtsTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/SensorCtsTestActivity.java
index 77f3a41..35bff24 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/SensorCtsTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/SensorCtsTestActivity.java
@@ -86,7 +86,12 @@
 
     @Override
     protected void activityCleanUp() {
-        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
+        runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
+            }
+        });
         mScreenManipulator.turnScreenOn();
         mWakeLock.release();
     }
@@ -94,7 +99,9 @@
     @Override
     protected void onDestroy() {
         super.onDestroy();
-        mScreenManipulator.releaseScreenOn();
+        if (mScreenManipulator != null) {
+            mScreenManipulator.releaseScreenOn();
+        }
     }
 
     /**
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/PowerTestHostLink.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/PowerTestHostLink.java
index 59caadf..0041aec 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/PowerTestHostLink.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/PowerTestHostLink.java
@@ -23,6 +23,7 @@
 import android.hardware.SensorEvent;
 import android.hardware.SensorEventListener;
 import android.hardware.SensorManager;
+import android.hardware.cts.helpers.SensorCtsHelper;
 import android.net.LocalServerSocket;
 import android.net.LocalSocket;
 import android.util.Log;
@@ -216,7 +217,7 @@
                 response = RESPONSE_OK;
             }
         } else if (request.startsWith(REQUEST_EXTERNAL_STORAGE)){
-            response = System.getenv("EXTERNAL_STORAGE");
+            response = SensorCtsHelper.getSensorTestDataDirectory("power/").getAbsolutePath();
             Log.d(TAG,"External storage is " + response);
         } else if (request.startsWith(REQUEST_SCREEN_OFF)) {
             try {
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/SensorFeaturesDeactivator.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/SensorFeaturesDeactivator.java
index 75c0ec0..d69d343 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/SensorFeaturesDeactivator.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/SensorFeaturesDeactivator.java
@@ -57,8 +57,7 @@
         mKeepScreenOnMode.requestToSetMode(mStateContainer, false);
         mLocationMode.requestToSetMode(mStateContainer, false);
 
-        // TODO: try to use adb shell dumpsys sensorservice to find out if there are clients still
-        // registered at this time
+        // TODO: find a way to find out if there are clients still registered at this time
         mStateContainer.getTestLogger()
                 .logInstructions(R.string.snsr_sensor_feature_deactivation);
         mStateContainer.waitForUserToContinue();
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/SensorSettingContainer.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/SensorSettingContainer.java
index 9fa40e3..9a0d7e5 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/SensorSettingContainer.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/SensorSettingContainer.java
@@ -62,7 +62,7 @@
         BaseSensorTestActivity.SensorTestLogger logger = stateContainer.getTestLogger();
         String settingName = getSettingName(stateContainer);
         if (getCurrentSettingMode() == modeOn) {
-            logger.logInstructions(R.string.snsr_setting_mode_set, settingName, modeOn);
+            logger.logMessage(R.string.snsr_setting_mode_set, settingName, modeOn);
             return;
         }
 
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/SensorTestScreenManipulator.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/SensorTestScreenManipulator.java
index bfe2ba7..0263975 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/SensorTestScreenManipulator.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/SensorTestScreenManipulator.java
@@ -57,7 +57,7 @@
     private final DevicePolicyManager mDevicePolicyManager;
     private final ComponentName mComponentName;
     private final PowerManager.WakeLock mWakeUpScreenWakeLock;
-    private final PowerManager.WakeLock mKeepScreenWakeLock;
+    private final PowerManager.WakeLock mKeepScreenOnWakeLock;
 
     private InternalBroadcastReceiver mBroadcastReceiver;
     private boolean mTurnOffScreenOnPowerDisconnected;
@@ -74,7 +74,7 @@
         PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
         mWakeUpScreenWakeLock = powerManager.newWakeLock(levelAndFlags, "SensorTestWakeUpScreen");
         mWakeUpScreenWakeLock.setReferenceCounted(false);
-        mKeepScreenWakeLock = powerManager.newWakeLock(levelAndFlags, "SensorTestKeepScreenOn");
+        mKeepScreenOnWakeLock = powerManager.newWakeLock(levelAndFlags, "SensorTestKeepScreenOn");
         mWakeUpScreenWakeLock.setReferenceCounted(false);
     }
 
@@ -141,12 +141,12 @@
      * presses the device's power button.
      */
     public synchronized void turnScreenOn() {
-        if (mKeepScreenWakeLock.isHeld()) {
+        if (mKeepScreenOnWakeLock.isHeld()) {
             // recover from cases when we could get out of sync, this can happen because the user
             // can press the power button, and other wake-locks can prevent intents to be received
-            mKeepScreenWakeLock.release();
+            mKeepScreenOnWakeLock.release();
         }
-        mKeepScreenWakeLock.acquire();
+        mKeepScreenOnWakeLock.acquire();
     }
 
     /**
@@ -155,10 +155,10 @@
      * See {@link #turnScreenOn()} for more information.
      */
     public synchronized void releaseScreenOn() {
-        if (!mKeepScreenWakeLock.isHeld()) {
+        if (!mKeepScreenOnWakeLock.isHeld()) {
             return;
         }
-        mKeepScreenWakeLock.release();
+        mKeepScreenOnWakeLock.release();
     }
 
     /**
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/AndroidManifest.xml b/hostsidetests/devicepolicy/app/ManagedProfile/AndroidManifest.xml
index e156a4f..643400b 100644
--- a/hostsidetests/devicepolicy/app/ManagedProfile/AndroidManifest.xml
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/AndroidManifest.xml
@@ -76,6 +76,7 @@
                 android:name="android.support.FILE_PROVIDER_PATHS"
                 android:resource="@xml/filepaths" />
         </provider>
+        <activity android:name=".TestActivity" />
     </application>
 
     <instrumentation android:name="android.test.InstrumentationTestRunner"
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/crossprofileintentfilters/ManagedProfileActivity.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/crossprofileintentfilters/ManagedProfileActivity.java
index a91f633..a383e2c 100644
--- a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/crossprofileintentfilters/ManagedProfileActivity.java
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/crossprofileintentfilters/ManagedProfileActivity.java
@@ -31,6 +31,8 @@
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
-        Log.i(TAG, "Roger that!");
+        Log.i(TAG, "Managed profile activity started!");
+        setResult(RESULT_OK);
+        finish();
     }
 }
\ No newline at end of file
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/crossprofileintentfilters/ManagedProfileTest.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/crossprofileintentfilters/ManagedProfileTest.java
index 0e3822b..47ecfcb 100644
--- a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/crossprofileintentfilters/ManagedProfileTest.java
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/crossprofileintentfilters/ManagedProfileTest.java
@@ -16,9 +16,13 @@
 package com.android.cts.managedprofile;
 
 import android.app.admin.DevicePolicyManager;
+import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.content.pm.PackageManager;
+import android.test.ActivityInstrumentationTestCase2;
+
+import static com.android.cts.managedprofile.BaseManagedProfileTest.ADMIN_RECEIVER_COMPONENT;
 
 /**
  * Test for {@link DevicePolicyManager#addCrossProfileIntentFilter} API.
@@ -27,14 +31,21 @@
  * in the primary profile, one to {@code ManagedProfileActivity.ACTION} in the secondary profile,
  * and one to {@code AllUsersActivity.ACTION} in both profiles.
  */
-public class ManagedProfileTest extends BaseManagedProfileTest {
+public class ManagedProfileTest extends ActivityInstrumentationTestCase2<TestActivity> {
 
     private PackageManager mPackageManager;
+    private DevicePolicyManager mDevicePolicyManager;
+
+    public ManagedProfileTest() {
+        super(TestActivity.class);
+    }
 
     @Override
     protected void setUp() throws Exception {
         super.setUp();
-        mPackageManager = getContext().getPackageManager();
+        mPackageManager = getActivity().getPackageManager();
+        mDevicePolicyManager = (DevicePolicyManager)
+                getActivity().getSystemService(Context.DEVICE_POLICY_SERVICE);
     }
 
     @Override
@@ -55,6 +66,8 @@
 
         assertTrue(mPackageManager.queryIntentActivities(
                 new Intent(PrimaryUserActivity.ACTION), /* flags = */ 0).isEmpty());
+        getActivity().startActivity(ManagedProfileActivity.ACTION);
+        assertTrue(getActivity().checkActivityStarted());
     }
 
     public void testAddCrossProfileIntentFilter_primary() {
@@ -68,6 +81,8 @@
 
         assertEquals(1, mPackageManager.queryIntentActivities(
                 new Intent(PrimaryUserActivity.ACTION), /* flags = */ 0).size());
+        getActivity().startActivity(PrimaryUserActivity.ACTION);
+        assertTrue(getActivity().checkActivityStarted());
     }
 
     public void testAddCrossProfileIntentFilter_all() {
@@ -81,6 +96,8 @@
 
         assertEquals(2, mPackageManager.queryIntentActivities(
                 new Intent(AllUsersActivity.ACTION), /* flags = */ 0).size());
+        // If we used startActivity(), the user would have a disambiguation dialog presented which
+        // requires human intervention, so we won't be testing like that
     }
 
     public void testAddCrossProfileIntentFilter_managed() {
@@ -95,5 +112,7 @@
         // We should still be resolving in the profile
         assertEquals(1, mPackageManager.queryIntentActivities(
                 new Intent(ManagedProfileActivity.ACTION), /* flags = */ 0).size());
+        getActivity().startActivity(ManagedProfileActivity.ACTION);
+        assertTrue(getActivity().checkActivityStarted());
     }
 }
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/crossprofileintentfilters/PrimaryUserActivity.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/crossprofileintentfilters/PrimaryUserActivity.java
index f6fa172..35f70be 100644
--- a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/crossprofileintentfilters/PrimaryUserActivity.java
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/crossprofileintentfilters/PrimaryUserActivity.java
@@ -31,6 +31,8 @@
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
-        Log.i(TAG, "Roger that!");
+        Log.i(TAG, "Primary user activity started!");
+        setResult(RESULT_OK);
+        finish();
     }
 }
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/crossprofileintentfilters/PrimaryUserTest.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/crossprofileintentfilters/PrimaryUserTest.java
index af400a7..7098d9e 100644
--- a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/crossprofileintentfilters/PrimaryUserTest.java
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/crossprofileintentfilters/PrimaryUserTest.java
@@ -17,9 +17,8 @@
 
 import android.app.admin.DevicePolicyManager;
 import android.content.Intent;
-import android.content.IntentFilter;
 import android.content.pm.PackageManager;
-import android.test.AndroidTestCase;
+import android.test.ActivityInstrumentationTestCase2;
 
 /**
  * Test for {@link DevicePolicyManager#addCrossProfileIntentFilter} API, for
@@ -32,28 +31,39 @@
  * Note that the {code DevicePolicyManager#clearCrossProfileIntentFilters} as well as more complex
  * test scenarios can be found in {@link ManagedProfileTest}.
  */
-public class PrimaryUserTest extends AndroidTestCase {
+public class PrimaryUserTest extends ActivityInstrumentationTestCase2<TestActivity> {
 
     private PackageManager mPackageManager;
 
+    public PrimaryUserTest() {
+        super(TestActivity.class);
+    }
+
     @Override
     protected void setUp() throws Exception {
         super.setUp();
-        mPackageManager = getContext().getPackageManager();
+        mPackageManager = getActivity().getPackageManager();
     }
 
     public void testAddCrossProfileIntentFilter_primary() {
         assertEquals(1, mPackageManager.queryIntentActivities(
                 new Intent(PrimaryUserActivity.ACTION), /* flags = */ 0).size());
+        getActivity().startActivity(PrimaryUserActivity.ACTION);
+        assertTrue(getActivity().checkActivityStarted());
     }
 
     public void testAddCrossProfileIntentFilter_all() {
         assertEquals(2, mPackageManager.queryIntentActivities(
                 new Intent(AllUsersActivity.ACTION), /* flags = */ 0).size());
+        
+        // If we used startActivity(), the user would have a disambiguation dialog presented which
+        // requires human intervention, so we won't be testing like that
     }
 
     public void testAddCrossProfileIntentFilter_managed() {
         assertEquals(1, mPackageManager.queryIntentActivities(
                 new Intent(ManagedProfileActivity.ACTION), /* flags = */ 0).size());
+        getActivity().startActivity(ManagedProfileActivity.ACTION);
+        assertTrue(getActivity().checkActivityStarted());
     }
 }
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/crossprofileintentfilters/TestActivity.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/crossprofileintentfilters/TestActivity.java
new file mode 100644
index 0000000..b0e22b6
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/crossprofileintentfilters/TestActivity.java
@@ -0,0 +1,54 @@
+/*
+ * 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 com.android.cts.managedprofile;
+
+import android.app.Activity;
+import android.content.Intent;
+import android.util.Log;
+
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Dummy activity necessary for the tests.
+ */
+public class TestActivity extends Activity {
+    private static final String TAG = TestActivity.class.getName();
+
+    private final Semaphore mActivityStartedSemaphore = new Semaphore(0);
+
+    public void startActivity(String action) {
+        startActivityForResult(new Intent(action), /* requestCode= */ 0);
+    }
+
+    public boolean checkActivityStarted() {
+        Log.i(TAG, "Waiting to see if an activity was started");
+        try {
+            return mActivityStartedSemaphore.tryAcquire(5, TimeUnit.SECONDS);
+        } catch (InterruptedException e) {
+           return false;
+        }
+    }
+
+    @Override
+    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+        Log.i(TAG, "An activity sent a result");
+        if (resultCode != RESULT_OK) {
+            Log.w(TAG, "Activity returned error code: " + resultCode);
+        }
+        mActivityStartedSemaphore.release();
+    }
+}
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseDevicePolicyTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseDevicePolicyTest.java
index abd5a99..15c7725 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseDevicePolicyTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseDevicePolicyTest.java
@@ -79,13 +79,16 @@
         String command = "am start-user " + userId;
         String commandOutput = getDevice().executeShellCommand(command);
         CLog.logAndDisplay(LogLevel.INFO, "Output for command " + command + ": " + commandOutput);
-        assertTrue(commandOutput.startsWith("Success:"));
+        assertTrue(commandOutput + " expected to start with \"Success:\"",
+                commandOutput.startsWith("Success:"));
     }
 
     protected int getMaxNumberOfUsersSupported() throws DeviceNotAvailableException {
         // TODO: move this to ITestDevice once it supports users
         String command = "pm get-max-users";
         String commandOutput = getDevice().executeShellCommand(command);
+        CLog.i("Output for command " + command + ": " + commandOutput);
+
         try {
             return Integer.parseInt(commandOutput.substring(commandOutput.lastIndexOf(" ")).trim());
         } catch (NumberFormatException e) {
@@ -97,18 +100,20 @@
     protected ArrayList<Integer> listUsers() throws DeviceNotAvailableException {
         String command = "pm list users";
         String commandOutput = getDevice().executeShellCommand(command);
+        CLog.i("Output for command " + command + ": " + commandOutput);
 
         // Extract the id of all existing users.
         String[] lines = commandOutput.split("\\r?\\n");
-        assertTrue(lines.length >= 1);
-        assertEquals(lines[0], "Users:");
+        assertTrue(commandOutput + " should contain at least one line", lines.length >= 1);
+        assertEquals(commandOutput, lines[0], "Users:");
 
         ArrayList<Integer> users = new ArrayList<Integer>();
         for (int i = 1; i < lines.length; i++) {
             // Individual user is printed out like this:
             // \tUserInfo{$id$:$name$:$Integer.toHexString(flags)$} [running]
             String[] tokens = lines[i].split("\\{|\\}|:");
-            assertTrue(tokens.length == 4 || tokens.length == 5);
+            assertTrue(lines[i] + " doesn't contain 4 or 5 tokens",
+                    tokens.length == 4 || tokens.length == 5);
             users.add(Integer.parseInt(tokens[1]));
         }
         return users;
@@ -200,14 +205,16 @@
         // TODO: Move this logic to ITestDevice.
         String command = "pm list features";
         String commandOutput = getDevice().executeShellCommand(command);
+        CLog.i("Output for command " + command + ": " + commandOutput);
 
         // Extract the id of the new user.
         HashSet<String> availableFeatures = new HashSet<String>();
         for (String feature: commandOutput.split("\\s+")) {
             // Each line in the output of the command has the format "feature:{FEATURE_VALUE}".
             String[] tokens = feature.split(":");
-            assertTrue(tokens.length > 1);
-            assertEquals("feature", tokens[0]);
+            assertTrue("\"" + feature + "\" expected to have format feature:{FEATURE_VALUE}",
+                    tokens.length > 1);
+            assertEquals(feature, "feature", tokens[0]);
             availableFeatures.add(tokens[1]);
         }
 
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java
index 39e2b95..b84e9fe 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java
@@ -86,14 +86,15 @@
             return;
         }
         String testClass = DEVICE_OWNER_PKG + "." + testClassName;
-        assertTrue(runDeviceTests(DEVICE_OWNER_PKG, testClass));
+        assertTrue(testClass + " failed.", runDeviceTests(DEVICE_OWNER_PKG, testClass));
     }
 
     private void setDeviceOwner(String componentName) throws DeviceNotAvailableException {
         String command = "dpm set-device-owner '" + componentName + "'";
         String commandOutput = getDevice().executeShellCommand(command);
         CLog.logAndDisplay(LogLevel.INFO, "Output for command " + command + ": " + commandOutput);
-        assertTrue(commandOutput.startsWith("Success:"));
+        assertTrue(commandOutput + " expected to start with \"Success:\"",
+                commandOutput.startsWith("Success:"));
     }
 
 }
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java
index 7fc33f0..4e57b28 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java
@@ -142,8 +142,9 @@
 
         // Extract the id of the new user.
         String[] tokens = commandOutput.split("\\s+");
-        assertTrue(tokens.length > 0);
-        assertEquals("Success:", tokens[0]);
+        assertTrue(commandOutput + " expected to have format \"Success: {USER_ID}\"",
+                tokens.length > 0);
+        assertEquals(commandOutput, "Success:", tokens[0]);
         return Integer.parseInt(tokens[tokens.length-1]);
     }
 
@@ -152,6 +153,7 @@
         String command = "dpm set-profile-owner '" + componentName + "' " + userId;
         String commandOutput = getDevice().executeShellCommand(command);
         CLog.logAndDisplay(LogLevel.INFO, "Output for command " + command + ": " + commandOutput);
-        assertTrue(commandOutput.startsWith("Success:"));
+        assertTrue(commandOutput + " expected to start with \"Success:\"",
+                commandOutput.startsWith("Success:"));
     }
 }
diff --git a/libs/deviceutil/Android.mk b/libs/deviceutil/Android.mk
index d5a2c57..8c81ee4 100644
--- a/libs/deviceutil/Android.mk
+++ b/libs/deviceutil/Android.mk
@@ -29,3 +29,5 @@
 LOCAL_SDK_VERSION := current
 
 include $(BUILD_STATIC_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/libs/deviceutil/jni/Android.mk b/libs/deviceutil/jni/Android.mk
new file mode 100644
index 0000000..b801a4d
--- /dev/null
+++ b/libs/deviceutil/jni/Android.mk
@@ -0,0 +1,32 @@
+# Copyright (C) 2010 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.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := libcts_jni
+
+# Don't include this package in any configuration by default.
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_SRC_FILES := \
+		CtsJniOnLoad.cpp \
+		android_cts_FileUtils.cpp
+
+LOCAL_C_INCLUDES := $(JNI_H_INCLUDE)
+
+LOCAL_SHARED_LIBRARIES := libnativehelper liblog libdl
+
+include $(BUILD_SHARED_LIBRARY)
\ No newline at end of file
diff --git a/libs/deviceutil/jni/CtsJniOnLoad.cpp b/libs/deviceutil/jni/CtsJniOnLoad.cpp
new file mode 100644
index 0000000..abf8e01
--- /dev/null
+++ b/libs/deviceutil/jni/CtsJniOnLoad.cpp
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2010 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.
+ */
+
+#include <jni.h>
+#include <stdio.h>
+
+extern int register_android_cts_FileUtils(JNIEnv*);
+
+jint JNI_OnLoad(JavaVM *vm, void *reserved) {
+    JNIEnv *env = NULL;
+
+    if (vm->GetEnv((void **) &env, JNI_VERSION_1_4) != JNI_OK) {
+        return JNI_ERR;
+    }
+
+    if (register_android_cts_FileUtils(env)) {
+      return JNI_ERR;
+    }
+
+    return JNI_VERSION_1_4;
+}
diff --git a/tests/tests/security/jni/android_security_cts_FileUtils.cpp b/libs/deviceutil/jni/android_cts_FileUtils.cpp
similarity index 80%
rename from tests/tests/security/jni/android_security_cts_FileUtils.cpp
rename to libs/deviceutil/jni/android_cts_FileUtils.cpp
index 8009c04..91b74bf 100644
--- a/tests/tests/security/jni/android_security_cts_FileUtils.cpp
+++ b/libs/deviceutil/jni/android_cts_FileUtils.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2014 The Android Open Source Project
+ * Copyright (C) 2011 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.
@@ -40,12 +40,12 @@
 
 /*
  * Native methods used by
- * cts/tests/src/android/security/cts/FileUtils.java
+ * cts/libs/deviceutil/src/android/cts/util/FileUtils.java
  *
- * Copied from hidden API: frameworks/base/core/jni/android_security_FileUtils.cpp
+ * Copied from hidden API: frameworks/base/core/jni/android_FileUtils.cpp
  */
 
-jboolean android_security_cts_FileUtils_getFileStatus(JNIEnv* env, jobject thiz,
+jboolean android_cts_FileUtils_getFileStatus(JNIEnv* env, jobject thiz,
         jstring path, jobject fileStatus, jboolean statLinks)
 {
     const char* pathStr = env->GetStringUTFChars(path, NULL);
@@ -77,21 +77,21 @@
     return ret;
 }
 
-jstring android_security_cts_FileUtils_getUserName(JNIEnv* env, jobject thiz,
+jstring android_cts_FileUtils_getUserName(JNIEnv* env, jobject thiz,
         jint uid)
 {
     struct passwd *pwd = getpwuid(uid);
     return env->NewStringUTF(pwd->pw_name);
 }
 
-jstring android_security_cts_FileUtils_getGroupName(JNIEnv* env, jobject thiz,
+jstring android_cts_FileUtils_getGroupName(JNIEnv* env, jobject thiz,
         jint gid)
 {
     struct group *grp = getgrgid(gid);
     return env->NewStringUTF(grp->gr_name);
 }
 
-jint android_security_cts_FileUtils_setPermissions(JNIEnv* env, jobject clazz,
+jint android_cts_FileUtils_setPermissions(JNIEnv* env, jobject clazz,
         jstring file, jint mode)
 {
     const char *fileStr = env->GetStringUTFChars(file, NULL);
@@ -110,22 +110,22 @@
 }
 
 static JNINativeMethod gMethods[] = {
-    {  "getFileStatus", "(Ljava/lang/String;Landroid/security/cts/FileUtils$FileStatus;Z)Z",
-            (void *) android_security_cts_FileUtils_getFileStatus  },
+    {  "getFileStatus", "(Ljava/lang/String;Landroid/cts/util/FileUtils$FileStatus;Z)Z",
+            (void *) android_cts_FileUtils_getFileStatus  },
     {  "getUserName", "(I)Ljava/lang/String;",
-            (void *) android_security_cts_FileUtils_getUserName  },
+            (void *) android_cts_FileUtils_getUserName  },
     {  "getGroupName", "(I)Ljava/lang/String;",
-            (void *) android_security_cts_FileUtils_getGroupName  },
+            (void *) android_cts_FileUtils_getGroupName  },
     {  "setPermissions", "(Ljava/lang/String;I)I",
-            (void *) android_security_cts_FileUtils_setPermissions },
+            (void *) android_cts_FileUtils_setPermissions },
 };
 
-int register_android_security_cts_FileUtils(JNIEnv* env)
+int register_android_cts_FileUtils(JNIEnv* env)
 {
-    jclass clazz = env->FindClass("android/security/cts/FileUtils");
+    jclass clazz = env->FindClass("android/cts/util/FileUtils");
     assert(clazz != null);
 
-    gFileStatusClass = env->FindClass("android/security/cts/FileUtils$FileStatus");
+    gFileStatusClass = env->FindClass("android/cts/util/FileUtils$FileStatus");
     assert(gFileStatusClass != null);
     gFileStatusDevFieldID = env->GetFieldID(gFileStatusClass, "dev", "I");
     gFileStatusInoFieldID = env->GetFieldID(gFileStatusClass, "ino", "I");
diff --git a/libs/deviceutil/src/android/app/cts/CTSResult.java b/libs/deviceutil/src/android/cts/util/CTSResult.java
similarity index 96%
rename from libs/deviceutil/src/android/app/cts/CTSResult.java
rename to libs/deviceutil/src/android/cts/util/CTSResult.java
index ae4dbfd..c780f57 100644
--- a/libs/deviceutil/src/android/app/cts/CTSResult.java
+++ b/libs/deviceutil/src/android/cts/util/CTSResult.java
@@ -14,7 +14,7 @@
  * the License.
  */
 
-package android.app.cts;
+package android.cts.util;
 
 public interface CTSResult {
     public static final int RESULT_OK = 1;
diff --git a/libs/deviceutil/src/android/provider/cts/FileCopyHelper.java b/libs/deviceutil/src/android/cts/util/FileCopyHelper.java
similarity index 98%
rename from libs/deviceutil/src/android/provider/cts/FileCopyHelper.java
rename to libs/deviceutil/src/android/cts/util/FileCopyHelper.java
index 507eb06..e84e920 100644
--- a/libs/deviceutil/src/android/provider/cts/FileCopyHelper.java
+++ b/libs/deviceutil/src/android/cts/util/FileCopyHelper.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package android.provider.cts;
+package android.cts.util;
 
 import android.content.Context;
 
diff --git a/tests/tests/os/src/android/os/cts/FileUtils.java b/libs/deviceutil/src/android/cts/util/FileUtils.java
similarity index 98%
rename from tests/tests/os/src/android/os/cts/FileUtils.java
rename to libs/deviceutil/src/android/cts/util/FileUtils.java
index 8600d8b..055f2d6 100644
--- a/tests/tests/os/src/android/os/cts/FileUtils.java
+++ b/libs/deviceutil/src/android/cts/util/FileUtils.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package android.os.cts;
+package android.cts.util;
 
 import java.io.ByteArrayOutputStream;
 import java.io.File;
@@ -54,7 +54,7 @@
     public static final int S_IXOTH = 00001;
 
     static {
-        System.loadLibrary("ctsos_jni");
+        System.loadLibrary("cts_jni");
     }
 
     public static class FileStatus {
diff --git a/tests/tests/os/src/android/os/cts/IBinderParcelable.java b/libs/deviceutil/src/android/cts/util/IBinderParcelable.java
similarity index 97%
rename from tests/tests/os/src/android/os/cts/IBinderParcelable.java
rename to libs/deviceutil/src/android/cts/util/IBinderParcelable.java
index e48f58a..c80716e 100644
--- a/tests/tests/os/src/android/os/cts/IBinderParcelable.java
+++ b/libs/deviceutil/src/android/cts/util/IBinderParcelable.java
@@ -13,7 +13,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package android.os.cts;
+package android.cts.util;
 
 import android.os.IBinder;
 import android.os.Parcel;
diff --git a/tests/tests/widget/src/android/widget/cts/NullWebViewUtils.java b/libs/deviceutil/src/android/cts/util/NullWebViewUtils.java
similarity index 98%
rename from tests/tests/widget/src/android/widget/cts/NullWebViewUtils.java
rename to libs/deviceutil/src/android/cts/util/NullWebViewUtils.java
index d7a73fa..e1b23f7 100644
--- a/tests/tests/widget/src/android/widget/cts/NullWebViewUtils.java
+++ b/libs/deviceutil/src/android/cts/util/NullWebViewUtils.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package android.widget.cts;
+package android.cts.util;
 
 import android.content.Context;
 import android.content.pm.PackageManager;
diff --git a/tests/tests/os/src/android/os/cts/ReadElf.java b/libs/deviceutil/src/android/cts/util/ReadElf.java
similarity index 99%
rename from tests/tests/os/src/android/os/cts/ReadElf.java
rename to libs/deviceutil/src/android/cts/util/ReadElf.java
index 4a20031..559cbd0 100644
--- a/tests/tests/os/src/android/os/cts/ReadElf.java
+++ b/libs/deviceutil/src/android/cts/util/ReadElf.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package android.os.cts;
+package android.cts.util;
 
 import java.io.File;
 import java.io.IOException;
diff --git a/tests/tests/telephony/src/android/telephony/cts/TestThread.java b/libs/deviceutil/src/android/cts/util/TestThread.java
similarity index 98%
rename from tests/tests/telephony/src/android/telephony/cts/TestThread.java
rename to libs/deviceutil/src/android/cts/util/TestThread.java
index 9bf40de..14df61c 100644
--- a/tests/tests/telephony/src/android/telephony/cts/TestThread.java
+++ b/libs/deviceutil/src/android/cts/util/TestThread.java
@@ -13,7 +13,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package android.telephony.cts;
+package android.cts.util;
 
 /**
  * Thread class for executing a Runnable containing assertions in a separate thread.
diff --git a/tests/tests/view/src/android/view/cts/WidgetTestUtils.java b/libs/deviceutil/src/android/cts/util/WidgetTestUtils.java
similarity index 98%
rename from tests/tests/view/src/android/view/cts/WidgetTestUtils.java
rename to libs/deviceutil/src/android/cts/util/WidgetTestUtils.java
index e82e9df..813672e 100644
--- a/tests/tests/view/src/android/view/cts/WidgetTestUtils.java
+++ b/libs/deviceutil/src/android/cts/util/WidgetTestUtils.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package android.view.cts;
+package android.cts.util;
 
 import org.xmlpull.v1.XmlPullParser;
 import org.xmlpull.v1.XmlPullParserException;
diff --git a/libs/deviceutillegacy/Android.mk b/libs/deviceutillegacy/Android.mk
new file mode 100644
index 0000000..852ce38
--- /dev/null
+++ b/libs/deviceutillegacy/Android.mk
@@ -0,0 +1,30 @@
+# 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.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_STATIC_JAVA_LIBRARIES := ctsdeviceutil
+
+LOCAL_SRC_FILES := \
+    $(call all-java-files-under, src)
+
+LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
+
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_MODULE := ctsdeviceutillegacy
+
+include $(BUILD_STATIC_JAVA_LIBRARY)
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebViewOnUiThread.java b/libs/deviceutillegacy/src/android/webkit/cts/WebViewOnUiThread.java
similarity index 99%
rename from tests/tests/webkit/src/android/webkit/cts/WebViewOnUiThread.java
rename to libs/deviceutillegacy/src/android/webkit/cts/WebViewOnUiThread.java
index 9b2d803..b9d3af1 100644
--- a/tests/tests/webkit/src/android/webkit/cts/WebViewOnUiThread.java
+++ b/libs/deviceutillegacy/src/android/webkit/cts/WebViewOnUiThread.java
@@ -17,6 +17,7 @@
 package android.webkit.cts;
 
 import android.cts.util.PollingCheck;
+import android.cts.util.TestThread;
 import android.graphics.Bitmap;
 import android.graphics.Picture;
 import android.graphics.Rect;
diff --git a/tests/app/src/android/app/cts/CTSActivityTestCaseBase.java b/tests/app/src/android/app/cts/CTSActivityTestCaseBase.java
index 9ab1965..efe693a 100644
--- a/tests/app/src/android/app/cts/CTSActivityTestCaseBase.java
+++ b/tests/app/src/android/app/cts/CTSActivityTestCaseBase.java
@@ -16,6 +16,7 @@
 
 package android.app.cts;
 
+import android.cts.util.CTSResult;
 import android.test.InstrumentationTestCase;
 
 public class CTSActivityTestCaseBase extends InstrumentationTestCase implements CTSResult {
diff --git a/tests/app/src/android/app/cts/IBinderParcelable.java b/tests/app/src/android/app/cts/IBinderParcelable.java
deleted file mode 100644
index 228097f..0000000
--- a/tests/app/src/android/app/cts/IBinderParcelable.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (C) 2009 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.os.IBinder;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-public class IBinderParcelable implements Parcelable {
-    public IBinder binder;
-
-    public IBinderParcelable(IBinder source) {
-        binder = source;
-    }
-
-    public int describeContents() {
-        return 0;
-    }
-
-    public void writeToParcel(Parcel dest, int flags) {
-        dest.writeStrongBinder(binder);
-    }
-
-    public static final Parcelable.Creator<IBinderParcelable>
-        CREATOR = new Parcelable.Creator<IBinderParcelable>() {
-
-        public IBinderParcelable createFromParcel(Parcel source) {
-            return new IBinderParcelable(source);
-        }
-
-        public IBinderParcelable[] newArray(int size) {
-            return new IBinderParcelable[size];
-        }
-    };
-
-    private IBinderParcelable(Parcel source) {
-        binder = source.readStrongBinder();
-    }
-}
diff --git a/tests/app/src/android/app/cts/LocalActivityManagerTestHelper.java b/tests/app/src/android/app/cts/LocalActivityManagerTestHelper.java
index 76af648..70764e4 100644
--- a/tests/app/src/android/app/cts/LocalActivityManagerTestHelper.java
+++ b/tests/app/src/android/app/cts/LocalActivityManagerTestHelper.java
@@ -21,9 +21,9 @@
 import android.app.ActivityGroup;
 import android.app.LocalActivityManager;
 import android.content.Intent;
+import android.cts.util.CTSResult;
 import android.os.Bundle;
 import android.view.Window;
-import android.app.cts.CTSResult;
 
 public class LocalActivityManagerTestHelper extends ActivityGroup {
 
diff --git a/tests/app/src/android/app/cts/LocalService.java b/tests/app/src/android/app/cts/LocalService.java
index 22273b0..6c4ae99 100644
--- a/tests/app/src/android/app/cts/LocalService.java
+++ b/tests/app/src/android/app/cts/LocalService.java
@@ -18,6 +18,7 @@
 
 import android.app.Service;
 import android.content.Intent;
+import android.cts.util.IBinderParcelable;
 import android.os.Binder;
 import android.os.IBinder;
 import android.os.Parcel;
diff --git a/tests/app/src/android/app/cts/SearchManagerStubActivity.java b/tests/app/src/android/app/cts/SearchManagerStubActivity.java
index 6385fef..0dbd832 100644
--- a/tests/app/src/android/app/cts/SearchManagerStubActivity.java
+++ b/tests/app/src/android/app/cts/SearchManagerStubActivity.java
@@ -20,6 +20,7 @@
 import android.app.SearchManager;
 import android.content.ComponentName;
 import android.content.Context;
+import android.cts.util.CTSResult;
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.Message;
diff --git a/tests/expectations/knownfailures.txt b/tests/expectations/knownfailures.txt
index 2f436ee..1852af5 100644
--- a/tests/expectations/knownfailures.txt
+++ b/tests/expectations/knownfailures.txt
@@ -73,11 +73,37 @@
     "android.admin.cts.DevicePolicyManagerTest#testPasswordQuality_numeric",
     "android.admin.cts.DevicePolicyManagerTest#testPasswordQuality_alphabetic",
     "android.admin.cts.DevicePolicyManagerTest#testPasswordQuality_alphanumeric",
+    "android.admin.cts.DevicePolicyManagerTest#testPasswordQuality_complexUpperCase",
+    "android.admin.cts.DevicePolicyManagerTest#testPasswordQuality_complexLowerCase",
+    "android.admin.cts.DevicePolicyManagerTest#testPasswordQuality_complexLetters",
+    "android.admin.cts.DevicePolicyManagerTest#testPasswordQuality_complexNumeric",
+    "android.admin.cts.DevicePolicyManagerTest#testPasswordQuality_complexSymbols",
+    "android.admin.cts.DevicePolicyManagerTest#testPasswordQuality_complexNonLetter",
     "android.admin.cts.DevicePolicyManagerTest#testGetMaximumFailedPasswordsForWipe"
   ],
   bug: 17496766
 },
 {
+  description: "As per new CTS test case adding policy",
+  names: [
+    "com.android.cts.managedprofile.PrimaryUserTest#testAddCrossProfileIntentFilter_primary",
+    "com.android.cts.managedprofile.PrimaryUserTest#testAddCrossProfileIntentFilter_all",
+    "com.android.cts.managedprofile.PrimaryUserTest#testAddCrossProfileIntentFilter_managed",
+    "com.android.cts.managedprofile.ManagedProfile#testClearCrossProfileIntentFilters",
+    "com.android.cts.managedprofile.ManagedProfile#testAddCrossProfileIntentFilter_primary",
+    "com.android.cts.managedprofile.ManagedProfile#testAddCrossProfileIntentFilter_all",
+    "com.android.cts.managedprofile.ManagedProfile#testAddCrossProfileIntentFilter_managed"
+  ],
+  bug: 15900074
+},
+{
+  description: "these tests locks the screen with an emtpy password or swipe-to-unlock, blocking subsequent test to dismiss keyguard",
+  names: [
+    "com.android.cts.devicepolicy.DeviceOwnerTest#testKeyManagement"
+  ],
+  bug: 17496766
+},
+{
   description: "Current implementation of uninstallAllUserCaCerts does not throw expected security exception, wait for fix from framework",
   names: [
     "android.admin.cts.DevicePolicyManagerTest#testUninstallAllUserCaCerts_failIfNotProfileOwner"
@@ -180,7 +206,15 @@
     "android.hardware.cts.SensorBatchingTests#testGeomagneticRotationVector_50hz_flush",
     "android.hardware.cts.SensorIntegrationTests#testSensorsWithSeveralClients",
     "android.hardware.cts.SensorIntegrationTests#testSensorsMovingRates",
-    "android.hardware.cts.SensorIntegrationTests#testSensorStoppingInteraction",
+    "android.hardware.cts.SensorIntegrationTests#testAccelerometerAccelerometerStopping",
+    "android.hardware.cts.SensorIntegrationTests#testAccelerometerGyroscopeStopping",
+    "android.hardware.cts.SensorIntegrationTests#testAccelerometerMagneticFieldStopping",
+    "android.hardware.cts.SensorIntegrationTests#testGyroscopeAccelerometerStopping",
+    "android.hardware.cts.SensorIntegrationTests#testGyroscopeGyroscopeStopping",
+    "android.hardware.cts.SensorIntegrationTests#testGyroscopeMagneticFieldStopping",
+    "android.hardware.cts.SensorIntegrationTests#testMagneticFieldAccelerometerStopping",
+    "android.hardware.cts.SensorIntegrationTests#testMagneticFieldGyroscopeStopping",
+    "android.hardware.cts.SensorIntegrationTests#testMagneticFieldMagneticFieldStopping",
     "android.hardware.cts.SingleSensorTests#testSensorProperties",
     "android.hardware.cts.SingleSensorTests#testAccelerometer_fastest",
     "android.hardware.cts.SingleSensorTests#testAccelerometer_100hz",
diff --git a/tests/tests/admin/src/android/admin/cts/DevicePolicyManagerTest.java b/tests/tests/admin/src/android/admin/cts/DevicePolicyManagerTest.java
index 7f8fa3c..d0255f3 100644
--- a/tests/tests/admin/src/android/admin/cts/DevicePolicyManagerTest.java
+++ b/tests/tests/admin/src/android/admin/cts/DevicePolicyManagerTest.java
@@ -29,6 +29,8 @@
 
 import java.util.List;
 
+import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_COMPLEX;
+
 /**
  * Test that exercises {@link DevicePolicyManager}. The test requires that the
  * CtsDeviceAdminReceiver be installed via the CtsDeviceAdmin.apk and be
@@ -40,6 +42,7 @@
 
     private DevicePolicyManager mDevicePolicyManager;
     private ComponentName mComponent;
+    private ComponentName mSecondComponent;
     private boolean mDeviceAdmin;
 
     private static final String TEST_CA_STRING1 =
@@ -65,6 +68,7 @@
         mDevicePolicyManager = (DevicePolicyManager)
                 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
         mComponent = DeviceAdminInfoTest.getReceiverComponent();
+        mSecondComponent = DeviceAdminInfoTest.getSecondReceiverComponent();
         mDeviceAdmin =
                 mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN);
         setBlankPassword();
@@ -242,6 +246,264 @@
         assertTrue(mDevicePolicyManager.resetPassword("abcd123", 0));
     }
 
+    public void testPasswordQuality_complexUpperCase() {
+        if (!mDeviceAdmin) {
+            Log.w(TAG, "Skipping testPasswordQuality_complexUpperCase");
+            return;
+        }
+
+        mDevicePolicyManager.setPasswordQuality(mComponent, PASSWORD_QUALITY_COMPLEX);
+        assertEquals(PASSWORD_QUALITY_COMPLEX, mDevicePolicyManager.getPasswordQuality(mComponent));
+        resetComplexPasswordRestrictions();
+
+        String caseDescription = "minimum UpperCase=0";
+        assertPasswordSucceeds("abc", caseDescription);
+        assertPasswordSucceeds("aBc", caseDescription);
+        assertPasswordSucceeds("ABC", caseDescription);
+        assertPasswordSucceeds("ABCD", caseDescription);
+
+        mDevicePolicyManager.setPasswordMinimumUpperCase(mComponent, 1);
+        assertEquals(1, mDevicePolicyManager.getPasswordMinimumUpperCase(mComponent));
+        caseDescription = "minimum UpperCase=1";
+        assertPasswordFails("abc", caseDescription);
+        assertPasswordSucceeds("aBc", caseDescription);
+        assertPasswordSucceeds("ABC", caseDescription);
+        assertPasswordSucceeds("ABCD", caseDescription);
+
+        mDevicePolicyManager.setPasswordMinimumUpperCase(mComponent, 3);
+        assertEquals(3, mDevicePolicyManager.getPasswordMinimumUpperCase(mComponent));
+        caseDescription = "minimum UpperCase=3";
+        assertPasswordFails("abc", caseDescription);
+        assertPasswordFails("aBC", caseDescription);
+        assertPasswordSucceeds("ABC", caseDescription);
+        assertPasswordSucceeds("ABCD", caseDescription);
+    }
+
+    public void testPasswordQuality_complexLowerCase() {
+        if (!mDeviceAdmin) {
+            Log.w(TAG, "Skipping testPasswordQuality_complexLowerCase");
+            return;
+        }
+
+        mDevicePolicyManager.setPasswordQuality(mComponent, PASSWORD_QUALITY_COMPLEX);
+        assertEquals(PASSWORD_QUALITY_COMPLEX, mDevicePolicyManager.getPasswordQuality(mComponent));
+        resetComplexPasswordRestrictions();
+
+        String caseDescription = "minimum LowerCase=0";
+        assertPasswordSucceeds("ABCD", caseDescription);
+        assertPasswordSucceeds("aBC", caseDescription);
+        assertPasswordSucceeds("abc", caseDescription);
+        assertPasswordSucceeds("abcd", caseDescription);
+
+        mDevicePolicyManager.setPasswordMinimumLowerCase(mComponent, 1);
+        assertEquals(1, mDevicePolicyManager.getPasswordMinimumLowerCase(mComponent));
+        caseDescription = "minimum LowerCase=1";
+        assertPasswordFails("ABCD", caseDescription);
+        assertPasswordSucceeds("aBC", caseDescription);
+        assertPasswordSucceeds("abc", caseDescription);
+        assertPasswordSucceeds("abcd", caseDescription);
+
+        mDevicePolicyManager.setPasswordMinimumLowerCase(mComponent, 3);
+        assertEquals(3, mDevicePolicyManager.getPasswordMinimumLowerCase(mComponent));
+        caseDescription = "minimum LowerCase=3";
+        assertPasswordFails("ABCD", caseDescription);
+        assertPasswordFails("aBC", caseDescription);
+        assertPasswordSucceeds("abc", caseDescription);
+        assertPasswordSucceeds("abcd", caseDescription);
+    }
+
+    public void testPasswordQuality_complexLetters() {
+        if (!mDeviceAdmin) {
+            Log.w(TAG, "Skipping testPasswordQuality_complexLetters");
+            return;
+        }
+
+        mDevicePolicyManager.setPasswordQuality(mComponent, PASSWORD_QUALITY_COMPLEX);
+        assertEquals(PASSWORD_QUALITY_COMPLEX, mDevicePolicyManager.getPasswordQuality(mComponent));
+        resetComplexPasswordRestrictions();
+
+        String caseDescription = "minimum Letters=0";
+        assertPasswordSucceeds("1234", caseDescription);
+        assertPasswordSucceeds("a23", caseDescription);
+        assertPasswordSucceeds("abc", caseDescription);
+        assertPasswordSucceeds("abcd", caseDescription);
+
+        mDevicePolicyManager.setPasswordMinimumLetters(mComponent, 1);
+        assertEquals(1, mDevicePolicyManager.getPasswordMinimumLetters(mComponent));
+        caseDescription = "minimum Letters=1";
+        assertPasswordFails("1234", caseDescription);
+        assertPasswordSucceeds("a23", caseDescription);
+        assertPasswordSucceeds("abc", caseDescription);
+        assertPasswordSucceeds("abcd", caseDescription);
+
+        mDevicePolicyManager.setPasswordMinimumLetters(mComponent, 3);
+        assertEquals(3, mDevicePolicyManager.getPasswordMinimumLetters(mComponent));
+        caseDescription = "minimum Letters=3";
+        assertPasswordFails("1234", caseDescription);
+        assertPasswordFails("a23", caseDescription);
+        assertPasswordSucceeds("abc", caseDescription);
+        assertPasswordSucceeds("abcd", caseDescription);
+    }
+
+    public void testPasswordQuality_complexNumeric() {
+        if (!mDeviceAdmin) {
+            Log.w(TAG, "Skipping testPasswordQuality_complexNumeric");
+            return;
+        }
+
+        mDevicePolicyManager.setPasswordQuality(mComponent, PASSWORD_QUALITY_COMPLEX);
+        assertEquals(PASSWORD_QUALITY_COMPLEX, mDevicePolicyManager.getPasswordQuality(mComponent));
+        resetComplexPasswordRestrictions();
+
+        String caseDescription = "minimum Numeric=0";
+        assertPasswordSucceeds("abcd", caseDescription);
+        assertPasswordSucceeds("1bc", caseDescription);
+        assertPasswordSucceeds("123", caseDescription);
+        assertPasswordSucceeds("1234", caseDescription);
+
+        mDevicePolicyManager.setPasswordMinimumNumeric(mComponent, 1);
+        assertEquals(1, mDevicePolicyManager.getPasswordMinimumNumeric(mComponent));
+        caseDescription = "minimum Numeric=1";
+        assertPasswordFails("abcd", caseDescription);
+        assertPasswordSucceeds("1bc", caseDescription);
+        assertPasswordSucceeds("123", caseDescription);
+        assertPasswordSucceeds("1234", caseDescription);
+
+        mDevicePolicyManager.setPasswordMinimumNumeric(mComponent, 3);
+        assertEquals(3, mDevicePolicyManager.getPasswordMinimumNumeric(mComponent));
+        caseDescription = "minimum Numeric=3";
+        assertPasswordFails("abcd", caseDescription);
+        assertPasswordFails("1bc", caseDescription);
+        assertPasswordSucceeds("123", caseDescription);
+        assertPasswordSucceeds("1234", caseDescription);
+    }
+
+    public void testPasswordQuality_complexSymbols() {
+        if (!mDeviceAdmin) {
+            Log.w(TAG, "Skipping testPasswordQuality_complexSymbols");
+            return;
+        }
+
+        mDevicePolicyManager.setPasswordQuality(mComponent, PASSWORD_QUALITY_COMPLEX);
+        assertEquals(PASSWORD_QUALITY_COMPLEX, mDevicePolicyManager.getPasswordQuality(mComponent));
+        resetComplexPasswordRestrictions();
+
+        String caseDescription = "minimum Symbols=0";
+        assertPasswordSucceeds("abcd", caseDescription);
+        assertPasswordSucceeds("_bc", caseDescription);
+        assertPasswordSucceeds("@#!", caseDescription);
+        assertPasswordSucceeds("_@#!", caseDescription);
+
+        mDevicePolicyManager.setPasswordMinimumSymbols(mComponent, 1);
+        assertEquals(1, mDevicePolicyManager.getPasswordMinimumSymbols(mComponent));
+        caseDescription = "minimum Symbols=1";
+        assertPasswordFails("abcd", caseDescription);
+        assertPasswordSucceeds("_bc", caseDescription);
+        assertPasswordSucceeds("@#!", caseDescription);
+        assertPasswordSucceeds("_@#!", caseDescription);
+
+        mDevicePolicyManager.setPasswordMinimumSymbols(mComponent, 3);
+        assertEquals(3, mDevicePolicyManager.getPasswordMinimumSymbols(mComponent));
+        caseDescription = "minimum Symbols=3";
+        assertPasswordFails("abcd", caseDescription);
+        assertPasswordFails("_bc", caseDescription);
+        assertPasswordSucceeds("@#!", caseDescription);
+        assertPasswordSucceeds("_@#!", caseDescription);
+    }
+
+    public void testPasswordQuality_complexNonLetter() {
+        if (!mDeviceAdmin) {
+            Log.w(TAG, "Skipping testPasswordQuality_complexNonLetter");
+            return;
+        }
+
+        mDevicePolicyManager.setPasswordQuality(mComponent, PASSWORD_QUALITY_COMPLEX);
+        assertEquals(PASSWORD_QUALITY_COMPLEX, mDevicePolicyManager.getPasswordQuality(mComponent));
+        resetComplexPasswordRestrictions();
+
+        String caseDescription = "minimum NonLetter=0";
+        assertPasswordSucceeds("Abcd", caseDescription);
+        assertPasswordSucceeds("_bcd", caseDescription);
+        assertPasswordSucceeds("3bcd", caseDescription);
+        assertPasswordSucceeds("_@3c", caseDescription);
+        assertPasswordSucceeds("_25!", caseDescription);
+
+        mDevicePolicyManager.setPasswordMinimumNonLetter(mComponent, 1);
+        assertEquals(1, mDevicePolicyManager.getPasswordMinimumNonLetter(mComponent));
+        caseDescription = "minimum NonLetter=1";
+        assertPasswordFails("Abcd", caseDescription);
+        assertPasswordSucceeds("_bcd", caseDescription);
+        assertPasswordSucceeds("3bcd", caseDescription);
+        assertPasswordSucceeds("_@3c", caseDescription);
+        assertPasswordSucceeds("_25!", caseDescription);
+
+        mDevicePolicyManager.setPasswordMinimumNonLetter(mComponent, 3);
+        assertEquals(3, mDevicePolicyManager.getPasswordMinimumNonLetter(mComponent));
+        caseDescription = "minimum NonLetter=3";
+        assertPasswordFails("Abcd", caseDescription);
+        assertPasswordFails("_bcd", caseDescription);
+        assertPasswordFails("3bcd", caseDescription);
+        assertPasswordSucceeds("c_@3c", caseDescription);
+        assertPasswordSucceeds("_25!", caseDescription);
+    }
+
+    public void testPasswordHistoryLength() {
+        if (!mDeviceAdmin) {
+            Log.w(TAG, "Skipping testPasswordHistoryLength");
+            return;
+        }
+        // Password history length restriction is only imposed if password quality is at least
+        // numeric.
+        mDevicePolicyManager.setPasswordQuality(mComponent,
+                DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC);
+        int originalValue = mDevicePolicyManager.getPasswordHistoryLength(mComponent);
+        try {
+            mDevicePolicyManager.setPasswordHistoryLength(mComponent, 3);
+            assertEquals(3, mDevicePolicyManager.getPasswordHistoryLength(mComponent));
+            // Although it would make sense we cannot test if password history restrictions
+            // are enforced as DevicePolicyManagerService.resetPassword fails to do so at the
+            // moment. See b/17707820
+        } finally {
+            mDevicePolicyManager.setPasswordHistoryLength(mComponent, originalValue);
+        }
+    }
+
+    public void testPasswordExpirationTimeout() {
+        if (!mDeviceAdmin) {
+            Log.w(TAG, "Skipping testPasswordExpirationTimeout");
+            return;
+        }
+        long originalValue = mDevicePolicyManager.getPasswordExpirationTimeout(mComponent);
+        try {
+            for (long testLength : new long[] {
+                    0L, 864000000L /* ten days */, 8640000000L /* 100 days */}) {
+                mDevicePolicyManager.setPasswordExpirationTimeout(mComponent, testLength);
+                assertEquals(testLength,
+                        mDevicePolicyManager.getPasswordExpirationTimeout(mComponent));
+            }
+        } finally {
+            mDevicePolicyManager.setPasswordExpirationTimeout(mComponent, originalValue);
+        }
+    }
+
+    public void testMaximumTimeToLock() {
+        if (!mDeviceAdmin) {
+            Log.w(TAG, "Skipping testMaximumTimeToLock");
+            return;
+        }
+        long originalValue = mDevicePolicyManager.getMaximumTimeToLock(mComponent);
+        try {
+            for (long testLength : new long[] {
+                    5000L /* 5 sec */, 60000L /* 1 min */, 1800000 /* 30 min */}) {
+                mDevicePolicyManager.setMaximumTimeToLock(mComponent, testLength);
+                assertEquals(testLength,
+                        mDevicePolicyManager.getMaximumTimeToLock(mComponent));
+            }
+        } finally {
+            mDevicePolicyManager.setMaximumTimeToLock(mComponent, originalValue);
+        }
+    }
+
     public void testCreateUser_failIfNotDeviceOwner() {
         if (!mDeviceAdmin) {
             Log.w(TAG, "Skipping testCreateUser_failIfNotDeviceOwner");
@@ -641,4 +903,33 @@
         assertTrue("message is: "+ message,
                 message.contains("does not own the profile"));
     }
+
+    private void resetComplexPasswordRestrictions() {
+        /**
+         * Not enough to reset only mComponent as
+         * {@link DevicePolicyManager#resetPassword(String, int)} checks restrictions across all
+         * admin components.
+         */
+        for (ComponentName adminComponent : new ComponentName[] {mComponent, mSecondComponent}) {
+            mDevicePolicyManager.setPasswordMinimumLength(adminComponent, 0);
+            mDevicePolicyManager.setPasswordMinimumUpperCase(adminComponent, 0);
+            mDevicePolicyManager.setPasswordMinimumLowerCase(adminComponent, 0);
+            mDevicePolicyManager.setPasswordMinimumLetters(adminComponent, 0);
+            mDevicePolicyManager.setPasswordMinimumNumeric(adminComponent, 0);
+            mDevicePolicyManager.setPasswordMinimumSymbols(adminComponent, 0);
+            mDevicePolicyManager.setPasswordMinimumNonLetter(adminComponent, 0);
+        }
+    }
+
+    private void assertPasswordFails(String password, String restriction) {
+        boolean passwordResetResult = mDevicePolicyManager.resetPassword(password, /* flags= */0);
+        assertFalse("Password '" + password + "' should have failed on " + restriction,
+                passwordResetResult);
+    }
+
+    private void assertPasswordSucceeds(String password, String restriction) {
+        boolean passwordResetResult = mDevicePolicyManager.resetPassword(password, /* flags= */0);
+        assertTrue("Password '" + password + "' failed on " + restriction, passwordResetResult);
+        assertTrue(mDevicePolicyManager.isActivePasswordSufficient());
+    }
 }
diff --git a/tests/tests/app/src/android/app/cts/LocalActivityManagerTest.java b/tests/tests/app/src/android/app/cts/LocalActivityManagerTest.java
index 1b40476..db3baba 100644
--- a/tests/tests/app/src/android/app/cts/LocalActivityManagerTest.java
+++ b/tests/tests/app/src/android/app/cts/LocalActivityManagerTest.java
@@ -20,6 +20,7 @@
 import android.app.Instrumentation;
 import android.app.LocalActivityManager;
 import android.content.Intent;
+import android.cts.util.CTSResult;
 import android.test.InstrumentationTestCase;
 import android.test.UiThreadTest;
 
diff --git a/tests/tests/app/src/android/app/cts/SearchManagerTest.java b/tests/tests/app/src/android/app/cts/SearchManagerTest.java
index 8e465e8..1cece76 100644
--- a/tests/tests/app/src/android/app/cts/SearchManagerTest.java
+++ b/tests/tests/app/src/android/app/cts/SearchManagerTest.java
@@ -17,6 +17,7 @@
 package android.app.cts;
 
 import android.content.Intent;
+import android.cts.util.CTSResult;
 
 public class SearchManagerTest extends CTSActivityTestCaseBase {
 
diff --git a/tests/tests/app/src/android/app/cts/ServiceTest.java b/tests/tests/app/src/android/app/cts/ServiceTest.java
index 675b7ae..b66f4c8 100644
--- a/tests/tests/app/src/android/app/cts/ServiceTest.java
+++ b/tests/tests/app/src/android/app/cts/ServiceTest.java
@@ -20,6 +20,7 @@
 import android.content.Context;
 import android.content.Intent;
 import android.content.ServiceConnection;
+import android.cts.util.IBinderParcelable;
 import android.os.Binder;
 import android.os.Bundle;
 import android.os.IBinder;
diff --git a/tests/tests/content/src/android/content/pm/cts/ComponentInfoTest.java b/tests/tests/content/src/android/content/pm/cts/ComponentInfoTest.java
index 361bfe4..14a42c0 100644
--- a/tests/tests/content/src/android/content/pm/cts/ComponentInfoTest.java
+++ b/tests/tests/content/src/android/content/pm/cts/ComponentInfoTest.java
@@ -20,6 +20,7 @@
 import android.content.pm.ComponentInfo;
 import android.content.pm.PackageManager;
 import android.content.pm.PackageManager.NameNotFoundException;
+import android.cts.util.WidgetTestUtils;
 import android.graphics.drawable.BitmapDrawable;
 import android.graphics.drawable.Drawable;
 import android.os.Parcel;
diff --git a/tests/tests/content/src/android/content/pm/cts/WidgetTestUtils.java b/tests/tests/content/src/android/content/pm/cts/WidgetTestUtils.java
deleted file mode 100644
index 6efd8b1..0000000
--- a/tests/tests/content/src/android/content/pm/cts/WidgetTestUtils.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * Copyright (C) 2008 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.content.pm.cts;
-
-import org.xmlpull.v1.XmlPullParser;
-import org.xmlpull.v1.XmlPullParserException;
-
-import android.content.Context;
-import android.content.res.Resources;
-import android.graphics.Bitmap;
-import android.graphics.BitmapFactory;
-
-import java.io.IOException;
-
-import junit.framework.Assert;
-
-/**
- * The useful methods for widget test.
- */
-public class WidgetTestUtils {
-    /**
-     * Assert that two bitmaps are equal.
-     *
-     * @param Bitmap b1 the first bitmap which needs to compare.
-     * @param Bitmap b2 the second bitmap which needs to compare.
-     */
-    public static void assertEquals(Bitmap b1, Bitmap b2) {
-        if (b1 == b2) {
-            return;
-        }
-
-        if (b1 == null || b2 == null) {
-            Assert.fail("the bitmaps are not equal");
-        }
-
-        // b1 and b2 are all not null.
-        if (b1.getWidth() != b2.getWidth() || b1.getHeight() != b2.getHeight()
-            || b1.getConfig() != b2.getConfig()) {
-            Assert.fail("the bitmaps are not equal");
-        }
-
-        int w = b1.getWidth();
-        int h = b1.getHeight();
-        int s = w * h;
-        int[] pixels1 = new int[s];
-        int[] pixels2 = new int[s];
-
-        b1.getPixels(pixels1, 0, w, 0, 0, w, h);
-        b2.getPixels(pixels2, 0, w, 0, 0, w, h);
-
-        for (int i = 0; i < s; i++) {
-            if (pixels1[i] != pixels2[i]) {
-                Assert.fail("the bitmaps are not equal");
-            }
-        }
-    }
-
-    /**
-     * Find beginning of the special element.
-     * @param parser XmlPullParser will be parsed.
-     * @param firstElementName the target element name.
-     *
-     * @throws XmlPullParserException if XML Pull Parser related faults occur.
-     * @throws IOException if I/O-related error occur when parsing.
-     */
-    public static final void beginDocument(XmlPullParser parser, String firstElementName)
-            throws XmlPullParserException, IOException {
-        Assert.assertNotNull(parser);
-        Assert.assertNotNull(firstElementName);
-
-        int type;
-        while ((type = parser.next()) != XmlPullParser.START_TAG
-                && type != XmlPullParser.END_DOCUMENT) {
-            ;
-        }
-
-        if (!parser.getName().equals(firstElementName)) {
-            throw new XmlPullParserException("Unexpected start tag: found " + parser.getName()
-                    + ", expected " + firstElementName);
-        }
-    }
-
-    /**
-     * Compare the expected pixels with actual, scaling for the target context density
-     *
-     * @throws AssertionFailedError
-     */
-    public static void assertScaledPixels(int expected, int actual, Context context) {
-        Assert.assertEquals(expected * context.getResources().getDisplayMetrics().density,
-                actual, 3);
-    }
-
-    /** Converts dips into pixels using the {@link Context}'s density. */
-    public static int convertDipToPixels(Context context, int dip) {
-      float density = context.getResources().getDisplayMetrics().density;
-      return Math.round(density * dip);
-    }
-
-    /**
-     * Retrieve a bitmap that can be used for comparison on any density
-     * @param resources
-     * @return the {@link Bitmap} or <code>null</code>
-     */
-    public static Bitmap getUnscaledBitmap(Resources resources, int resId) {
-        BitmapFactory.Options options = new BitmapFactory.Options();
-        options.inScaled = false;
-        return BitmapFactory.decodeResource(resources, resId, options);
-    }
-
-    /**
-     * Retrieve a dithered bitmap that can be used for comparison on any density
-     * @param resources
-     * @param config the preferred config for the returning bitmap
-     * @return the {@link Bitmap} or <code>null</code>
-     */
-    public static Bitmap getUnscaledAndDitheredBitmap(Resources resources,
-            int resId, Bitmap.Config config) {
-        BitmapFactory.Options options = new BitmapFactory.Options();
-        options.inDither = true;
-        options.inScaled = false;
-        options.inPreferredConfig = config;
-        return BitmapFactory.decodeResource(resources, resId, options);
-    }
-}
diff --git a/tests/tests/graphics/src/android/graphics/cts/BitmapTest.java b/tests/tests/graphics/src/android/graphics/cts/BitmapTest.java
index 4ea89c7..f58b871 100644
--- a/tests/tests/graphics/src/android/graphics/cts/BitmapTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/BitmapTest.java
@@ -19,6 +19,7 @@
 
 
 import android.content.res.Resources;
+import android.cts.util.WidgetTestUtils;
 import android.graphics.Bitmap;
 import android.graphics.BitmapFactory;
 import android.graphics.Canvas;
diff --git a/tests/tests/graphics/src/android/graphics/cts/MovieTest.java b/tests/tests/graphics/src/android/graphics/cts/MovieTest.java
index 2facdc9..b18b800 100644
--- a/tests/tests/graphics/src/android/graphics/cts/MovieTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/MovieTest.java
@@ -24,12 +24,12 @@
 import java.io.OutputStream;
 
 import android.content.Context;
+import android.cts.util.WidgetTestUtils;
 import android.graphics.Canvas;
 import android.graphics.Movie;
 import android.graphics.Paint;
 import android.test.ActivityInstrumentationTestCase2;
 
-
 public class MovieTest extends ActivityInstrumentationTestCase2<MockActivity> {
     private Movie mMovie;
     private final int MOVIE = com.android.cts.graphics.R.drawable.animated;
diff --git a/tests/tests/graphics/src/android/graphics/cts/WidgetTestUtils.java b/tests/tests/graphics/src/android/graphics/cts/WidgetTestUtils.java
deleted file mode 100644
index 63bafac..0000000
--- a/tests/tests/graphics/src/android/graphics/cts/WidgetTestUtils.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * Copyright (C) 2008 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 org.xmlpull.v1.XmlPullParser;
-import org.xmlpull.v1.XmlPullParserException;
-
-import android.content.Context;
-import android.content.res.Resources;
-import android.graphics.Bitmap;
-import android.graphics.BitmapFactory;
-
-import java.io.IOException;
-
-import junit.framework.Assert;
-
-/**
- * The useful methods for widget test.
- */
-public class WidgetTestUtils {
-    /**
-     * Assert that two bitmaps are equal.
-     *
-     * @param Bitmap b1 the first bitmap which needs to compare.
-     * @param Bitmap b2 the second bitmap which needs to compare.
-     */
-    public static void assertEquals(Bitmap b1, Bitmap b2) {
-        if (b1 == b2) {
-            return;
-        }
-
-        if (b1 == null || b2 == null) {
-            Assert.fail("the bitmaps are not equal");
-        }
-
-        // b1 and b2 are all not null.
-        if (b1.getWidth() != b2.getWidth() || b1.getHeight() != b2.getHeight()
-            || b1.getConfig() != b2.getConfig()) {
-            Assert.fail("the bitmaps are not equal");
-        }
-
-        int w = b1.getWidth();
-        int h = b1.getHeight();
-        int s = w * h;
-        int[] pixels1 = new int[s];
-        int[] pixels2 = new int[s];
-
-        b1.getPixels(pixels1, 0, w, 0, 0, w, h);
-        b2.getPixels(pixels2, 0, w, 0, 0, w, h);
-
-        for (int i = 0; i < s; i++) {
-            if (pixels1[i] != pixels2[i]) {
-                Assert.fail("the bitmaps are not equal");
-            }
-        }
-    }
-
-    /**
-     * Find beginning of the special element.
-     * @param parser XmlPullParser will be parsed.
-     * @param firstElementName the target element name.
-     *
-     * @throws XmlPullParserException if XML Pull Parser related faults occur.
-     * @throws IOException if I/O-related error occur when parsing.
-     */
-    public static final void beginDocument(XmlPullParser parser, String firstElementName)
-            throws XmlPullParserException, IOException {
-        Assert.assertNotNull(parser);
-        Assert.assertNotNull(firstElementName);
-
-        int type;
-        while ((type = parser.next()) != XmlPullParser.START_TAG
-                && type != XmlPullParser.END_DOCUMENT) {
-            ;
-        }
-
-        if (!parser.getName().equals(firstElementName)) {
-            throw new XmlPullParserException("Unexpected start tag: found " + parser.getName()
-                    + ", expected " + firstElementName);
-        }
-    }
-
-    /**
-     * Compare the expected pixels with actual, scaling for the target context density
-     *
-     * @throws AssertionFailedError
-     */
-    public static void assertScaledPixels(int expected, int actual, Context context) {
-        Assert.assertEquals(expected * context.getResources().getDisplayMetrics().density,
-                actual, 3);
-    }
-
-    /** Converts dips into pixels using the {@link Context}'s density. */
-    public static int convertDipToPixels(Context context, int dip) {
-      float density = context.getResources().getDisplayMetrics().density;
-      return Math.round(density * dip);
-    }
-
-    /**
-     * Retrieve a bitmap that can be used for comparison on any density
-     * @param resources
-     * @return the {@link Bitmap} or <code>null</code>
-     */
-    public static Bitmap getUnscaledBitmap(Resources resources, int resId) {
-        BitmapFactory.Options options = new BitmapFactory.Options();
-        options.inScaled = false;
-        return BitmapFactory.decodeResource(resources, resId, options);
-    }
-
-    /**
-     * Retrieve a dithered bitmap that can be used for comparison on any density
-     * @param resources
-     * @param config the preferred config for the returning bitmap
-     * @return the {@link Bitmap} or <code>null</code>
-     */
-    public static Bitmap getUnscaledAndDitheredBitmap(Resources resources,
-            int resId, Bitmap.Config config) {
-        BitmapFactory.Options options = new BitmapFactory.Options();
-        options.inDither = true;
-        options.inScaled = false;
-        options.inPreferredConfig = config;
-        return BitmapFactory.decodeResource(resources, resId, options);
-    }
-}
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 9766a45..f18a1cf 100644
--- a/tests/tests/hardware/src/android/hardware/camera2/cts/StillCaptureTest.java
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/StillCaptureTest.java
@@ -140,11 +140,6 @@
                 Log.i(TAG, "Testing JPEG exif for Camera " + mCameraIds[i]);
                 openDevice(mCameraIds[i]);
 
-                if (mStaticInfo.isHardwareLevelLegacy()) {
-                    Log.i(TAG, "Skipping test on legacy devices");
-                    continue;
-                }
-
                 jpegExifTestByCamera();
             } finally {
                 closeDevice();
diff --git a/tests/tests/hardware/src/android/hardware/camera2/cts/helpers/StaticMetadata.java b/tests/tests/hardware/src/android/hardware/camera2/cts/helpers/StaticMetadata.java
index 11d7ac0..fb2001f 100644
--- a/tests/tests/hardware/src/android/hardware/camera2/cts/helpers/StaticMetadata.java
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/helpers/StaticMetadata.java
@@ -1282,7 +1282,7 @@
         if (isHardwareLevelLimitedOrBetter()) {
             float compensationStepF =
                     (float) compensationStep.getNumerator() / compensationStep.getDenominator();
-            checkTrueForKey(key, " value must be no more than 1/2", compensationStepF < 0.5f);
+            checkTrueForKey(key, " value must be no more than 1/2", compensationStepF <= 0.5f);
         }
 
         return compensationStep;
diff --git a/tests/tests/hardware/src/android/hardware/cts/SensorBatchingTests.java b/tests/tests/hardware/src/android/hardware/cts/SensorBatchingTests.java
index d00194f..687826c 100644
--- a/tests/tests/hardware/src/android/hardware/cts/SensorBatchingTests.java
+++ b/tests/tests/hardware/src/android/hardware/cts/SensorBatchingTests.java
@@ -18,9 +18,7 @@
 
 import android.hardware.Sensor;
 import android.hardware.SensorManager;
-import android.hardware.cts.helpers.SensorCtsHelper;
 import android.hardware.cts.helpers.SensorStats;
-import android.hardware.cts.helpers.SensorTestInformation;
 import android.hardware.cts.helpers.TestSensorEnvironment;
 import android.hardware.cts.helpers.sensoroperations.TestSensorFlushOperation;
 import android.hardware.cts.helpers.sensoroperations.TestSensorOperation;
@@ -267,12 +265,7 @@
         TestSensorOperation operation =
                 new TestSensorOperation(environment, testDurationSec, TimeUnit.SECONDS);
 
-        executeTest(
-                operation,
-                sensorType,
-                rateUs,
-                maxBatchReportLatencyUs,
-                false /* flushExpected */);
+        executeTest(environment, operation, false /* flushExpected */);
     }
 
     private void runFlushSensorTest(int sensorType, int rateUs, int maxBatchReportLatencySec)
@@ -289,19 +282,12 @@
         TestSensorFlushOperation operation =
                 new TestSensorFlushOperation(environment, flushDurationSec, TimeUnit.SECONDS);
 
-        executeTest(
-                operation,
-                sensorType,
-                rateUs,
-                maxBatchReportLatencyUs,
-                true /* flushExpected */);
+        executeTest(environment, operation, true /* flushExpected */);
     }
 
     private void executeTest(
+            TestSensorEnvironment environment,
             VerifiableSensorOperation operation,
-            int sensorType,
-            int rateUs,
-            int maxBatchReportLatencyUs,
             boolean flushExpected) throws Throwable {
         operation.addDefaultVerifications();
         operation.setLogEvents(true);
@@ -311,18 +297,20 @@
         } finally {
             SensorStats.logStats(TAG, operation.getStats());
 
-            String sensorName = SensorTestInformation.getSanitizedSensorName(sensorType);
             String sensorRate;
-            if (rateUs == SensorManager.SENSOR_DELAY_FASTEST) {
+            if (environment.getRequestedSamplingPeriodUs() == SensorManager.SENSOR_DELAY_FASTEST) {
                 sensorRate = "fastest";
             } else {
-                sensorRate = String.format("%.0fhz",
-                        SensorCtsHelper.getFrequency(rateUs, TimeUnit.MICROSECONDS));
+                sensorRate = String.format("%.0fhz", environment.getFrequencyHz());
             }
-            String batching = maxBatchReportLatencyUs > 0 ? "_batching" : "";
+            String batching = environment.getMaxReportLatencyUs() > 0 ? "_batching" : "";
             String flush = flushExpected ? "_flush" : "";
-            String fileName = String.format("sensor_batching_%s_%s%s%s.txt",
-                    sensorName, sensorRate, batching, flush);
+            String fileName = String.format(
+                    "batching_%s_%s%s%s.txt",
+                    SensorStats.getSanitizedSensorName(environment.getSensor()),
+                    sensorRate,
+                    batching,
+                    flush);
             SensorStats.logStatsToFile(fileName, operation.getStats());
         }
     }
diff --git a/tests/tests/hardware/src/android/hardware/cts/SensorIntegrationTests.java b/tests/tests/hardware/src/android/hardware/cts/SensorIntegrationTests.java
index 3c9eef9..50cb12d 100644
--- a/tests/tests/hardware/src/android/hardware/cts/SensorIntegrationTests.java
+++ b/tests/tests/hardware/src/android/hardware/cts/SensorIntegrationTests.java
@@ -15,13 +15,9 @@
  */
 package android.hardware.cts;
 
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
 import android.content.Context;
 import android.hardware.Sensor;
 import android.hardware.SensorManager;
-import android.hardware.cts.helpers.SensorCtsHelper;
 import android.hardware.cts.helpers.SensorStats;
 import android.hardware.cts.helpers.TestSensorEnvironment;
 import android.hardware.cts.helpers.sensoroperations.ParallelSensorOperation;
@@ -32,6 +28,7 @@
 import android.hardware.cts.helpers.sensorverification.EventOrderingVerification;
 
 import java.util.Random;
+import java.util.concurrent.TimeUnit;
 
 /**
  * Set of tests that verifies proper interaction of the sensors in the platform.
@@ -44,25 +41,6 @@
     private static final String TAG = "SensorIntegrationTests";
 
     /**
-     * Builder for the test suite.
-     * This is the method that will build dynamically the set of test cases to execute.
-     * Each 'base' test case is composed by three parts:
-     * - the matrix definition
-     * - the test method that will execute the test case
-     * - a static method that will combine both and add test case instances to the test suite
-     */
-    public static Test suite() {
-        TestSuite testSuite = new TestSuite();
-
-        // add test generation routines
-        addTestToSuite(testSuite, "testSensorsWithSeveralClients");
-        addTestToSuite(testSuite, "testSensorsMovingRates");
-        createStoppingTestCases(testSuite);
-
-        return testSuite;
-    }
-
-    /**
      * This test focuses in the interaction of continuous and batching clients for the same Sensor
      * under test. The verification ensures that sensor clients can interact with the System and
      * not affect other clients in the way.
@@ -87,7 +65,7 @@
      */
     public void testSensorsWithSeveralClients() throws Throwable {
         final int ITERATIONS = 50;
-        final int MAX_REPORTING_LATENCY_IN_SECONDS = 5;
+        final int MAX_REPORTING_LATENCY_US = (int) TimeUnit.SECONDS.toMicros(5);
         final Context context = getContext();
 
         int sensorTypes[] = {
@@ -113,7 +91,7 @@
                     sensorType,
                     shouldEmulateSensorUnderLoad(),
                     sensor.getMinDelay(),
-                    SensorCtsHelper.getSecondsAsMicroSeconds(MAX_REPORTING_LATENCY_IN_SECONDS));
+                    MAX_REPORTING_LATENCY_US);
             TestSensorOperation batchingOperation =
                     new TestSensorOperation(batchingEnvironment, 100 /* eventCount */);
             batchingOperation.addVerification(new EventOrderingVerification());
@@ -183,24 +161,41 @@
      * Regress:
      * - b/10641388
      */
-    private int mSensorTypeTester;
-    private int mSensorTypeTestee;
 
-    private static void createStoppingTestCases(TestSuite testSuite) {
-        int sensorTypes[] = {
-                Sensor.TYPE_ACCELEROMETER,
-                Sensor.TYPE_GYROSCOPE,
-                Sensor.TYPE_MAGNETIC_FIELD};
+    public void testAccelerometerAccelerometerStopping()  throws Throwable {
+        verifySensorStoppingInteraction(Sensor.TYPE_ACCELEROMETER, Sensor.TYPE_ACCELEROMETER);
+    }
 
-        for(int sensorTypeTester : sensorTypes) {
-            for(int sensorTypeTestee : sensorTypes) {
-                SensorIntegrationTests test = new SensorIntegrationTests();
-                test.mSensorTypeTester = sensorTypeTester;
-                test.mSensorTypeTestee = sensorTypeTestee;
-                test.setName("testSensorStoppingInteraction");
-                testSuite.addTest(test);
-            }
-        }
+    public void testAccelerometerGyroscopeStopping()  throws Throwable {
+        verifySensorStoppingInteraction(Sensor.TYPE_ACCELEROMETER, Sensor.TYPE_GYROSCOPE);
+    }
+
+    public void testAccelerometerMagneticFieldStopping()  throws Throwable {
+        verifySensorStoppingInteraction(Sensor.TYPE_ACCELEROMETER, Sensor.TYPE_MAGNETIC_FIELD);
+    }
+
+    public void testGyroscopeAccelerometerStopping()  throws Throwable {
+        verifySensorStoppingInteraction(Sensor.TYPE_GYROSCOPE, Sensor.TYPE_ACCELEROMETER);
+    }
+
+    public void testGyroscopeGyroscopeStopping()  throws Throwable {
+        verifySensorStoppingInteraction(Sensor.TYPE_GYROSCOPE, Sensor.TYPE_GYROSCOPE);
+    }
+
+    public void testGyroscopeMagneticFieldStopping()  throws Throwable {
+        verifySensorStoppingInteraction(Sensor.TYPE_GYROSCOPE, Sensor.TYPE_MAGNETIC_FIELD);
+    }
+
+    public void testMagneticFieldAccelerometerStopping()  throws Throwable {
+        verifySensorStoppingInteraction(Sensor.TYPE_MAGNETIC_FIELD, Sensor.TYPE_ACCELEROMETER);
+    }
+
+    public void testMagneticFieldGyroscopeStopping()  throws Throwable {
+        verifySensorStoppingInteraction(Sensor.TYPE_MAGNETIC_FIELD, Sensor.TYPE_GYROSCOPE);
+    }
+
+    public void testMagneticFieldMagneticFieldStopping()  throws Throwable {
+        verifySensorStoppingInteraction(Sensor.TYPE_MAGNETIC_FIELD, Sensor.TYPE_MAGNETIC_FIELD);
     }
 
     /**
@@ -223,12 +218,14 @@
      * It is important to look at the internals of the Sensor HAL to identify how the interaction
      * of several clients can lead to the failing state.
      */
-    public void testSensorStoppingInteraction() throws Throwable {
+    public void verifySensorStoppingInteraction(
+            int sensorTypeTestee,
+            int sensorTypeTester) throws Throwable {
         Context context = getContext();
 
         TestSensorEnvironment testerEnvironment = new TestSensorEnvironment(
                 context,
-                mSensorTypeTester,
+                sensorTypeTester,
                 shouldEmulateSensorUnderLoad(),
                 SensorManager.SENSOR_DELAY_FASTEST);
         TestSensorOperation tester =
@@ -237,7 +234,7 @@
 
         TestSensorEnvironment testeeEnvironment = new TestSensorEnvironment(
                 context,
-                mSensorTypeTestee,
+                sensorTypeTestee,
                 shouldEmulateSensorUnderLoad(),
                 SensorManager.SENSOR_DELAY_FASTEST);
         VerifiableSensorOperation testee =
@@ -274,14 +271,7 @@
     }
 
     private int generateReportLatencyInUs() {
-        int reportLatency = SensorCtsHelper.getSecondsAsMicroSeconds(
-                mGenerator.nextInt(5) + 1);
-        return reportLatency;
-    }
-
-    private static void addTestToSuite(TestSuite testSuite, String testName) {
-        SensorIntegrationTests test = new SensorIntegrationTests();
-        test.setName(testName);
-        testSuite.addTest(test);
+        long reportLatencyUs = TimeUnit.SECONDS.toMicros(mGenerator.nextInt(5) + 1);
+        return (int) reportLatencyUs;
     }
 }
diff --git a/tests/tests/hardware/src/android/hardware/cts/SingleSensorTests.java b/tests/tests/hardware/src/android/hardware/cts/SingleSensorTests.java
index a323ffa..3bd4a03 100644
--- a/tests/tests/hardware/src/android/hardware/cts/SingleSensorTests.java
+++ b/tests/tests/hardware/src/android/hardware/cts/SingleSensorTests.java
@@ -19,9 +19,7 @@
 import android.content.Context;
 import android.hardware.Sensor;
 import android.hardware.SensorManager;
-import android.hardware.cts.helpers.SensorCtsHelper;
 import android.hardware.cts.helpers.SensorStats;
-import android.hardware.cts.helpers.SensorTestInformation;
 import android.hardware.cts.helpers.TestSensorEnvironment;
 import android.hardware.cts.helpers.sensoroperations.TestSensorOperation;
 
@@ -118,12 +116,13 @@
         for (Entry<Integer, Object[]> entry : expectedProperties.entrySet()) {
             Sensor sensor = sensorManager.getDefaultSensor(entry.getKey());
             if (sensor != null) {
-                String sensorName = SensorTestInformation.getSensorName(entry.getKey());
                 if (entry.getValue()[0] != null) {
                     int expected = (Integer) entry.getValue()[0];
                     String msg = String.format(
                             "%s: min delay %dus expected to be less than or equal to %dus",
-                            sensorName, sensor.getMinDelay(), expected);
+                            sensor.getName(),
+                            sensor.getMinDelay(),
+                            expected);
                     assertTrue(msg, sensor.getMinDelay() <= expected);
                 }
             }
@@ -550,15 +549,16 @@
         } finally {
             SensorStats.logStats(TAG, op.getStats());
 
-            String sensorName = SensorTestInformation.getSanitizedSensorName(sensorType);
             String sensorRate;
             if (rateUs == SensorManager.SENSOR_DELAY_FASTEST) {
                 sensorRate = "fastest";
             } else {
-                sensorRate = String.format("%.0fhz",
-                        SensorCtsHelper.getFrequency(rateUs, TimeUnit.MICROSECONDS));
+                sensorRate = String.format("%.0fhz", environment.getFrequencyHz());
             }
-            String fileName = String.format("single_sensor_%s_%s.txt", sensorName, sensorRate);
+            String fileName = String.format(
+                    "single_%s_%s.txt",
+                    SensorStats.getSanitizedSensorName(environment.getSensor()),
+                    sensorRate);
             SensorStats.logStatsToFile(fileName, op.getStats());
         }
     }
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/CollectingSensorEventListener.java b/tests/tests/hardware/src/android/hardware/cts/helpers/CollectingSensorEventListener.java
index 981d74c..c11b29f 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/CollectingSensorEventListener.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/CollectingSensorEventListener.java
@@ -18,9 +18,10 @@
 
 import android.hardware.SensorEvent;
 import android.hardware.SensorEventListener2;
-import android.os.SystemClock;
 
-import java.util.concurrent.ConcurrentLinkedDeque;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
 import java.util.concurrent.TimeUnit;
 
 /**
@@ -28,8 +29,7 @@
  * This should only be used for short tests.
  */
 public class CollectingSensorEventListener extends TestSensorEventListener {
-    private final ConcurrentLinkedDeque<TestSensorEvent> mSensorEventsList =
-            new ConcurrentLinkedDeque<TestSensorEvent>();
+    private final ArrayList<TestSensorEvent> mSensorEventsList = new ArrayList<TestSensorEvent>();
 
     /**
      * Constructs a {@link CollectingSensorEventListener} with an additional
@@ -52,7 +52,9 @@
     @Override
     public void onSensorChanged(SensorEvent event) {
         super.onSensorChanged(event);
-        mSensorEventsList.addLast(new TestSensorEvent(event, SystemClock.elapsedRealtimeNanos()));
+        synchronized (mSensorEventsList) {
+            mSensorEventsList.add(new TestSensorEvent(event));
+        }
     }
 
     /**
@@ -82,14 +84,18 @@
     /**
      * Get the {@link TestSensorEvent} array from the event queue.
      */
-    public TestSensorEvent[] getEvents() {
-        return mSensorEventsList.toArray(new TestSensorEvent[0]);
+    public List<TestSensorEvent> getEvents() {
+        synchronized (mSensorEventsList) {
+            return Collections.unmodifiableList(mSensorEventsList);
+        }
     }
 
     /**
      * Clear the event queue.
      */
     public void clearEvents() {
-        mSensorEventsList.clear();
+        synchronized (mSensorEventsList) {
+            mSensorEventsList.clear();
+        }
     }
-}
\ No newline at end of file
+}
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/SensorCalibratedUncalibratedVerifier.java b/tests/tests/hardware/src/android/hardware/cts/helpers/SensorCalibratedUncalibratedVerifier.java
new file mode 100644
index 0000000..b3b8559
--- /dev/null
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/SensorCalibratedUncalibratedVerifier.java
@@ -0,0 +1,128 @@
+/*
+ * 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.hardware.cts.helpers;
+
+import junit.framework.Assert;
+
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * A bundled sensor test operation/verification.
+ *
+ * It verifies the relationship between measurements from calibrated sensors and their corresponding
+ * uncalibrated sensors comply to the following equation:
+ *  calibrated = uncalibrated - bias
+ */
+// TODO: refactor into proper test operation/verification classes:
+// currently this is the only verification that requires input from multiple sensors, and the class
+// is factored into: operation, verification, and listener as other sensor test operations
+public class SensorCalibratedUncalibratedVerifier {
+
+    private final TestSensorManager mCalibratedSensorManager;
+    private final TestSensorManager mUncalibratedSensorManager;
+    private final float mThreshold;
+
+    public SensorCalibratedUncalibratedVerifier(
+            TestSensorEnvironment calibratedEnvironment,
+            TestSensorEnvironment uncalibratedEnvironment,
+            float threshold) {
+        mCalibratedSensorManager = new TestSensorManager(calibratedEnvironment);
+        mUncalibratedSensorManager = new TestSensorManager(uncalibratedEnvironment);
+        mThreshold = threshold;
+    }
+
+    /**
+     * Executes the operation: it collects the data and run verifications on it.
+     */
+    public void execute() throws Throwable {
+        CollectingSensorEventListener calibratedTestListener = new CollectingSensorEventListener();
+        CollectingSensorEventListener uncalibratedTestListener = new CollectingSensorEventListener();
+        mCalibratedSensorManager.registerListener(calibratedTestListener);
+        mUncalibratedSensorManager.registerListener(uncalibratedTestListener);
+
+        Thread.sleep(TimeUnit.SECONDS.toMillis(10));
+
+        mCalibratedSensorManager.unregisterListener();
+        mUncalibratedSensorManager.unregisterListener();
+
+        verifyMeasurements(
+                calibratedTestListener.getEvents(),
+                uncalibratedTestListener.getEvents(),
+                mThreshold);
+    }
+
+    private void verifyMeasurements(
+            List<TestSensorEvent> calibratedEvents,
+            List<TestSensorEvent> uncalibratedEvents,
+            float threshold) {
+        long measuredSamplingPeriodNs = SensorCtsHelper.getSamplingPeriodNs(calibratedEvents);
+        long synchronizationPeriodNs = measuredSamplingPeriodNs / 2;
+        int eventsValidated = 0;
+
+        // TODO: this makes the algorithm O(n^2) when we could have it O(n), but it has little
+        // impact on the overall test duration because the data collection is what takes the most
+        // time
+        for (TestSensorEvent calibratedEvent : calibratedEvents) {
+            long calibratedTimestampNs = calibratedEvent.timestamp;
+            long lowerTimestampThresholdNs = calibratedTimestampNs - synchronizationPeriodNs;
+            long upperTimestampThresholdNs = calibratedTimestampNs + synchronizationPeriodNs;
+
+            for (TestSensorEvent uncalibratedEvent : uncalibratedEvents) {
+                long uncalibratedTimestampNs = uncalibratedEvent.timestamp;
+                if (uncalibratedTimestampNs > lowerTimestampThresholdNs
+                        && uncalibratedTimestampNs < upperTimestampThresholdNs) {
+                    // perform validation
+                    verifyCalibratedUncalibratedPair(
+                            calibratedEvent,
+                            uncalibratedEvent,
+                            threshold);
+                    ++eventsValidated;
+                }
+            }
+        }
+
+        String eventsValidatedMessage = String.format(
+                "Expected to find at least one Calibrated/Uncalibrated event pair for validation."
+                        + " Found=%d",
+                eventsValidated);
+        Assert.assertTrue(eventsValidatedMessage, eventsValidated > 0);
+    }
+
+    private void verifyCalibratedUncalibratedPair(
+            TestSensorEvent calibratedEvent,
+            TestSensorEvent uncalibratedEvent,
+            float threshold) {
+        for (int i = 0; i < 3; ++i) {
+            float calibrated = calibratedEvent.values[i];
+            float uncalibrated = uncalibratedEvent.values[i];
+            float bias = uncalibratedEvent.values[i + 3];
+            String message = String.format(
+                    "Calibrated (%s) and Uncalibrated (%s) sensor readings are expected to satisfy:"
+                            + " calibrated = uncalibrated - bias. Axis=%d, Calibrated=%s, "
+                            + "Uncalibrated=%s, Bias=%s, Threshold=%s",
+                    calibratedEvent.sensor.getName(),
+                    uncalibratedEvent.sensor.getName(),
+                    i,
+                    calibrated,
+                    uncalibrated,
+                    bias,
+                    threshold);
+            Assert.assertEquals(message, calibrated, uncalibrated - bias, threshold);
+        }
+    }
+}
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/SensorCtsHelper.java b/tests/tests/hardware/src/android/hardware/cts/helpers/SensorCtsHelper.java
index 52f37e8..1f1b290 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/SensorCtsHelper.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/SensorCtsHelper.java
@@ -15,6 +15,8 @@
  */
 package android.hardware.cts.helpers;
 
+import java.io.File;
+import java.io.IOException;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
@@ -24,7 +26,7 @@
 /**
  * Set of static helper methods for CTS tests.
  */
-//TODO: Refactor this class and SensorTestInformation into several more well defined helper classes
+//TODO: Refactor this class into several more well defined helper classes
 public class SensorCtsHelper {
 
     private static final long NANOS_PER_MILLI = 1000000;
@@ -90,6 +92,19 @@
     }
 
     /**
+     * @return The (measured) sampling rate of a collection of {@link TestSensorEvent}.
+     */
+    public static long getSamplingPeriodNs(List<TestSensorEvent> collection) {
+        int collectionSize = collection.size();
+        if (collectionSize < 2) {
+            return 0;
+        }
+        TestSensorEvent firstEvent = collection.get(0);
+        TestSensorEvent lastEvent = collection.get(collectionSize - 1);
+        return (lastEvent.timestamp - firstEvent.timestamp) / (collectionSize - 1);
+    }
+
+    /**
      * Calculate the bias-corrected standard deviation of a collection.
      *
      * @throws IllegalArgumentException if the collection is null or empty
@@ -114,10 +129,15 @@
     }
 
     /**
-     * Convert number of seconds to number of microseconds.
+     * @return The magnitude (norm) represented by the given array of values.
      */
-    public static int getSecondsAsMicroSeconds(int seconds) {
-        return (int) TimeUnit.MICROSECONDS.convert(seconds, TimeUnit.SECONDS);
+    public static double getMagnitude(float[] values) {
+        float sumOfSquares = 0.0f;
+        for (float value : values) {
+            sumOfSquares += value * value;
+        }
+        double magnitude = Math.sqrt(sumOfSquares);
+        return magnitude;
     }
 
     /**
@@ -141,7 +161,7 @@
      * @return The formatted string
      */
     public static String formatAssertionMessage(String label, TestSensorEnvironment environment) {
-        return formatAssertionMessage(label, environment, "");
+        return formatAssertionMessage(label, environment, "Failed");
     }
 
     /**
@@ -176,15 +196,45 @@
             TestSensorEnvironment environment,
             String extras) {
         return String.format(
-                "%s | sensor=%s, rateUs=%d, maxBatchReportLatenchUs=%d | %s",
+                "%s | sensor='%s', samplingPeriodUs=%d, maxReportLatencyUs=%d | %s",
                 label,
-                SensorTestInformation.getSensorName(environment.getSensor().getType()),
+                environment.getSensor().getName(),
                 environment.getRequestedSamplingPeriodUs(),
                 environment.getMaxReportLatencyUs(),
                 extras);
     }
 
     /**
+     * @return A {@link File} representing a root directory to store sensor tests data.
+     */
+    public static File getSensorTestDataDirectory() throws IOException {
+        File dataDirectory = new File(System.getenv("EXTERNAL_STORAGE"), "sensorTests/");
+        return createDirectoryStructure(dataDirectory);
+    }
+
+    /**
+     * Creates the directory structure for the given sensor test data sub-directory.
+     *
+     * @param subdirectory The sub-directory's name.
+     */
+    public static File getSensorTestDataDirectory(String subdirectory) throws IOException {
+        File subdirectoryFile = new File(getSensorTestDataDirectory(), subdirectory);
+        return createDirectoryStructure(subdirectoryFile);
+    }
+
+    /**
+     * Ensures that the directory structure represented by the given {@link File} is created.
+     */
+    private static File createDirectoryStructure(File directoryStructure) throws IOException {
+        directoryStructure.mkdirs();
+        if (!directoryStructure.isDirectory()) {
+            throw new IOException("Unable to create directory structure for "
+                    + directoryStructure.getAbsolutePath());
+        }
+        return directoryStructure;
+    }
+
+    /**
      * Validate that a collection is not null or empty.
      *
      * @throws IllegalStateException if collection is null or empty.
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 53e4cae..e727092 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/SensorNotSupportedException.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/SensorNotSupportedException.java
@@ -16,13 +16,65 @@
 
 package android.hardware.cts.helpers;
 
+import android.hardware.Sensor;
+
 /**
  * Exception that indicates that a given sensor is not supported in the device.
  */
 public class SensorNotSupportedException extends SensorTestStateNotSupportedException {
     public SensorNotSupportedException(int sensorType) {
-        super("Sensor '%s' of type %d is not supported.",
-                SensorTestInformation.getSensorName(sensorType),
-                sensorType);
+        super("Sensor '%s' of type %d is not supported.", getSensorName(sensorType), sensorType);
+    }
+
+    private static String getSensorName(int sensorType) {
+        return String.format("%s (%d)", getSimpleSensorName(sensorType), sensorType);
+    }
+
+    @SuppressWarnings("deprecation")
+    private static String getSimpleSensorName(int sensorType) {
+        switch(sensorType) {
+            case Sensor.TYPE_ACCELEROMETER:
+                return "Accelerometer";
+            case Sensor.TYPE_MAGNETIC_FIELD:
+                return "Magnetic Field";
+            case Sensor.TYPE_ORIENTATION:
+                return "Orientation";
+            case Sensor.TYPE_GYROSCOPE:
+                return "Gyroscope";
+            case Sensor.TYPE_LIGHT:
+                return "Light";
+            case Sensor.TYPE_PRESSURE:
+                return "Pressure";
+            case Sensor.TYPE_TEMPERATURE:
+                return "Temperature";
+            case Sensor.TYPE_PROXIMITY:
+                return "Proximity";
+            case Sensor.TYPE_GRAVITY:
+                return "Gravity";
+            case Sensor.TYPE_LINEAR_ACCELERATION:
+                return "Linear Acceleration";
+            case Sensor.TYPE_ROTATION_VECTOR:
+                return "Rotation Vector";
+            case Sensor.TYPE_RELATIVE_HUMIDITY:
+                return "Relative Humidity";
+            case Sensor.TYPE_AMBIENT_TEMPERATURE:
+                return "Ambient Temperature";
+            case Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED:
+                return "Magnetic Field Uncalibrated";
+            case Sensor.TYPE_GAME_ROTATION_VECTOR:
+                return "Game Rotation Vector";
+            case Sensor.TYPE_GYROSCOPE_UNCALIBRATED:
+                return "Gyroscope Uncalibrated";
+            case Sensor.TYPE_SIGNIFICANT_MOTION:
+                return "Significant Motion";
+            case Sensor.TYPE_STEP_DETECTOR:
+                return "Step Detector";
+            case Sensor.TYPE_STEP_COUNTER:
+                return "Step Counter";
+            case Sensor.TYPE_GEOMAGNETIC_ROTATION_VECTOR:
+                return "Geomagnetic Rotation Vector";
+            default:
+                return "<Unknown>";
+        }
     }
 }
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 1a500d4..7be6c0c 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/SensorStats.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/SensorStats.java
@@ -16,8 +16,8 @@
 
 package android.hardware.cts.helpers;
 
+import android.hardware.Sensor;
 import android.hardware.cts.helpers.sensoroperations.ISensorOperation;
-import android.os.Environment;
 import android.util.Log;
 
 import java.io.BufferedWriter;
@@ -49,7 +49,7 @@
     public static final String EVENT_OUT_OF_ORDER_COUNT_KEY = "event_out_of_order_count";
     public static final String EVENT_OUT_OF_ORDER_POSITIONS_KEY = "event_out_of_order_positions";
     public static final String FREQUENCY_KEY = "frequency";
-    public static final String JITTER_95_PERCENTILE_KEY = "jitter_95_percentile";
+    public static final String JITTER_95_PERCENTILE_PERCENT_KEY = "jitter_95_percentile_percent";
     public static final String MEAN_KEY = "mean";
     public static final String STANDARD_DEVIATION_KEY = "standard_deviation";
     public static final String MAGNITUDE_KEY = "magnitude";
@@ -134,8 +134,10 @@
      * Utility method to log the stats to a file. Will overwrite the file if it already exists.
      */
     public static void logStatsToFile(String fileName, SensorStats stats) throws IOException {
-        final BufferedWriter writer = new BufferedWriter(new FileWriter(
-                new File(Environment.getExternalStorageDirectory(), fileName), false));
+        File statsDirectory = SensorCtsHelper.getSensorTestDataDirectory("stats/");
+        File logFile = new File(statsDirectory, fileName);
+        final BufferedWriter writer =
+                new BufferedWriter(new FileWriter(logFile, false /* append */));
         final Map<String, Object> flattened = stats.flatten();
         try {
             for (String key : getSortedKeys(flattened)) {
@@ -148,6 +150,20 @@
         }
     }
 
+    /**
+     * Provides a sanitized sensor name, that can be used in file names.
+     * See {@link #logStatsToFile(String, SensorStats)}.
+     */
+    public static String getSanitizedSensorName(Sensor sensor) throws IOException {
+        String sensorType = sensor.getStringType();
+        String sanitizedSensorType = sensorType.replaceAll("[^a-zA-Z0-9_\\-]", "_");
+        if (sanitizedSensorType.matches("_*")) {
+            throw new IOException("Unable to sanitize sensor type (" + sensorType + "). This is a"
+                    + " 'test framework' issue and the sanitation routine must be fixed.");
+        }
+        return sanitizedSensorType;
+    }
+
     private static List<String> getSortedKeys(Map<String, Object> flattenedStats) {
         List<String> keys = new ArrayList<String>(flattenedStats.keySet());
         Collections.sort(keys);
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/SensorTestInformation.java b/tests/tests/hardware/src/android/hardware/cts/helpers/SensorTestInformation.java
deleted file mode 100644
index 86c164d..0000000
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/SensorTestInformation.java
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * Copyright (C) 2013 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.hardware.cts.helpers;
-
-import android.hardware.Sensor;
-
-/**
- * A 'property' bag of sensor information used for testing purposes.
- */
-// TODO: Refactor this class and SensorCtsHelper into several more well defined helper classes
-public class SensorTestInformation {
-    private SensorTestInformation() {}
-
-    public static String getSensorName(Sensor sensor) {
-        return getSensorName(sensor.getType());
-    }
-
-    public static String getSensorName(int sensorType) {
-        return String.format("%s (%d)", getSimpleSensorName(sensorType), sensorType);
-    }
-
-    @SuppressWarnings("deprecation")
-    public static String getSimpleSensorName(int sensorType) {
-        switch(sensorType) {
-            case Sensor.TYPE_ACCELEROMETER:
-                return "Accelerometer";
-            case Sensor.TYPE_MAGNETIC_FIELD:
-                return "Magnetic Field";
-            case Sensor.TYPE_ORIENTATION:
-                return "Orientation";
-            case Sensor.TYPE_GYROSCOPE:
-                return "Gyroscope";
-            case Sensor.TYPE_LIGHT:
-                return "Light";
-            case Sensor.TYPE_PRESSURE:
-                return "Pressure";
-            case Sensor.TYPE_TEMPERATURE:
-                return "Temperature";
-            case Sensor.TYPE_PROXIMITY:
-                return "Proximity";
-            case Sensor.TYPE_GRAVITY:
-                return "Gravity";
-            case Sensor.TYPE_LINEAR_ACCELERATION:
-                return "Linear Acceleration";
-            case Sensor.TYPE_ROTATION_VECTOR:
-                return "Rotation Vector";
-            case Sensor.TYPE_RELATIVE_HUMIDITY:
-                return "Relative Humidity";
-            case Sensor.TYPE_AMBIENT_TEMPERATURE:
-                return "Ambient Temperature";
-            case Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED:
-                return "Magnetic Field Uncalibrated";
-            case Sensor.TYPE_GAME_ROTATION_VECTOR:
-                return "Game Rotation Vector";
-            case Sensor.TYPE_GYROSCOPE_UNCALIBRATED:
-                return "Gyroscope Uncalibrated";
-            case Sensor.TYPE_SIGNIFICANT_MOTION:
-                return "Significant Motion";
-            case Sensor.TYPE_STEP_DETECTOR:
-                return "Step Detector";
-            case Sensor.TYPE_STEP_COUNTER:
-                return "Step Counter";
-            case Sensor.TYPE_GEOMAGNETIC_ROTATION_VECTOR:
-                return "Geomagnetic Rotation Vector";
-            default:
-                return "<Unknown>";
-        }
-    }
-
-    @SuppressWarnings("deprecation")
-    public static String getSanitizedSensorName(int sensorType) {
-        switch(sensorType) {
-            case Sensor.TYPE_ACCELEROMETER:
-                return "Accelerometer";
-            case Sensor.TYPE_MAGNETIC_FIELD:
-                return "MagneticField";
-            case Sensor.TYPE_ORIENTATION:
-                return "Orientation";
-            case Sensor.TYPE_GYROSCOPE:
-                return "Gyroscope";
-            case Sensor.TYPE_LIGHT:
-                return "Light";
-            case Sensor.TYPE_PRESSURE:
-                return "Pressure";
-            case Sensor.TYPE_TEMPERATURE:
-                return "Temperature";
-            case Sensor.TYPE_PROXIMITY:
-                return "Proximity";
-            case Sensor.TYPE_GRAVITY:
-                return "Gravity";
-            case Sensor.TYPE_LINEAR_ACCELERATION:
-                return "LinearAcceleration";
-            case Sensor.TYPE_ROTATION_VECTOR:
-                return "RotationVector";
-            case Sensor.TYPE_RELATIVE_HUMIDITY:
-                return "RelativeHumidity";
-            case Sensor.TYPE_AMBIENT_TEMPERATURE:
-                return "AmbientTemperature";
-            case Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED:
-                return "MagneticFieldUncalibrated";
-            case Sensor.TYPE_GAME_ROTATION_VECTOR:
-                return "GameRotationVector";
-            case Sensor.TYPE_GYROSCOPE_UNCALIBRATED:
-                return "GyroscopeUncalibrated";
-            case Sensor.TYPE_SIGNIFICANT_MOTION:
-                return "SignificantMotion";
-            case Sensor.TYPE_STEP_DETECTOR:
-                return "StepDetector";
-            case Sensor.TYPE_STEP_COUNTER:
-                return "StepCounter";
-            case Sensor.TYPE_GEOMAGNETIC_ROTATION_VECTOR:
-                return "GeomagneticRotationVector";
-            default:
-                return String.format("UnknownSensorType%d", sensorType);
-        }
-    }
-}
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/TestSensorEvent.java b/tests/tests/hardware/src/android/hardware/cts/helpers/TestSensorEvent.java
index 80a55e7..e8500f1 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/TestSensorEvent.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/TestSensorEvent.java
@@ -19,6 +19,7 @@
 import android.hardware.Sensor;
 import android.hardware.SensorEvent;
 import android.hardware.SensorEventListener2;
+import android.os.SystemClock;
 
 /**
  * Class for holding information about individual {@link SensorEvent}s.
@@ -31,6 +32,16 @@
     public final float values[];
 
     /**
+     * Constructor that sets {@link #receivedTimestamp} to
+     * {@link SystemClock#elapsedRealtimeNanos()}
+     *
+     * @param event the received sensor event
+     */
+    public TestSensorEvent(SensorEvent event) {
+        this(event, SystemClock.elapsedRealtimeNanos());
+    }
+
+    /**
      * Construct a TestSensorEvent from {@link SensorEvent} data and a received timestamp.
      *
      * @param event the {@link SensorEvent} to be cloned
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 5197184..4505633 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/TestSensorEventListener.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/TestSensorEventListener.java
@@ -169,8 +169,9 @@
             String message = SensorCtsHelper.formatAssertionMessage(
                     "WaitForEvents",
                     mEnvironment,
-                    "count:%d, available:%d",
-                    eventCount, mEventLatch.getCount());
+                    "requested:%d, received:%d",
+                    eventCount,
+                    eventCount - mEventLatch.getCount());
             Assert.assertTrue(message, mEventLatch.await(timeoutUs, TimeUnit.MICROSECONDS));
         } catch(InterruptedException e) {
             // Ignore
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/ValidatingSensorEventListener.java b/tests/tests/hardware/src/android/hardware/cts/helpers/ValidatingSensorEventListener.java
index ae7ea04..299f470 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/ValidatingSensorEventListener.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/ValidatingSensorEventListener.java
@@ -19,7 +19,6 @@
 import android.hardware.SensorEvent;
 import android.hardware.SensorEventListener2;
 import android.hardware.cts.helpers.sensorverification.ISensorVerification;
-import android.os.SystemClock;
 
 import java.util.Collection;
 import java.util.LinkedList;
@@ -74,7 +73,7 @@
      */
     @Override
     public void onSensorChanged(SensorEvent event) {
-        TestSensorEvent testEvent = new TestSensorEvent(event, SystemClock.elapsedRealtimeNanos());
+        TestSensorEvent testEvent = new TestSensorEvent(event);
         for (ISensorVerification verification : mVerifications) {
             verification.addSensorEvent(testEvent);
         }
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/sensoroperations/SensorOperationTest.java b/tests/tests/hardware/src/android/hardware/cts/helpers/sensoroperations/SensorOperationTest.java
index 38ad498..15b6978 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/sensoroperations/SensorOperationTest.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/sensoroperations/SensorOperationTest.java
@@ -137,7 +137,6 @@
         } catch (AssertionError e) {
             // Expected
             System.out.println(e.getMessage());
-            // TODO: Verify that the exception rethrown was at t=5ms.
         }
 
         statsKeys = op.getStats().flatten().keySet();
@@ -178,7 +177,6 @@
         } catch (AssertionError e) {
             // Expected
             System.out.println(e.getMessage());
-            // TODO: Verify that the exception rethrown was at t=5ms.
         }
 
         statsKeys = op.getStats().flatten().keySet();
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/sensoroperations/VerifiableSensorOperation.java b/tests/tests/hardware/src/android/hardware/cts/helpers/sensoroperations/VerifiableSensorOperation.java
index 55a880a..c635a75 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/sensoroperations/VerifiableSensorOperation.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/sensoroperations/VerifiableSensorOperation.java
@@ -20,7 +20,6 @@
 
 import android.hardware.cts.helpers.SensorCtsHelper;
 import android.hardware.cts.helpers.SensorStats;
-import android.hardware.cts.helpers.SensorTestInformation;
 import android.hardware.cts.helpers.TestSensorEnvironment;
 import android.hardware.cts.helpers.TestSensorEventListener;
 import android.hardware.cts.helpers.TestSensorManager;
@@ -96,9 +95,7 @@
      */
     @Override
     public void execute() {
-        getStats().addValue(
-                "sensor_name",
-                SensorTestInformation.getSensorName(mEnvironment.getSensor()));
+        getStats().addValue("sensor_name", mEnvironment.getSensor().getName());
 
         ValidatingSensorEventListener listener = new ValidatingSensorEventListener(mVerifications);
         listener.setLogEvents(mLogEvents);
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/EventGapVerification.java b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/EventGapVerification.java
index 962e5ad..156afa8 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/EventGapVerification.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/EventGapVerification.java
@@ -25,6 +25,9 @@
     // 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 = 1;
+
     private final int mExpectedDelayUs;
 
     private final List<IndexedEventPair> mEventGaps = new LinkedList<IndexedEventPair>();
@@ -105,15 +108,16 @@
      */
     @Override
     protected void addSensorEventInternal(TestSensorEvent event) {
-        if (mPreviousEvent != null) {
-            long deltaNs = event.timestamp - mPreviousEvent.timestamp;
-            long deltaUs = TimeUnit.MICROSECONDS.convert(deltaNs, TimeUnit.NANOSECONDS);
-            if (deltaUs > mExpectedDelayUs * THRESHOLD) {
-                mEventGaps.add(new IndexedEventPair(mIndex, event, mPreviousEvent));
+        if (mIndex >= TRUNCATE_EVENTS_COUNT) {
+            if (mPreviousEvent != null) {
+                long deltaNs = event.timestamp - mPreviousEvent.timestamp;
+                long deltaUs = TimeUnit.MICROSECONDS.convert(deltaNs, TimeUnit.NANOSECONDS);
+                if (deltaUs > mExpectedDelayUs * THRESHOLD) {
+                    mEventGaps.add(new IndexedEventPair(mIndex, event, mPreviousEvent));
+                }
             }
+            mPreviousEvent = event;
         }
-
-        mPreviousEvent = event;
         mIndex++;
     }
 }
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/JitterVerification.java b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/JitterVerification.java
index 97d2f5b..f95ea0b 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/JitterVerification.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/JitterVerification.java
@@ -23,13 +23,11 @@
 import android.hardware.cts.helpers.SensorStats;
 import android.hardware.cts.helpers.TestSensorEnvironment;
 import android.hardware.cts.helpers.TestSensorEvent;
+import android.util.SparseIntArray;
 
 import java.util.ArrayList;
-import java.util.HashMap;
 import java.util.LinkedList;
 import java.util.List;
-import java.util.Map;
-import java.util.concurrent.TimeUnit;
 
 /**
  * A {@link ISensorVerification} which verifies that the sensor jitter is in an acceptable range.
@@ -38,26 +36,22 @@
     public static final String PASSED_KEY = "jitter_passed";
 
     // sensorType: threshold (% of expected period)
-    private static final Map<Integer, Integer> DEFAULTS = new HashMap<Integer, Integer>(12);
+    private static final SparseIntArray DEFAULTS = new SparseIntArray(12);
     static {
         // Use a method so that the @deprecation warning can be set for that method only
         setDefaults();
     }
 
-    private final int mExpected;
-    private final int mThreshold;
-
-    private List<Long> mTimestamps = new LinkedList<Long>();
+    private final int mThresholdAsPercentage;
+    private final List<Long> mTimestamps = new LinkedList<Long>();
 
     /**
      * Construct a {@link JitterVerification}
      *
-     * @param expected the expected period in ns
-     * @param threshold the acceptable margin of error as a percentage
+     * @param thresholdAsPercentage the acceptable margin of error as a percentage
      */
-    public JitterVerification(int expected, int threshold) {
-        mExpected = expected;
-        mThreshold = threshold;
+    public JitterVerification(int thresholdAsPercentage) {
+        mThresholdAsPercentage = thresholdAsPercentage;
     }
 
     /**
@@ -68,40 +62,48 @@
      */
     public static JitterVerification getDefault(TestSensorEnvironment environment) {
         int sensorType = environment.getSensor().getType();
-        if (!DEFAULTS.containsKey(sensorType)) {
+        int threshold = DEFAULTS.get(sensorType, -1);
+        if (threshold == -1) {
             return null;
         }
-
-        int expected = (int) TimeUnit.NANOSECONDS
-                .convert(environment.getExpectedSamplingPeriodUs(), TimeUnit.MICROSECONDS);
-        return new JitterVerification(expected, DEFAULTS.get(sensorType));
+        return new JitterVerification(threshold);
     }
 
     /**
      * Verify that the 95th percentile of the jitter is in the acceptable range. Add
-     * {@value #PASSED_KEY} and {@value SensorStats#JITTER_95_PERCENTILE_KEY} keys to
+     * {@value #PASSED_KEY} and {@value SensorStats#JITTER_95_PERCENTILE_PERCENT_KEY} keys to
      * {@link SensorStats}.
      *
      * @throws AssertionError if the verification failed.
      */
     @Override
     public void verify(TestSensorEnvironment environment, SensorStats stats) {
-        if (mTimestamps.size() < 2 || environment.isSensorSamplingRateOverloaded()) {
+        int timestampsCount = mTimestamps.size();
+        if (timestampsCount < 2 || environment.isSensorSamplingRateOverloaded()) {
             // the verification is not reliable in environments under load
             stats.addValue(PASSED_KEY, true);
             return;
         }
 
         List<Double> jitters = getJitterValues();
-        double jitter95Percentile = SensorCtsHelper.get95PercentileValue(jitters);
-        boolean failed = (jitter95Percentile > mExpected * (mThreshold / 100.0));
+        double jitter95PercentileNs = SensorCtsHelper.get95PercentileValue(jitters);
+        long firstTimestamp = mTimestamps.get(0);
+        long lastTimestamp = mTimestamps.get(timestampsCount - 1);
+        long measuredPeriodNs = (lastTimestamp - firstTimestamp) / (timestampsCount - 1);
+        double jitter95PercentilePercent = (jitter95PercentileNs * 100.0) / measuredPeriodNs;
+        stats.addValue(SensorStats.JITTER_95_PERCENTILE_PERCENT_KEY, jitter95PercentilePercent);
 
-        stats.addValue(PASSED_KEY, !failed);
-        stats.addValue(SensorStats.JITTER_95_PERCENTILE_KEY, jitter95Percentile);
+        boolean success = (jitter95PercentilePercent < mThresholdAsPercentage);
+        stats.addValue(PASSED_KEY, success);
 
-        if (failed) {
-            Assert.fail(String.format("Jitter out of range: jitter at 95th percentile=%.0fns "
-                    + "(expected <%.0fns)", jitter95Percentile, mExpected * (mThreshold / 100.0)));
+        if (!success) {
+            String message = String.format(
+                    "Jitter out of range: measured period=%dns, jitter(95th percentile)=%.2f%%"
+                            + " (expected < %d%%)",
+                    measuredPeriodNs,
+                    jitter95PercentilePercent,
+                    mThresholdAsPercentage);
+            Assert.fail(message);
         }
     }
 
@@ -110,7 +112,7 @@
      */
     @Override
     public JitterVerification clone() {
-        return new JitterVerification(mExpected, mThreshold);
+        return new JitterVerification(mThresholdAsPercentage);
     }
 
     /**
@@ -127,7 +129,7 @@
     List<Double> getJitterValues() {
         List<Long> deltas = new ArrayList<Long>(mTimestamps.size() - 1);
         for (int i = 1; i < mTimestamps.size(); i++) {
-            deltas.add(mTimestamps.get(i) - mTimestamps.get(i -1));
+            deltas.add(mTimestamps.get(i) - mTimestamps.get(i - 1));
         }
         double deltaMean = SensorCtsHelper.getMean(deltas);
         List<Double> jitters = new ArrayList<Double>(deltas.size());
@@ -139,18 +141,17 @@
 
     @SuppressWarnings("deprecation")
     private static void setDefaults() {
-        // Sensors that we don't want to test at this time but still want to record the values.
         DEFAULTS.put(Sensor.TYPE_ACCELEROMETER, Integer.MAX_VALUE);
         DEFAULTS.put(Sensor.TYPE_MAGNETIC_FIELD, Integer.MAX_VALUE);
+        DEFAULTS.put(Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED, Integer.MAX_VALUE);
         DEFAULTS.put(Sensor.TYPE_GYROSCOPE, Integer.MAX_VALUE);
+        DEFAULTS.put(Sensor.TYPE_GYROSCOPE_UNCALIBRATED, Integer.MAX_VALUE);
         DEFAULTS.put(Sensor.TYPE_ORIENTATION, Integer.MAX_VALUE);
         DEFAULTS.put(Sensor.TYPE_PRESSURE, Integer.MAX_VALUE);
         DEFAULTS.put(Sensor.TYPE_GRAVITY, Integer.MAX_VALUE);
         DEFAULTS.put(Sensor.TYPE_LINEAR_ACCELERATION, Integer.MAX_VALUE);
         DEFAULTS.put(Sensor.TYPE_ROTATION_VECTOR, Integer.MAX_VALUE);
-        DEFAULTS.put(Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED, Integer.MAX_VALUE);
         DEFAULTS.put(Sensor.TYPE_GAME_ROTATION_VECTOR, Integer.MAX_VALUE);
-        DEFAULTS.put(Sensor.TYPE_GYROSCOPE_UNCALIBRATED, Integer.MAX_VALUE);
         DEFAULTS.put(Sensor.TYPE_GEOMAGNETIC_ROTATION_VECTOR, Integer.MAX_VALUE);
     }
 }
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/JitterVerificationTest.java b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/JitterVerificationTest.java
index 26e3fa3..0c85b63 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/JitterVerificationTest.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/JitterVerificationTest.java
@@ -47,7 +47,7 @@
             timestamps[i] = i * 100000;
         }
         SensorStats stats = new SensorStats();
-        ISensorVerification verification = getVerification(1000, 1, timestamps);
+        ISensorVerification verification = getVerification(1, timestamps);
         verification.verify(environment, stats);
         verifyStats(stats, true, 0.0);
 
@@ -58,48 +58,48 @@
             timestamp += (i % 10 == 0) ? 500000 : 1000000;
         }
         stats = new SensorStats();
-        verification = getVerification(1000, 1, timestamps);
+        verification = getVerification(1, timestamps);
         try {
             verification.verify(environment, stats);
             fail("Expected an AssertionError");
         } catch (AssertionError e) {
             // Expected;
         }
-        verifyStats(stats, false, 449494.9494);
+        verifyStats(stats, false, 47.34);
     }
 
     public void testCalculateJitter() {
         long[] timestamps = new long[]{0, 1, 2, 3, 4};
-        JitterVerification verification = getVerification(1000, 1, timestamps);
+        JitterVerification verification = getVerification(1, timestamps);
         List<Double> jitterValues = verification.getJitterValues();
         assertEquals(4, jitterValues.size());
-        assertEquals(0.0, (double) jitterValues.get(0));
-        assertEquals(0.0, (double) jitterValues.get(1));
-        assertEquals(0.0, (double) jitterValues.get(2));
-        assertEquals(0.0, (double) jitterValues.get(3));
+        assertEquals(0.0, jitterValues.get(0));
+        assertEquals(0.0, jitterValues.get(1));
+        assertEquals(0.0, jitterValues.get(2));
+        assertEquals(0.0, jitterValues.get(3));
 
         timestamps = new long[]{0, 0, 2, 4, 4};
-        verification = getVerification(1000, 1, timestamps);
+        verification = getVerification(1, timestamps);
         jitterValues = verification.getJitterValues();
         assertEquals(4, jitterValues.size());
-        assertEquals(1.0, (double) jitterValues.get(0));
-        assertEquals(1.0, (double) jitterValues.get(1));
-        assertEquals(1.0, (double) jitterValues.get(2));
-        assertEquals(1.0, (double) jitterValues.get(3));
+        assertEquals(1.0, jitterValues.get(0));
+        assertEquals(1.0, jitterValues.get(1));
+        assertEquals(1.0, jitterValues.get(2));
+        assertEquals(1.0, jitterValues.get(3));
 
         timestamps = new long[]{0, 1, 4, 9, 16};
-        verification = getVerification(1000, 1, timestamps);
+        verification = getVerification(1, timestamps);
         jitterValues = verification.getJitterValues();
         assertEquals(4, jitterValues.size());
         assertEquals(4, jitterValues.size());
-        assertEquals(3.0, (double) jitterValues.get(0));
-        assertEquals(1.0, (double) jitterValues.get(1));
-        assertEquals(1.0, (double) jitterValues.get(2));
-        assertEquals(3.0, (double) jitterValues.get(3));
+        assertEquals(3.0, jitterValues.get(0));
+        assertEquals(1.0, jitterValues.get(1));
+        assertEquals(1.0, jitterValues.get(2));
+        assertEquals(3.0, jitterValues.get(3));
     }
 
-    private JitterVerification getVerification(int expected, int threshold, long ... timestamps) {
-        JitterVerification verification = new JitterVerification(expected, threshold);
+    private JitterVerification getVerification(int threshold, long ... timestamps) {
+        JitterVerification verification = new JitterVerification(threshold);
         for (long timestamp : timestamps) {
             verification.addSensorEvent(new TestSensorEvent(null, timestamp, 0, null));
         }
@@ -108,6 +108,9 @@
 
     private void verifyStats(SensorStats stats, boolean passed, double jitter95) {
         assertEquals(passed, stats.getValue(JitterVerification.PASSED_KEY));
-        assertEquals(jitter95, (Double) stats.getValue(SensorStats.JITTER_95_PERCENTILE_KEY), 0.1);
+        assertEquals(
+                jitter95,
+                (Double) stats.getValue(SensorStats.JITTER_95_PERCENTILE_PERCENT_KEY),
+                0.1);
     }
 }
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/MagnitudeVerification.java b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/MagnitudeVerification.java
index 2c90127..db8037d 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/MagnitudeVerification.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/MagnitudeVerification.java
@@ -20,6 +20,7 @@
 
 import android.hardware.Sensor;
 import android.hardware.SensorManager;
+import android.hardware.cts.helpers.SensorCtsHelper;
 import android.hardware.cts.helpers.SensorStats;
 import android.hardware.cts.helpers.TestSensorEnvironment;
 import android.hardware.cts.helpers.TestSensorEvent;
@@ -119,11 +120,7 @@
      */
     @Override
     protected void addSensorEventInternal(TestSensorEvent event) {
-        float sumOfSquares = 0.0f;
-        for (float value : event.values) {
-            sumOfSquares += value * value;
-        }
-        mSum += (float) Math.sqrt(sumOfSquares);
+        mSum += SensorCtsHelper.getMagnitude(event.values);
         mCount++;
     }
 
diff --git a/tests/tests/media/src/android/media/cts/AudioManagerStub.java b/tests/tests/media/src/android/media/cts/AudioManagerStub.java
index baae5fc..290b866 100644
--- a/tests/tests/media/src/android/media/cts/AudioManagerStub.java
+++ b/tests/tests/media/src/android/media/cts/AudioManagerStub.java
@@ -19,7 +19,7 @@
 import com.android.cts.media.R;
 
 import android.app.Activity;
-import android.app.cts.CTSResult;
+import android.cts.util.CTSResult;
 import android.content.Context;
 import android.content.Intent;
 import android.media.AudioManager;
diff --git a/tests/tests/media/src/android/media/cts/AudioTrackTest.java b/tests/tests/media/src/android/media/cts/AudioTrackTest.java
index 7de3716..d01ecec 100644
--- a/tests/tests/media/src/android/media/cts/AudioTrackTest.java
+++ b/tests/tests/media/src/android/media/cts/AudioTrackTest.java
@@ -1448,7 +1448,7 @@
     public void testPlayStreamByteBuffer() throws Exception {
         // constants for test
         final String TEST_NAME = "testPlayStreamByteBuffer";
-        final int TEST_FORMAT_ARRAY[] = {  // should hear 2 tones played 3 times
+        final int TEST_FORMAT_ARRAY[] = {  // should hear 4 tones played 3 times
                 AudioFormat.ENCODING_PCM_8BIT,
                 AudioFormat.ENCODING_PCM_16BIT,
                 AudioFormat.ENCODING_PCM_FLOAT,
@@ -1459,6 +1459,10 @@
         final int TEST_CONF_ARRAY[] = {
                 AudioFormat.CHANNEL_OUT_STEREO,
         };
+        final int TEST_WRITE_MODE_ARRAY[] = {
+                AudioTrack.WRITE_BLOCKING,
+                AudioTrack.WRITE_NON_BLOCKING,
+        };
         final int TEST_MODE = AudioTrack.MODE_STREAM;
         final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
 
@@ -1466,68 +1470,71 @@
             double frequency = 800; // frequency changes for each test
             for (int TEST_SR : TEST_SR_ARRAY) {
                 for (int TEST_CONF : TEST_CONF_ARRAY) {
-                    for (int useDirect = 0; useDirect < 2; ++useDirect) {
-                        // -------- initialization --------------
-                        int minBufferSize = AudioTrack.getMinBufferSize(TEST_SR,
-                                TEST_CONF, TEST_FORMAT); // in bytes
-                        int bufferSize = 12 * minBufferSize;
-                        int bufferSamples = bufferSize
-                                / AudioFormat.getBytesPerSample(TEST_FORMAT);
-                        AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR,
-                                TEST_CONF, TEST_FORMAT, minBufferSize, TEST_MODE);
-                        assertTrue(TEST_NAME, track.getState() == AudioTrack.STATE_INITIALIZED);
-                        boolean hasPlayed = false;
-                        int written = 0;
-                        ByteBuffer bb = (useDirect == 1)
-                                ? ByteBuffer.allocateDirect(bufferSize)
-                                        : ByteBuffer.allocate(bufferSize);
-                        bb.order(java.nio.ByteOrder.nativeOrder());
+                    for (int TEST_WRITE_MODE : TEST_WRITE_MODE_ARRAY) {
+                        for (int useDirect = 0; useDirect < 2; ++useDirect) {
+                            // -------- initialization --------------
+                            int minBufferSize = AudioTrack.getMinBufferSize(TEST_SR,
+                                    TEST_CONF, TEST_FORMAT); // in bytes
+                            int bufferSize = 12 * minBufferSize;
+                            int bufferSamples = bufferSize
+                                    / AudioFormat.getBytesPerSample(TEST_FORMAT);
+                            AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR,
+                                    TEST_CONF, TEST_FORMAT, minBufferSize, TEST_MODE);
+                            assertTrue(TEST_NAME,
+                                    track.getState() == AudioTrack.STATE_INITIALIZED);
+                            boolean hasPlayed = false;
+                            int written = 0;
+                            ByteBuffer bb = (useDirect == 1)
+                                    ? ByteBuffer.allocateDirect(bufferSize)
+                                            : ByteBuffer.allocate(bufferSize);
+                            bb.order(java.nio.ByteOrder.nativeOrder());
 
-                        // -------- test --------------
-                        switch (TEST_FORMAT) {
-                        case AudioFormat.ENCODING_PCM_8BIT: {
-                            byte data[] = createSoundDataInByteArray(
-                                    bufferSamples, TEST_SR,
-                                    frequency);
-                            bb.put(data);
-                            bb.flip();
-                            } break;
-                        case AudioFormat.ENCODING_PCM_16BIT: {
-                            short data[] = createSoundDataInShortArray(
-                                    bufferSamples, TEST_SR,
-                                    frequency);
-                            ShortBuffer sb = bb.asShortBuffer();
-                            sb.put(data);
-                            bb.limit(sb.limit() * 2);
-                            } break;
-                        case AudioFormat.ENCODING_PCM_FLOAT: {
-                            float data[] = createSoundDataInFloatArray(
-                                    bufferSamples, TEST_SR,
-                                    frequency);
-                            FloatBuffer fb = bb.asFloatBuffer();
-                            fb.put(data);
-                            bb.limit(fb.limit() * 4);
-                            } break;
-                        }
-
-                        while (written < bufferSize) {
-                            int ret = track.write(bb,
-                                    Math.min(bufferSize - written, minBufferSize),
-                                    AudioTrack.WRITE_BLOCKING);
-                            assertTrue(TEST_NAME, ret >= 0);
-                            written += ret;
-                            if (!hasPlayed) {
-                                track.play();
-                                hasPlayed = true;
+                            // -------- test --------------
+                            switch (TEST_FORMAT) {
+                                case AudioFormat.ENCODING_PCM_8BIT: {
+                                    byte data[] = createSoundDataInByteArray(
+                                            bufferSamples, TEST_SR,
+                                            frequency);
+                                    bb.put(data);
+                                    bb.flip();
+                                } break;
+                                case AudioFormat.ENCODING_PCM_16BIT: {
+                                    short data[] = createSoundDataInShortArray(
+                                            bufferSamples, TEST_SR,
+                                            frequency);
+                                    ShortBuffer sb = bb.asShortBuffer();
+                                    sb.put(data);
+                                    bb.limit(sb.limit() * 2);
+                                } break;
+                                case AudioFormat.ENCODING_PCM_FLOAT: {
+                                    float data[] = createSoundDataInFloatArray(
+                                            bufferSamples, TEST_SR,
+                                            frequency);
+                                    FloatBuffer fb = bb.asFloatBuffer();
+                                    fb.put(data);
+                                    bb.limit(fb.limit() * 4);
+                                } break;
                             }
-                        }
 
-                        Thread.sleep(WAIT_MSEC);
-                        track.stop();
-                        Thread.sleep(WAIT_MSEC);
-                        // -------- tear down --------------
-                        track.release();
-                        frequency += 200; // increment test tone frequency
+                            while (written < bufferSize) {
+                                int ret = track.write(bb,
+                                        Math.min(bufferSize - written, minBufferSize),
+                                        TEST_WRITE_MODE);
+                                assertTrue(TEST_NAME, ret >= 0);
+                                written += ret;
+                                if (!hasPlayed) {
+                                    track.play();
+                                    hasPlayed = true;
+                                }
+                            }
+
+                            Thread.sleep(WAIT_MSEC);
+                            track.stop();
+                            Thread.sleep(WAIT_MSEC);
+                            // -------- tear down --------------
+                            track.release();
+                            frequency += 200; // increment test tone frequency
+                        }
                     }
                 }
             }
diff --git a/tests/tests/media/src/android/media/cts/MediaScannerConnectionTest.java b/tests/tests/media/src/android/media/cts/MediaScannerConnectionTest.java
index 4234a5b..ddf87b8 100644
--- a/tests/tests/media/src/android/media/cts/MediaScannerConnectionTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaScannerConnectionTest.java
@@ -21,12 +21,12 @@
 
 import android.content.ComponentName;
 import android.content.Context;
+import android.cts.util.FileCopyHelper;
 import android.cts.util.PollingCheck;
 import android.media.MediaScannerConnection;
 import android.media.MediaScannerConnection.MediaScannerConnectionClient;
 import android.net.Uri;
 import android.os.IBinder;
-import android.provider.cts.FileCopyHelper;
 import android.test.AndroidTestCase;
 
 import java.io.File;
diff --git a/tests/tests/media/src/android/media/cts/MediaScannerTest.java b/tests/tests/media/src/android/media/cts/MediaScannerTest.java
index b537467..4b42690 100644
--- a/tests/tests/media/src/android/media/cts/MediaScannerTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaScannerTest.java
@@ -26,6 +26,7 @@
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.content.res.AssetFileDescriptor;
+import android.cts.util.FileCopyHelper;
 import android.cts.util.PollingCheck;
 import android.database.Cursor;
 import android.media.MediaMetadataRetriever;
@@ -38,7 +39,6 @@
 import android.os.IBinder;
 import android.os.SystemClock;
 import android.provider.MediaStore;
-import android.provider.cts.FileCopyHelper;
 import android.test.AndroidTestCase;
 import android.util.Log;
 
diff --git a/tests/tests/os/Android.mk b/tests/tests/os/Android.mk
index f0fb88a..1d78af4 100644
--- a/tests/tests/os/Android.mk
+++ b/tests/tests/os/Android.mk
@@ -25,7 +25,7 @@
 
 LOCAL_STATIC_JAVA_LIBRARIES := ctsdeviceutil ctstestrunner guava
 
-LOCAL_JNI_SHARED_LIBRARIES := libctsos_jni
+LOCAL_JNI_SHARED_LIBRARIES := libcts_jni libctsos_jni
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src) \
         src/android/os/cts/IParcelFileDescriptorPeer.aidl \
diff --git a/tests/tests/os/jni/Android.mk b/tests/tests/os/jni/Android.mk
index a39b5d1..3d3bc33 100644
--- a/tests/tests/os/jni/Android.mk
+++ b/tests/tests/os/jni/Android.mk
@@ -25,8 +25,7 @@
 		CtsOsJniOnLoad.cpp \
 		android_os_cts_CpuInstructions.cpp.arm \
 		android_os_cts_TaggedPointer.cpp \
-		android_os_cts_OSFeatures.cpp \
-		android_os_cts_FileUtils.cpp \
+		android_os_cts_OSFeatures.cpp
 
 LOCAL_C_INCLUDES := $(JNI_H_INCLUDE)
 
diff --git a/tests/tests/os/jni/CtsOsJniOnLoad.cpp b/tests/tests/os/jni/CtsOsJniOnLoad.cpp
index ef69732..c6b88f5 100644
--- a/tests/tests/os/jni/CtsOsJniOnLoad.cpp
+++ b/tests/tests/os/jni/CtsOsJniOnLoad.cpp
@@ -25,8 +25,6 @@
 
 extern int register_android_os_cts_OSFeatures(JNIEnv*);
 
-extern int register_android_os_cts_FileUtils(JNIEnv*);
-
 jint JNI_OnLoad(JavaVM *vm, void *reserved) {
     JNIEnv *env = NULL;
 
@@ -50,9 +48,5 @@
         return JNI_ERR;
     }
 
-    if (register_android_os_cts_FileUtils(env)) {
-      return JNI_ERR;
-    }
-
     return JNI_VERSION_1_4;
 }
diff --git a/tests/tests/os/jni/android_os_cts_FileUtils.cpp b/tests/tests/os/jni/android_os_cts_FileUtils.cpp
deleted file mode 100644
index 2b7e282..0000000
--- a/tests/tests/os/jni/android_os_cts_FileUtils.cpp
+++ /dev/null
@@ -1,145 +0,0 @@
-/* 
- * Copyright (C) 2011 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.
- */
-
-#include <grp.h>
-#include <jni.h>
-#include <pwd.h>
-#include <stdio.h>
-#include <string.h>
-#include <sys/errno.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <assert.h>
-
-static jclass gFileStatusClass;
-static jfieldID gFileStatusDevFieldID;
-static jfieldID gFileStatusInoFieldID;
-static jfieldID gFileStatusModeFieldID;
-static jfieldID gFileStatusNlinkFieldID;
-static jfieldID gFileStatusUidFieldID;
-static jfieldID gFileStatusGidFieldID;
-static jfieldID gFileStatusSizeFieldID;
-static jfieldID gFileStatusBlksizeFieldID;
-static jfieldID gFileStatusBlocksFieldID;
-static jfieldID gFileStatusAtimeFieldID;
-static jfieldID gFileStatusMtimeFieldID;
-static jfieldID gFileStatusCtimeFieldID;
-
-/*
- * Native methods used by
- * cts/tests/src/android/os/cts/FileUtils.java
- *
- * Copied from hidden API: frameworks/base/core/jni/android_os_FileUtils.cpp
- */
-
-jboolean android_os_cts_FileUtils_getFileStatus(JNIEnv* env, jobject thiz,
-        jstring path, jobject fileStatus, jboolean statLinks)
-{
-    const char* pathStr = env->GetStringUTFChars(path, NULL);
-    jboolean ret = false;
-    struct stat s;
-
-    int res = statLinks == true ? lstat(pathStr, &s) : stat(pathStr, &s);
-
-    if (res == 0) {
-        ret = true;
-        if (fileStatus != NULL) {
-            env->SetIntField(fileStatus, gFileStatusDevFieldID, s.st_dev);
-            env->SetIntField(fileStatus, gFileStatusInoFieldID, s.st_ino);
-            env->SetIntField(fileStatus, gFileStatusModeFieldID, s.st_mode);
-            env->SetIntField(fileStatus, gFileStatusNlinkFieldID, s.st_nlink);
-            env->SetIntField(fileStatus, gFileStatusUidFieldID, s.st_uid);
-            env->SetIntField(fileStatus, gFileStatusGidFieldID, s.st_gid);
-            env->SetLongField(fileStatus, gFileStatusSizeFieldID, s.st_size);
-            env->SetIntField(fileStatus, gFileStatusBlksizeFieldID, s.st_blksize);
-            env->SetLongField(fileStatus, gFileStatusBlocksFieldID, s.st_blocks);
-            env->SetLongField(fileStatus, gFileStatusAtimeFieldID, s.st_atime);
-            env->SetLongField(fileStatus, gFileStatusMtimeFieldID, s.st_mtime);
-            env->SetLongField(fileStatus, gFileStatusCtimeFieldID, s.st_ctime);
-        }
-    }
-
-    env->ReleaseStringUTFChars(path, pathStr);
-
-    return ret;
-}
-
-jstring android_os_cts_FileUtils_getUserName(JNIEnv* env, jobject thiz,
-        jint uid)
-{
-    struct passwd *pwd = getpwuid(uid);
-    return env->NewStringUTF(pwd->pw_name);
-}
-
-jstring android_os_cts_FileUtils_getGroupName(JNIEnv* env, jobject thiz,
-        jint gid)
-{
-    struct group *grp = getgrgid(gid);
-    return env->NewStringUTF(grp->gr_name);
-}
-
-jint android_os_cts_FileUtils_setPermissions(JNIEnv* env, jobject clazz,
-        jstring file, jint mode)
-{
-    const char *fileStr = env->GetStringUTFChars(file, NULL);
-    if (fileStr == NULL) {
-        return -1;
-    }
-
-    if (strlen(fileStr) <= 0) {
-        env->ReleaseStringUTFChars(file, fileStr);
-        return ENOENT;
-    } 
-
-    jint returnValue = chmod(fileStr, mode) == 0 ? 0 : errno;
-    env->ReleaseStringUTFChars(file, fileStr);
-    return returnValue;
-}
-
-static JNINativeMethod gMethods[] = {
-    {  "getFileStatus", "(Ljava/lang/String;Landroid/os/cts/FileUtils$FileStatus;Z)Z",
-            (void *) android_os_cts_FileUtils_getFileStatus  },
-    {  "getUserName", "(I)Ljava/lang/String;",
-            (void *) android_os_cts_FileUtils_getUserName  },
-    {  "getGroupName", "(I)Ljava/lang/String;",
-            (void *) android_os_cts_FileUtils_getGroupName  },
-    {  "setPermissions", "(Ljava/lang/String;I)I",
-            (void *) android_os_cts_FileUtils_setPermissions },
-};
-
-int register_android_os_cts_FileUtils(JNIEnv* env)
-{
-    jclass clazz = env->FindClass("android/os/cts/FileUtils");
-    assert(clazz != null);
-
-    gFileStatusClass = env->FindClass("android/os/cts/FileUtils$FileStatus");
-    assert(gFileStatusClass != null);
-    gFileStatusDevFieldID = env->GetFieldID(gFileStatusClass, "dev", "I");
-    gFileStatusInoFieldID = env->GetFieldID(gFileStatusClass, "ino", "I");
-    gFileStatusModeFieldID = env->GetFieldID(gFileStatusClass, "mode", "I");
-    gFileStatusNlinkFieldID = env->GetFieldID(gFileStatusClass, "nlink", "I");
-    gFileStatusUidFieldID = env->GetFieldID(gFileStatusClass, "uid", "I");
-    gFileStatusGidFieldID = env->GetFieldID(gFileStatusClass, "gid", "I");
-    gFileStatusSizeFieldID = env->GetFieldID(gFileStatusClass, "size", "J");
-    gFileStatusBlksizeFieldID = env->GetFieldID(gFileStatusClass, "blksize", "I");
-    gFileStatusBlocksFieldID = env->GetFieldID(gFileStatusClass, "blocks", "J");
-    gFileStatusAtimeFieldID = env->GetFieldID(gFileStatusClass, "atime", "J");
-    gFileStatusMtimeFieldID = env->GetFieldID(gFileStatusClass, "mtime", "J");
-    gFileStatusCtimeFieldID = env->GetFieldID(gFileStatusClass, "ctime", "J");
-
-    return env->RegisterNatives(clazz, gMethods, 
-            sizeof(gMethods) / sizeof(JNINativeMethod)); 
-}
diff --git a/tests/tests/os/src/android/os/cts/AbiTest.java b/tests/tests/os/src/android/os/cts/AbiTest.java
index a342669..ee2c168 100644
--- a/tests/tests/os/src/android/os/cts/AbiTest.java
+++ b/tests/tests/os/src/android/os/cts/AbiTest.java
@@ -16,7 +16,7 @@
 
 package android.os.cts;
 
-import android.os.cts.ReadElf;
+import android.cts.util.ReadElf;
 
 import java.io.File;
 
diff --git a/tests/tests/os/src/android/os/cts/BuildVersionTest.java b/tests/tests/os/src/android/os/cts/BuildVersionTest.java
index 3cb0181..e7ad28e 100644
--- a/tests/tests/os/src/android/os/cts/BuildVersionTest.java
+++ b/tests/tests/os/src/android/os/cts/BuildVersionTest.java
@@ -31,10 +31,8 @@
     private static final Set<String> EXPECTED_RELEASES =
         new HashSet<String>(Arrays.asList("4.4W.1", "4.4W", "4.4", "4.4.1", "4.4.2", "4.4.3"));
     private static final int EXPECTED_SDK = 20;
-    private static final Set<String> EXPECTED_BUILD_VARIANTS =
-            new HashSet<String>(Arrays.asList("user", "userdebug", "eng"));
-    private static final Set<String> EXPECTED_TAGS =
-            new HashSet<String>(Arrays.asList("test-keys", "dev-keys", "release-keys"));
+    private static final String EXPECTED_BUILD_VARIANT = "user";
+    private static final String EXPECTED_TAG = "release-keys";
 
     @SuppressWarnings("deprecation")
     public void testReleaseVersion() {
@@ -77,10 +75,8 @@
         assertTrue(fingerprintSegs[4].contains(":"));
         String[] buildNumberVariant = fingerprintSegs[4].split(":");
         String buildVariant = buildNumberVariant[1];
-        assertAnyOf("Variant", buildVariant, EXPECTED_BUILD_VARIANTS);
-
-        // Build.TAGS
-        assertAnyOf("TAGS", fingerprintSegs[5], EXPECTED_TAGS);
+        assertEquals("Variant", EXPECTED_BUILD_VARIANT, buildVariant);
+        assertEquals("Tag", EXPECTED_TAG, fingerprintSegs[5]);
     }
 
     private void assertNotEmpty(String value) {
diff --git a/tests/tests/os/src/android/os/cts/ConditionVariableTest.java b/tests/tests/os/src/android/os/cts/ConditionVariableTest.java
index 559f890..cad9dec 100644
--- a/tests/tests/os/src/android/os/cts/ConditionVariableTest.java
+++ b/tests/tests/os/src/android/os/cts/ConditionVariableTest.java
@@ -16,6 +16,7 @@
 package android.os.cts;
 
 import junit.framework.TestCase;
+import android.cts.util.TestThread;
 import android.os.ConditionVariable;
 
 public class ConditionVariableTest extends TestCase {
diff --git a/tests/tests/os/src/android/os/cts/DebugTest.java b/tests/tests/os/src/android/os/cts/DebugTest.java
index c05c78a..c097240 100644
--- a/tests/tests/os/src/android/os/cts/DebugTest.java
+++ b/tests/tests/os/src/android/os/cts/DebugTest.java
@@ -22,6 +22,7 @@
 import java.util.logging.Logger;
 
 import android.content.Context;
+import android.cts.util.TestThread;
 import android.os.Debug;
 import android.test.AndroidTestCase;
 import dalvik.system.VMDebug;
diff --git a/tests/tests/os/src/android/os/cts/HandlerTest.java b/tests/tests/os/src/android/os/cts/HandlerTest.java
index fc775e4..7183d7e 100644
--- a/tests/tests/os/src/android/os/cts/HandlerTest.java
+++ b/tests/tests/os/src/android/os/cts/HandlerTest.java
@@ -17,6 +17,7 @@
 package android.os.cts;
 
 import junit.framework.TestCase;
+import android.cts.util.TestThread;
 import android.os.Handler;
 import android.os.Looper;
 import android.os.Message;
diff --git a/tests/tests/os/src/android/os/cts/LocalService.java b/tests/tests/os/src/android/os/cts/LocalService.java
index 0353c23..cc427f8 100644
--- a/tests/tests/os/src/android/os/cts/LocalService.java
+++ b/tests/tests/os/src/android/os/cts/LocalService.java
@@ -18,6 +18,7 @@
 
 import android.app.Service;
 import android.content.Intent;
+import android.cts.util.IBinderParcelable;
 import android.os.Binder;
 import android.os.IBinder;
 import android.os.Parcel;
diff --git a/tests/tests/os/src/android/os/cts/LooperTest.java b/tests/tests/os/src/android/os/cts/LooperTest.java
index e71b752..79a55c6 100644
--- a/tests/tests/os/src/android/os/cts/LooperTest.java
+++ b/tests/tests/os/src/android/os/cts/LooperTest.java
@@ -16,6 +16,7 @@
 
 package android.os.cts;
 
+import android.cts.util.TestThread;
 import android.os.Handler;
 import android.os.Looper;
 import android.os.Message;
diff --git a/tests/tests/os/src/android/os/cts/TestThread.java b/tests/tests/os/src/android/os/cts/TestThread.java
deleted file mode 100644
index 1a28a20..0000000
--- a/tests/tests/os/src/android/os/cts/TestThread.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright (C) 2009 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.os.cts;
-
-/**
- * Thread class for executing a Runnable containing assertions in a separate thread.
- * Uncaught exceptions in the Runnable are rethrown in the context of the the thread
- * calling the <code>runTest()</code> method.
- */
-public final class TestThread extends Thread {
-    private Throwable mThrowable;
-    private Runnable mTarget;
-
-    public TestThread(Runnable target) {
-        mTarget = target;
-    }
-
-    @Override
-    public final void run() {
-        try {
-            mTarget.run();
-        } catch (Throwable t) {
-            mThrowable = t;
-        }
-    }
-
-    /**
-     * Run the target Runnable object and wait until the test finish or throw
-     * out Exception if test fail.
-     *
-     * @param runTime
-     * @throws Throwable
-     */
-    public void runTest(long runTime) throws Throwable {
-        start();
-        joinAndCheck(runTime);
-    }
-
-    /**
-     * Get the Throwable object which is thrown when test running
-     * @return  The Throwable object
-     */
-    public Throwable getThrowable() {
-        return mThrowable;
-    }
-
-    /**
-     * Set the Throwable object which is thrown when test running
-     * @param t The Throwable object
-     */
-    public void setThrowable(Throwable t) {
-        mThrowable = t;
-    }
-
-    /**
-     * Wait for the test thread to complete and throw the stored exception if there is one.
-     *
-     * @param runTime The time to wait for the test thread to complete.
-     * @throws Throwable
-     */
-    public void joinAndCheck(long runTime) throws Throwable {
-        this.join(runTime);
-        if (this.isAlive()) {
-            this.interrupt();
-            this.join(runTime);
-            throw new Exception("Thread did not finish within allotted time.");
-        }
-        checkException();
-    }
-
-    /**
-     * Check whether there is an exception when running Runnable object.
-     * @throws Throwable
-     */
-    public void checkException() throws Throwable {
-        if (mThrowable != null) {
-            throw mThrowable;
-        }
-    }
-}
diff --git a/tests/tests/os/src/android/os/storage/cts/StorageManagerTest.java b/tests/tests/os/src/android/os/storage/cts/StorageManagerTest.java
index 7d2d4ff..a8e8e64 100644
--- a/tests/tests/os/src/android/os/storage/cts/StorageManagerTest.java
+++ b/tests/tests/os/src/android/os/storage/cts/StorageManagerTest.java
@@ -22,7 +22,7 @@
 import android.content.res.Resources;
 import android.content.res.Resources.NotFoundException;
 import android.os.Environment;
-import android.os.cts.FileUtils;
+import android.cts.util.FileUtils;
 import android.os.storage.OnObbStateChangeListener;
 import android.os.storage.StorageManager;
 import android.test.AndroidTestCase;
diff --git a/tests/tests/provider/Android.mk b/tests/tests/provider/Android.mk
index 81ff9ee..fdc02e9 100644
--- a/tests/tests/provider/Android.mk
+++ b/tests/tests/provider/Android.mk
@@ -25,6 +25,8 @@
 
 LOCAL_STATIC_JAVA_LIBRARIES := ctsdeviceutil ctstestrunner
 
+LOCAL_JNI_SHARED_LIBRARIES := libcts_jni
+
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 LOCAL_PACKAGE_NAME := CtsProviderTestCases
diff --git a/tests/tests/provider/src/android/provider/cts/ContactsContract_PhotoTest.java b/tests/tests/provider/src/android/provider/cts/ContactsContract_PhotoTest.java
index 45ba8b8..8c97c22 100644
--- a/tests/tests/provider/src/android/provider/cts/ContactsContract_PhotoTest.java
+++ b/tests/tests/provider/src/android/provider/cts/ContactsContract_PhotoTest.java
@@ -19,6 +19,7 @@
 import android.content.ContentProviderClient;
 import android.content.ContentResolver;
 import android.content.Context;
+import android.cts.util.FileUtils;
 import android.provider.ContactsContract;
 import android.provider.ContactsContract.CommonDataKinds.Photo;
 import android.provider.ContactsContract.Contacts;
diff --git a/tests/tests/provider/src/android/provider/cts/FileUtils.java b/tests/tests/provider/src/android/provider/cts/FileUtils.java
deleted file mode 100644
index 0766e6d..0000000
--- a/tests/tests/provider/src/android/provider/cts/FileUtils.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright (C) 2011 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.provider.cts;
-
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-
-/** Bits and pieces copied from hidden API of android.os.FileUtils. */
-public class FileUtils {
-
-    /**
-     * Copy data from a source stream to destFile.
-     * Return true if succeed, return false if failed.
-     */
-    public static boolean copyToFile(InputStream inputStream, File destFile) {
-        try {
-            if (destFile.exists()) {
-                destFile.delete();
-            }
-            FileOutputStream out = new FileOutputStream(destFile);
-            try {
-                byte[] buffer = new byte[4096];
-                int bytesRead;
-                while ((bytesRead = inputStream.read(buffer)) >= 0) {
-                    out.write(buffer, 0, bytesRead);
-                }
-            } finally {
-                out.flush();
-                try {
-                    out.getFD().sync();
-                } catch (IOException e) {
-                }
-                out.close();
-            }
-            return true;
-        } catch (IOException e) {
-            return false;
-        }
-    }
-
-    public static void createFile(File file, int numBytes) throws IOException {
-        File parentFile = file.getParentFile();
-        if (parentFile != null) {
-            parentFile.mkdirs();
-        }
-        byte[] buffer = new byte[numBytes];
-        FileOutputStream output = new FileOutputStream(file);
-        try {
-            output.write(buffer);
-        } finally {
-            output.close();
-        }
-    }
-
-    public static byte[] readInputStreamFully(InputStream is) {
-        ByteArrayOutputStream os = new ByteArrayOutputStream();
-        byte[] buffer = new byte[32768];
-        int count;
-        try {
-            while ((count = is.read(buffer)) != -1) {
-                os.write(buffer, 0, count);
-            }
-            is.close();
-        } catch (IOException e) {
-            throw new RuntimeException(e);
-        }
-        return os.toByteArray();
-    }
-}
diff --git a/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_AlbumsTest.java b/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_AlbumsTest.java
index bad1108..84da62a 100644
--- a/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_AlbumsTest.java
+++ b/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_AlbumsTest.java
@@ -21,6 +21,7 @@
 import android.content.ContentResolver;
 import android.content.ContentValues;
 import android.content.res.AssetFileDescriptor;
+import android.cts.util.FileCopyHelper;
 import android.database.Cursor;
 import android.net.Uri;
 import android.os.Environment;
diff --git a/tests/tests/provider/src/android/provider/cts/MediaStore_FilesTest.java b/tests/tests/provider/src/android/provider/cts/MediaStore_FilesTest.java
index 67396d4..0eae82b 100644
--- a/tests/tests/provider/src/android/provider/cts/MediaStore_FilesTest.java
+++ b/tests/tests/provider/src/android/provider/cts/MediaStore_FilesTest.java
@@ -22,6 +22,7 @@
 import android.content.ContentUris;
 import android.content.ContentValues;
 import android.content.Context;
+import android.cts.util.FileCopyHelper;
 import android.database.Cursor;
 import android.net.Uri;
 import android.os.Environment;
diff --git a/tests/tests/provider/src/android/provider/cts/MediaStore_Images_MediaTest.java b/tests/tests/provider/src/android/provider/cts/MediaStore_Images_MediaTest.java
index bc86b0a..7469f8e 100644
--- a/tests/tests/provider/src/android/provider/cts/MediaStore_Images_MediaTest.java
+++ b/tests/tests/provider/src/android/provider/cts/MediaStore_Images_MediaTest.java
@@ -21,6 +21,8 @@
 import android.content.ContentResolver;
 import android.content.ContentValues;
 import android.content.Context;
+import android.cts.util.FileCopyHelper;
+import android.cts.util.FileUtils;
 import android.database.Cursor;
 import android.graphics.Bitmap;
 import android.graphics.BitmapFactory;
diff --git a/tests/tests/provider/src/android/provider/cts/MediaStore_Images_ThumbnailsTest.java b/tests/tests/provider/src/android/provider/cts/MediaStore_Images_ThumbnailsTest.java
index 025be2c..ec9db8b 100644
--- a/tests/tests/provider/src/android/provider/cts/MediaStore_Images_ThumbnailsTest.java
+++ b/tests/tests/provider/src/android/provider/cts/MediaStore_Images_ThumbnailsTest.java
@@ -22,6 +22,7 @@
 import android.content.ContentUris;
 import android.content.ContentValues;
 import android.content.Context;
+import android.cts.util.FileCopyHelper;
 import android.database.Cursor;
 import android.graphics.Bitmap;
 import android.graphics.BitmapFactory;
@@ -35,6 +36,7 @@
 
 import java.io.File;
 import java.util.ArrayList;
+import android.util.DisplayMetrics;
 
 public class MediaStore_Images_ThumbnailsTest extends InstrumentationTestCase {
     private ArrayList<Uri> mRowsAdded;
@@ -111,7 +113,9 @@
 
     public void testQueryExternalMiniThumbnails() {
         // insert the image by bitmap
-        Bitmap src = BitmapFactory.decodeResource(mContext.getResources(), R.raw.scenery);
+        BitmapFactory.Options opts = new BitmapFactory.Options();
+        opts.inTargetDensity = DisplayMetrics.DENSITY_XHIGH;
+        Bitmap src = BitmapFactory.decodeResource(mContext.getResources(), R.raw.scenery,opts);
         String stringUrl = null;
         try{
             stringUrl = Media.insertImage(mContentResolver, src, null, null);
diff --git a/tests/tests/provider/src/android/provider/cts/MediaStore_VideoTest.java b/tests/tests/provider/src/android/provider/cts/MediaStore_VideoTest.java
index 2c9ebd1..89de9c6 100644
--- a/tests/tests/provider/src/android/provider/cts/MediaStore_VideoTest.java
+++ b/tests/tests/provider/src/android/provider/cts/MediaStore_VideoTest.java
@@ -21,6 +21,7 @@
 import android.content.ContentResolver;
 import android.content.ContentValues;
 import android.content.Context;
+import android.cts.util.FileCopyHelper;
 import android.database.Cursor;
 import android.net.Uri;
 import android.provider.MediaStore.Video;
diff --git a/tests/tests/provider/src/android/provider/cts/MediaStore_Video_MediaTest.java b/tests/tests/provider/src/android/provider/cts/MediaStore_Video_MediaTest.java
index c3f5070..f84b75c 100644
--- a/tests/tests/provider/src/android/provider/cts/MediaStore_Video_MediaTest.java
+++ b/tests/tests/provider/src/android/provider/cts/MediaStore_Video_MediaTest.java
@@ -22,6 +22,8 @@
 import android.content.ContentResolver;
 import android.content.ContentValues;
 import android.content.Context;
+import android.cts.util.FileCopyHelper;
+import android.cts.util.FileUtils;
 import android.database.Cursor;
 import android.net.Uri;
 import android.os.Environment;
diff --git a/tests/tests/provider/src/android/provider/cts/MediaStore_Video_ThumbnailsTest.java b/tests/tests/provider/src/android/provider/cts/MediaStore_Video_ThumbnailsTest.java
index e74cce4..b6175be 100644
--- a/tests/tests/provider/src/android/provider/cts/MediaStore_Video_ThumbnailsTest.java
+++ b/tests/tests/provider/src/android/provider/cts/MediaStore_Video_ThumbnailsTest.java
@@ -21,6 +21,7 @@
 import android.content.ContentResolver;
 import android.content.ContentUris;
 import android.content.ContentValues;
+import android.cts.util.FileCopyHelper;
 import android.database.Cursor;
 import android.media.MediaCodecInfo;
 import android.media.MediaCodecList;
diff --git a/tests/tests/provider/src/android/provider/cts/PhotoUtil.java b/tests/tests/provider/src/android/provider/cts/PhotoUtil.java
index 3f5f873..ec4fdef 100644
--- a/tests/tests/provider/src/android/provider/cts/PhotoUtil.java
+++ b/tests/tests/provider/src/android/provider/cts/PhotoUtil.java
@@ -19,6 +19,7 @@
 import com.android.cts.provider.R;
 
 import android.content.Context;
+import android.cts.util.FileUtils;
 
 import java.io.InputStream;
 
diff --git a/tests/tests/security/Android.mk b/tests/tests/security/Android.mk
index 10ad5f8..dfb7884 100644
--- a/tests/tests/security/Android.mk
+++ b/tests/tests/security/Android.mk
@@ -22,7 +22,7 @@
 
 LOCAL_JAVA_LIBRARIES := android.test.runner
 
-LOCAL_JNI_SHARED_LIBRARIES := libctssecurity_jni
+LOCAL_JNI_SHARED_LIBRARIES := libctssecurity_jni libcts_jni
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)\
                    src/android/security/cts/activity/ISecureRandomService.aidl
diff --git a/tests/tests/security/jni/Android.mk b/tests/tests/security/jni/Android.mk
index 84f62c0..fa862c1 100644
--- a/tests/tests/security/jni/Android.mk
+++ b/tests/tests/security/jni/Android.mk
@@ -31,7 +31,6 @@
 		android_security_cts_SeccompDeathTestService.cpp \
 		android_security_cts_SELinuxTest.cpp \
 		android_security_cts_MMapExecutableTest.cpp \
-		android_security_cts_FileUtils.cpp \
 		android_security_cts_NetlinkSocket.cpp
 
 LOCAL_C_INCLUDES := $(JNI_H_INCLUDE)
diff --git a/tests/tests/security/jni/CtsSecurityJniOnLoad.cpp b/tests/tests/security/jni/CtsSecurityJniOnLoad.cpp
index d9a5f28..0e91b4e 100644
--- a/tests/tests/security/jni/CtsSecurityJniOnLoad.cpp
+++ b/tests/tests/security/jni/CtsSecurityJniOnLoad.cpp
@@ -26,7 +26,6 @@
 extern int register_android_security_cts_SeccompDeathTestService(JNIEnv*);
 extern int register_android_security_cts_SELinuxTest(JNIEnv*);
 extern int register_android_security_cts_MMapExecutableTest(JNIEnv* env);
-extern int register_android_security_cts_FileUtils(JNIEnv*);
 
 jint JNI_OnLoad(JavaVM *vm, void *reserved) {
     JNIEnv *env = NULL;
@@ -67,10 +66,6 @@
         return JNI_ERR;
     }
 
-    if (register_android_security_cts_FileUtils(env)) {
-        return JNI_ERR;
-    }
-
     if (register_android_security_cts_NetlinkSocket(env)) {
         return JNI_ERR;
     }
diff --git a/tests/tests/security/src/android/security/cts/AslrTest.java b/tests/tests/security/src/android/security/cts/AslrTest.java
index f1552f6..913b49b 100644
--- a/tests/tests/security/src/android/security/cts/AslrTest.java
+++ b/tests/tests/security/src/android/security/cts/AslrTest.java
@@ -24,7 +24,7 @@
 import java.io.FileReader;
 import java.io.IOException;
 
-import android.security.cts.ReadElf;
+import android.cts.util.ReadElf;
 
 /**
  * Verify that ASLR is properly enabled on Android Compatible devices.
diff --git a/tests/tests/security/src/android/security/cts/BannedFilesTest.java b/tests/tests/security/src/android/security/cts/BannedFilesTest.java
index a71dcce..8076f8e 100644
--- a/tests/tests/security/src/android/security/cts/BannedFilesTest.java
+++ b/tests/tests/security/src/android/security/cts/BannedFilesTest.java
@@ -16,7 +16,7 @@
 
 package android.security.cts;
 
-import android.security.cts.FileUtils;
+import android.cts.util.FileUtils;
 
 import junit.framework.TestCase;
 
diff --git a/tests/tests/security/src/android/security/cts/FileUtils.java b/tests/tests/security/src/android/security/cts/FileUtils.java
deleted file mode 100644
index 3708f68..0000000
--- a/tests/tests/security/src/android/security/cts/FileUtils.java
+++ /dev/null
@@ -1,163 +0,0 @@
-/*
- * 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.security.cts;
-
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-
-/** Bits and pieces copied from hidden API of android.os.FileUtils. */
-public class FileUtils {
-
-    public static final int S_IFMT  = 0170000;
-    public static final int S_IFSOCK = 0140000;
-    public static final int S_IFLNK = 0120000;
-    public static final int S_IFREG = 0100000;
-    public static final int S_IFBLK = 0060000;
-    public static final int S_IFDIR = 0040000;
-    public static final int S_IFCHR = 0020000;
-    public static final int S_IFIFO = 0010000;
-
-    public static final int S_ISUID = 0004000;
-    public static final int S_ISGID = 0002000;
-    public static final int S_ISVTX = 0001000;
-
-    public static final int S_IRWXU = 00700;
-    public static final int S_IRUSR = 00400;
-    public static final int S_IWUSR = 00200;
-    public static final int S_IXUSR = 00100;
-
-    public static final int S_IRWXG = 00070;
-    public static final int S_IRGRP = 00040;
-    public static final int S_IWGRP = 00020;
-    public static final int S_IXGRP = 00010;
-
-    public static final int S_IRWXO = 00007;
-    public static final int S_IROTH = 00004;
-    public static final int S_IWOTH = 00002;
-    public static final int S_IXOTH = 00001;
-
-    static {
-        System.loadLibrary("ctssecurity_jni");
-    }
-
-    public static class FileStatus {
-
-        public int dev;
-        public int ino;
-        public int mode;
-        public int nlink;
-        public int uid;
-        public int gid;
-        public int rdev;
-        public long size;
-        public int blksize;
-        public long blocks;
-        public long atime;
-        public long mtime;
-        public long ctime;
-
-        public boolean hasModeFlag(int flag) {
-            if (((S_IRWXU | S_IRWXG | S_IRWXO) & flag) != flag) {
-                throw new IllegalArgumentException("Inappropriate flag " + flag);
-            }
-            return (mode & flag) == flag;
-        }
-
-        public boolean isOfType(int type) {
-            if ((type & S_IFMT) != type) {
-                throw new IllegalArgumentException("Unknown type " + type);
-            }
-            return (mode & S_IFMT) == type;
-        }
-    }
-
-    /**
-     * @param path of the file to stat
-     * @param status object to set the fields on
-     * @param statLinks or don't stat links (lstat vs stat)
-     * @return whether or not we were able to stat the file
-     */
-    public native static boolean getFileStatus(String path, FileStatus status, boolean statLinks);
-
-    public native static String getUserName(int uid);
-
-    public native static String getGroupName(int gid);
-
-    public native static int setPermissions(String file, int mode);
-
-    /**
-     * Copy data from a source stream to destFile.
-     * Return true if succeed, return false if failed.
-     */
-    public static boolean copyToFile(InputStream inputStream, File destFile) {
-        try {
-            if (destFile.exists()) {
-                destFile.delete();
-            }
-            FileOutputStream out = new FileOutputStream(destFile);
-            try {
-                byte[] buffer = new byte[4096];
-                int bytesRead;
-                while ((bytesRead = inputStream.read(buffer)) >= 0) {
-                    out.write(buffer, 0, bytesRead);
-                }
-            } finally {
-                out.flush();
-                try {
-                    out.getFD().sync();
-                } catch (IOException e) {
-                }
-                out.close();
-            }
-            return true;
-        } catch (IOException e) {
-            return false;
-        }
-    }
-
-    public static void createFile(File file, int numBytes) throws IOException {
-        File parentFile = file.getParentFile();
-        if (parentFile != null) {
-            parentFile.mkdirs();
-        }
-        byte[] buffer = new byte[numBytes];
-        FileOutputStream output = new FileOutputStream(file);
-        try {
-            output.write(buffer);
-        } finally {
-            output.close();
-        }
-    }
-
-    public static byte[] readInputStreamFully(InputStream is) {
-        ByteArrayOutputStream os = new ByteArrayOutputStream();
-        byte[] buffer = new byte[32768];
-        int count;
-        try {
-            while ((count = is.read(buffer)) != -1) {
-                os.write(buffer, 0, count);
-            }
-            is.close();
-        } catch (IOException e) {
-            throw new RuntimeException(e);
-        }
-        return os.toByteArray();
-    }
-}
diff --git a/tests/tests/security/src/android/security/cts/ReadElf.java b/tests/tests/security/src/android/security/cts/ReadElf.java
deleted file mode 100644
index a9a4e3c..0000000
--- a/tests/tests/security/src/android/security/cts/ReadElf.java
+++ /dev/null
@@ -1,523 +0,0 @@
-/*
- * 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.security.cts;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.RandomAccessFile;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * A poor man's implementation of the readelf command. This program is
- * designed to parse ELF (Executable and Linkable Format) files.
- */
-public class ReadElf implements AutoCloseable {
-    /** The magic values for the ELF identification. */
-    private static final byte[] ELF_IDENT = {
-            (byte) 0x7F, (byte) 'E', (byte) 'L', (byte) 'F',
-    };
-
-    private static final int EI_CLASS = 4;
-    private static final int EI_DATA = 5;
-
-    private static final int EM_386 = 3;
-    private static final int EM_MIPS = 8;
-    private static final int EM_ARM = 40;
-    // http://en.wikipedia.org/wiki/Qualcomm_Hexagon
-    private static final int EM_QDSP6 = 164;
-
-    /** Size of the e_ident[] structure in the ELF header. */
-    private static final int EI_NIDENT = 16;
-
-    /** Offset from end of ident structure in half-word sizes. */
-    private static final int OFFSET_TYPE = 0;
-
-    /** Machine type. */
-    private static final int OFFSET_MACHINE = 1;
-
-    /** ELF version. */
-    private static final int OFFSET_VERSION = 2;
-
-    /**
-     * The offset to which the system transfers control. e.g., the first thing
-     * executed.
-     */
-    private static final int OFFSET_ENTRY = 4;
-
-    /** Program header offset in bytes. */
-    private static final int OFFSET_PHOFF = 6;
-
-    /** Segment header offset in bytes. */
-    private static final int OFFSET_SHOFF = 8;
-
-    /** Processor-specific flags for binary. */
-    private static final int OFFSET_FLAGS = 10;
-
-    /** ELF header size in bytes. */
-    private static final int OFFSET_EHSIZE = 12;
-
-    /** All program headers entry size in bytes. */
-    private static final int OFFSET_PHENTSIZE = 13;
-
-    /** Number of program headers in ELF. */
-    private static final int OFFSET_PHNUM = 14;
-
-    /** All segment headers entry size in bytes. */
-    private static final int OFFSET_SHENTSIZE = 15;
-
-    /** Number of segment headers in ELF. */
-    private static final int OFFSET_SHNUM = 16;
-
-    /** The section header index that refers to string table. */
-    private static final int OFFSET_SHSTRNDX = 17;
-
-    /** Program header offset for type of this program header. */
-    private static final int PHOFF_TYPE = 0;
-
-    /** Program header offset for absolute offset in file. */
-    private static final int PHOFF_OFFSET = 2;
-
-    /** Program header offset for virtual address. */
-    private static final int PHOFF_VADDR = 4;
-
-    /** Program header offset for physical address. */
-    private static final int PHOFF_PADDR = 6;
-
-    /** Program header offset for file size in bytes. */
-    private static final int PHOFF_FILESZ = 8;
-
-    /** Program header offset for memory size in bytes. */
-    private static final int PHOFF_MEMSZ = 10;
-
-    /** Program header offset for flags. */
-    private static final int PHOFF_FLAGS = 12;
-
-    /**
-     * Program header offset for required alignment. 0 or 1 means no alignment
-     * necessary.
-     */
-    private static final int PHOFF_ALIGN = 14;
-
-    /** Index into string pool for segment name. */
-    private static final long SHOFF_NAME = 0;
-
-    /** Segment header offset for type (half-words) */
-    private static final long SHOFF_TYPE = 2;
-
-    /** Segment header offset for offset (meta!) (half-words) */
-    private static final long SHOFF_OFFSET = 8;
-
-    /** Segment header offset for size (half-words) */
-    private static final long SHOFF_SIZE = 10;
-
-    /** Data is presented in LSB format. */
-    private static final int ELFDATA2LSB = 1;
-
-    /** Date is presented in MSB format. */
-    private static final int ELFDATA2MSB = 2;
-
-    private static final int ELFCLASS32 = 1;
-
-    private static final int ELFCLASS64 = 2;
-
-    private static final long PT_LOAD = 1;
-
-    /** Section Type: Symbol Table */
-    private static final int SHT_SYMTAB = 2;
-
-    /** Section Type: String Table */
-    private static final int SHT_STRTAB = 3;
-
-    /** Section Type: Dynamic **/
-    private static final int SHT_DYNAMIC = 6;
-
-    /** Section Type: Dynamic Symbol Table */
-    private static final int SHT_DYNSYM = 11;
-
-    /** Symbol Table Entry: Name offset */
-    private static final int SYMTAB_NAME = 0;
-
-    /** Symbol Table Entry: SymTab Info */
-    private static final int SYMTAB_ST_INFO = 6;
-
-    /** Symbol Table Entry size (half-words) */
-    private static final int SYMTAB_ENTRY_HALFWORD_SIZE = 7;
-
-    /**
-     * Symbol Table Entry size (extra in bytes) to cover "st_info" and
-     * "st_other"
-     */
-    private static final int SYMTAB_ENTRY_BYTE_EXTRA_SIZE = 2;
-
-    public static class Symbol {
-        public static final int STB_LOCAL = 0;
-
-        public static final int STB_GLOBAL = 1;
-
-        public static final int STB_WEAK = 2;
-
-        public static final int STB_LOPROC = 13;
-
-        public static final int STB_HIPROC = 15;
-
-        public final String name;
-
-        public final int bind;
-
-        public final int type;
-
-        Symbol(String name, int st_info) {
-            this.name = name;
-            this.bind = (st_info >> 4) & 0x0F;
-            this.type = st_info & 0x0F;
-        }
-    };
-
-    private final String mPath;
-    private final RandomAccessFile mFile;
-    private final byte[] mBuffer = new byte[512];
-    private int mEndian;
-    private boolean mIsDynamic;
-    private boolean mIsPIE;
-    private int mType;
-    private int mWordSize;
-    private int mHalfWordSize;
-
-    /** Symbol Table offset */
-    private long mSymTabOffset;
-
-    /** Symbol Table size */
-    private long mSymTabSize;
-
-    /** Dynamic Symbol Table offset */
-    private long mDynSymOffset;
-
-    /** Dynamic Symbol Table size */
-    private long mDynSymSize;
-
-    /** Section Header String Table offset */
-    private long mShStrTabOffset;
-
-    /** Section Header String Table size */
-    private long mShStrTabSize;
-
-    /** String Table offset */
-    private long mStrTabOffset;
-
-    /** String Table size */
-    private long mStrTabSize;
-
-    /** Dynamic String Table offset */
-    private long mDynStrOffset;
-
-    /** Dynamic String Table size */
-    private long mDynStrSize;
-
-    /** Symbol Table symbol names */
-    private Map<String, Symbol> mSymbols;
-
-    /** Dynamic Symbol Table symbol names */
-    private Map<String, Symbol> mDynamicSymbols;
-
-    public static ReadElf read(File file) throws IOException {
-        return new ReadElf(file);
-    }
-
-    public boolean isDynamic() {
-        return mIsDynamic;
-    }
-
-    public int getType() {
-        return mType;
-    }
-
-    public boolean isPIE() {
-        return mIsPIE;
-    }
-
-    private ReadElf(File file) throws IOException {
-        mPath = file.getPath();
-        mFile = new RandomAccessFile(file, "r");
-
-        if (mFile.length() < EI_NIDENT) {
-            throw new IllegalArgumentException("Too small to be an ELF file: " + file);
-        }
-
-        readIdent();
-        readHeader();
-    }
-
-    public void close() {
-        try {
-            mFile.close();
-        } catch (IOException ignored) {
-        }
-    }
-
-    protected void finalize() throws Throwable {
-        try {
-            close();
-        } finally {
-            super.finalize();
-        }
-    }
-
-    private void readHeader() throws IOException {
-        mType = readHalf(getHeaderOffset(OFFSET_TYPE));
-        int e_machine = readHalf(getHeaderOffset(OFFSET_MACHINE));
-        if (e_machine != EM_386 && e_machine != EM_MIPS && e_machine != EM_ARM &&
-                e_machine != EM_QDSP6) {
-            throw new IOException("Invalid ELF e_machine: " + e_machine + ": " + mPath);
-        }
-
-        final long shOffset = readWord(getHeaderOffset(OFFSET_SHOFF));
-        final int shNumber = readHalf(getHeaderOffset(OFFSET_SHNUM));
-        final int shSize = readHalf(getHeaderOffset(OFFSET_SHENTSIZE));
-        final int shStrIndex = readHalf(getHeaderOffset(OFFSET_SHSTRNDX));
-
-        readSectionHeaders(shOffset, shNumber, shSize, shStrIndex);
-
-        final long phOffset = readWord(getHeaderOffset(OFFSET_PHOFF));
-        final int phNumber = readHalf(getHeaderOffset(OFFSET_PHNUM));
-        final int phSize = readHalf(getHeaderOffset(OFFSET_PHENTSIZE));
-
-        readProgramHeaders(phOffset, phNumber, phSize);
-    }
-
-    private void readSectionHeaders(long tableOffset, int shNumber, int shSize, int shStrIndex)
-            throws IOException {
-        // Read the Section Header String Table offset first.
-        {
-            final long shStrTabShOffset = tableOffset + shStrIndex * shSize;
-            final long type = readWord(shStrTabShOffset + mHalfWordSize * SHOFF_TYPE);
-
-            if (type == SHT_STRTAB) {
-                mShStrTabOffset = readWord(shStrTabShOffset + mHalfWordSize * SHOFF_OFFSET);
-                mShStrTabSize = readWord(shStrTabShOffset + mHalfWordSize * SHOFF_SIZE);
-            }
-        }
-
-        for (int i = 0; i < shNumber; i++) {
-            // Don't bother to re-read the Section Header StrTab.
-            if (i == shStrIndex) {
-                continue;
-            }
-
-            final long shOffset = tableOffset + i * shSize;
-
-            final long type = readWord(shOffset + mHalfWordSize * SHOFF_TYPE);
-            if ((type == SHT_SYMTAB) || (type == SHT_DYNSYM)) {
-                final long nameOffset = readWord(shOffset + mHalfWordSize * SHOFF_NAME);
-                final long offset = readWord(shOffset + mHalfWordSize * SHOFF_OFFSET);
-                final long size = readWord(shOffset + mHalfWordSize * SHOFF_SIZE);
-
-                final String symTabName = readShStrTabEntry(nameOffset);
-                if (".symtab".equals(symTabName)) {
-                    mSymTabOffset = offset;
-                    mSymTabSize = size;
-                } else if (".dynsym".equals(symTabName)) {
-                    mDynSymOffset = offset;
-                    mDynSymSize = size;
-                }
-            } else if (type == SHT_STRTAB) {
-                final long nameOffset = readWord(shOffset + mHalfWordSize * SHOFF_NAME);
-                final long offset = readWord(shOffset + mHalfWordSize * SHOFF_OFFSET);
-                final long size = readWord(shOffset + mHalfWordSize * SHOFF_SIZE);
-
-                final String strTabName = readShStrTabEntry(nameOffset);
-                if (".strtab".equals(strTabName)) {
-                    mStrTabOffset = offset;
-                    mStrTabSize = size;
-                } else if (".dynstr".equals(strTabName)) {
-                    mDynStrOffset = offset;
-                    mDynStrSize = size;
-                }
-            } else if (type == SHT_DYNAMIC) {
-                mIsDynamic = true;
-            }
-        }
-    }
-
-    private void readProgramHeaders(long phOffset, int phNumber, int phSize) throws IOException {
-        for (int i = 0; i < phNumber; i++) {
-            final long baseOffset = phOffset + i * phSize;
-            final long type = readWord(baseOffset);
-            if (type == PT_LOAD) {
-                final long virtAddress = readWord(baseOffset + mHalfWordSize * PHOFF_VADDR);
-                if (virtAddress == 0) {
-                    mIsPIE = true;
-                }
-            }
-        }
-    }
-
-    private void readSymbolTable(Map<String, Symbol> symbolMap, long symStrOffset, long symStrSize,
-            long symOffset, long symSize) throws IOException {
-        final long symEnd = symOffset + symSize;
-        for (long off = symOffset; off < symEnd; off += SYMTAB_ENTRY_HALFWORD_SIZE * mHalfWordSize
-                + SYMTAB_ENTRY_BYTE_EXTRA_SIZE) {
-            long strOffset = readWord(off + SYMTAB_NAME);
-            if (strOffset == 0) {
-                continue;
-            }
-
-            final String symName = readStrTabEntry(symStrOffset, symStrSize, strOffset);
-            if (symName != null) {
-                final int st_info = readByte(off + SYMTAB_ST_INFO);
-                symbolMap.put(symName, new Symbol(symName, st_info));
-            }
-        }
-    }
-
-    private String readShStrTabEntry(long strOffset) throws IOException {
-        if ((mShStrTabOffset == 0) || (strOffset < 0) || (strOffset >= mShStrTabSize)) {
-            return null;
-        }
-
-        return readString(mShStrTabOffset + strOffset);
-    }
-
-    private String readStrTabEntry(long tableOffset, long tableSize, long strOffset)
-            throws IOException {
-        if ((tableOffset == 0) || (strOffset < 0) || (strOffset >= tableSize)) {
-            return null;
-        }
-
-        return readString(tableOffset + strOffset);
-    }
-
-    private int getHeaderOffset(int halfWorldOffset) {
-        return EI_NIDENT + halfWorldOffset * mHalfWordSize;
-    }
-
-    private int readByte(long offset) throws IOException {
-        mFile.seek(offset);
-        mFile.readFully(mBuffer, 0, 1);
-
-        return mBuffer[0] & 0xff;
-    }
-
-    private int readHalf(long offset) throws IOException {
-        mFile.seek(offset);
-        mFile.readFully(mBuffer, 0, mWordSize);
-
-        final int answer;
-        if (mEndian == ELFDATA2LSB) {
-            answer = mBuffer[1] << 8 | (mBuffer[0] & 0xff);
-        } else {
-            answer = mBuffer[0] << 8 | (mBuffer[1] & 0xff);
-        }
-
-        return answer;
-    }
-
-    private long readWord(long offset) throws IOException {
-        mFile.seek(offset);
-        mFile.readFully(mBuffer, 0, mWordSize);
-
-        int answer = 0;
-        if (mEndian == ELFDATA2LSB) {
-            for (int i = mWordSize - 1; i >= 0; i--) {
-                answer = (answer << 8) | (mBuffer[i] & 0xff);
-            }
-        } else {
-            final int N = mWordSize - 1;
-            for (int i = 0; i <= N; i++) {
-                answer = (answer << 8) | (mBuffer[i] & 0xff);
-            }
-        }
-
-        return answer;
-    }
-
-    private String readString(long offset) throws IOException {
-        mFile.seek(offset);
-        mFile.readFully(mBuffer, 0, (int) Math.min(mBuffer.length, mFile.length() - offset));
-
-        for (int i = 0; i < mBuffer.length; i++) {
-            if (mBuffer[i] == 0) {
-                return new String(mBuffer, 0, i);
-            }
-        }
-
-        return null;
-    }
-
-    private void readIdent() throws IOException {
-        mFile.seek(0);
-        mFile.readFully(mBuffer, 0, EI_NIDENT);
-
-        if ((mBuffer[0] != ELF_IDENT[0]) || (mBuffer[1] != ELF_IDENT[1])
-                || (mBuffer[2] != ELF_IDENT[2]) || (mBuffer[3] != ELF_IDENT[3])) {
-            throw new IllegalArgumentException("Invalid ELF file: " + mPath);
-        }
-
-        int elfClass = mBuffer[EI_CLASS];
-        if (elfClass == ELFCLASS32) {
-            mWordSize = 4;
-            mHalfWordSize = 2;
-        } else if (elfClass == ELFCLASS64) {
-            throw new IOException("Unsupported ELFCLASS64 file: " + mPath);
-        } else {
-            throw new IOException("Invalid ELF EI_CLASS: " + elfClass + ": " + mPath);
-        }
-
-        mEndian = mBuffer[EI_DATA];
-        if (mEndian == ELFDATA2LSB) {
-        } else if (mEndian == ELFDATA2MSB) {
-            throw new IOException("Unsupported ELFDATA2MSB file: " + mPath);
-        } else {
-            throw new IOException("Invalid ELF EI_DATA: " + mEndian + ": " + mPath);
-        }
-    }
-
-    public Symbol getSymbol(String name) {
-        if ((mSymTabOffset == 0) && (mSymTabSize == 0)) {
-            return null;
-        }
-
-        if (mSymbols == null) {
-            mSymbols = new HashMap<String, Symbol>();
-            try {
-                readSymbolTable(mSymbols, mStrTabOffset, mStrTabSize, mSymTabOffset, mSymTabSize);
-            } catch (IOException e) {
-                return null;
-            }
-        }
-
-        return mSymbols.get(name);
-    }
-
-    public Symbol getDynamicSymbol(String name) {
-        if ((mDynSymOffset == 0) && (mDynSymSize == 0)) {
-            return null;
-        }
-
-        if (mDynamicSymbols == null) {
-            mDynamicSymbols = new HashMap<String, Symbol>();
-            try {
-                readSymbolTable(mDynamicSymbols, mDynStrOffset, mDynStrSize, mDynSymOffset,
-                        mDynSymSize);
-            } catch (IOException e) {
-                return null;
-            }
-        }
-
-        return mDynamicSymbols.get(name);
-    }
-}
diff --git a/tests/tests/telephony/Android.mk b/tests/tests/telephony/Android.mk
index e15d0d5..85864f9 100644
--- a/tests/tests/telephony/Android.mk
+++ b/tests/tests/telephony/Android.mk
@@ -24,7 +24,7 @@
 
 LOCAL_JAVA_LIBRARIES := telephony-common
 
-LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner
+LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner ctsdeviceutil
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
diff --git a/tests/tests/telephony/src/android/telephony/cts/CellLocationTest.java b/tests/tests/telephony/src/android/telephony/cts/CellLocationTest.java
index 00c9844..c1f5757 100644
--- a/tests/tests/telephony/src/android/telephony/cts/CellLocationTest.java
+++ b/tests/tests/telephony/src/android/telephony/cts/CellLocationTest.java
@@ -17,6 +17,8 @@
 
 
 import android.content.Context;
+import android.cts.util.ReadElf;
+import android.cts.util.TestThread;
 import android.os.Looper;
 import android.net.ConnectivityManager;
 import android.telephony.CellLocation;
diff --git a/tests/tests/telephony/src/android/telephony/cts/PhoneStateListenerTest.java b/tests/tests/telephony/src/android/telephony/cts/PhoneStateListenerTest.java
index 9d8f842..f0f977a 100644
--- a/tests/tests/telephony/src/android/telephony/cts/PhoneStateListenerTest.java
+++ b/tests/tests/telephony/src/android/telephony/cts/PhoneStateListenerTest.java
@@ -16,6 +16,8 @@
 package android.telephony.cts;
 
 import android.content.Context;
+import android.cts.util.ReadElf;
+import android.cts.util.TestThread;
 import android.os.Looper;
 import android.telephony.CellLocation;
 import android.telephony.PhoneStateListener;
diff --git a/tests/tests/telephony/src/android/telephony/cts/TelephonyManagerTest.java b/tests/tests/telephony/src/android/telephony/cts/TelephonyManagerTest.java
index b9c720c..8575c32 100644
--- a/tests/tests/telephony/src/android/telephony/cts/TelephonyManagerTest.java
+++ b/tests/tests/telephony/src/android/telephony/cts/TelephonyManagerTest.java
@@ -19,6 +19,8 @@
 import android.bluetooth.BluetoothAdapter;
 import android.content.Context;
 import android.content.pm.PackageManager;
+import android.cts.util.ReadElf;
+import android.cts.util.TestThread;
 import android.net.ConnectivityManager;
 import android.net.wifi.WifiInfo;
 import android.net.wifi.WifiManager;
@@ -86,13 +88,11 @@
                     }
                 };
                 mTelephonyManager.listen(mListener, PhoneStateListener.LISTEN_CELL_LOCATION);
-
+                CellLocation.requestLocationUpdate();
                 Looper.loop();
             }
         });
         t.start();
-
-        CellLocation.requestLocationUpdate();
         synchronized (mLock) {
             while (!mOnCellLocationChangedCalled) {
                 mLock.wait();
@@ -104,24 +104,21 @@
         t = new TestThread(new Runnable() {
             public void run() {
                 Looper.prepare();
-
                 // unregister the listener
                 mTelephonyManager.listen(mListener, PhoneStateListener.LISTEN_NONE);
                 mOnCellLocationChangedCalled = false;
                 // unregister again, to make sure doing so does not call the listener
                 mTelephonyManager.listen(mListener, PhoneStateListener.LISTEN_NONE);
-
+                CellLocation.requestLocationUpdate();
                 Looper.loop();
             }
         });
-        t.start();
 
-        CellLocation.requestLocationUpdate();
+        t.start();
         synchronized (mLock) {
             mLock.wait(TOLERANCE);
         }
-        //Fix me: unregister for listener is not support today. Will be added soon
-        //assertFalse(mOnCellLocationChangedCalled);
+        assertFalse(mOnCellLocationChangedCalled);
     }
 
     /**
diff --git a/tests/tests/text/Android.mk b/tests/tests/text/Android.mk
index df2d324..7b2def1 100644
--- a/tests/tests/text/Android.mk
+++ b/tests/tests/text/Android.mk
@@ -23,7 +23,7 @@
 
 LOCAL_JAVA_LIBRARIES := android.test.runner
 
-LOCAL_STATIC_JAVA_LIBRARIES := ctsdeviceutil ctstestrunner
+LOCAL_STATIC_JAVA_LIBRARIES := ctsdeviceutil ctsdeviceutillegacy ctstestrunner
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
diff --git a/tests/tests/text/src/android/text/cts/EmojiCtsActivity.java b/tests/tests/text/src/android/text/cts/EmojiCtsActivity.java
index eb88426..195bdf1 100644
--- a/tests/tests/text/src/android/text/cts/EmojiCtsActivity.java
+++ b/tests/tests/text/src/android/text/cts/EmojiCtsActivity.java
@@ -20,6 +20,7 @@
 
 import android.app.Activity;
 import android.os.Bundle;
+import android.cts.util.NullWebViewUtils;
 import android.webkit.WebView;
 
 public class EmojiCtsActivity extends Activity {
diff --git a/tests/tests/text/src/android/text/cts/EmojiTest.java b/tests/tests/text/src/android/text/cts/EmojiTest.java
index b753739..e1249f3 100644
--- a/tests/tests/text/src/android/text/cts/EmojiTest.java
+++ b/tests/tests/text/src/android/text/cts/EmojiTest.java
@@ -17,6 +17,7 @@
 package android.text.cts;
 
 import android.content.Context;
+import android.cts.util.NullWebViewUtils;
 import android.graphics.Bitmap;
 import android.graphics.Canvas;
 import android.graphics.Paint;
@@ -27,6 +28,7 @@
 import android.view.View;
 import android.widget.TextView;
 import android.widget.EditText;
+import android.webkit.cts.WebViewOnUiThread;
 
 public class EmojiTest extends ActivityInstrumentationTestCase2<EmojiCtsActivity> {
 
diff --git a/tests/tests/text/src/android/text/cts/NullWebViewUtils.java b/tests/tests/text/src/android/text/cts/NullWebViewUtils.java
deleted file mode 100644
index 86d0843..0000000
--- a/tests/tests/text/src/android/text/cts/NullWebViewUtils.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright (C) 2010 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.text.cts;
-
-import android.content.Context;
-import android.content.pm.PackageManager;
-
-/**
- * Utilities to enable the android.webkit.* CTS tests (and others that rely on a functioning
- * android.webkit.WebView implementation) to determine whether a functioning WebView is present
- * on the device or not.
- *
- * Test cases that require android.webkit.* classes should wrap their first usage of WebView in a
- * try catch block, and pass any exception that is thrown to
- * NullWebViewUtils.determineIfWebViewAvailable. The return value of
- * NullWebViewUtils.isWebViewAvailable will then determine if the test should expect to be able to
- * use a WebView.
- */
-public class NullWebViewUtils {
-
-    private static boolean sWebViewUnavailable;
-
-    /**
-     * @param context Current Activity context, used to query the PackageManager.
-     * @param t       An exception thrown by trying to invoke android.webkit.* APIs.
-     */
-    public static void determineIfWebViewAvailable(Context context, Throwable t) {
-        sWebViewUnavailable = !hasWebViewFeature(context) && checkCauseWasUnsupportedOperation(t);
-    }
-
-    /**
-     * After calling determineIfWebViewAvailable, this returns whether a WebView is available on the
-     * device and wheter the test can rely on it.
-     * @return True iff. PackageManager determined that there is no WebView on the device and the
-     *         exception thrown from android.webkit.* was UnsupportedOperationException.
-     */
-    public static boolean isWebViewAvailable() {
-        return !sWebViewUnavailable;
-    }
-
-    private static boolean hasWebViewFeature(Context context) {
-        // Query the system property that determins if there is a functional WebView on the device.
-        PackageManager pm = context.getPackageManager();
-        return pm.hasSystemFeature(PackageManager.FEATURE_WEBVIEW);
-    }
-
-    private static boolean checkCauseWasUnsupportedOperation(Throwable t) {
-        if (t == null) return false;
-        while (t.getCause() != null) {
-            t = t.getCause();
-        }
-        return t instanceof UnsupportedOperationException;
-    }
-
-    /**
-     * Some CTS tests (by design) first use android.webkit.* from a background thread. This helper
-     * allows the test to catch the UnsupportedOperationException from that background thread, and
-     * then query the result from the test main thread.
-     */
-    public static class NullWebViewFromThreadExceptionHandler
-            implements Thread.UncaughtExceptionHandler {
-        private Throwable mPendingException;
-
-        @Override
-        public void uncaughtException(Thread t, Throwable e) {
-            mPendingException = e;
-        }
-
-        public boolean isWebViewAvailable(Context context) {
-            return hasWebViewFeature(context) ||
-                    !checkCauseWasUnsupportedOperation(mPendingException);
-        }
-    }
-}
\ No newline at end of file
diff --git a/tests/tests/text/src/android/text/cts/WebViewOnUiThread.java b/tests/tests/text/src/android/text/cts/WebViewOnUiThread.java
deleted file mode 100644
index 3d62ce4..0000000
--- a/tests/tests/text/src/android/text/cts/WebViewOnUiThread.java
+++ /dev/null
@@ -1,980 +0,0 @@
-/*
- * Copyright (C) 2011 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.text.cts;
-
-import android.cts.util.PollingCheck;
-import android.graphics.Bitmap;
-import android.graphics.Picture;
-import android.graphics.Rect;
-import android.os.Bundle;
-import android.os.Looper;
-import android.os.Message;
-import android.os.SystemClock;
-import android.print.PrintDocumentAdapter;
-import android.test.InstrumentationTestCase;
-import android.util.DisplayMetrics;
-import android.view.View;
-import android.view.ViewGroup;
-import android.view.ViewParent;
-import android.webkit.DownloadListener;
-import android.webkit.CookieManager;
-import android.webkit.ValueCallback;
-import android.webkit.WebBackForwardList;
-import android.webkit.WebChromeClient;
-import android.webkit.WebSettings;
-import android.webkit.WebView.HitTestResult;
-import android.webkit.WebView.PictureListener;
-import android.webkit.WebView;
-import android.webkit.WebViewClient;
-
-import junit.framework.Assert;
-
-import java.io.File;
-import java.util.concurrent.Callable;
-import java.util.Map;
-
-/**
- * Many tests need to run WebView code in the UI thread. This class
- * wraps a WebView so that calls are ensured to arrive on the UI thread.
- *
- * All methods may be run on either the UI thread or test thread.
- */
-public class WebViewOnUiThread {
-    /**
-     * The maximum time, in milliseconds (10 seconds) to wait for a load
-     * to be triggered.
-     */
-    private static final long LOAD_TIMEOUT = 10000;
-
-    /**
-     * Set to true after onPageFinished is called.
-     */
-    private boolean mLoaded;
-
-    /**
-     * Set to true after onNewPicture is called. Reset when onPageStarted
-     * is called.
-     */
-    private boolean mNewPicture;
-
-    /**
-     * The progress, in percentage, of the page load. Valid values are between
-     * 0 and 100.
-     */
-    private int mProgress;
-
-    /**
-     * The test that this class is being used in. Used for runTestOnUiThread.
-     */
-    private InstrumentationTestCase mTest;
-
-    /**
-     * The WebView that calls will be made on.
-     */
-    private WebView mWebView;
-
-    /**
-     * Initializes the webView with a WebViewClient, WebChromeClient,
-     * and PictureListener to prepare for loadUrlAndWaitForCompletion.
-     *
-     * A new WebViewOnUiThread should be called during setUp so as to
-     * reinitialize between calls.
-     *
-     * @param test The test in which this is being run.
-     * @param webView The webView that the methods should call.
-     * @see loadUrlAndWaitForCompletion
-     */
-    public WebViewOnUiThread(InstrumentationTestCase test, WebView webView) {
-        mTest = test;
-        mWebView = webView;
-        final WebViewClient webViewClient = new WaitForLoadedClient(this);
-        final WebChromeClient webChromeClient = new WaitForProgressClient(this);
-        runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                mWebView.setWebViewClient(webViewClient);
-                mWebView.setWebChromeClient(webChromeClient);
-                mWebView.setPictureListener(new WaitForNewPicture());
-            }
-        });
-    }
-
-    /**
-     * Called after a test is complete and the WebView should be disengaged from
-     * the tests.
-     */
-    public void cleanUp() {
-        clearHistory();
-        clearCache(true);
-        setPictureListener(null);
-        setWebChromeClient(null);
-        setWebViewClient(null);
-    }
-
-    /**
-     * Called from WaitForNewPicture, this is used to indicate that
-     * the page has been drawn.
-     */
-    synchronized public void onNewPicture() {
-        mNewPicture = true;
-        this.notifyAll();
-    }
-
-    /**
-     * Called from WaitForLoadedClient, this is used to clear the picture
-     * draw state so that draws before the URL begins loading don't count.
-     */
-    synchronized public void onPageStarted() {
-        mNewPicture = false; // Earlier paints won't count.
-    }
-
-    /**
-     * Called from WaitForLoadedClient, this is used to indicate that
-     * the page is loaded, but not drawn yet.
-     */
-    synchronized public void onPageFinished() {
-        mLoaded = true;
-        this.notifyAll();
-    }
-
-    /**
-     * Called from the WebChrome client, this sets the current progress
-     * for a page.
-     * @param progress The progress made so far between 0 and 100.
-     */
-    synchronized public void onProgressChanged(int progress) {
-        mProgress = progress;
-        this.notifyAll();
-    }
-
-    public void setWebViewClient(final WebViewClient webViewClient) {
-        runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                mWebView.setWebViewClient(webViewClient);
-            }
-        });
-    }
-
-    public void setWebChromeClient(final WebChromeClient webChromeClient) {
-        runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                mWebView.setWebChromeClient(webChromeClient);
-            }
-        });
-    }
-
-    public void setPictureListener(final PictureListener pictureListener) {
-        runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                mWebView.setPictureListener(pictureListener);
-            }
-        });
-    }
-
-    public void setNetworkAvailable(final boolean available) {
-        runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                mWebView.setNetworkAvailable(available);
-            }
-        });
-    }
-
-    public void setDownloadListener(final DownloadListener listener) {
-        runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                mWebView.setDownloadListener(listener);
-            }
-        });
-    }
-
-    public void setBackgroundColor(final int color) {
-        runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                mWebView.setBackgroundColor(color);
-            }
-        });
-    }
-
-    public void clearCache(final boolean includeDiskFiles) {
-        runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                mWebView.clearCache(includeDiskFiles);
-            }
-        });
-    }
-
-    public void clearHistory() {
-        runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                mWebView.clearHistory();
-            }
-        });
-    }
-
-    public void requestFocus() {
-        runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                mWebView.requestFocus();
-            }
-        });
-    }
-
-    public boolean canZoomIn() {
-        return getValue(new ValueGetter<Boolean>() {
-            @Override
-            public Boolean capture() {
-                return mWebView.canZoomIn();
-            }
-        });
-    }
-
-    public boolean zoomIn() {
-        return getValue(new ValueGetter<Boolean>() {
-            @Override
-            public Boolean capture() {
-                return mWebView.zoomIn();
-            }
-        });
-    }
-
-    public boolean zoomOut() {
-        return getValue(new ValueGetter<Boolean>() {
-            @Override
-            public Boolean capture() {
-                return mWebView.zoomOut();
-            }
-        });
-    }
-
-    public void setFindListener(final WebView.FindListener listener) {
-        runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                mWebView.setFindListener(listener);
-            }
-        });
-    }
-
-    public void removeJavascriptInterface(final String interfaceName) {
-        runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                mWebView.removeJavascriptInterface(interfaceName);
-            }
-        });
-    }
-
-    public void addJavascriptInterface(final Object object, final String name) {
-        runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                mWebView.addJavascriptInterface(object, name);
-            }
-        });
-    }
-
-    public void flingScroll(final int vx, final int vy) {
-        runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                mWebView.flingScroll(vx, vy);
-            }
-        });
-    }
-
-    public void requestFocusNodeHref(final Message hrefMsg) {
-        runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                mWebView.requestFocusNodeHref(hrefMsg);
-            }
-        });
-    }
-
-    public void requestImageRef(final Message msg) {
-        runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                mWebView.requestImageRef(msg);
-            }
-        });
-    }
-
-    public void setInitialScale(final int scaleInPercent) {
-        runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                mWebView.setInitialScale(scaleInPercent);
-            }
-        });
-    }
-
-    public void clearSslPreferences() {
-        runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                mWebView.clearSslPreferences();
-            }
-        });
-    }
-
-    public void clearClientCertPreferences(final Runnable onCleared) {
-        runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                WebView.clearClientCertPreferences(onCleared);
-            }
-        });
-    }
-
-    public void resumeTimers() {
-        runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                mWebView.resumeTimers();
-            }
-        });
-    }
-
-    public void findNext(final boolean forward) {
-        runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                mWebView.findNext(forward);
-            }
-        });
-    }
-
-    public void clearMatches() {
-        runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                mWebView.clearMatches();
-            }
-        });
-    }
-
-    /**
-     * Calls loadUrl on the WebView and then waits onPageFinished,
-     * onNewPicture and onProgressChange to reach 100.
-     * Test fails if the load timeout elapses.
-     * @param url The URL to load.
-     */
-    public void loadUrlAndWaitForCompletion(final String url) {
-        callAndWait(new Runnable() {
-            @Override
-            public void run() {
-                mWebView.loadUrl(url);
-            }
-        });
-    }
-
-    /**
-     * Calls loadUrl on the WebView and then waits onPageFinished,
-     * onNewPicture and onProgressChange to reach 100.
-     * Test fails if the load timeout elapses.
-     * @param url The URL to load.
-     * @param extraHeaders The additional headers to be used in the HTTP request.
-     */
-    public void loadUrlAndWaitForCompletion(final String url,
-            final Map<String, String> extraHeaders) {
-        callAndWait(new Runnable() {
-            @Override
-            public void run() {
-                mWebView.loadUrl(url, extraHeaders);
-            }
-        });
-    }
-
-    public void loadUrl(final String url) {
-        runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                mWebView.loadUrl(url);
-            }
-        });
-    }
-
-    public void stopLoading() {
-        runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                mWebView.stopLoading();
-            }
-        });
-    }
-
-    public void postUrlAndWaitForCompletion(final String url, final byte[] postData) {
-        callAndWait(new Runnable() {
-            @Override
-            public void run() {
-                mWebView.postUrl(url, postData);
-            }
-        });
-    }
-
-    public void loadDataAndWaitForCompletion(final String data,
-            final String mimeType, final String encoding) {
-        callAndWait(new Runnable() {
-            @Override
-            public void run() {
-                mWebView.loadData(data, mimeType, encoding);
-            }
-        });
-    }
-
-    public void loadDataWithBaseURLAndWaitForCompletion(final String baseUrl,
-            final String data, final String mimeType, final String encoding,
-            final String historyUrl) {
-        callAndWait(new Runnable() {
-            @Override
-            public void run() {
-                mWebView.loadDataWithBaseURL(baseUrl, data, mimeType, encoding,
-                        historyUrl);
-            }
-        });
-    }
-
-    /**
-     * Reloads a page and waits for it to complete reloading. Use reload
-     * if it is a form resubmission and the onFormResubmission responds
-     * by telling WebView not to resubmit it.
-     */
-    public void reloadAndWaitForCompletion() {
-        callAndWait(new Runnable() {
-            @Override
-            public void run() {
-                mWebView.reload();
-            }
-        });
-    }
-
-    /**
-     * Reload the previous URL. Use reloadAndWaitForCompletion unless
-     * it is a form resubmission and the onFormResubmission responds
-     * by telling WebView not to resubmit it.
-     */
-    public void reload() {
-        runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                mWebView.reload();
-            }
-        });
-    }
-
-    /**
-     * Use this only when JavaScript causes a page load to wait for the
-     * page load to complete. Otherwise use loadUrlAndWaitForCompletion or
-     * similar functions.
-     */
-    public void waitForLoadCompletion() {
-        waitForCriteria(LOAD_TIMEOUT,
-                new Callable<Boolean>() {
-                    @Override
-                    public Boolean call() {
-                        return isLoaded();
-                    }
-                });
-        clearLoad();
-    }
-
-    private void waitForCriteria(long timeout, Callable<Boolean> doneCriteria) {
-        if (isUiThread()) {
-            waitOnUiThread(timeout, doneCriteria);
-        } else {
-            waitOnTestThread(timeout, doneCriteria);
-        }
-    }
-
-    public String getTitle() {
-        return getValue(new ValueGetter<String>() {
-            @Override
-            public String capture() {
-                return mWebView.getTitle();
-            }
-        });
-    }
-
-    public WebSettings getSettings() {
-        return getValue(new ValueGetter<WebSettings>() {
-            @Override
-            public WebSettings capture() {
-                return mWebView.getSettings();
-            }
-        });
-    }
-
-    public WebBackForwardList copyBackForwardList() {
-        return getValue(new ValueGetter<WebBackForwardList>() {
-            @Override
-            public WebBackForwardList capture() {
-                return mWebView.copyBackForwardList();
-            }
-        });
-    }
-
-    public Bitmap getFavicon() {
-        return getValue(new ValueGetter<Bitmap>() {
-            @Override
-            public Bitmap capture() {
-                return mWebView.getFavicon();
-            }
-        });
-    }
-
-    public String getUrl() {
-        return getValue(new ValueGetter<String>() {
-            @Override
-            public String capture() {
-                return mWebView.getUrl();
-            }
-        });
-    }
-
-    public int getProgress() {
-        return getValue(new ValueGetter<Integer>() {
-            @Override
-            public Integer capture() {
-                return mWebView.getProgress();
-            }
-        });
-    }
-
-    public int getHeight() {
-        return getValue(new ValueGetter<Integer>() {
-            @Override
-            public Integer capture() {
-                return mWebView.getHeight();
-            }
-        });
-    }
-
-    public int getContentHeight() {
-        return getValue(new ValueGetter<Integer>() {
-            @Override
-            public Integer capture() {
-                return mWebView.getContentHeight();
-            }
-        });
-    }
-
-    public boolean savePicture(final Bundle b, final File dest) {
-        return getValue(new ValueGetter<Boolean>() {
-            @Override
-            public Boolean capture() {
-                return mWebView.savePicture(b, dest);
-            }
-        });
-    }
-
-    public boolean pageUp(final boolean top) {
-        return getValue(new ValueGetter<Boolean>() {
-            @Override
-            public Boolean capture() {
-                return mWebView.pageUp(top);
-            }
-        });
-    }
-
-    public boolean pageDown(final boolean bottom) {
-        return getValue(new ValueGetter<Boolean>() {
-            @Override
-            public Boolean capture() {
-                return mWebView.pageDown(bottom);
-            }
-        });
-    }
-
-    public int[] getLocationOnScreen() {
-        final int[] location = new int[2];
-        return getValue(new ValueGetter<int[]>() {
-            @Override
-            public int[] capture() {
-                mWebView.getLocationOnScreen(location);
-                return location;
-            }
-        });
-    }
-
-    public float getScale() {
-        return getValue(new ValueGetter<Float>() {
-            @Override
-            public Float capture() {
-                return mWebView.getScale();
-            }
-        });
-    }
-
-    public boolean requestFocus(final int direction,
-            final Rect previouslyFocusedRect) {
-        return getValue(new ValueGetter<Boolean>() {
-            @Override
-            public Boolean capture() {
-                return mWebView.requestFocus(direction, previouslyFocusedRect);
-            }
-        });
-    }
-
-    public HitTestResult getHitTestResult() {
-        return getValue(new ValueGetter<HitTestResult>() {
-            @Override
-            public HitTestResult capture() {
-                return mWebView.getHitTestResult();
-            }
-        });
-    }
-
-    public int getScrollX() {
-        return getValue(new ValueGetter<Integer>() {
-            @Override
-            public Integer capture() {
-                return mWebView.getScrollX();
-            }
-        });
-    }
-
-    public int getScrollY() {
-        return getValue(new ValueGetter<Integer>() {
-            @Override
-            public Integer capture() {
-                return mWebView.getScrollY();
-            }
-        });
-    }
-
-    public final DisplayMetrics getDisplayMetrics() {
-        return getValue(new ValueGetter<DisplayMetrics>() {
-            @Override
-            public DisplayMetrics capture() {
-                return mWebView.getContext().getResources().getDisplayMetrics();
-            }
-        });
-    }
-
-    public boolean requestChildRectangleOnScreen(final View child,
-            final Rect rect,
-            final boolean immediate) {
-        return getValue(new ValueGetter<Boolean>() {
-            @Override
-            public Boolean capture() {
-                return mWebView.requestChildRectangleOnScreen(child, rect,
-                        immediate);
-            }
-        });
-    }
-
-    public int findAll(final String find) {
-        return getValue(new ValueGetter<Integer>() {
-            @Override
-            public Integer capture() {
-                return mWebView.findAll(find);
-            }
-        });
-    }
-
-    public Picture capturePicture() {
-        return getValue(new ValueGetter<Picture>() {
-            @Override
-            public Picture capture() {
-                return mWebView.capturePicture();
-            }
-        });
-    }
-
-    public void evaluateJavascript(final String script, final ValueCallback<String> result) {
-        runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                mWebView.evaluateJavascript(script, result);
-            }
-        });
-    }
-
-    public WebView createWebView() {
-        return getValue(new ValueGetter<WebView>() {
-            @Override
-            public WebView capture() {
-                return new WebView(mWebView.getContext());
-            }
-        });
-    }
-
-    public PrintDocumentAdapter createPrintDocumentAdapter() {
-        return getValue(new ValueGetter<PrintDocumentAdapter>() {
-            @Override
-            public PrintDocumentAdapter capture() {
-                return mWebView.createPrintDocumentAdapter();
-            }
-        });
-    }
-
-    public void setLayoutHeightToMatchParent() {
-        runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                ViewParent parent = mWebView.getParent();
-                if (parent instanceof ViewGroup) {
-                    ((ViewGroup) parent).getLayoutParams().height =
-                        ViewGroup.LayoutParams.MATCH_PARENT;
-                }
-                mWebView.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT;
-                mWebView.requestLayout();
-            }
-        });
-    }
-
-    public void setAcceptThirdPartyCookies(final boolean accept) {
-        runOnUiThread(new Runnable() {
-            @Override
-            public void run() {
-                CookieManager.getInstance().setAcceptThirdPartyCookies(mWebView, accept);
-            }
-        });
-    }
-
-    public boolean acceptThirdPartyCookies() {
-        return getValue(new ValueGetter<Boolean>() {
-            @Override
-            public Boolean capture() {
-                return CookieManager.getInstance().acceptThirdPartyCookies(mWebView);
-            }
-        });
-    }
-
-    /**
-     * Helper for running code on the UI thread where an exception is
-     * a test failure. If this is already the UI thread then it runs
-     * the code immediately.
-     *
-     * @see runTestOnUiThread
-     * @param r The code to run in the UI thread
-     */
-    public void runOnUiThread(Runnable r) {
-        try {
-            if (isUiThread()) {
-                r.run();
-            } else {
-                mTest.runTestOnUiThread(r);
-            }
-        } catch (Throwable t) {
-            Assert.fail("Unexpected error while running on UI thread: "
-                    + t.getMessage());
-        }
-    }
-
-    /**
-     * Accessor for underlying WebView.
-     * @return The WebView being wrapped by this class.
-     */
-    public WebView getWebView() {
-        return mWebView;
-    }
-
-    private<T> T getValue(ValueGetter<T> getter) {
-        runOnUiThread(getter);
-        return getter.getValue();
-    }
-
-    private abstract class ValueGetter<T> implements Runnable {
-        private T mValue;
-
-        @Override
-        public void run() {
-            mValue = capture();
-        }
-
-        protected abstract T capture();
-
-        public T getValue() {
-           return mValue;
-        }
-    }
-
-    /**
-     * Returns true if the current thread is the UI thread based on the
-     * Looper.
-     */
-    private static boolean isUiThread() {
-        return (Looper.myLooper() == Looper.getMainLooper());
-    }
-
-    /**
-     * @return Whether or not the load has finished.
-     */
-    private synchronized boolean isLoaded() {
-        return mLoaded && mNewPicture && mProgress == 100;
-    }
-
-    /**
-     * Makes a WebView call, waits for completion and then resets the
-     * load state in preparation for the next load call.
-     * @param call The call to make on the UI thread prior to waiting.
-     */
-    private void callAndWait(Runnable call) {
-        Assert.assertTrue("WebViewOnUiThread.load*AndWaitForCompletion calls "
-                + "may not be mixed with load* calls directly on WebView "
-                + "without calling waitForLoadCompletion after the load",
-                !isLoaded());
-        clearLoad(); // clear any extraneous signals from a previous load.
-        runOnUiThread(call);
-        waitForLoadCompletion();
-    }
-
-    /**
-     * Called whenever a load has been completed so that a subsequent call to
-     * waitForLoadCompletion doesn't return immediately.
-     */
-    synchronized private void clearLoad() {
-        mLoaded = false;
-        mNewPicture = false;
-        mProgress = 0;
-    }
-
-    /**
-     * Uses a polling mechanism, while pumping messages to check when the
-     * criteria is met.
-     */
-    private void waitOnUiThread(long timeout, final Callable<Boolean> doneCriteria) {
-        new PollingCheck(timeout) {
-            @Override
-            protected boolean check() {
-                pumpMessages();
-                try {
-                    return doneCriteria.call();
-                } catch (Exception e) {
-                    Assert.fail("Unexpected error while checking the criteria: "
-                            + e.getMessage());
-                    return true;
-                }
-            }
-        }.run();
-    }
-
-    /**
-     * Uses a wait/notify to check when the criteria is met.
-     */
-    private synchronized void waitOnTestThread(long timeout, Callable<Boolean> doneCriteria) {
-        try {
-            long waitEnd = SystemClock.uptimeMillis() + timeout;
-            long timeRemaining = timeout;
-            while (!doneCriteria.call() && timeRemaining > 0) {
-                this.wait(timeRemaining);
-                timeRemaining = waitEnd - SystemClock.uptimeMillis();
-            }
-            Assert.assertTrue("Action failed to complete before timeout", doneCriteria.call());
-        } catch (InterruptedException e) {
-            // We'll just drop out of the loop and fail
-        } catch (Exception e) {
-            Assert.fail("Unexpected error while checking the criteria: "
-                    + e.getMessage());
-        }
-    }
-
-    /**
-     * Pumps all currently-queued messages in the UI thread and then exits.
-     * This is useful to force processing while running tests in the UI thread.
-     */
-    private void pumpMessages() {
-        class ExitLoopException extends RuntimeException {
-        }
-
-        // Force loop to exit when processing this. Loop.quit() doesn't
-        // work because this is the main Loop.
-        mWebView.getHandler().post(new Runnable() {
-            @Override
-            public void run() {
-                throw new ExitLoopException(); // exit loop!
-            }
-        });
-        try {
-            // Pump messages until our message gets through.
-            Looper.loop();
-        } catch (ExitLoopException e) {
-        }
-    }
-
-    /**
-     * A WebChromeClient used to capture the onProgressChanged for use
-     * in waitFor functions. If a test must override the WebChromeClient,
-     * it can derive from this class or call onProgressChanged
-     * directly.
-     */
-    public static class WaitForProgressClient extends WebChromeClient {
-        private WebViewOnUiThread mOnUiThread;
-
-        public WaitForProgressClient(WebViewOnUiThread onUiThread) {
-            mOnUiThread = onUiThread;
-        }
-
-        @Override
-        public void onProgressChanged(WebView view, int newProgress) {
-            super.onProgressChanged(view, newProgress);
-            mOnUiThread.onProgressChanged(newProgress);
-        }
-    }
-
-    /**
-     * A WebViewClient that captures the onPageFinished for use in
-     * waitFor functions. Using initializeWebView sets the WaitForLoadedClient
-     * into the WebView. If a test needs to set a specific WebViewClient and
-     * needs the waitForCompletion capability then it should derive from
-     * WaitForLoadedClient or call WebViewOnUiThread.onPageFinished.
-     */
-    public static class WaitForLoadedClient extends WebViewClient {
-        private WebViewOnUiThread mOnUiThread;
-
-        public WaitForLoadedClient(WebViewOnUiThread onUiThread) {
-            mOnUiThread = onUiThread;
-        }
-
-        @Override
-        public void onPageFinished(WebView view, String url) {
-            super.onPageFinished(view, url);
-            mOnUiThread.onPageFinished();
-        }
-
-        @Override
-        public void onPageStarted(WebView view, String url, Bitmap favicon) {
-            super.onPageStarted(view, url, favicon);
-            mOnUiThread.onPageStarted();
-        }
-    }
-
-    /**
-     * A PictureListener that captures the onNewPicture for use in
-     * waitForLoadCompletion. Using initializeWebView sets the PictureListener
-     * into the WebView. If a test needs to set a specific PictureListener and
-     * needs the waitForCompletion capability then it should call
-     * WebViewOnUiThread.onNewPicture.
-     */
-    private class WaitForNewPicture implements PictureListener {
-        @Override
-        public void onNewPicture(WebView view, Picture picture) {
-            WebViewOnUiThread.this.onNewPicture();
-        }
-    }
-}
diff --git a/tests/tests/text/src/android/text/cts/WidgetTestUtils.java b/tests/tests/text/src/android/text/cts/WidgetTestUtils.java
deleted file mode 100644
index d41b242..0000000
--- a/tests/tests/text/src/android/text/cts/WidgetTestUtils.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * Copyright (C) 2008 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.text.cts;
-
-import org.xmlpull.v1.XmlPullParser;
-import org.xmlpull.v1.XmlPullParserException;
-
-import android.content.Context;
-import android.content.res.Resources;
-import android.graphics.Bitmap;
-import android.graphics.BitmapFactory;
-
-import java.io.IOException;
-
-import junit.framework.Assert;
-
-/**
- * The useful methods for widget test.
- */
-public class WidgetTestUtils {
-    /**
-     * Assert that two bitmaps are equal.
-     *
-     * @param Bitmap b1 the first bitmap which needs to compare.
-     * @param Bitmap b2 the second bitmap which needs to compare.
-     */
-    public static void assertEquals(Bitmap b1, Bitmap b2) {
-        if (b1 == b2) {
-            return;
-        }
-
-        if (b1 == null || b2 == null) {
-            Assert.fail("the bitmaps are not equal");
-        }
-
-        // b1 and b2 are all not null.
-        if (b1.getWidth() != b2.getWidth() || b1.getHeight() != b2.getHeight()
-            || b1.getConfig() != b2.getConfig()) {
-            Assert.fail("the bitmaps are not equal");
-        }
-
-        int w = b1.getWidth();
-        int h = b1.getHeight();
-        int s = w * h;
-        int[] pixels1 = new int[s];
-        int[] pixels2 = new int[s];
-
-        b1.getPixels(pixels1, 0, w, 0, 0, w, h);
-        b2.getPixels(pixels2, 0, w, 0, 0, w, h);
-
-        for (int i = 0; i < s; i++) {
-            if (pixels1[i] != pixels2[i]) {
-                Assert.fail("the bitmaps are not equal");
-            }
-        }
-    }
-
-    /**
-     * Find beginning of the special element.
-     * @param parser XmlPullParser will be parsed.
-     * @param firstElementName the target element name.
-     *
-     * @throws XmlPullParserException if XML Pull Parser related faults occur.
-     * @throws IOException if I/O-related error occur when parsing.
-     */
-    public static final void beginDocument(XmlPullParser parser, String firstElementName)
-            throws XmlPullParserException, IOException {
-        Assert.assertNotNull(parser);
-        Assert.assertNotNull(firstElementName);
-
-        int type;
-        while ((type = parser.next()) != XmlPullParser.START_TAG
-                && type != XmlPullParser.END_DOCUMENT) {
-            ;
-        }
-
-        if (!parser.getName().equals(firstElementName)) {
-            throw new XmlPullParserException("Unexpected start tag: found " + parser.getName()
-                    + ", expected " + firstElementName);
-        }
-    }
-
-    /**
-     * Compare the expected pixels with actual, scaling for the target context density
-     *
-     * @throws AssertionFailedError
-     */
-    public static void assertScaledPixels(int expected, int actual, Context context) {
-        Assert.assertEquals(expected * context.getResources().getDisplayMetrics().density,
-                actual, 3);
-    }
-
-    /** Converts dips into pixels using the {@link Context}'s density. */
-    public static int convertDipToPixels(Context context, int dip) {
-      float density = context.getResources().getDisplayMetrics().density;
-      return Math.round(density * dip);
-    }
-
-    /**
-     * Retrieve a bitmap that can be used for comparison on any density
-     * @param resources
-     * @return the {@link Bitmap} or <code>null</code>
-     */
-    public static Bitmap getUnscaledBitmap(Resources resources, int resId) {
-        BitmapFactory.Options options = new BitmapFactory.Options();
-        options.inScaled = false;
-        return BitmapFactory.decodeResource(resources, resId, options);
-    }
-
-    /**
-     * Retrieve a dithered bitmap that can be used for comparison on any density
-     * @param resources
-     * @param config the preferred config for the returning bitmap
-     * @return the {@link Bitmap} or <code>null</code>
-     */
-    public static Bitmap getUnscaledAndDitheredBitmap(Resources resources,
-            int resId, Bitmap.Config config) {
-        BitmapFactory.Options options = new BitmapFactory.Options();
-        options.inDither = true;
-        options.inScaled = false;
-        options.inPreferredConfig = config;
-        return BitmapFactory.decodeResource(resources, resId, options);
-    }
-}
diff --git a/tests/tests/text/src/android/text/method/cts/ScrollingMovementMethodTest.java b/tests/tests/text/src/android/text/method/cts/ScrollingMovementMethodTest.java
index c186cde..73fd763 100644
--- a/tests/tests/text/src/android/text/method/cts/ScrollingMovementMethodTest.java
+++ b/tests/tests/text/src/android/text/method/cts/ScrollingMovementMethodTest.java
@@ -18,6 +18,7 @@
 
 import dalvik.annotation.KnownFailure;
 
+import android.cts.util.WidgetTestUtils;
 import android.os.SystemClock;
 import android.test.ActivityInstrumentationTestCase2;
 import android.text.Layout;
@@ -33,7 +34,6 @@
 import android.view.ViewGroup.LayoutParams;
 import android.widget.TextView;
 import android.widget.TextView.BufferType;
-import android.text.cts.WidgetTestUtils;
 
 /**
  * Test {@link ScrollingMovementMethod}. The class is an implementation of interface
diff --git a/tests/tests/text/src/android/text/style/cts/ImageSpanTest.java b/tests/tests/text/src/android/text/style/cts/ImageSpanTest.java
index a98c748..6f056d0 100644
--- a/tests/tests/text/src/android/text/style/cts/ImageSpanTest.java
+++ b/tests/tests/text/src/android/text/style/cts/ImageSpanTest.java
@@ -20,6 +20,7 @@
 
 
 import android.content.Context;
+import android.cts.util.WidgetTestUtils;
 import android.graphics.Bitmap;
 import android.graphics.drawable.BitmapDrawable;
 import android.graphics.drawable.Drawable;
@@ -27,7 +28,6 @@
 import android.test.AndroidTestCase;
 import android.text.style.DynamicDrawableSpan;
 import android.text.style.ImageSpan;
-import android.text.cts.WidgetTestUtils;
 
 public class ImageSpanTest extends AndroidTestCase {
     public void testConstructor() {
diff --git a/tests/tests/view/src/android/view/cts/MenuInflaterTest.java b/tests/tests/view/src/android/view/cts/MenuInflaterTest.java
index bd483f9..40d1d3d 100644
--- a/tests/tests/view/src/android/view/cts/MenuInflaterTest.java
+++ b/tests/tests/view/src/android/view/cts/MenuInflaterTest.java
@@ -23,6 +23,7 @@
 import android.app.Activity;
 import android.content.Context;
 import android.content.res.Resources;
+import android.cts.util.WidgetTestUtils;
 import android.graphics.Bitmap;
 import android.graphics.BitmapFactory;
 import android.graphics.drawable.BitmapDrawable;
diff --git a/tests/tests/view/src/android/view/cts/ViewGroupCtsActivity.java b/tests/tests/view/src/android/view/cts/ViewGroupCtsActivity.java
index 71bb28c..880a450 100644
--- a/tests/tests/view/src/android/view/cts/ViewGroupCtsActivity.java
+++ b/tests/tests/view/src/android/view/cts/ViewGroupCtsActivity.java
@@ -17,7 +17,7 @@
 package android.view.cts;
 
 import android.app.Activity;
-import android.app.cts.CTSResult;
+import android.cts.util.CTSResult;
 import android.os.Bundle;
 import android.os.Handler;
 import android.widget.TextView;
diff --git a/tests/tests/view/src/android/view/cts/ViewGroupTest.java b/tests/tests/view/src/android/view/cts/ViewGroupTest.java
index 55428de..f1064a7 100644
--- a/tests/tests/view/src/android/view/cts/ViewGroupTest.java
+++ b/tests/tests/view/src/android/view/cts/ViewGroupTest.java
@@ -19,9 +19,9 @@
 import com.android.internal.util.XmlUtils;
 
 
-import android.app.cts.CTSResult;
 import android.content.Context;
 import android.content.Intent;
+import android.cts.util.CTSResult;
 import android.content.res.XmlResourceParser;
 import android.graphics.Bitmap;
 import android.graphics.Canvas;
diff --git a/tests/tests/webkit/Android.mk b/tests/tests/webkit/Android.mk
index 1d593df..c2d8c3c 100644
--- a/tests/tests/webkit/Android.mk
+++ b/tests/tests/webkit/Android.mk
@@ -23,7 +23,7 @@
 
 LOCAL_JAVA_LIBRARIES := android.test.runner
 
-LOCAL_STATIC_JAVA_LIBRARIES := ctsdeviceutil ctstestserver ctstestrunner
+LOCAL_STATIC_JAVA_LIBRARIES := ctsdeviceutil ctsdeviceutillegacy ctstestserver ctstestrunner
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
diff --git a/tests/tests/webkit/src/android/webkit/cts/CookieManagerTest.java b/tests/tests/webkit/src/android/webkit/cts/CookieManagerTest.java
index 9db7c21..c612886 100644
--- a/tests/tests/webkit/src/android/webkit/cts/CookieManagerTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/CookieManagerTest.java
@@ -16,6 +16,7 @@
 
 package android.webkit.cts;
 
+import android.cts.util.NullWebViewUtils;
 import android.cts.util.PollingCheck;
 import android.test.ActivityInstrumentationTestCase2;
 import android.webkit.CookieManager;
diff --git a/tests/tests/webkit/src/android/webkit/cts/CookieSyncManagerCtsActivity.java b/tests/tests/webkit/src/android/webkit/cts/CookieSyncManagerCtsActivity.java
index 51eeed3..e623405 100644
--- a/tests/tests/webkit/src/android/webkit/cts/CookieSyncManagerCtsActivity.java
+++ b/tests/tests/webkit/src/android/webkit/cts/CookieSyncManagerCtsActivity.java
@@ -17,6 +17,7 @@
 package android.webkit.cts;
 
 import android.app.Activity;
+import android.cts.util.NullWebViewUtils;
 import android.os.Bundle;
 import android.webkit.CookieSyncManager;
 import android.webkit.WebView;
diff --git a/tests/tests/webkit/src/android/webkit/cts/CookieTest.java b/tests/tests/webkit/src/android/webkit/cts/CookieTest.java
index bc5e3b0..555266b 100644
--- a/tests/tests/webkit/src/android/webkit/cts/CookieTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/CookieTest.java
@@ -16,6 +16,7 @@
 
 package android.webkit.cts;
 
+import android.cts.util.NullWebViewUtils;
 import android.test.ActivityInstrumentationTestCase2;
 import android.webkit.CookieManager;
 import android.webkit.CookieSyncManager;
diff --git a/tests/tests/webkit/src/android/webkit/cts/GeolocationTest.java b/tests/tests/webkit/src/android/webkit/cts/GeolocationTest.java
index 63990bf..ba0e0e9 100644
--- a/tests/tests/webkit/src/android/webkit/cts/GeolocationTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/GeolocationTest.java
@@ -17,6 +17,7 @@
 package android.webkit.cts;
 
 import android.content.Context;
+import android.cts.util.NullWebViewUtils;
 import android.cts.util.PollingCheck;
 import android.graphics.Bitmap;
 import android.location.Criteria;
diff --git a/tests/tests/webkit/src/android/webkit/cts/HttpAuthHandlerTest.java b/tests/tests/webkit/src/android/webkit/cts/HttpAuthHandlerTest.java
index fbda04b..5c86987 100644
--- a/tests/tests/webkit/src/android/webkit/cts/HttpAuthHandlerTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/HttpAuthHandlerTest.java
@@ -16,6 +16,7 @@
 
 package android.webkit.cts;
 
+import android.cts.util.NullWebViewUtils;
 import android.test.ActivityInstrumentationTestCase2;
 import android.webkit.HttpAuthHandler;
 import android.webkit.WebView;
diff --git a/tests/tests/webkit/src/android/webkit/cts/NullWebViewUtils.java b/tests/tests/webkit/src/android/webkit/cts/NullWebViewUtils.java
deleted file mode 100644
index c52219f..0000000
--- a/tests/tests/webkit/src/android/webkit/cts/NullWebViewUtils.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright (C) 2010 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.webkit.cts;
-
-import android.content.Context;
-import android.content.pm.PackageManager;
-
-/**
- * Utilities to enable the android.webkit.* CTS tests (and others that rely on a functioning
- * android.webkit.WebView implementation) to determine whether a functioning WebView is present
- * on the device or not.
- *
- * Test cases that require android.webkit.* classes should wrap their first usage of WebView in a
- * try catch block, and pass any exception that is thrown to
- * NullWebViewUtils.determineIfWebViewAvailable. The return value of
- * NullWebViewUtils.isWebViewAvailable will then determine if the test should expect to be able to
- * use a WebView.
- */
-public class NullWebViewUtils {
-
-    private static boolean sWebViewUnavailable;
-
-    /**
-     * @param context Current Activity context, used to query the PackageManager.
-     * @param t       An exception thrown by trying to invoke android.webkit.* APIs.
-     */
-    public static void determineIfWebViewAvailable(Context context, Throwable t) {
-        sWebViewUnavailable = !hasWebViewFeature(context) && checkCauseWasUnsupportedOperation(t);
-    }
-
-    /**
-     * After calling determineIfWebViewAvailable, this returns whether a WebView is available on the
-     * device and wheter the test can rely on it.
-     * @return True iff. PackageManager determined that there is no WebView on the device and the
-     *         exception thrown from android.webkit.* was UnsupportedOperationException.
-     */
-    public static boolean isWebViewAvailable() {
-        return !sWebViewUnavailable;
-    }
-
-    private static boolean hasWebViewFeature(Context context) {
-        // Query the system property that determins if there is a functional WebView on the device.
-        PackageManager pm = context.getPackageManager();
-        return pm.hasSystemFeature(PackageManager.FEATURE_WEBVIEW);
-    }
-
-    private static boolean checkCauseWasUnsupportedOperation(Throwable t) {
-        if (t == null) return false;
-        while (t.getCause() != null) {
-            t = t.getCause();
-        }
-        return t instanceof UnsupportedOperationException;
-    }
-
-    /**
-     * Some CTS tests (by design) first use android.webkit.* from a background thread. This helper
-     * allows the test to catch the UnsupportedOperationException from that background thread, and
-     * then query the result from the test main thread.
-     */
-    public static class NullWebViewFromThreadExceptionHandler
-            implements Thread.UncaughtExceptionHandler {
-        private Throwable mPendingException;
-
-        @Override
-        public void uncaughtException(Thread t, Throwable e) {
-            mPendingException = e;
-        }
-
-        public boolean isWebViewAvailable(Context context) {
-            return hasWebViewFeature(context) ||
-                    !checkCauseWasUnsupportedOperation(mPendingException);
-        }
-    }
-}
\ No newline at end of file
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebBackForwardListTest.java b/tests/tests/webkit/src/android/webkit/cts/WebBackForwardListTest.java
index 21a5b98..7d25b84 100644
--- a/tests/tests/webkit/src/android/webkit/cts/WebBackForwardListTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebBackForwardListTest.java
@@ -16,6 +16,7 @@
 
 package android.webkit.cts;
 
+import android.cts.util.NullWebViewUtils;
 import android.cts.util.PollingCheck;
 import android.test.ActivityInstrumentationTestCase2;
 import android.webkit.WebBackForwardList;
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebChromeClientTest.java b/tests/tests/webkit/src/android/webkit/cts/WebChromeClientTest.java
index 6a94a99..150fd86 100644
--- a/tests/tests/webkit/src/android/webkit/cts/WebChromeClientTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebChromeClientTest.java
@@ -16,6 +16,7 @@
 
 package android.webkit.cts;
 
+import android.cts.util.NullWebViewUtils;
 import android.cts.util.PollingCheck;
 import android.graphics.Bitmap;
 import android.os.Message;
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebHistoryItemTest.java b/tests/tests/webkit/src/android/webkit/cts/WebHistoryItemTest.java
index d4f326b..a6b647d 100644
--- a/tests/tests/webkit/src/android/webkit/cts/WebHistoryItemTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebHistoryItemTest.java
@@ -16,6 +16,7 @@
 
 package android.webkit.cts;
 
+import android.cts.util.NullWebViewUtils;
 import android.cts.util.PollingCheck;
 import android.graphics.Bitmap;
 import android.test.ActivityInstrumentationTestCase2;
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebSettingsTest.java b/tests/tests/webkit/src/android/webkit/cts/WebSettingsTest.java
index 3e7a592..33a9cee 100644
--- a/tests/tests/webkit/src/android/webkit/cts/WebSettingsTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebSettingsTest.java
@@ -16,6 +16,7 @@
 package android.webkit.cts;
 
 import android.content.Context;
+import android.cts.util.NullWebViewUtils;
 import android.cts.util.PollingCheck;
 import android.graphics.Bitmap;
 import android.net.http.SslError;
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java b/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java
index 2430c8c..5b906ba 100644
--- a/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java
@@ -17,6 +17,7 @@
 package android.webkit.cts;
 
 import android.cts.util.EvaluateJsResultPollingCheck;
+import android.cts.util.NullWebViewUtils;
 import android.cts.util.PollingCheck;
 import android.graphics.Bitmap;
 import android.os.Message;
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebViewCtsActivity.java b/tests/tests/webkit/src/android/webkit/cts/WebViewCtsActivity.java
index d809a42..9af7266 100644
--- a/tests/tests/webkit/src/android/webkit/cts/WebViewCtsActivity.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebViewCtsActivity.java
@@ -19,6 +19,7 @@
 import com.android.cts.webkit.R;
 
 import android.app.Activity;
+import android.cts.util.NullWebViewUtils;
 import android.os.Bundle;
 import android.view.ViewGroup;
 import android.view.ViewParent;
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebViewSslTest.java b/tests/tests/webkit/src/android/webkit/cts/WebViewSslTest.java
index 8aa0145..378bf6e 100644
--- a/tests/tests/webkit/src/android/webkit/cts/WebViewSslTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebViewSslTest.java
@@ -16,6 +16,7 @@
 
 package android.webkit.cts;
 
+import android.cts.util.NullWebViewUtils;
 import android.cts.util.PollingCheck;
 import android.net.Uri;
 import android.net.http.SslCertificate;
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebViewStartupTest.java b/tests/tests/webkit/src/android/webkit/cts/WebViewStartupTest.java
index 8f4dcc2..776cfab 100644
--- a/tests/tests/webkit/src/android/webkit/cts/WebViewStartupTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebViewStartupTest.java
@@ -18,6 +18,7 @@
 
 
 import android.content.Context;
+import android.cts.util.NullWebViewUtils;
 import android.cts.util.PollingCheck;
 import android.test.ActivityInstrumentationTestCase2;
 import android.test.UiThreadTest;
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java b/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java
index 1d8a02a..ef64f4d 100755
--- a/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java
@@ -20,6 +20,7 @@
 import android.content.Context;
 import android.content.res.AssetManager;
 import android.cts.util.EvaluateJsResultPollingCheck;
+import android.cts.util.NullWebViewUtils;
 import android.cts.util.PollingCheck;
 import android.graphics.Bitmap;
 import android.graphics.Bitmap.Config;
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebView_WebViewTransportTest.java b/tests/tests/webkit/src/android/webkit/cts/WebView_WebViewTransportTest.java
index 0c04706..1db7fca 100644
--- a/tests/tests/webkit/src/android/webkit/cts/WebView_WebViewTransportTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebView_WebViewTransportTest.java
@@ -16,6 +16,7 @@
 
 package android.webkit.cts;
 
+import android.cts.util.NullWebViewUtils;
 import android.test.ActivityInstrumentationTestCase2;
 import android.test.UiThreadTest;
 import android.webkit.WebView;
diff --git a/tests/tests/widget/res/layout/autocompletetextview_layout.xml b/tests/tests/widget/res/layout/autocompletetextview_layout.xml
index 7fd183c..25a8541 100644
--- a/tests/tests/widget/res/layout/autocompletetextview_layout.xml
+++ b/tests/tests/widget/res/layout/autocompletetextview_layout.xml
@@ -28,5 +28,6 @@
         android:completionThreshold="1"
         android:completionHint="@string/tabs_1"
         android:layout_width="match_parent"
-        android:layout_height="wrap_content" />
+        android:layout_height="wrap_content"
+        android:inputType="none"/>
 </LinearLayout>
diff --git a/tests/tests/widget/res/layout/popupwindow.xml b/tests/tests/widget/res/layout/popupwindow.xml
index e6b0aed..2508115 100644
--- a/tests/tests/widget/res/layout/popupwindow.xml
+++ b/tests/tests/widget/res/layout/popupwindow.xml
@@ -16,17 +16,16 @@
 
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                 android:layout_width="match_parent"
-                android:layout_height="wrap_content"
+                android:layout_height="match_parent"
                 android:orientation="vertical">
 
     <TextView android:id="@+id/anchor_upper"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
-        android:text="@string/text_view_hint"
-        android:layout_weight="1"/>
+        android:text="@string/text_view_hint" />
 
     <LinearLayout android:layout_width="match_parent"
-                android:layout_height="wrap_content"
+                android:layout_height="0dp"
                 android:layout_weight="1">
 
         <TextView android:id="@+id/anchor_middle_left"
@@ -46,7 +45,6 @@
     <TextView android:id="@+id/anchor_lower"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
-        android:text="@string/text_view_hint"
-        android:layout_weight="1"/>
+        android:text="@string/text_view_hint" />
 
 </LinearLayout>
diff --git a/tests/tests/widget/src/android/widget/cts/AbsListViewTest.java b/tests/tests/widget/src/android/widget/cts/AbsListViewTest.java
index b6a96fb..9d8c7d2 100644
--- a/tests/tests/widget/src/android/widget/cts/AbsListViewTest.java
+++ b/tests/tests/widget/src/android/widget/cts/AbsListViewTest.java
@@ -25,6 +25,7 @@
 import android.app.Instrumentation;
 import android.content.Context;
 import android.cts.util.PollingCheck;
+import android.cts.util.WidgetTestUtils;
 import android.graphics.Canvas;
 import android.graphics.Color;
 import android.graphics.Rect;
diff --git a/tests/tests/widget/src/android/widget/cts/AbsListView_LayoutParamsTest.java b/tests/tests/widget/src/android/widget/cts/AbsListView_LayoutParamsTest.java
index 413bc2a..305a9e2 100644
--- a/tests/tests/widget/src/android/widget/cts/AbsListView_LayoutParamsTest.java
+++ b/tests/tests/widget/src/android/widget/cts/AbsListView_LayoutParamsTest.java
@@ -21,6 +21,7 @@
 
 import org.xmlpull.v1.XmlPullParser;
 
+import android.cts.util.WidgetTestUtils;
 import android.test.AndroidTestCase;
 import android.util.AttributeSet;
 import android.util.Xml;
diff --git a/tests/tests/widget/src/android/widget/cts/AbsoluteLayoutTest.java b/tests/tests/widget/src/android/widget/cts/AbsoluteLayoutTest.java
index 053f42b..bac2479 100644
--- a/tests/tests/widget/src/android/widget/cts/AbsoluteLayoutTest.java
+++ b/tests/tests/widget/src/android/widget/cts/AbsoluteLayoutTest.java
@@ -24,6 +24,7 @@
 
 import android.app.Activity;
 import android.content.Context;
+import android.cts.util.WidgetTestUtils;
 import android.test.ActivityInstrumentationTestCase2;
 import android.util.AttributeSet;
 import android.util.Xml;
diff --git a/tests/tests/widget/src/android/widget/cts/AbsoluteLayout_LayoutParamsTest.java b/tests/tests/widget/src/android/widget/cts/AbsoluteLayout_LayoutParamsTest.java
index 685f2d3..ebc4e74 100644
--- a/tests/tests/widget/src/android/widget/cts/AbsoluteLayout_LayoutParamsTest.java
+++ b/tests/tests/widget/src/android/widget/cts/AbsoluteLayout_LayoutParamsTest.java
@@ -22,6 +22,7 @@
 import org.xmlpull.v1.XmlPullParser;
 import org.xmlpull.v1.XmlPullParserException;
 
+import android.cts.util.WidgetTestUtils;
 import android.test.AndroidTestCase;
 import android.util.AttributeSet;
 import android.util.Xml;
diff --git a/tests/tests/widget/src/android/widget/cts/AutoCompleteTextViewTest.java b/tests/tests/widget/src/android/widget/cts/AutoCompleteTextViewTest.java
index 9fa4959..da99fa3 100644
--- a/tests/tests/widget/src/android/widget/cts/AutoCompleteTextViewTest.java
+++ b/tests/tests/widget/src/android/widget/cts/AutoCompleteTextViewTest.java
@@ -24,7 +24,9 @@
 
 import android.app.Activity;
 import android.app.Instrumentation;
+import android.app.UiModeManager;
 import android.content.Context;
+import android.content.res.Configuration;
 import android.cts.util.PollingCheck;
 import android.graphics.Rect;
 import android.test.ActivityInstrumentationTestCase2;
@@ -104,6 +106,12 @@
         }
     }
 
+    boolean isTvMode() {
+        UiModeManager uiModeManager = (UiModeManager) getActivity().getSystemService(
+                Context.UI_MODE_SERVICE);
+        return uiModeManager.getCurrentModeType() == Configuration.UI_MODE_TYPE_TELEVISION;
+    }
+
     @UiThreadTest
     public void testConstructor() {
         XmlPullParser parser;
@@ -432,6 +440,9 @@
     }
 
     public void testPerformFiltering() throws Throwable {
+        if (isTvMode()) {
+            return;
+        }
         runTestOnUiThread(new Runnable() {
             public void run() {
                 mAutoCompleteTextView.setAdapter(mAdapter);
@@ -502,6 +513,9 @@
     }
 
     public void testPerformCompletion() throws Throwable {
+        if (isTvMode()) {
+            return;
+        }
         final MockOnItemClickListener listener = new MockOnItemClickListener();
         assertFalse(mAutoCompleteTextView.isPerformingCompletion());
 
diff --git a/tests/tests/widget/src/android/widget/cts/CursorAdapterTest.java b/tests/tests/widget/src/android/widget/cts/CursorAdapterTest.java
index 8cc0754..0916e59 100644
--- a/tests/tests/widget/src/android/widget/cts/CursorAdapterTest.java
+++ b/tests/tests/widget/src/android/widget/cts/CursorAdapterTest.java
@@ -20,6 +20,8 @@
 
 import android.content.Context;
 import android.cts.util.PollingCheck;
+import android.cts.util.ReadElf;
+import android.cts.util.TestThread;
 import android.database.ContentObserver;
 import android.database.Cursor;
 import android.database.DataSetObserver;
diff --git a/tests/tests/widget/src/android/widget/cts/FilterTest.java b/tests/tests/widget/src/android/widget/cts/FilterTest.java
index 76de481..2c598dd 100644
--- a/tests/tests/widget/src/android/widget/cts/FilterTest.java
+++ b/tests/tests/widget/src/android/widget/cts/FilterTest.java
@@ -18,6 +18,8 @@
 
 
 import android.cts.util.PollingCheck;
+import android.cts.util.ReadElf;
+import android.cts.util.TestThread;
 import android.os.Looper;
 import android.test.ActivityInstrumentationTestCase2;
 import android.widget.Filter;
diff --git a/tests/tests/widget/src/android/widget/cts/FrameLayoutTest.java b/tests/tests/widget/src/android/widget/cts/FrameLayoutTest.java
index dcab088..31d9fff 100644
--- a/tests/tests/widget/src/android/widget/cts/FrameLayoutTest.java
+++ b/tests/tests/widget/src/android/widget/cts/FrameLayoutTest.java
@@ -17,6 +17,7 @@
 package android.widget.cts;
 
 import android.content.res.ColorStateList;
+import android.cts.util.WidgetTestUtils;
 import android.graphics.Canvas;
 import android.graphics.Color;
 import android.graphics.ColorFilter;
diff --git a/tests/tests/widget/src/android/widget/cts/FrameLayout_LayoutParamsTest.java b/tests/tests/widget/src/android/widget/cts/FrameLayout_LayoutParamsTest.java
index d8f1296..1e7082f 100644
--- a/tests/tests/widget/src/android/widget/cts/FrameLayout_LayoutParamsTest.java
+++ b/tests/tests/widget/src/android/widget/cts/FrameLayout_LayoutParamsTest.java
@@ -22,6 +22,7 @@
 import org.xmlpull.v1.XmlPullParser;
 import org.xmlpull.v1.XmlPullParserException;
 
+import android.cts.util.WidgetTestUtils;
 import android.test.AndroidTestCase;
 import android.util.AttributeSet;
 import android.util.Xml;
diff --git a/tests/tests/widget/src/android/widget/cts/GalleryTest.java b/tests/tests/widget/src/android/widget/cts/GalleryTest.java
index a2deab9..2813965 100644
--- a/tests/tests/widget/src/android/widget/cts/GalleryTest.java
+++ b/tests/tests/widget/src/android/widget/cts/GalleryTest.java
@@ -26,6 +26,7 @@
 import android.app.Activity;
 import android.app.Instrumentation;
 import android.content.Context;
+import android.cts.util.WidgetTestUtils;
 import android.os.SystemClock;
 import android.test.ActivityInstrumentationTestCase2;
 import android.test.UiThreadTest;
diff --git a/tests/tests/widget/src/android/widget/cts/Gallery_LayoutParamsTest.java b/tests/tests/widget/src/android/widget/cts/Gallery_LayoutParamsTest.java
index de90ed3..0502e38 100644
--- a/tests/tests/widget/src/android/widget/cts/Gallery_LayoutParamsTest.java
+++ b/tests/tests/widget/src/android/widget/cts/Gallery_LayoutParamsTest.java
@@ -22,6 +22,7 @@
 import org.xmlpull.v1.XmlPullParserException;
 
 import android.content.res.XmlResourceParser;
+import android.cts.util.WidgetTestUtils;
 import android.test.AndroidTestCase;
 import android.widget.Gallery.LayoutParams;
 
diff --git a/tests/tests/widget/src/android/widget/cts/HorizontalScrollViewTest.java b/tests/tests/widget/src/android/widget/cts/HorizontalScrollViewTest.java
index 2862865..36398c3 100644
--- a/tests/tests/widget/src/android/widget/cts/HorizontalScrollViewTest.java
+++ b/tests/tests/widget/src/android/widget/cts/HorizontalScrollViewTest.java
@@ -24,6 +24,7 @@
 import android.app.Activity;
 import android.content.Context;
 import android.cts.util.PollingCheck;
+import android.cts.util.WidgetTestUtils;
 import android.graphics.Rect;
 import android.test.ActivityInstrumentationTestCase2;
 import android.test.UiThreadTest;
diff --git a/tests/tests/widget/src/android/widget/cts/ImageSwitcherTest.java b/tests/tests/widget/src/android/widget/cts/ImageSwitcherTest.java
index c0e606c..eb75557 100644
--- a/tests/tests/widget/src/android/widget/cts/ImageSwitcherTest.java
+++ b/tests/tests/widget/src/android/widget/cts/ImageSwitcherTest.java
@@ -23,6 +23,7 @@
 
 import android.content.Context;
 import android.content.res.Resources;
+import android.cts.util.WidgetTestUtils;
 import android.graphics.Bitmap;
 import android.graphics.BitmapFactory;
 import android.graphics.drawable.BitmapDrawable;
diff --git a/tests/tests/widget/src/android/widget/cts/ImageViewTest.java b/tests/tests/widget/src/android/widget/cts/ImageViewTest.java
index 7b0b65a..c93d4a1 100644
--- a/tests/tests/widget/src/android/widget/cts/ImageViewTest.java
+++ b/tests/tests/widget/src/android/widget/cts/ImageViewTest.java
@@ -29,6 +29,7 @@
 
 import android.app.Activity;
 import android.content.Context;
+import android.cts.util.WidgetTestUtils;
 import android.graphics.Bitmap;
 import android.graphics.BitmapFactory;
 import android.graphics.Canvas;
diff --git a/tests/tests/widget/src/android/widget/cts/RemoteViewsActivityTest.java b/tests/tests/widget/src/android/widget/cts/RemoteViewsActivityTest.java
index a03edce..ab109b1 100644
--- a/tests/tests/widget/src/android/widget/cts/RemoteViewsActivityTest.java
+++ b/tests/tests/widget/src/android/widget/cts/RemoteViewsActivityTest.java
@@ -17,6 +17,7 @@
 package android.widget.cts;
 
 import android.app.Activity;
+import android.cts.util.NullWebViewUtils;
 import android.os.Parcel;
 import android.test.ActivityInstrumentationTestCase2;
 import android.test.suitebuilder.annotation.MediumTest;
diff --git a/tests/tests/widget/src/android/widget/cts/RemoteViewsCtsActivity.java b/tests/tests/widget/src/android/widget/cts/RemoteViewsCtsActivity.java
index 6826eb3..4da5aa2 100644
--- a/tests/tests/widget/src/android/widget/cts/RemoteViewsCtsActivity.java
+++ b/tests/tests/widget/src/android/widget/cts/RemoteViewsCtsActivity.java
@@ -19,6 +19,7 @@
 import com.android.cts.widget.R;
 
 import android.app.Activity;
+import android.cts.util.NullWebViewUtils;
 import android.os.Bundle;
 import android.widget.RemoteViews;
 
diff --git a/tests/tests/widget/src/android/widget/cts/RemoteViewsTest.java b/tests/tests/widget/src/android/widget/cts/RemoteViewsTest.java
index 8d1cddf..328f9f3 100644
--- a/tests/tests/widget/src/android/widget/cts/RemoteViewsTest.java
+++ b/tests/tests/widget/src/android/widget/cts/RemoteViewsTest.java
@@ -26,6 +26,7 @@
 import android.app.Instrumentation.ActivityMonitor;
 import android.content.Intent;
 import android.content.res.ColorStateList;
+import android.cts.util.WidgetTestUtils;
 import android.graphics.Bitmap;
 import android.graphics.BitmapFactory;
 import android.graphics.drawable.BitmapDrawable;
diff --git a/tests/tests/widget/src/android/widget/cts/SimpleAdapterTest.java b/tests/tests/widget/src/android/widget/cts/SimpleAdapterTest.java
index 90ff617..c530293 100644
--- a/tests/tests/widget/src/android/widget/cts/SimpleAdapterTest.java
+++ b/tests/tests/widget/src/android/widget/cts/SimpleAdapterTest.java
@@ -20,6 +20,7 @@
 
 
 import android.content.Context;
+import android.cts.util.WidgetTestUtils;
 import android.graphics.Bitmap;
 import android.graphics.drawable.BitmapDrawable;
 import android.test.InstrumentationTestCase;
diff --git a/tests/tests/widget/src/android/widget/cts/SimpleCursorAdapterTest.java b/tests/tests/widget/src/android/widget/cts/SimpleCursorAdapterTest.java
index f19dce7..13184de 100644
--- a/tests/tests/widget/src/android/widget/cts/SimpleCursorAdapterTest.java
+++ b/tests/tests/widget/src/android/widget/cts/SimpleCursorAdapterTest.java
@@ -20,6 +20,7 @@
 
 
 import android.content.Context;
+import android.cts.util.WidgetTestUtils;
 import android.database.Cursor;
 import android.database.MatrixCursor;
 import android.graphics.Bitmap;
diff --git a/tests/tests/widget/src/android/widget/cts/SimpleCursorTreeAdapterTest.java b/tests/tests/widget/src/android/widget/cts/SimpleCursorTreeAdapterTest.java
index 0db5322..c9fdbc3 100644
--- a/tests/tests/widget/src/android/widget/cts/SimpleCursorTreeAdapterTest.java
+++ b/tests/tests/widget/src/android/widget/cts/SimpleCursorTreeAdapterTest.java
@@ -20,6 +20,7 @@
 
 
 import android.content.Context;
+import android.cts.util.WidgetTestUtils;
 import android.database.Cursor;
 import android.database.MatrixCursor;
 import android.graphics.Bitmap;
diff --git a/tests/tests/widget/src/android/widget/cts/TabHostTest.java b/tests/tests/widget/src/android/widget/cts/TabHostTest.java
index 3af8d9c..00ecd40 100644
--- a/tests/tests/widget/src/android/widget/cts/TabHostTest.java
+++ b/tests/tests/widget/src/android/widget/cts/TabHostTest.java
@@ -22,6 +22,7 @@
 import android.app.Activity;
 import android.app.ActivityGroup;
 import android.content.Intent;
+import android.cts.util.WidgetTestUtils;
 import android.test.ActivityInstrumentationTestCase2;
 import android.test.UiThreadTest;
 import android.view.View;
diff --git a/tests/tests/widget/src/android/widget/cts/TestThread.java b/tests/tests/widget/src/android/widget/cts/TestThread.java
deleted file mode 100644
index 78295b9..0000000
--- a/tests/tests/widget/src/android/widget/cts/TestThread.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright (C) 2009 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.widget.cts;
-
-/**
- * Thread class for executing a Runnable containing assertions in a separate thread.
- * Uncaught exceptions in the Runnable are rethrown in the context of the the thread
- * calling the <code>runTest()</code> method.
- */
-public final class TestThread extends Thread {
-    private Throwable mThrowable;
-    private Runnable mTarget;
-
-    public TestThread(Runnable target) {
-        mTarget = target;
-    }
-
-    @Override
-    public final void run() {
-        try {
-            mTarget.run();
-        } catch (Throwable t) {
-            mThrowable = t;
-        }
-    }
-
-    /**
-     * Run the target Runnable object and wait until the test finish or throw
-     * out Exception if test fail.
-     *
-     * @param runTime
-     * @throws Throwable
-     */
-    public void runTest(long runTime) throws Throwable {
-        start();
-        joinAndCheck(runTime);
-    }
-
-    /**
-     * Get the Throwable object which is thrown when test running
-     * @return  The Throwable object
-     */
-    public Throwable getThrowable() {
-        return mThrowable;
-    }
-
-    /**
-     * Set the Throwable object which is thrown when test running
-     * @param t The Throwable object
-     */
-    public void setThrowable(Throwable t) {
-        mThrowable = t;
-    }
-
-    /**
-     * Wait for the test thread to complete and throw the stored exception if there is one.
-     *
-     * @param runTime The time to wait for the test thread to complete.
-     * @throws Throwable
-     */
-    public void joinAndCheck(long runTime) throws Throwable {
-        this.join(runTime);
-        if (this.isAlive()) {
-            this.interrupt();
-            this.join(runTime);
-            throw new Exception("Thread did not finish within allotted time.");
-        }
-        checkException();
-    }
-
-    /**
-     * Check whether there is an exception when running Runnable object.
-     * @throws Throwable
-     */
-    public void checkException() throws Throwable {
-        if (mThrowable != null) {
-            throw mThrowable;
-        }
-    }
-}
diff --git a/tests/tests/widget/src/android/widget/cts/TextViewTest.java b/tests/tests/widget/src/android/widget/cts/TextViewTest.java
index c5d9985..72193e7 100644
--- a/tests/tests/widget/src/android/widget/cts/TextViewTest.java
+++ b/tests/tests/widget/src/android/widget/cts/TextViewTest.java
@@ -28,6 +28,7 @@
 import android.content.res.ColorStateList;
 import android.content.res.Resources.NotFoundException;
 import android.cts.util.PollingCheck;
+import android.cts.util.WidgetTestUtils;
 import android.graphics.Bitmap;
 import android.graphics.Color;
 import android.graphics.Paint;
diff --git a/tests/tests/widget/src/android/widget/cts/ViewGroupCtsActivity.java b/tests/tests/widget/src/android/widget/cts/ViewGroupCtsActivity.java
index 378395e..4e14fc2 100644
--- a/tests/tests/widget/src/android/widget/cts/ViewGroupCtsActivity.java
+++ b/tests/tests/widget/src/android/widget/cts/ViewGroupCtsActivity.java
@@ -17,7 +17,7 @@
 package android.widget.cts;
 
 import android.app.Activity;
-import android.app.cts.CTSResult;
+import android.cts.util.CTSResult;
 import android.os.Bundle;
 import android.os.Handler;
 import android.widget.TextView;
diff --git a/tests/tests/widget/src/android/widget/cts/WidgetTestUtils.java b/tests/tests/widget/src/android/widget/cts/WidgetTestUtils.java
deleted file mode 100644
index 2df6629..0000000
--- a/tests/tests/widget/src/android/widget/cts/WidgetTestUtils.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * Copyright (C) 2008 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.widget.cts;
-
-import org.xmlpull.v1.XmlPullParser;
-import org.xmlpull.v1.XmlPullParserException;
-
-import android.content.Context;
-import android.content.res.Resources;
-import android.graphics.Bitmap;
-import android.graphics.BitmapFactory;
-
-import java.io.IOException;
-
-import junit.framework.Assert;
-
-/**
- * The useful methods for widget test.
- */
-public class WidgetTestUtils {
-    /**
-     * Assert that two bitmaps are equal.
-     *
-     * @param Bitmap b1 the first bitmap which needs to compare.
-     * @param Bitmap b2 the second bitmap which needs to compare.
-     */
-    public static void assertEquals(Bitmap b1, Bitmap b2) {
-        if (b1 == b2) {
-            return;
-        }
-
-        if (b1 == null || b2 == null) {
-            Assert.fail("the bitmaps are not equal");
-        }
-
-        // b1 and b2 are all not null.
-        if (b1.getWidth() != b2.getWidth() || b1.getHeight() != b2.getHeight()
-            || b1.getConfig() != b2.getConfig()) {
-            Assert.fail("the bitmaps are not equal");
-        }
-
-        int w = b1.getWidth();
-        int h = b1.getHeight();
-        int s = w * h;
-        int[] pixels1 = new int[s];
-        int[] pixels2 = new int[s];
-
-        b1.getPixels(pixels1, 0, w, 0, 0, w, h);
-        b2.getPixels(pixels2, 0, w, 0, 0, w, h);
-
-        for (int i = 0; i < s; i++) {
-            if (pixels1[i] != pixels2[i]) {
-                Assert.fail("the bitmaps are not equal");
-            }
-        }
-    }
-
-    /**
-     * Find beginning of the special element.
-     * @param parser XmlPullParser will be parsed.
-     * @param firstElementName the target element name.
-     *
-     * @throws XmlPullParserException if XML Pull Parser related faults occur.
-     * @throws IOException if I/O-related error occur when parsing.
-     */
-    public static final void beginDocument(XmlPullParser parser, String firstElementName)
-            throws XmlPullParserException, IOException {
-        Assert.assertNotNull(parser);
-        Assert.assertNotNull(firstElementName);
-
-        int type;
-        while ((type = parser.next()) != XmlPullParser.START_TAG
-                && type != XmlPullParser.END_DOCUMENT) {
-            ;
-        }
-
-        if (!parser.getName().equals(firstElementName)) {
-            throw new XmlPullParserException("Unexpected start tag: found " + parser.getName()
-                    + ", expected " + firstElementName);
-        }
-    }
-
-    /**
-     * Compare the expected pixels with actual, scaling for the target context density
-     *
-     * @throws AssertionFailedError
-     */
-    public static void assertScaledPixels(int expected, int actual, Context context) {
-        Assert.assertEquals(expected * context.getResources().getDisplayMetrics().density,
-                actual, 3);
-    }
-
-    /** Converts dips into pixels using the {@link Context}'s density. */
-    public static int convertDipToPixels(Context context, int dip) {
-      float density = context.getResources().getDisplayMetrics().density;
-      return Math.round(density * dip);
-    }
-
-    /**
-     * Retrieve a bitmap that can be used for comparison on any density
-     * @param resources
-     * @return the {@link Bitmap} or <code>null</code>
-     */
-    public static Bitmap getUnscaledBitmap(Resources resources, int resId) {
-        BitmapFactory.Options options = new BitmapFactory.Options();
-        options.inScaled = false;
-        return BitmapFactory.decodeResource(resources, resId, options);
-    }
-
-    /**
-     * Retrieve a dithered bitmap that can be used for comparison on any density
-     * @param resources
-     * @param config the preferred config for the returning bitmap
-     * @return the {@link Bitmap} or <code>null</code>
-     */
-    public static Bitmap getUnscaledAndDitheredBitmap(Resources resources,
-            int resId, Bitmap.Config config) {
-        BitmapFactory.Options options = new BitmapFactory.Options();
-        options.inDither = true;
-        options.inScaled = false;
-        options.inPreferredConfig = config;
-        return BitmapFactory.decodeResource(resources, resId, options);
-    }
-}
diff --git a/tests/webgl/src/android/webgl/WebGLActivity.java b/tests/webgl/src/android/webgl/WebGLActivity.java
index e88de16..3f911c4 100644
--- a/tests/webgl/src/android/webgl/WebGLActivity.java
+++ b/tests/webgl/src/android/webgl/WebGLActivity.java
@@ -19,9 +19,9 @@
 import android.app.Activity;
 import android.content.Context;
 import android.content.res.Resources;
+import android.cts.util.NullWebViewUtils;
 import android.os.Bundle;
 import android.util.Log;
-import android.webgl.cts.NullWebViewUtils;
 import android.webgl.cts.R;
 import android.webkit.WebView;
 import android.webkit.JavascriptInterface;
diff --git a/tests/webgl/src/android/webgl/cts/NullWebViewUtils.java b/tests/webgl/src/android/webgl/cts/NullWebViewUtils.java
deleted file mode 100644
index 861cc22..0000000
--- a/tests/webgl/src/android/webgl/cts/NullWebViewUtils.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright (C) 2010 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.webgl.cts;
-
-import android.content.Context;
-import android.content.pm.PackageManager;
-
-/**
- * Utilities to enable the android.webkit.* CTS tests (and others that rely on a functioning
- * android.webkit.WebView implementation) to determine whether a functioning WebView is present
- * on the device or not.
- *
- * Test cases that require android.webkit.* classes should wrap their first usage of WebView in a
- * try catch block, and pass any exception that is thrown to
- * NullWebViewUtils.determineIfWebViewAvailable. The return value of
- * NullWebViewUtils.isWebViewAvailable will then determine if the test should expect to be able to
- * use a WebView.
- */
-public class NullWebViewUtils {
-
-    private static boolean sWebViewUnavailable;
-
-    /**
-     * @param context Current Activity context, used to query the PackageManager.
-     * @param t       An exception thrown by trying to invoke android.webkit.* APIs.
-     */
-    public static void determineIfWebViewAvailable(Context context, Throwable t) {
-        sWebViewUnavailable = !hasWebViewFeature(context) && checkCauseWasUnsupportedOperation(t);
-    }
-
-    /**
-     * After calling determineIfWebViewAvailable, this returns whether a WebView is available on the
-     * device and wheter the test can rely on it.
-     * @return True iff. PackageManager determined that there is no WebView on the device and the
-     *         exception thrown from android.webkit.* was UnsupportedOperationException.
-     */
-    public static boolean isWebViewAvailable() {
-        return !sWebViewUnavailable;
-    }
-
-    private static boolean hasWebViewFeature(Context context) {
-        // Query the system property that determins if there is a functional WebView on the device.
-        PackageManager pm = context.getPackageManager();
-        return pm.hasSystemFeature(PackageManager.FEATURE_WEBVIEW);
-    }
-
-    private static boolean checkCauseWasUnsupportedOperation(Throwable t) {
-        if (t == null) return false;
-        while (t.getCause() != null) {
-            t = t.getCause();
-        }
-        return t instanceof UnsupportedOperationException;
-    }
-
-    /**
-     * Some CTS tests (by design) first use android.webkit.* from a background thread. This helper
-     * allows the test to catch the UnsupportedOperationException from that background thread, and
-     * then query the result from the test main thread.
-     */
-    public static class NullWebViewFromThreadExceptionHandler
-            implements Thread.UncaughtExceptionHandler {
-        private Throwable mPendingException;
-
-        @Override
-        public void uncaughtException(Thread t, Throwable e) {
-            mPendingException = e;
-        }
-
-        public boolean isWebViewAvailable(Context context) {
-            return hasWebViewFeature(context) ||
-                    !checkCauseWasUnsupportedOperation(mPendingException);
-        }
-    }
-}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/DeqpTestRunner.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/DeqpTestRunner.java
index c185cec..35b8a66 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/DeqpTestRunner.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/DeqpTestRunner.java
@@ -34,6 +34,7 @@
 
     private static final String DEQP_ONDEVICE_APK = "com.drawelements.deqp.apk";
     private static final String DEQP_ONDEVICE_PKG = "com.drawelements.deqp";
+    private static final String INCOMPLETE_LOG_MESSAGE = "Crash: Incomplete test log";
 
     private final int TESTCASE_BATCH_LIMIT = 1000;
 
@@ -218,7 +219,7 @@
 
         if (!mGotTestResult) {
             mListener.testFailed(mCurrentTestId,
-                    "Log doesn't contain test result");
+                    INCOMPLETE_LOG_MESSAGE);
         }
 
         if (mLogData && mCurrentTestLog != null && mCurrentTestLog.length() > 0) {
@@ -254,11 +255,11 @@
                 || code.compareTo("InternalError") == 0 || code.compareTo("Crash") == 0
                 || code.compareTo("Timeout") == 0) {
             mListener.testFailed(mCurrentTestId,
-                    code + ":" + details);
+                    code + ": " + details);
             mGotTestResult = true;
         } else {
             mListener.testFailed(mCurrentTestId,
-                    "Unknown result code: " + code + ":" + details);
+                    "Unknown result code: " + code + ": " + details);
             mGotTestResult = true;
         }
     }
@@ -492,7 +493,7 @@
                     }
                     if (!mGotTestResult) {
                         mListener.testFailed(mCurrentTestId,
-                            "Log doesn't contain test result");
+                            INCOMPLETE_LOG_MESSAGE);
                     }
 
                     mListener.testEnded(mCurrentTestId, emptyMap);