am 95fcc727: am 7d1fc75d: am f8693fe8: Merge "Fix Contacts_PeopleTest" into gingerbread

* commit '95fcc72729be0339f37ddf23c5a4e1cd48f59d72':
  Fix Contacts_PeopleTest
diff --git a/development/ide/eclipse/.classpath b/development/ide/eclipse/.classpath
index 8cba973..3f11bd1 100644
--- a/development/ide/eclipse/.classpath
+++ b/development/ide/eclipse/.classpath
@@ -3,7 +3,6 @@
     <classpathentry kind="src" path="cts/apps/CtsVerifier/src"/>
     <classpathentry kind="src" path="cts/apps/CtsVerifier/tests/src"/>
     <classpathentry kind="src" path="cts/libs/annotation/src"/>
-    <classpathentry kind="src" path="cts/libs/vogar-expect/src"/>
     <classpathentry kind="src" path="cts/tests/ApiDemosReferenceTest/src"/>
     <classpathentry kind="src" path="cts/tests/ProcessTest/src"/>
     <classpathentry kind="src" path="cts/tests/ProcessTest/NoShareUidApp/src"/>
diff --git a/tests/SignatureTest/Android.mk b/tests/SignatureTest/Android.mk
index 18c7cea..4166002 100644
--- a/tests/SignatureTest/Android.mk
+++ b/tests/SignatureTest/Android.mk
@@ -20,7 +20,7 @@
 # and when built explicitly put it in the data partition
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 LOCAL_JAVA_LIBRARIES := android.test.runner
 
diff --git a/tests/SignatureTest/AndroidManifest.xml b/tests/SignatureTest/AndroidManifest.xml
index 696dc57..762dfae 100644
--- a/tests/SignatureTest/AndroidManifest.xml
+++ b/tests/SignatureTest/AndroidManifest.xml
@@ -30,10 +30,16 @@
             </intent-filter>
         </activity>
 
+        <uses-library android:name="android.test.runner" />
     </application>
 
     <instrumentation android:name=".InstrumentationRunner"
                      android:targetPackage="android.tests.sigtest"
                      android:label="API Signature Test"/>
 
+    <instrumentation android:name="android.test.InstrumentationTestRunner"
+        android:targetPackage="android.tests.sigtest"
+        android:label="Simple API Signature Test">
+    </instrumentation>
+
 </manifest>
diff --git a/tests/SignatureTest/src/android/tests/sigtest/SimpleSignatureTest.java b/tests/SignatureTest/src/android/tests/sigtest/SimpleSignatureTest.java
new file mode 100644
index 0000000..c206c9a49
--- /dev/null
+++ b/tests/SignatureTest/src/android/tests/sigtest/SimpleSignatureTest.java
@@ -0,0 +1,324 @@
+/*
+ * 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.tests.sigtest;
+
+import android.content.res.Resources;
+import android.test.AndroidTestCase;
+import android.tests.sigtest.JDiffClassDescription.JDiffConstructor;
+import android.tests.sigtest.JDiffClassDescription.JDiffField;
+import android.tests.sigtest.JDiffClassDescription.JDiffMethod;
+import android.tests.sigtest.SignatureTestActivity.FAILURE_TYPE;
+
+import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
+
+import java.io.IOException;
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+
+/**
+ * A simpler version of {@link SignatureTest} that performs the signature check via a JUnit test.
+ * <p/>
+ * Eventually the existing  {@link SignatureTest} and {@link SignatureActivity} will be deleted
+ * once the move to a tradefederation based CTS harness is complete.
+ */
+public class SimpleSignatureTest extends AndroidTestCase {
+
+    private static final String TAG_ROOT = "api";
+    private static final String TAG_PACKAGE = "package";
+    private static final String TAG_CLASS = "class";
+    private static final String TAG_INTERFACE = "interface";
+    private static final String TAG_IMPLEMENTS = "implements";
+    private static final String TAG_CONSTRUCTOR = "constructor";
+    private static final String TAG_METHOD = "method";
+    private static final String TAG_PARAM = "parameter";
+    private static final String TAG_EXCEPTION = "exception";
+    private static final String TAG_FIELD = "field";
+
+    private static final String MODIFIER_ABSTRACT = "abstract";
+    private static final String MODIFIER_FINAL = "final";
+    private static final String MODIFIER_NATIVE = "native";
+    private static final String MODIFIER_PRIVATE = "private";
+    private static final String MODIFIER_PROTECTED = "protected";
+    private static final String MODIFIER_PUBLIC = "public";
+    private static final String MODIFIER_STATIC = "static";
+    private static final String MODIFIER_SYNCHRONIZED = "synchronized";
+    private static final String MODIFIER_TRANSIENT = "transient";
+    private static final String MODIFIER_VOLATILE = "volatile";
+    private static final String MODIFIER_VISIBILITY = "visibility";
+
+    private static final String ATTRIBUTE_NAME = "name";
+    private static final String ATTRIBUTE_EXTENDS = "extends";
+    private static final String ATTRIBUTE_TYPE = "type";
+    private static final String ATTRIBUTE_RETURN = "return";
+
+    private static ArrayList<String> mDebugArray = new ArrayList<String>();
+
+    private HashSet<String> mKeyTagSet;
+    private TestResultObserver mResultObserver;
+
+    private class TestResultObserver implements ResultObserver {
+        boolean mDidFail = false;
+        StringBuilder mErrorString = new StringBuilder();
+
+        public void notifyFailure(FAILURE_TYPE type, String name, String errorMessage) {
+            mDidFail = true;
+            mErrorString.append("\n");
+            mErrorString.append(type.toString().toLowerCase());
+            mErrorString.append(":\t");
+            mErrorString.append(name);
+        }
+    }
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        mKeyTagSet = new HashSet<String>();
+        mKeyTagSet.addAll(Arrays.asList(new String[] {
+                TAG_PACKAGE, TAG_CLASS, TAG_INTERFACE, TAG_IMPLEMENTS, TAG_CONSTRUCTOR,
+                TAG_METHOD, TAG_PARAM, TAG_EXCEPTION, TAG_FIELD }));
+        mResultObserver = new TestResultObserver();
+    }
+
+    /**
+     * Tests that the device's API matches the expected set defined in xml.
+     * <p/>
+     * Will check the entire API, and then report the complete list of failures
+     */
+    public void testSignature() {
+        Resources r = getContext().getResources();
+        Class rClass = R.xml.class;
+        Field[] fs = rClass.getFields();
+        for (Field f : fs) {
+            try {
+                start(r.getXml(f.getInt(rClass)));
+            } catch (Exception e) {
+                mResultObserver.notifyFailure(FAILURE_TYPE.CAUGHT_EXCEPTION, e.getMessage(),
+                        e.getMessage());
+            }
+        }
+        if (mResultObserver.mDidFail) {
+            fail(mResultObserver.mErrorString.toString());
+        }
+    }
+
+    private  void beginDocument(XmlPullParser parser, String firstElementName)
+            throws XmlPullParserException, IOException {
+        int type;
+        while ((type=parser.next()) != XmlPullParser.START_TAG
+                   && type != XmlPullParser.END_DOCUMENT) { }
+
+        if (type != XmlPullParser.START_TAG) {
+            throw new XmlPullParserException("No start tag found");
+        }
+
+        if (!parser.getName().equals(firstElementName)) {
+            throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() +
+                    ", expected " + firstElementName);
+        }
+    }
+
+    /**
+     * Signature test entry point.
+     */
+    private void start(XmlPullParser parser) throws XmlPullParserException, IOException {
+        JDiffClassDescription currentClass = null;
+        String currentPackage = "";
+        JDiffMethod currentMethod = null;
+
+        beginDocument(parser, TAG_ROOT);
+        int type;
+        while (true) {
+            type = XmlPullParser.START_DOCUMENT;
+            while ((type=parser.next()) != XmlPullParser.START_TAG
+                       && type != XmlPullParser.END_DOCUMENT
+                       && type != XmlPullParser.END_TAG) {
+
+            }
+
+            if (type == XmlPullParser.END_TAG) {
+                if (TAG_CLASS.equals(parser.getName())
+                        || TAG_INTERFACE.equals(parser.getName())) {
+                    currentClass.checkSignatureCompliance();
+                } else if (TAG_PACKAGE.equals(parser.getName())) {
+                    currentPackage = "";
+                }
+                continue;
+            }
+
+            if (type == XmlPullParser.END_DOCUMENT) {
+                break;
+            }
+
+            String tagname = parser.getName();
+            if (!mKeyTagSet.contains(tagname)) {
+                continue;
+            }
+
+            if (type == XmlPullParser.START_TAG && tagname.equals(TAG_PACKAGE)) {
+                currentPackage = parser.getAttributeValue(null, ATTRIBUTE_NAME);
+            } else if (tagname.equals(TAG_CLASS)) {
+                currentClass = loadClassInfo(parser, false, currentPackage);
+            } else if (tagname.equals(TAG_INTERFACE)) {
+                currentClass = loadClassInfo(parser, true, currentPackage);
+            } else if (tagname.equals(TAG_IMPLEMENTS)) {
+                currentClass.addImplInterface(parser.getAttributeValue(null, ATTRIBUTE_NAME));
+            } else if (tagname.equals(TAG_CONSTRUCTOR)) {
+                JDiffConstructor constructor = loadConstructorInfo(parser, currentClass);
+                currentClass.addConstructor(constructor);
+                currentMethod = constructor;
+            } else if (tagname.equals(TAG_METHOD)) {
+                currentMethod = loadMethodInfo(currentClass.getClassName(), parser);
+                currentClass.addMethod(currentMethod);
+            } else if (tagname.equals(TAG_PARAM)) {
+                currentMethod.addParam(parser.getAttributeValue(null, ATTRIBUTE_TYPE));
+            } else if (tagname.equals(TAG_EXCEPTION)) {
+                currentMethod.addException(parser.getAttributeValue(null, ATTRIBUTE_TYPE));
+            } else if (tagname.equals(TAG_FIELD)) {
+                JDiffField field = loadFieldInfo(currentClass.getClassName(), parser);
+                currentClass.addField(field);
+            } else {
+                throw new RuntimeException(
+                        "unknow tag exception:" + tagname);
+            }
+        }
+    }
+
+    /**
+     * Load field information from xml to memory.
+     *
+     * @param className of the class being examined which will be shown in error messages
+     * @param parser The XmlPullParser which carries the xml information.
+     * @return the new field
+     */
+    private JDiffField loadFieldInfo(String className, XmlPullParser parser) {
+        String fieldName = parser.getAttributeValue(null, ATTRIBUTE_NAME);
+        String fieldType = parser.getAttributeValue(null, ATTRIBUTE_TYPE);
+        int modifier = jdiffModifierToReflectionFormat(className, parser);
+        return new JDiffField(fieldName, fieldType, modifier);
+    }
+
+    /**
+     * Load method information from xml to memory.
+     *
+     * @param className of the class being examined which will be shown in error messages
+     * @param parser The XmlPullParser which carries the xml information.
+     * @return the newly loaded method.
+     */
+    private JDiffMethod loadMethodInfo(String className, XmlPullParser parser) {
+        String methodName = parser.getAttributeValue(null, ATTRIBUTE_NAME);
+        String returnType = parser.getAttributeValue(null, ATTRIBUTE_RETURN);
+        int modifier = jdiffModifierToReflectionFormat(className, parser);
+        return new JDiffMethod(methodName, modifier, returnType);
+    }
+
+    /**
+     * Load constructor information from xml to memory.
+     *
+     * @param parser The XmlPullParser which carries the xml information.
+     * @param currentClass the current class being loaded.
+     * @return the new constructor
+     */
+    private JDiffConstructor loadConstructorInfo(XmlPullParser parser,
+                                                 JDiffClassDescription currentClass) {
+        String name = currentClass.getClassName();
+        int modifier = jdiffModifierToReflectionFormat(name, parser);
+        return new JDiffConstructor(name, modifier);
+    }
+
+    /**
+     * Load class or interface information to memory.
+     *
+     * @param parser The XmlPullParser which carries the xml information.
+     * @param isInterface true if the current class is an interface, otherwise is false.
+     * @param pkg the name of the java package this class can be found in.
+     * @return the new class description.
+     */
+    private JDiffClassDescription loadClassInfo(XmlPullParser parser,
+                                                boolean isInterface,
+                                                String pkg) {
+        String className = parser.getAttributeValue(null, ATTRIBUTE_NAME);
+        JDiffClassDescription currentClass = new JDiffClassDescription(pkg,
+                                                                       className,
+                                                                       mResultObserver);
+        currentClass.setModifier(jdiffModifierToReflectionFormat(className, parser));
+        currentClass.setType(isInterface ? JDiffClassDescription.JDiffType.INTERFACE :
+                             JDiffClassDescription.JDiffType.CLASS);
+        currentClass.setExtendsClass(parser.getAttributeValue(null, ATTRIBUTE_EXTENDS));
+        return currentClass;
+    }
+
+    /**
+     * Convert string modifier to int modifier.
+     *
+     * @param name of the class/method/field being examined which will be shown in error messages
+     * @param key modifier name
+     * @param value modifier value
+     * @return converted modifier value
+     */
+    private static int modifierDescriptionToReflectedType(String name, String key, String value) {
+        if (key.equals(MODIFIER_ABSTRACT)) {
+            return value.equals("true") ? Modifier.ABSTRACT : 0;
+        } else if (key.equals(MODIFIER_FINAL)) {
+            return value.equals("true") ? Modifier.FINAL : 0;
+        } else if (key.equals(MODIFIER_NATIVE)) {
+            return value.equals("true") ? Modifier.NATIVE : 0;
+        } else if (key.equals(MODIFIER_STATIC)) {
+            return value.equals("true") ? Modifier.STATIC : 0;
+        } else if (key.equals(MODIFIER_SYNCHRONIZED)) {
+            return value.equals("true") ? Modifier.SYNCHRONIZED : 0;
+        } else if (key.equals(MODIFIER_TRANSIENT)) {
+            return value.equals("true") ? Modifier.TRANSIENT : 0;
+        } else if (key.equals(MODIFIER_VOLATILE)) {
+            return value.equals("true") ? Modifier.VOLATILE : 0;
+        } else if (key.equals(MODIFIER_VISIBILITY)) {
+            if (value.equals(MODIFIER_PRIVATE)) {
+                throw new RuntimeException("Private visibility found in API spec: " + name);
+            } else if (value.equals(MODIFIER_PROTECTED)) {
+                return Modifier.PROTECTED;
+            } else if (value.equals(MODIFIER_PUBLIC)) {
+                return Modifier.PUBLIC;
+            } else if ("".equals(value)) {
+                // If the visibility is "", it means it has no modifier.
+                // which is package private. We should return 0 for this modifier.
+                return 0;
+            } else {
+                throw new RuntimeException("Unknown modifier found in API spec: " + value);
+            }
+        }
+        return 0;
+    }
+
+    /**
+     * Transfer string modifier to int one.
+     *
+     * @param name of the class/method/field being examined which will be shown in error messages
+     * @param parser XML resource parser
+     * @return converted modifier
+     */
+    private static int jdiffModifierToReflectionFormat(String name, XmlPullParser parser){
+        int modifier = 0;
+        for (int i = 0;i < parser.getAttributeCount();i++) {
+            modifier |= modifierDescriptionToReflectedType(name, parser.getAttributeName(i),
+                    parser.getAttributeValue(i));
+        }
+        return modifier;
+    }
+}
diff --git a/tests/accessibilityservice/res/values/strings.xml b/tests/accessibilityservice/res/values/strings.xml
index 4c717c1..3730f85 100644
--- a/tests/accessibilityservice/res/values/strings.xml
+++ b/tests/accessibilityservice/res/values/strings.xml
@@ -20,31 +20,4 @@
     <!-- String title of the mock accessibility service -->
     <string name="title_delegating_accessibility_service">Delegating Accessibility Service</string>
 
-    <!-- String title of the accessibility end-to-end test activity -->
-    <string name="accessibility_end_to_end_test_activity">End-to-end test</string>
-
-    <!-- String value of used as text input -->
-    <string name="text_input_blah">Blah</string>
-
-    <!-- String value of used as text input -->
-    <string name="text_input_blah_blah">Blah blah</string>
-
-    <!-- String title of the button -->
-    <string name="button_title">Click me</string>
-
-    <!-- String value of the first list item -->
-    <string name="first_list_item">First list item</string>
-
-    <!-- String value of the second list item -->
-    <string name="second_list_item">Second list item</string>
-
-    <!-- String alert title -->
-    <string name="alert_title">Alert title</string>
-
-    <!-- String alert message -->
-    <string name="alert_message">Alert message</string>
-
-    <!-- String notification message -->
-    <string name="notification_message">Notification message</string>
-
 </resources>
diff --git a/tests/appsecurity-tests/test-apps/PermissionDeclareApp/AndroidManifest.xml b/tests/appsecurity-tests/test-apps/PermissionDeclareApp/AndroidManifest.xml
index 683ec9e..de71966 100644
--- a/tests/appsecurity-tests/test-apps/PermissionDeclareApp/AndroidManifest.xml
+++ b/tests/appsecurity-tests/test-apps/PermissionDeclareApp/AndroidManifest.xml
@@ -31,6 +31,8 @@
     <application>
         <receiver android:name="GrantUriPermission" android:exported="true">
         </receiver>
+        <receiver android:name="SetInstallerPackage" android:exported="true">
+        </receiver>
 
         <!-- Need a way for another app to try to access the permission. So create a content
         provider which is enforced by the permission -->
diff --git a/tests/appsecurity-tests/test-apps/PermissionDeclareApp/src/com/android/cts/permissiondeclareapp/GrantUriPermission.java b/tests/appsecurity-tests/test-apps/PermissionDeclareApp/src/com/android/cts/permissiondeclareapp/GrantUriPermission.java
index 8c14575..31a3f47 100644
--- a/tests/appsecurity-tests/test-apps/PermissionDeclareApp/src/com/android/cts/permissiondeclareapp/GrantUriPermission.java
+++ b/tests/appsecurity-tests/test-apps/PermissionDeclareApp/src/com/android/cts/permissiondeclareapp/GrantUriPermission.java
@@ -1,3 +1,19 @@
+/*
+ * 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 com.android.cts.permissiondeclareapp;
 
 import android.content.BroadcastReceiver;
diff --git a/tests/appsecurity-tests/test-apps/PermissionDeclareApp/src/com/android/cts/permissiondeclareapp/SetInstallerPackage.java b/tests/appsecurity-tests/test-apps/PermissionDeclareApp/src/com/android/cts/permissiondeclareapp/SetInstallerPackage.java
new file mode 100644
index 0000000..ea06d8c
--- /dev/null
+++ b/tests/appsecurity-tests/test-apps/PermissionDeclareApp/src/com/android/cts/permissiondeclareapp/SetInstallerPackage.java
@@ -0,0 +1,41 @@
+/*
+ * 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 com.android.cts.permissiondeclareapp;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+public class SetInstallerPackage extends BroadcastReceiver {
+    @Override
+    public void onReceive(Context context, Intent intent) {
+        String targetPackage = intent.getStringExtra("target");
+        String installerPackage = intent.getStringExtra("installer");
+        try {
+            context.getPackageManager().setInstallerPackageName(targetPackage, installerPackage);
+            if (isOrderedBroadcast()) {
+                setResultCode(101);
+            }
+        } catch (SecurityException e) {
+            Log.i("SetInstallerPackage", "Security exception", e);
+            if (isOrderedBroadcast()) {
+                setResultCode(100);
+            }
+        }
+    }
+}
diff --git a/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/src/com/android/cts/usespermissiondiffcertapp/ModifyInstallerPackageTest.java b/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/src/com/android/cts/usespermissiondiffcertapp/ModifyInstallerPackageTest.java
new file mode 100644
index 0000000..989e24b
--- /dev/null
+++ b/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/src/com/android/cts/usespermissiondiffcertapp/ModifyInstallerPackageTest.java
@@ -0,0 +1,212 @@
+/*
+ * 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 com.android.cts.usespermissiondiffcertapp;
+
+import android.content.BroadcastReceiver;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.net.Uri;
+import android.os.SystemClock;
+import android.test.AndroidTestCase;
+import android.util.Log;
+
+/**
+ * Tests that one application can and can not modify the installer package
+ * of another application is appropriate.
+ *
+ * Accesses app cts/tests/appsecurity-tests/test-apps/PermissionDeclareApp/...
+ */
+public class ModifyInstallerPackageTest extends AndroidTestCase {
+    static final ComponentName SET_INSTALLER_PACKAGE_COMP
+            = new ComponentName("com.android.cts.permissiondeclareapp",
+                    "com.android.cts.permissiondeclareapp.SetInstallerPackage");
+    static final String OTHER_PACKAGE = "com.android.cts.permissiondeclareapp";
+    static final String MY_PACKAGE = "com.android.cts.usespermissiondiffcertapp";
+
+    static class SetInstallerPackageReceiver extends BroadcastReceiver {
+        boolean mHaveResult = false;
+        boolean mGoodResult = false;
+        boolean mSucceeded = false;
+
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            synchronized (this) {
+                mHaveResult = true;
+                switch (getResultCode()) {
+                    case 100:
+                        mGoodResult = true;
+                        mSucceeded = false;
+                        break;
+                    case 101:
+                        mGoodResult = true;
+                        mSucceeded = true;
+                        break;
+                    default:
+                        mGoodResult = false;
+                        break;
+                }
+                notifyAll();
+            }
+        }
+
+        void assertSuccess(String failureMessage) {
+            synchronized (this) {
+                final long startTime = SystemClock.uptimeMillis();
+                while (!mHaveResult) {
+                    try {
+                        wait(5000);
+                    } catch (InterruptedException e) {
+                    }
+                    if (SystemClock.uptimeMillis() >= (startTime+5000)) {
+                        throw new RuntimeException("Timeout");
+                    }
+                }
+                if (!mGoodResult) {
+                    fail("Broadcast receiver did not return good result");
+                }
+                if (!mSucceeded) {
+                    fail(failureMessage);
+                }
+            }
+        }
+
+        void assertFailure(String failureMessage) {
+            synchronized (this) {
+                final long startTime = SystemClock.uptimeMillis();
+                while (!mHaveResult) {
+                    try {
+                        wait(5000);
+                    } catch (InterruptedException e) {
+                    }
+                    if (SystemClock.uptimeMillis() >= (startTime+5000)) {
+                        throw new RuntimeException("Timeout");
+                    }
+                }
+                if (!mGoodResult) {
+                    fail("Broadcast receiver did not return good result");
+                }
+                if (mSucceeded) {
+                    fail(failureMessage);
+                }
+            }
+        }
+    }
+
+    PackageManager getPackageManager() {
+        return getContext().getPackageManager();
+    }
+
+    /**
+     * Test that we can set the installer package name.
+     */
+    public void testSetInstallPackage() {
+        // Pre-condition.
+        assertEquals(null, getPackageManager().getInstallerPackageName(OTHER_PACKAGE));
+
+        getPackageManager().setInstallerPackageName(OTHER_PACKAGE, MY_PACKAGE);
+        assertEquals(MY_PACKAGE, getPackageManager().getInstallerPackageName(OTHER_PACKAGE));
+
+        // Clean up.
+        getPackageManager().setInstallerPackageName(OTHER_PACKAGE, null);
+        assertEquals(null, getPackageManager().getInstallerPackageName(OTHER_PACKAGE));
+    }
+
+    /**
+     * Test that we fail if trying to set an installer package with an unknown
+     * target package name.
+     */
+    public void testSetInstallPackageBadTarget() {
+        try {
+            getPackageManager().setInstallerPackageName("thisdoesnotexistihope!", MY_PACKAGE);
+            fail("setInstallerPackageName did not throw IllegalArgumentException");
+        } catch (IllegalArgumentException e) {
+            // That's what we want!
+        }
+    }
+
+    /**
+     * Test that we fail if trying to set an installer package with an unknown
+     * installer package name.
+     */
+    public void testSetInstallPackageBadInstaller() {
+        try {
+            getPackageManager().setInstallerPackageName(OTHER_PACKAGE, "thisdoesnotexistihope!");
+            fail("setInstallerPackageName did not throw IllegalArgumentException");
+        } catch (IllegalArgumentException e) {
+            // That's what we want!
+        }
+        assertEquals(null, getPackageManager().getInstallerPackageName(OTHER_PACKAGE));
+    }
+
+    /**
+     * Test that we fail if trying to set an installer package that is not
+     * signed with our cert.
+     */
+    public void testSetInstallPackageWrongCertificate() {
+        // Pre-condition.
+        assertEquals(null, getPackageManager().getInstallerPackageName(OTHER_PACKAGE));
+
+        try {
+            getPackageManager().setInstallerPackageName(OTHER_PACKAGE, OTHER_PACKAGE);
+            fail("setInstallerPackageName did not throw SecurityException");
+        } catch (SecurityException e) {
+            // That's what we want!
+        }
+
+        assertEquals(null, getPackageManager().getInstallerPackageName(OTHER_PACKAGE));
+    }
+
+    /**
+     * Test that we fail if trying to set an installer package that is not
+     * signed with the same cert as the currently set installer.
+     */
+    public void testSetInstallPackageConflictingInstaller() {
+        // Pre-condition.
+        assertEquals(null, getPackageManager().getInstallerPackageName(OTHER_PACKAGE));
+
+        // Have the other package set the installer, under its cert.
+        Intent intent = new Intent();
+        intent.setComponent(SET_INSTALLER_PACKAGE_COMP);
+        intent.putExtra("target", OTHER_PACKAGE);
+        intent.putExtra("installer", OTHER_PACKAGE);
+        SetInstallerPackageReceiver receiver = new SetInstallerPackageReceiver();
+        getContext().sendOrderedBroadcast(intent, null, receiver, null, 0, null, null);
+        receiver.assertSuccess("Failure initializing with other installer");
+
+        assertEquals(OTHER_PACKAGE, getPackageManager().getInstallerPackageName(OTHER_PACKAGE));
+
+        try {
+            getPackageManager().setInstallerPackageName(OTHER_PACKAGE, MY_PACKAGE);
+            fail("setInstallerPackageName did not throw SecurityException");
+        } catch (SecurityException e) {
+            // That's what we want!
+        }
+
+        assertEquals(OTHER_PACKAGE, getPackageManager().getInstallerPackageName(OTHER_PACKAGE));
+
+        // Now clear the installer
+        intent.putExtra("target", OTHER_PACKAGE);
+        intent.putExtra("installer", (String)null);
+        receiver = new SetInstallerPackageReceiver();
+        getContext().sendOrderedBroadcast(intent, null, receiver, null, 0, null, null);
+        receiver.assertSuccess("Failure clearing other installer");
+
+        assertEquals(null, getPackageManager().getInstallerPackageName(OTHER_PACKAGE));
+    }
+}
diff --git a/tests/assets/webkit/jsform.html b/tests/assets/webkit/jsform.html
index ddf01f8..1781194 100644
--- a/tests/assets/webkit/jsform.html
+++ b/tests/assets/webkit/jsform.html
@@ -24,7 +24,7 @@
             }
         }
     </script>
-    <body onload="fireSubmit()">
+    <body onload="window.setTimeout(function() { fireSubmit(); }, 0);">
         javascript form test
         <form id="formId" action="test.html#result" method="post">
             <input type="hidden" name="foo" value="bar" />
diff --git a/tests/core/luni-io/Android.mk b/tests/core/luni-io/Android.mk
index ed39e03..6669c6a 100644
--- a/tests/core/luni-io/Android.mk
+++ b/tests/core/luni-io/Android.mk
@@ -24,7 +24,7 @@
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES := $(call all-java-files-under,../../../../libcore/luni/src/test/java/tests/api/java/io) \
-	$(call all-java-files-under,../../../../libcore/luni/src/test/java/org/apache/harmony/luni/tests/java/io) \
+	$(call all-java-files-under,../../../../libcore/luni/src/test/java/libcore/java/io) \
 	$(call all-java-files-under,../../../../libcore/support/src/test/java/) \
 	$(call all-java-files-under,../../../../libcore/luni/src/test/java/org/apache/harmony/luni/tests/pkg1) \
 	$(call all-java-files-under,../../../../libcore/luni/src/test/java/org/apache/harmony/luni/tests/pkg2) \
diff --git a/tests/core/luni-lang/Android.mk b/tests/core/luni-lang/Android.mk
index a31b881..c3528ec 100644
--- a/tests/core/luni-lang/Android.mk
+++ b/tests/core/luni-lang/Android.mk
@@ -23,7 +23,7 @@
 ##########################################################
 include $(CLEAR_VARS)
 
-LOCAL_SRC_FILES := $(call all-java-files-under,../../../../libcore/luni/src/test/java/org/apache/harmony/luni/tests/java/lang) \
+LOCAL_SRC_FILES := \
 	$(call all-java-files-under,../../../../libcore/luni/src/test/java/tests/api/java/lang) \
 	$(call all-java-files-under,../../../../libcore/support/src/test/java/) \
 	../../../../libcore/luni/src/test/java/tests/luni/AllTestsLang.java
diff --git a/tests/core/xml/Android.mk b/tests/core/xml/Android.mk
index 4f8af07..0f643a0 100644
--- a/tests/core/xml/Android.mk
+++ b/tests/core/xml/Android.mk
@@ -26,7 +26,6 @@
 LOCAL_SRC_FILES := $(call all-java-files-under,../../../../libcore/xml/src/test/java) \
 	$(call all-java-files-under,../../../../libcore/dom/src/test) \
 	$(call all-java-files-under,../../../../libcore/junit/src/test/java/junit) \
-	$(call all-java-files-under,../../../../libcore/luni/src/test/java/org/apache/harmony/xml) \
 	$(call all-java-files-under,../../../../libcore/luni/src/test/java/tests/api/javax/xml/parsers) \
 	$(call all-java-files-under,../../../../libcore/luni/src/test/java/tests/api/org/xml/sax) \
 	$(call all-java-files-under,../../../../libcore/luni/src/test/java/tests/api/org/xml/sax/support) \
diff --git a/tests/expectations/knownfailures-2.3_r1.txt b/tests/expectations/knownfailures-2.3_r1.txt
deleted file mode 100644
index 2be2078..0000000
--- a/tests/expectations/knownfailures-2.3_r1.txt
+++ /dev/null
@@ -1,34 +0,0 @@
-[
-/* These tests consistently fail on GRH78. */
-{ name: "android.location.cts.GeocoderTest#testGetFromLocation" },
-{ name: "android.location.cts.GeocoderTest#testGetFromLocationName" },
-{ name: "android.net.cts.ListeningPortsTest#testNoListeningUdp6Ports" },
-{ name: "android.webkit.cts.WebSettingsTest#testSetAppCacheEnabled" },
-{ name: "android.net.cts.SSLCertificateSocketFactoryTest" },
-
-/* These tests pass when executed individually but fail when running CTS as a whole on GRH78. */
-{
-  name: "org.apache.harmony.luni.tests.internal.net.www.protocol.https.HttpsURLConnectionTest#testProxyConnection",
-  bug: 3184701
-},
-{
-  name: "org.apache.harmony.luni.tests.internal.net.www.protocol.https.HttpsURLConnectionTest#testProxyAuthConnection",
-  bug: 3184701
-},
-{
-  name: "org.apache.harmony.luni.tests.internal.net.www.protocol.https.HttpsURLConnectionTest#testConsequentProxyConnection",
-  bug: 3184701
-},
-{
-  name: "org.apache.harmony.luni.tests.internal.net.www.protocol.https.HttpsURLConnectionTest#testProxyAuthConnection_doOutput",
-  bug: 3184701
-},
-{
-  name: "org.apache.harmony.luni.tests.internal.net.www.protocol.https.HttpsURLConnectionTest#testProxyAuthConnectionFailed",
-  bug: 3184701
-},
-{
-  name: "org.apache.harmony.luni.tests.internal.net.www.protocol.https.HttpsURLConnectionTest#testProxyConnection_Not_Found_Response",
-  bug: 3184701
-}
-]
diff --git a/tests/res/layout/checkedtextview_layout.xml b/tests/res/layout/checkedtextview_layout.xml
index f8085a39..d5b9c1f 100644
--- a/tests/res/layout/checkedtextview_layout.xml
+++ b/tests/res/layout/checkedtextview_layout.xml
@@ -16,7 +16,7 @@
 
 <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">
 
     <ListView android:id="@+id/checkedtextview_listview"
         android:orientation="vertical"
diff --git a/tests/res/layout/dialog_stub_layout.xml b/tests/res/layout/dialog_stub_layout.xml
index 11b502f..b0a8861 100644
--- a/tests/res/layout/dialog_stub_layout.xml
+++ b/tests/res/layout/dialog_stub_layout.xml
@@ -14,65 +14,8 @@
      limitations under the License.
 -->
 
-<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/screen"
-    android:layout_width="match_parent" android:layout_height="match_parent"
-    android:orientation="vertical">
-    <LinearLayout
-        android:layout_width="match_parent" android:layout_height="match_parent"
-        android:orientation="vertical">
-        <Button android:id="@+id/dialog_test_button_1"
-            android:layout_width="match_parent" android:layout_height="wrap_content"
-            android:text="@string/dialog_stub_dialog_test_button1"/>
-        <Button android:id="@+id/dialog_test_button_2"
-            android:layout_width="match_parent" android:layout_height="wrap_content"
-            android:text="@string/dialog_stub_dialog_test_button2"/>
-        <Button android:id="@+id/dialog_test_button_3"
-            android:layout_width="match_parent" android:layout_height="wrap_content"
-            android:text="@string/dialog_stub_dialog_test_button3"/>
-        <Button android:id="@+id/dialog_test_button_4"
-            android:layout_width="match_parent" android:layout_height="wrap_content"
-            android:text="@string/dialog_stub_dialog_test_button4"/>
-        <Button android:id="@+id/dialog_test_button_5"
-            android:layout_width="match_parent" android:layout_height="wrap_content"
-            android:text="@string/dialog_stub_dialog_test_button5"/>
-        <Button android:id="@+id/dialog_test_button_6"
-            android:layout_width="match_parent" android:layout_height="wrap_content"
-            android:text="@string/dialog_stub_dialog_test_button6"/>
-        <Button android:id="@+id/dialog_test_button_7"
-            android:layout_width="match_parent" android:layout_height="wrap_content"
-            android:text="@string/dialog_stub_dialog_test_button7"/>
-        <Button android:id="@+id/dialog_test_button_8"
-            android:layout_width="match_parent" android:layout_height="wrap_content"
-            android:text="@string/dialog_stub_dialog_test_button8"/>
-        <Button android:id="@+id/dialog_test_button_9"
-            android:layout_width="match_parent" android:layout_height="wrap_content"
-            android:text="@string/dialog_stub_dialog_test_button9"/>
-        <Button android:id="@+id/dialog_test_button_10"
-            android:layout_width="match_parent" android:layout_height="wrap_content"
-            android:text="@string/dialog_stub_dialog_test_button10"/>
-        <Button android:id="@+id/dialog_test_button_11"
-            android:layout_width="match_parent" android:layout_height="wrap_content"
-            android:text="@string/dialog_stub_dialog_test_button11"/>
-        <Button android:id="@+id/dialog_test_button_12"
-            android:layout_width="match_parent" android:layout_height="wrap_content"
-            android:text="@string/dialog_stub_dialog_test_button12"/>
-        <Button android:id="@+id/dialog_test_button_13"
-            android:layout_width="match_parent" android:layout_height="wrap_content"
-            android:text="@string/dialog_stub_dialog_test_button13"/>
-         <Button android:id="@+id/dialog_test_button_14"
-            android:layout_width="match_parent" android:layout_height="wrap_content"
-            android:text="@string/dialog_stub_dialog_test_button14"/>
-        <Button android:id="@+id/dialog_test_button_15"
-            android:layout_width="match_parent" android:layout_height="wrap_content"
-            android:text="@string/dialog_stub_dialog_test_button15"/>
-        <Button android:id="@+id/dialog_test_button_16"
-            android:layout_width="match_parent" android:layout_height="wrap_content"
-            android:text="@string/dialog_stub_dialog_test_button16"/>
-        <Button android:id="@+id/dialog_test_button_17"
-            android:layout_width="match_parent" android:layout_height="wrap_content"
-            android:text="@string/dialog_stub_dialog_test_button17"/>
-        <Button android:id="@+id/dialog_test_button_18"
-            android:layout_width="match_parent" android:layout_height="wrap_content"
-            android:text="@string/dialog_stub_dialog_test_button18"/>
-    </LinearLayout>
-</ScrollView>
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
+        android:layout_width="match_parent" 
+        android:layout_height="match_parent"
+        >
+</LinearLayout>
diff --git a/tests/res/values/strings.xml b/tests/res/values/strings.xml
index a779b47..8fcd75a 100644
--- a/tests/res/values/strings.xml
+++ b/tests/res/values/strings.xml
@@ -40,24 +40,6 @@
     <string name="text">DialogTest</string>
     <string name="text_country">Country</string>
     <string name="text_name">Name</string>
-    <string name="dialog_stub_dialog_test_button1">Test Dialog without theme</string>
-    <string name="dialog_stub_dialog_test_button2">Test Dialog with theme</string>
-    <string name="dialog_stub_dialog_test_button3">Test AlertDialog</string>
-    <string name="dialog_stub_dialog_test_button4">Test AlertDialog with theme</string>
-    <string name="dialog_stub_dialog_test_button5">Test DatePickerDialog</string>
-    <string name="dialog_stub_dialog_test_button6">Test DatePickerDialog with theme</string>
-    <string name="dialog_stub_dialog_test_button7">Test TimePickerDialog</string>
-    <string name="dialog_stub_dialog_test_button8">Test TimePickerDialog with theme</string>
-    <string name="dialog_stub_dialog_test_button9">Test onStart() and onStop()</string>
-    <string name="dialog_stub_dialog_test_button10">Test AlertDialog deprecated</string>
-    <string name="dialog_stub_dialog_test_button11">Test AlertDialog callback</string>
-    <string name="dialog_stub_dialog_test_button12">Test AlertDialog setview </string>
-    <string name="dialog_stub_dialog_test_button13">Test AlertDialog deprecated with Message</string>
-    <string name="dialog_stub_dialog_test_button14">Test AlertDialog with theme</string>
-    <string name="dialog_stub_dialog_test_button15">Test AlertDialog cancelable</string>
-    <string name="dialog_stub_dialog_test_button16">Test AlertDialog can\'n cancelable</string>
-    <string name="dialog_stub_dialog_test_button17">Test Dialog cancelable</string>
-    <string name="dialog_stub_dialog_test_button18">Test Dialog not cancelable</string>
     <string name="hello_world">Hello, World!</string>
     <string name="hello_android">Hello, Android!</string>
     <string name="alert_dialog_username">Name:</string>
diff --git a/tests/src/android/app/cts/DialogStubActivity.java b/tests/src/android/app/cts/DialogStubActivity.java
index f715b51..817e716 100644
--- a/tests/src/android/app/cts/DialogStubActivity.java
+++ b/tests/src/android/app/cts/DialogStubActivity.java
@@ -16,6 +16,8 @@
 
 package android.app.cts;
 
+import com.android.cts.stub.R;
+
 import android.app.Activity;
 import android.app.AlertDialog;
 import android.app.DatePickerDialog;
@@ -25,21 +27,19 @@
 import android.app.TimePickerDialog.OnTimeSetListener;
 import android.content.Context;
 import android.content.DialogInterface;
+import android.content.Intent;
 import android.content.DialogInterface.OnCancelListener;
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.Message;
+import android.test.ActivityInstrumentationTestCase2;
 import android.util.Log;
 import android.view.KeyEvent;
 import android.view.LayoutInflater;
 import android.view.View;
-import android.view.View.OnClickListener;
-import android.widget.Button;
 import android.widget.DatePicker;
 import android.widget.TimePicker;
 
-import com.android.cts.stub.R;
-
 /*
  * Stub class for  Dialog, AlertDialog, DatePickerDialog, TimePickerDialog etc.
  */
@@ -289,49 +289,27 @@
         return (String) mDialog.getWindow().getAttributes().getTitle();
     }
 
+    private static final String TEST_DIALOG_NUMBER_EXTRA = "testDialogNumber";
+
+    public static <T extends Activity> T startDialogActivity(
+            ActivityInstrumentationTestCase2<T> testCase, int dialogNumber) {
+        Intent intent = new Intent(Intent.ACTION_MAIN);
+        intent.putExtra(TEST_DIALOG_NUMBER_EXTRA, dialogNumber);
+        testCase.setActivityIntent(intent);
+        return testCase.getActivity();
+    }
+
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
 
         setContentView(R.layout.dialog_stub_layout);
 
-        findViewById(R.id.dialog_test_button_1).setOnClickListener(
-                new MockClickListener(TEST_DIALOG_WITHOUT_THEME));
-        findViewById(R.id.dialog_test_button_2).setOnClickListener(
-                new MockClickListener(TEST_DIALOG_WITH_THEME));
-        findViewById(R.id.dialog_test_button_3).setOnClickListener(
-                new MockClickListener(TEST_ALERTDIALOG));
-        findViewById(R.id.dialog_test_button_4).setOnClickListener(
-                new MockClickListener(TEST_CUSTOM_ALERTDIALOG));
-        final Button dialogTestButton5 = (Button) findViewById(R.id.dialog_test_button_5);
-        dialogTestButton5.setOnClickListener(new MockClickListener(TEST_DATEPICKERDIALOG));
-        findViewById(R.id.dialog_test_button_6).setOnClickListener(
-                new MockClickListener(TEST_DATEPICKERDIALOG_WITH_THEME));
-        findViewById(R.id.dialog_test_button_7).setOnClickListener(
-                new MockClickListener(TEST_TIMEPICKERDIALOG));
-        findViewById(R.id.dialog_test_button_8).setOnClickListener(
-                new MockClickListener(TEST_TIMEPICKERDIALOG_WITH_THEME));
-        findViewById(R.id.dialog_test_button_9).setOnClickListener(
-                new MockClickListener(TEST_ONSTART_AND_ONSTOP));
-        findViewById(R.id.dialog_test_button_10).setOnClickListener(
-                new MockClickListener(TEST_ALERTDIALOG_DEPRECATED));
-        findViewById(R.id.dialog_test_button_11).setOnClickListener(
-                new MockClickListener(TEST_ALERTDIALOG_CALLBACK));
-        findViewById(R.id.dialog_test_button_12).setOnClickListener(
-                new MockClickListener(TEST_CUSTOM_ALERTDIALOG_VIEW));
-        findViewById(R.id.dialog_test_button_13).setOnClickListener(
-                new MockClickListener(TEST_ALERTDIALOG_DEPRECATED_WITH_MESSAGE));
-
-        findViewById(R.id.dialog_test_button_14).setOnClickListener(
-                new MockClickListener(TEST_ALERTDIALOG_THEME));
-        findViewById(R.id.dialog_test_button_15).setOnClickListener(
-                new MockClickListener(TEST_ALERTDIALOG_CANCELABLE));
-        findViewById(R.id.dialog_test_button_16).setOnClickListener(
-                new MockClickListener(TEST_ALERTDIALOG_NOT_CANCELABLE));
-        findViewById(R.id.dialog_test_button_17).setOnClickListener(
-                new MockClickListener(TEST_PROTECTED_CANCELABLE));
-        findViewById(R.id.dialog_test_button_18).setOnClickListener(
-                new MockClickListener(TEST_PROTECTED_NOT_CANCELABLE));
+        Intent intent = getIntent();
+        int dialogNum = intent.getIntExtra(TEST_DIALOG_NUMBER_EXTRA, -1);
+        if (dialogNum != -1) {
+            showDialog(dialogNum);
+        }
     }
 
     public void setUpTitle(final String title) {
@@ -383,18 +361,6 @@
 
     }
 
-    private class MockClickListener implements OnClickListener {
-        private final int mId;
-
-        public MockClickListener(final int id) {
-            mId = id;
-        }
-
-        public void onClick(View v) {
-            showDialog(mId);
-        }
-    }
-
     class MockOnClickListener implements DialogInterface.OnClickListener {
         private final int mId;
 
diff --git a/tests/src/android/app/cts/LaunchpadActivity.java b/tests/src/android/app/cts/LaunchpadActivity.java
index fa18ec5..7191e03 100644
--- a/tests/src/android/app/cts/LaunchpadActivity.java
+++ b/tests/src/android/app/cts/LaunchpadActivity.java
@@ -184,20 +184,20 @@
             });
         } else if (LIFECYCLE_SCREEN.equals(action)) {
             addPossibleLifecycle(LIFECYCLE_SCREEN + "_RESTART", new String[] {
-                    ON_START, ON_RESUME, DO_LOCAL_SCREEN, ON_FREEZE, ON_PAUSE,
+                    ON_START, ON_RESUME, DO_LOCAL_SCREEN, ON_PAUSE,
                     ON_RESTART, ON_START, ON_RESUME, DO_FINISH, ON_PAUSE
             });
             addPossibleLifecycle(LIFECYCLE_SCREEN + "_RESUME", new String[] {
-                    ON_START, ON_RESUME, DO_LOCAL_SCREEN, ON_FREEZE, ON_PAUSE,
+                    ON_START, ON_RESUME, DO_LOCAL_SCREEN, ON_PAUSE,
                     ON_RESUME, DO_FINISH, ON_PAUSE
             });
         } else if (LIFECYCLE_DIALOG.equals(action)) {
             addPossibleLifecycle(LIFECYCLE_DIALOG + "_RESTART", new String[] {
-                    ON_START, ON_RESUME, DO_LOCAL_DIALOG, ON_FREEZE, ON_PAUSE,
+                    ON_START, ON_RESUME, DO_LOCAL_DIALOG, ON_PAUSE,
                     ON_RESTART, ON_START, ON_RESUME, DO_FINISH, ON_PAUSE
             });
             addPossibleLifecycle(LIFECYCLE_DIALOG + "_RESUME", new String[] {
-                    ON_START, ON_RESUME, DO_LOCAL_DIALOG, ON_FREEZE, ON_PAUSE,
+                    ON_START, ON_RESUME, DO_LOCAL_DIALOG, ON_PAUSE,
                     ON_RESUME, DO_FINISH, ON_PAUSE
             });
         }
@@ -399,7 +399,6 @@
     @Override
     protected void onSaveInstanceState(Bundle icicle) {
         super.onSaveInstanceState(icicle);
-        checkLifecycle(ON_FREEZE);
         if (mBadParcelable) {
             icicle.putParcelable("baddy", new MyBadParcelable());
         }
@@ -451,13 +450,15 @@
 
         do {
             if (mExpectedLifecycle[mNextLifecycle].equals(where)) {
+                Log.w(TAG, "Matched: " + where);
                 break;
+            } else {
+                Log.w(TAG, "Expected " + mExpectedLifecycle[mNextLifecycle] + " but got " + where);
             }
         } while (switchToNextPossibleLifecycle());
 
         if (mExpectedLifecycle == null) {
             finishBad("Activity lifecycle for " + action + " incorrect: received " + where
-                    + " but expected " + mExpectedLifecycle[mNextLifecycle]
                     + " at " + mNextLifecycle);
             return;
         }
diff --git a/tests/src/android/app/cts/LocalActivityManagerTestHelper.java b/tests/src/android/app/cts/LocalActivityManagerTestHelper.java
index 0d21a9c..76af648 100644
--- a/tests/src/android/app/cts/LocalActivityManagerTestHelper.java
+++ b/tests/src/android/app/cts/LocalActivityManagerTestHelper.java
@@ -28,7 +28,7 @@
 public class LocalActivityManagerTestHelper extends ActivityGroup {
 
     public static final String ACTION_DISPATCH_RESUME = "dispatchResume";
-    public static final String ACTION_START_ACTIIVTY = "startActivity";
+    public static final String ACTION_START_ACTIVITY = "startActivity";
     public static final String ACTION_DISPATCH_CREATE = "dispatchCreate";
     public static final String ACTION_DISPATCH_STOP = "dispatchStop";
     public static final String ACTION_DISPATCH_PAUSE_TRUE = "dispatchPauseTrue";
@@ -66,7 +66,7 @@
         super.onResume();
         if (mCurrentAction.equals(ACTION_DISPATCH_RESUME)) {
             testDispatchResume();
-        } else if (mCurrentAction.equals(ACTION_START_ACTIIVTY)) {
+        } else if (mCurrentAction.equals(ACTION_START_ACTIVITY)) {
             testStartActivity();
         } else if (mCurrentAction.equals(ACTION_DISPATCH_CREATE)) {
             testDispatchCreate();
@@ -109,9 +109,7 @@
             fail();
             return;
         }
-
-        sResult.setResult(CTSResult.RESULT_OK);
-        finish();
+        pass();
     }
 
     private void testDispatchDestroy() {
@@ -146,9 +144,7 @@
             fail();
             return;
         }
-
-        sResult.setResult(CTSResult.RESULT_OK);
-        finish();
+        pass();
     }
 
     private void testSaveInstanceState() {
@@ -175,9 +171,7 @@
             fail();
             return;
         }
-
-        sResult.setResult(CTSResult.RESULT_OK);
-        finish();
+        pass();
     }
 
     private void testDispatchPauseFalse() {
@@ -191,9 +185,7 @@
             fail();
             return;
         }
-
-        sResult.setResult(CTSResult.RESULT_OK);
-        finish();
+        pass();
     }
 
     private void testDispatchPauseTrue() {
@@ -207,9 +199,7 @@
             fail();
             return;
         }
-
-        sResult.setResult(CTSResult.RESULT_OK);
-        finish();
+        pass();
     }
 
     private void testDispatchStop() {
@@ -229,9 +219,7 @@
             fail();
             return;
         }
-
-        sResult.setResult(CTSResult.RESULT_OK);
-        finish();
+        pass();
     }
 
     private void testDispatchCreate() {
@@ -269,8 +257,7 @@
             fail();
             return;
         }
-        sResult.setResult(CTSResult.RESULT_OK);
-        finish();
+        pass();
     }
 
     private void testStartActivity() {
@@ -324,13 +311,7 @@
             return;
         } catch (NullPointerException e) {
         }
-        sResult.setResult(CTSResult.RESULT_OK);
-        finish();
-    }
-
-    private void fail() {
-        sResult.setResult(CTSResult.RESULT_FAIL);
-        finish();
+        pass();
     }
 
     private void testDispatchResume() {
@@ -341,11 +322,19 @@
         LocalActivityManagerStubActivity.sIsOnResumeCalled = false;
         mLocalActivityManager.dispatchResume();
         if (LocalActivityManagerStubActivity.sIsOnResumeCalled) {
-            sResult.setResult(CTSResult.RESULT_OK);
+            pass();
         } else {
-            sResult.setResult(CTSResult.RESULT_FAIL);
+            fail();
         }
+    }
+
+    private void fail() {
+        sResult.setResult(CTSResult.RESULT_FAIL);
         finish();
     }
 
+    private void pass() {
+        sResult.setResult(CTSResult.RESULT_OK);
+        finish();
+    }
 }
diff --git a/tests/src/android/content/cts/MockSyncAdapter.java b/tests/src/android/content/cts/MockSyncAdapter.java
index 32b3a8d..df24749 100644
--- a/tests/src/android/content/cts/MockSyncAdapter.java
+++ b/tests/src/android/content/cts/MockSyncAdapter.java
@@ -23,13 +23,14 @@
 import android.os.Bundle;
 import android.os.RemoteException;
 
+import java.util.ArrayList;
 import java.util.concurrent.CountDownLatch;
 
 public class MockSyncAdapter extends ISyncAdapter.Stub {
 
     private static MockSyncAdapter sSyncAdapter = null;
 
-    private Account mAccount;
+    private ArrayList<Account> mAccounts = new ArrayList<Account>();
     private String mAuthority;
     private Bundle mExtras;
     private boolean mInitialized;
@@ -37,8 +38,8 @@
     private boolean mCancelSync;
     private CountDownLatch mLatch;
 
-    public Account getAccount() {
-        return mAccount;
+    public ArrayList<Account> getAccounts() {
+        return mAccounts;
     }
 
     public String getAuthority() {
@@ -62,7 +63,7 @@
     }
 
     public void clearData() {
-        mAccount = null;
+        mAccounts.clear();
         mAuthority = null;
         mExtras = null;
         mInitialized = false;
@@ -78,7 +79,7 @@
     public void startSync(ISyncContext syncContext, String authority, Account account,
             Bundle extras) throws RemoteException {
 
-        mAccount = account;
+        mAccounts.add(account);
         mAuthority = authority;
         mExtras = extras;
 
@@ -98,7 +99,7 @@
     }
 
     public void cancelSync(ISyncContext syncContext) throws RemoteException {
-        mAccount = null;
+        mAccounts.clear();
         mAuthority = null;
         mExtras = null;
 
@@ -114,7 +115,7 @@
     public void initialize(android.accounts.Account account, java.lang.String authority)
             throws android.os.RemoteException {
 
-        mAccount = account;
+        mAccounts.add(account);
         mAuthority = authority;
 
         mInitialized = true;
diff --git a/tests/src/android/provider/cts/FileCopyHelper.java b/tests/src/android/provider/cts/FileCopyHelper.java
index a9c53e5..4ee93ac 100644
--- a/tests/src/android/provider/cts/FileCopyHelper.java
+++ b/tests/src/android/provider/cts/FileCopyHelper.java
@@ -18,6 +18,8 @@
 
 import android.content.Context;
 
+import java.io.File;
+import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
@@ -95,4 +97,18 @@
             mContext.deleteFile(path);
         }
     }
+
+    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();
+        }
+    }
 }
diff --git a/tests/src/android/provider/cts/MediaStoreAudioTestHelper.java b/tests/src/android/provider/cts/MediaStoreAudioTestHelper.java
index 3cc3bbe..e6c9809 100644
--- a/tests/src/android/provider/cts/MediaStoreAudioTestHelper.java
+++ b/tests/src/android/provider/cts/MediaStoreAudioTestHelper.java
@@ -112,7 +112,7 @@
         public static final String EXTERNAL_DATA = Environment.getExternalStorageDirectory() +
                 "/" + FILE_NAME;
 
-        public static final long DATE_MODIFIED = System.currentTimeMillis();
+        public static final long DATE_MODIFIED = System.currentTimeMillis() / 1000;
 
         public static final String GENRE = "POP";
         @Override
diff --git a/tests/src/android/provider/cts/TestSearchRecentSuggestionsProvider.java b/tests/src/android/provider/cts/TestSearchRecentSuggestionsProvider.java
new file mode 100644
index 0000000..d1cb1ef
--- /dev/null
+++ b/tests/src/android/provider/cts/TestSearchRecentSuggestionsProvider.java
@@ -0,0 +1,29 @@
+/*
+ * 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.provider.cts;
+
+import android.content.SearchRecentSuggestionsProvider;
+
+public class TestSearchRecentSuggestionsProvider extends SearchRecentSuggestionsProvider {
+    final static String AUTHORITY = "android.provider.cts.TestSRSProvider";
+    final static int MODE = DATABASE_MODE_QUERIES + DATABASE_MODE_2LINES;
+
+    public TestSearchRecentSuggestionsProvider() {
+        super();
+        setupSuggestions(AUTHORITY, MODE);
+    }
+}
diff --git a/tests/src/android/view/cts/FocusHandlingStubActivity.java b/tests/src/android/view/cts/FocusHandlingStubActivity.java
index 2124550..9faa609 100644
--- a/tests/src/android/view/cts/FocusHandlingStubActivity.java
+++ b/tests/src/android/view/cts/FocusHandlingStubActivity.java
@@ -16,9 +16,10 @@
 
 package android.view.cts;
 
+import com.android.cts.stub.R;
+
 import android.app.Activity;
 import android.os.Bundle;
-import com.android.cts.stub.R;
 
 /**
  * A simple activity to test "Focus Handling"
@@ -27,6 +28,7 @@
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
+        setTheme(android.R.style.Theme_Holo_NoActionBar);
         setContentView(R.layout.focus_handling_layout);
     }
 }
diff --git a/tests/src/android/webkit/cts/CtsTestServer.java b/tests/src/android/webkit/cts/CtsTestServer.java
index 075f98d..91f4f1e 100644
--- a/tests/src/android/webkit/cts/CtsTestServer.java
+++ b/tests/src/android/webkit/cts/CtsTestServer.java
@@ -403,14 +403,12 @@
         if (path.startsWith(AUTH_PREFIX)) {
             // authentication required
             Header[] auth = request.getHeaders("Authorization");
-            if (auth.length > 0) {
-                if (auth[0].getValue().equals(AUTH_CREDENTIALS)) {
-                    // fall through and serve content
-                    path = path.substring(AUTH_PREFIX.length());
-                } else {
-                    // incorrect password
-                    response = createResponse(HttpStatus.SC_FORBIDDEN);
-                }
+            if ((auth.length > 0 && auth[0].getValue().equals(AUTH_CREDENTIALS))
+                // This is a hack to make sure that loads to this url's will always
+                // ask for authentication. This is what the test expects.
+                 && !path.endsWith("embedded_image.html")) {
+                // fall through and serve content
+                path = path.substring(AUTH_PREFIX.length());
             } else {
                 // request authorization
                 response = createResponse(HttpStatus.SC_UNAUTHORIZED);
diff --git a/tests/tests/accessibilityservice/AndroidManifest.xml b/tests/tests/accessibilityservice/AndroidManifest.xml
index 811c87f..b4fe6ab 100644
--- a/tests/tests/accessibilityservice/AndroidManifest.xml
+++ b/tests/tests/accessibilityservice/AndroidManifest.xml
@@ -24,7 +24,7 @@
       <uses-library android:name="android.test.runner"/>
 
       <activity android:label="@string/accessibility_end_to_end_test_activity"
-                android:name="android.accessibilityservice.cts.AccessibilityEndToEndTestActivity"/>
+              android:name="android.accessibilityservice.cts.AccessibilityEndToEndTestActivity"/>
 
   </application>
 
diff --git a/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityEndToEndTest.java b/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityEndToEndTest.java
index 5259753..89e5473 100644
--- a/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityEndToEndTest.java
+++ b/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityEndToEndTest.java
@@ -16,6 +16,8 @@
 
 package android.accessibilityservice.cts;
 
+import com.android.cts.accessibilityservice.R;
+
 import android.accessibilityservice.AccessibilityService;
 import android.accessibilityservice.IAccessibilityServiceDelegate;
 import android.accessibilityservice.IAccessibilityServiceDelegateConnection;
@@ -33,6 +35,7 @@
 import android.content.ServiceConnection;
 import android.content.pm.PackageManager;
 import android.content.pm.PackageManager.NameNotFoundException;
+import android.os.Build;
 import android.os.Handler;
 import android.os.IBinder;
 import android.os.Message;
@@ -47,8 +50,6 @@
 import android.widget.EditText;
 import android.widget.ListView;
 
-import com.android.cts.accessibilityservice.R;
-
 import junit.framework.TestCase;
 
 import java.util.Iterator;
@@ -56,23 +57,25 @@
 import java.util.List;
 import java.util.Queue;
 
+import junit.framework.TestCase;
+
 /**
  * This class performs end-to-end testing of the accessibility feature by
  * creating an {@link Activity} and poking around so {@link AccessibilityEvent}s
  * are generated and their correct dispatch verified.
- * </p>
- * Note: The end-to-end test is composed of two APKs, one with a delegating accessibility
+ * <p>
+ * Note: The end-to-end test is composed of two APKs, one with a mock accessibility
  * service, another with the instrumented activity and test cases. The motivation for
  * two APKs design is that CTS tests cannot access the secure settings which is
  * required for enabling accessibility and accessibility services. Therefore, manual
- * installation of the <strong>CtsDelegatingAccessibilityService.apk</strong>
- * whose source is located at <strong>cts/tests/accessibilityservice</strong> is required.
+ * installation of the <strong>CtsAccessibilityServiceTestMockService.apk</strong>
+ * whose source is located at <strong>cts/tests/accessibility</strong> is required.
  * Once the former package has been installed accessibility must be enabled (Settings ->
- * Accessibility), the delegating service must be enabled (Settings -> Accessibility
- * -> Delegating Accessibility Service), and then the CTS tests in this package can be
- * successfully run. Further, the delegate and tests run in separate processes since
+ * Accessibility), the mock service must be enabled (Settings -> Accessibility
+ * -> Mock Accessibility Service), and then the CTS tests in this package can be
+ * successfully run. Further, the mock and tests run in separate processes since
  * the instrumentation restarts the process in which it is running and this
- * breaks the binding between the delegating accessibility service and the system.
+ * breaks the binding between the mock accessibility service and the system.
  */
 public class AccessibilityEndToEndTest extends
         ActivityInstrumentationTestCase2<AccessibilityEndToEndTestActivity> {
@@ -114,15 +117,7 @@
      * @throws Exception If any error occurs.
      */
     public AccessibilityEndToEndTest() throws Exception {
-        super("com.android.cts.accessibilityservice", AccessibilityEndToEndTestActivity.class);
-    }
-
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
-        // wait for the activity to settle down so we do not receive
-        // the event for its start, thus breaking the tests
-        getInstrumentation().waitForIdleSync();
+        super(AccessibilityEndToEndTestActivity.class);
     }
 
     @LargeTest
@@ -224,8 +219,13 @@
         focusedEvent.setClassName(Button.class.getName());
         focusedEvent.setPackageName(getActivity().getPackageName());
         focusedEvent.getText().add(activity.getString(R.string.button_title));
-        focusedEvent.setItemCount(3);
-        focusedEvent.setCurrentItemIndex(2);
+        if (hasActivityActionBar()) {
+            focusedEvent.setItemCount(4);
+            focusedEvent.setCurrentItemIndex(3);
+        } else {
+            focusedEvent.setItemCount(3);
+            focusedEvent.setCurrentItemIndex(2);
+        }
         focusedEvent.setEnabled(true);
 
         // set expectations
@@ -247,7 +247,7 @@
 
     @LargeTest
     public void testTypeViewTextChangedAccessibilityEvent() throws Throwable {
-        Activity activity = getActivity();
+        final Activity activity = getActivity();
 
         // focus the edit text
         final EditText editText = (EditText) activity.findViewById(R.id.edittext);
@@ -413,6 +413,14 @@
         throw lastVerifyThrowable;
     }
 
+    /**
+     * @return Whether the activity has action bar.
+     */
+    private boolean hasActivityActionBar() {
+        return (getActivity().getApplicationInfo().targetSdkVersion
+                >= Build.VERSION_CODES.HONEYCOMB);
+    }
+
     static class MockAccessibilityService extends AccessibilityService implements
             ServiceConnection {
 
@@ -606,7 +614,6 @@
                 }
                 AccessibilityEvent expectedEvent = mExpectedEvents.poll();
                 assertEqualsAccessiblityEvent(expectedEvent, receivedEvent);
-
             }
         }
 
@@ -677,8 +684,7 @@
                     receivedEvent.isFullScreen());
             TestCase.assertEquals("itemCount has incorrect value", expectedEvent.getItemCount(),
                     receivedEvent.getItemCount());
-            // This will fail due to a bug fixed in Gingerbread. Bug 2593810 (removed the method).
-            // assertEqualsNotificationAsParcelableData(expectedEvent, receivedEvent);
+            assertEqualsNotificationAsParcelableData(expectedEvent, receivedEvent);
             TestCase.assertEquals("password has incorrect value", expectedEvent.isPassword(),
                     receivedEvent.isPassword());
             TestCase.assertEquals("removedCount has incorrect value", expectedEvent
@@ -687,6 +693,30 @@
         }
 
         /**
+         * Compares the {@link android.os.Parcelable} data of the
+         * <code>expectedEvent</code> and <code>receivedEvent</code> to verify
+         * that the received event is the one that is expected.
+         */
+        private void assertEqualsNotificationAsParcelableData(AccessibilityEvent expectedEvent,
+                AccessibilityEvent receivedEvent) {
+            String message = "parcelableData has incorrect value";
+            Notification expectedNotification = (Notification) expectedEvent.getParcelableData();
+            Notification receivedNotification = (Notification) receivedEvent.getParcelableData();
+
+            if (expectedNotification == null) {
+                if (receivedNotification == null) {
+                    return;
+                }
+            }
+
+            TestCase.assertNotNull(message, receivedNotification);
+
+            // we do a very simple sanity check
+            TestCase.assertEquals(message, expectedNotification.tickerText.toString(),
+                    receivedNotification.tickerText.toString());
+        }
+
+        /**
          * Compares the text of the <code>expectedEvent</code> and
          * <code>receivedEvent</code> by comparing the string representation of
          * the corresponding {@link CharSequence}s.
diff --git a/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityEndToEndTestActivity.java b/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityEndToEndTestActivity.java
index e806622..adfc9e6 100644
--- a/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityEndToEndTestActivity.java
+++ b/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityEndToEndTestActivity.java
@@ -16,6 +16,8 @@
 
 package android.accessibilityservice.cts;
 
+import com.android.cts.accessibilityservice.R;
+
 import android.app.Activity;
 import android.content.Context;
 import android.os.Bundle;
@@ -26,8 +28,6 @@
 import android.widget.ListView;
 import android.widget.TextView;
 
-import com.android.cts.accessibilityservice.R;
-
 /**
  * This class is an {@link Activity} used to perform end-to-end
  * testing of the accessibility feature by interaction with the
diff --git a/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityServiceInfoTest.java b/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityServiceInfoTest.java
index 48b4aae..ab7ecd7 100644
--- a/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityServiceInfoTest.java
+++ b/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityServiceInfoTest.java
@@ -72,8 +72,7 @@
                 receivedInfo.eventTypes);
         assertEquals("feedbackType not marshalled properly", sentInfo.feedbackType,
                 receivedInfo.feedbackType);
-        // This will fail here and is fixed in Froyo. Bug 2448479.
-        // assertEquals("flags not marshalled properly", sentInfo.flags, receivedInfo.flags);
+        assertEquals("flags not marshalled properly", sentInfo.flags, receivedInfo.flags);
         assertEquals("notificationTimeout not marshalled properly", sentInfo.notificationTimeout,
                 receivedInfo.notificationTimeout);
         assertEquals("packageNames not marshalled properly", sentInfo.packageNames.length,
diff --git a/tests/tests/accounts/src/android/accounts/cts/AccountManagerTest.java b/tests/tests/accounts/src/android/accounts/cts/AccountManagerTest.java
index e72e4db..e2c1f66 100644
--- a/tests/tests/accounts/src/android/accounts/cts/AccountManagerTest.java
+++ b/tests/tests/accounts/src/android/accounts/cts/AccountManagerTest.java
@@ -28,6 +28,7 @@
 import android.content.Context;
 import android.os.Bundle;
 import android.os.Handler;
+import android.os.StrictMode;
 import android.test.AndroidTestCase;
 
 import java.io.IOException;
@@ -1326,4 +1327,28 @@
                 handler);
         waitForLatch(latch);
     }
+
+    /**
+     * Tests that AccountManagerService is properly caching data.
+     */
+    public void testGetsAreCached() throws IOException, AuthenticatorException,
+            OperationCanceledException {
+
+        // Add an account,
+        assertEquals(false, isAccountPresent(am.getAccounts(), ACCOUNT));
+        addAccountExplicitly(ACCOUNT, ACCOUNT_PASSWORD, null /* userData */);
+
+        // Then verify that we don't hit disk retrieving it,
+        StrictMode.ThreadPolicy oldPolicy = StrictMode.getThreadPolicy();
+        try {
+            StrictMode.setThreadPolicy(
+                new StrictMode.ThreadPolicy.Builder().detectDiskReads().penaltyDeath().build());
+            Account[] accounts = am.getAccounts();
+            assertNotNull(accounts);
+            assertTrue(accounts.length > 0);
+        } finally {
+            StrictMode.setThreadPolicy(oldPolicy);
+        }
+    }
+
 }
diff --git a/tests/tests/app/src/android/app/cts/ActivityManagerTest.java b/tests/tests/app/src/android/app/cts/ActivityManagerTest.java
index 5b1c2b3..217a17c 100644
--- a/tests/tests/app/src/android/app/cts/ActivityManagerTest.java
+++ b/tests/tests/app/src/android/app/cts/ActivityManagerTest.java
@@ -305,4 +305,21 @@
         ConfigurationInfo conInf = mActivityManager.getDeviceConfigurationInfo();
         assertNotNull(conInf);
     }
+
+    /**
+     * Simple test for {@link ActivityManager.isUserAMonkey()} - verifies its false.
+     *
+     * TODO: test positive case
+     */
+    public void testIsUserAMonkey() {
+        assertFalse(ActivityManager.isUserAMonkey());
+    }
+
+    /**
+     * Verify that {@link ActivityManager.isRunningInTestHarness()} is false.
+     */
+    public void testIsRunningInTestHarness() {
+        assertFalse("isRunningInTestHarness must be false in production builds",
+                ActivityManager.isRunningInTestHarness());
+    }
 }
diff --git a/tests/tests/app/src/android/app/cts/AlertDialogTest.java b/tests/tests/app/src/android/app/cts/AlertDialogTest.java
index 4ab57da..b5711ed 100644
--- a/tests/tests/app/src/android/app/cts/AlertDialogTest.java
+++ b/tests/tests/app/src/android/app/cts/AlertDialogTest.java
@@ -16,6 +16,11 @@
 
 package android.app.cts;
 
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
+
 import android.app.AlertDialog;
 import android.app.Instrumentation;
 import android.content.Context;
@@ -29,10 +34,6 @@
 import android.view.KeyEvent;
 import android.view.View;
 import android.widget.Button;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
 
 /*
  * Test AlertDialog
@@ -55,15 +56,10 @@
     protected void setUp() throws Exception {
         super.setUp();
         mInstrumentation = getInstrumentation();
-        mActivity = getActivity();
     }
 
-    protected void popDialog(int index) {
-        while (index != 0) {
-            sendKeys(KeyEvent.KEYCODE_DPAD_DOWN);
-            index--;
-        }
-        sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
+    protected void startDialogActivity(int dialogNumber) {
+        mActivity = DialogStubActivity.startDialogActivity(this, dialogNumber);
     }
 
     @TestTargets({
@@ -121,7 +117,7 @@
     }
 
     private void doTestAlertDialog(int index) throws Throwable {
-        popDialog(index);
+        startDialogActivity(index);
         assertTrue(mActivity.getDialog().isShowing());
 
         mPositiveButton = ((AlertDialog) (mActivity.getDialog())).getButton(
@@ -294,7 +290,7 @@
         )
     })
     public void testAlertDialogDeprecatedAPIWithMessage() throws Throwable {
-        popDialog(DialogStubActivity.TEST_ALERTDIALOG_DEPRECATED_WITH_MESSAGE);
+        startDialogActivity(DialogStubActivity.TEST_ALERTDIALOG_DEPRECATED_WITH_MESSAGE);
         assertTrue(mActivity.getDialog().isShowing());
 
         mPositiveButton = ((AlertDialog) (mActivity.getDialog())).getButton(
@@ -368,7 +364,7 @@
         )
     })
     public void testCustomAlertDialog() {
-        popDialog(DialogStubActivity.TEST_CUSTOM_ALERTDIALOG);
+        startDialogActivity(DialogStubActivity.TEST_CUSTOM_ALERTDIALOG);
         assertTrue(mActivity.getDialog().isShowing());
     }
 
@@ -405,7 +401,7 @@
         )
     })
     public void testCustomAlertDialogView() {
-        popDialog(DialogStubActivity.TEST_CUSTOM_ALERTDIALOG_VIEW);
+        startDialogActivity(DialogStubActivity.TEST_CUSTOM_ALERTDIALOG_VIEW);
         assertTrue(mActivity.getDialog().isShowing());
     }
 
@@ -437,7 +433,7 @@
         )
     })
     public void testCallback() {
-        popDialog(DialogStubActivity.TEST_ALERTDIALOG_CALLBACK);
+        startDialogActivity(DialogStubActivity.TEST_ALERTDIALOG_CALLBACK);
         assertTrue(mActivity.onCreateCalled);
 
         mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_0);
@@ -453,7 +449,7 @@
         args = {Context.class, int.class}
     )
     public void testAlertDialogTheme() throws Exception {
-        popDialog(DialogStubActivity.TEST_ALERTDIALOG_THEME);
+        startDialogActivity(DialogStubActivity.TEST_ALERTDIALOG_THEME);
         assertTrue(mActivity.getDialog().isShowing());
     }
 
@@ -464,7 +460,7 @@
         args = {Context.class, boolean.class, OnCancelListener.class}
     )
     public void testAlertDialogCancelable() throws Exception {
-        popDialog(DialogStubActivity.TEST_ALERTDIALOG_CANCELABLE);
+        startDialogActivity(DialogStubActivity.TEST_ALERTDIALOG_CANCELABLE);
         assertTrue(mActivity.getDialog().isShowing());
         assertFalse(mActivity.onCancelCalled);
         mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
@@ -479,7 +475,7 @@
         args = {Context.class, boolean.class, OnCancelListener.class}
     )
     public void testAlertDialogNotCancelable() throws Exception {
-        popDialog(DialogStubActivity.TEST_ALERTDIALOG_NOT_CANCELABLE);
+        startDialogActivity(DialogStubActivity.TEST_ALERTDIALOG_NOT_CANCELABLE);
         assertTrue(mActivity.getDialog().isShowing());
         assertFalse(mActivity.onCancelCalled);
         mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
diff --git a/tests/tests/app/src/android/app/cts/DialogTest.java b/tests/tests/app/src/android/app/cts/DialogTest.java
index 6a48358..8cba3b5 100644
--- a/tests/tests/app/src/android/app/cts/DialogTest.java
+++ b/tests/tests/app/src/android/app/cts/DialogTest.java
@@ -15,8 +15,14 @@
  */
 package android.app.cts;
 
-import java.lang.ref.WeakReference;
 import com.android.cts.stub.R;
+
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
+import dalvik.annotation.ToBeFixed;
+
 import android.app.Dialog;
 import android.app.Instrumentation;
 import android.content.Context;
@@ -24,7 +30,6 @@
 import android.content.DialogInterface.OnCancelListener;
 import android.content.DialogInterface.OnDismissListener;
 import android.content.DialogInterface.OnKeyListener;
-import android.content.pm.ActivityInfo;
 import android.content.res.Resources;
 import android.content.res.TypedArray;
 import android.graphics.Canvas;
@@ -35,28 +40,23 @@
 import android.os.HandlerThread;
 import android.os.Looper;
 import android.os.Message;
+import android.os.SystemClock;
 import android.test.ActivityInstrumentationTestCase2;
 import android.view.KeyEvent;
 import android.view.LayoutInflater;
-import android.view.MenuItem;
 import android.view.MotionEvent;
 import android.view.View;
 import android.view.ViewGroup;
 import android.view.Window;
 import android.view.WindowManager;
 import android.widget.LinearLayout;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.ToBeFixed;
+
+import java.lang.ref.WeakReference;
 
 @TestTargetClass(Dialog.class)
 public class DialogTest extends ActivityInstrumentationTestCase2<DialogStubActivity> {
 
     protected static final long SLEEP_TIME = 200;
-    private static final long MOTION_DOWN_TIME = 0L;
-    private static final long MOTION_EVENT_TIME = 0L;
     private static final float MOTION_X = -20.0f;
     private static final float MOTION_Y = -20.0f;
     private static final String STUB_ACTIVITY_PACKAGE = "com.android.cts.stub";
@@ -84,30 +84,12 @@
     @Override
     protected void setUp() throws Exception {
         super.setUp();
-
         mInstrumentation = getInstrumentation();
         mContext = mInstrumentation.getContext();
-        mActivity = getActivity();
     }
 
-    @Override
-    protected void tearDown() throws Exception {
-        super.tearDown();
-
-        if (mActivity != null) {
-            mActivity.finish();
-        }
-    }
-
-    protected void popDialog(int index) {
-        assertTrue(index >= 0);
-
-        while (index != 0) {
-            sendKeys(KeyEvent.KEYCODE_DPAD_DOWN);
-            index--;
-        }
-
-        sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
+    private void startDialogActivity(int dialogNumber) {
+        mActivity = DialogStubActivity.startDialogActivity(this, dialogNumber);
     }
 
     @TestTargets({
@@ -139,7 +121,7 @@
             args = {}
         )
     })
-    public void testDialog(){
+    public void testConstructor(){
         new Dialog(mContext);
         Dialog d = new Dialog(mContext, 0);
         // According to javadoc of constructors, it will set theme to system default theme,
@@ -154,16 +136,17 @@
         final Window w = d.getWindow();
         ta = w.getContext().getTheme().obtainStyledAttributes(R.styleable.TextAppearance);
         assertTextAppearanceStyle(ta);
+    }
 
-        // test protected constructor
-        // Dialog(Context context, boolean cancelable, OnCancelListener cancelListener)
+    public void testConstructor_protectedCancellable() {
+        startDialogActivity(DialogStubActivity.TEST_PROTECTED_CANCELABLE);
         mActivity.onCancelListenerCalled = false;
-        popDialog(DialogStubActivity.TEST_PROTECTED_CANCELABLE);
         sendKeys(KeyEvent.KEYCODE_BACK);
         assertTrue(mActivity.onCancelListenerCalled);
+    }
 
-        // open DialogStubActivity.TEST_PROTECTED_NOT_CANCELABLE
-        sendKeys(KeyEvent.KEYCODE_DPAD_DOWN, KeyEvent.KEYCODE_DPAD_CENTER);
+    public void testConstructor_protectedNotCancellable() {
+        startDialogActivity(DialogStubActivity.TEST_PROTECTED_NOT_CANCELABLE);
         mActivity.onCancelListenerCalled = false;
         sendKeys(KeyEvent.KEYCODE_BACK);
         assertFalse(mActivity.onCancelListenerCalled);
@@ -209,7 +192,7 @@
         )
     })
     public void testOnStartCreateStop(){
-        popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+        startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
         final TestDialog d = (TestDialog) mActivity.getDialog();
 
         assertTrue(d.isOnStartCalled);
@@ -243,7 +226,7 @@
         )
     })
     public void testAccessOwnerActivity() {
-        popDialog(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+        startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
         Dialog d = mActivity.getDialog();
         assertNotNull(d);
         assertSame(mActivity, d.getOwnerActivity());
@@ -284,7 +267,7 @@
         )
     })
     public void testShow() throws Throwable {
-        popDialog(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+        startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
         final Dialog d = mActivity.getDialog();
         final View decor = d.getWindow().getDecorView();
 
@@ -324,7 +307,7 @@
         )
     })
     public void testOnSaveInstanceState() {
-        popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+        startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
         final TestDialog d = (TestDialog) mActivity.getDialog();
 
         assertFalse(d.isOnSaveInstanceStateCalled);
@@ -342,7 +325,7 @@
         args = {}
     )
     public void testGetCurrentFocus() throws Throwable {
-        popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+        startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
         final TestDialog d = (TestDialog) mActivity.getDialog();
         assertNull(d.getCurrentFocus());
         runTestOnUiThread(new Runnable() {
@@ -386,7 +369,7 @@
         )
     })
     public void testSetContentView() throws Throwable {
-        popDialog(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+        startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
         final Dialog d = mActivity.getDialog();
         assertNotNull(d);
 
@@ -472,7 +455,7 @@
     })
     public void testSetTitle() {
         final String expectedTitle = "Test Dialog Without theme";
-        popDialog(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+        startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
 
         assertNotNull(mActivity.getDialog());
         mActivity.setUpTitle(expectedTitle);
@@ -500,7 +483,7 @@
         )
     })
     public void testOnKeyDownKeyUp() {
-        popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+        startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
         final TestDialog d = (TestDialog) mActivity.getDialog();
         assertFalse(d.isOnKeyDownCalled);
         assertFalse(d.isOnKeyUpCalled);
@@ -524,7 +507,7 @@
          args = {int.class, int.class, android.view.KeyEvent.class}
      )
      public void testOnKeyMultiple() {
-         popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+         startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
          final TestDialog d = (TestDialog) mActivity.getDialog();
 
          assertNull(d.keyMultipleEvent);
@@ -553,15 +536,16 @@
         )
     })
     public void testTouchEvent() {
-        popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+        startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
         final TestDialog d = (TestDialog) mActivity.getDialog();
 
         assertNull(d.onTouchEvent);
         assertNull(d.touchEvent);
         assertFalse(d.isOnTouchEventCalled);
 
-        MotionEvent touchMotionEvent = MotionEvent.obtain(MOTION_DOWN_TIME,
-                MOTION_EVENT_TIME, MotionEvent.ACTION_DOWN,
+        long eventTime = SystemClock.uptimeMillis();
+        MotionEvent touchMotionEvent = MotionEvent.obtain(eventTime,
+                eventTime, MotionEvent.ACTION_DOWN,
                 MOTION_X, MOTION_Y, 0);
         // send a touch motion event, and System will call onTouchEvent
         mInstrumentation.sendPointerSync(touchMotionEvent);
@@ -576,8 +560,8 @@
 
         // set cancel on touch out side
         d.setCanceledOnTouchOutside(true);
-        touchMotionEvent = MotionEvent.obtain(MOTION_DOWN_TIME + 1,
-                MOTION_EVENT_TIME, MotionEvent.ACTION_DOWN,
+        touchMotionEvent = MotionEvent.obtain(eventTime + 1,
+                eventTime, MotionEvent.ACTION_DOWN,
                 MOTION_X, MOTION_Y, 0);
         // send a out side touch motion event, then the dialog will dismiss
         mInstrumentation.sendPointerSync(touchMotionEvent);
@@ -603,9 +587,10 @@
         )
     })
     public void testTrackballEvent() {
-        popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+        startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
         final TestDialog d = (TestDialog) mActivity.getDialog();
-        final MotionEvent trackBallEvent = MotionEvent.obtain(MOTION_DOWN_TIME, MOTION_EVENT_TIME,
+        long eventTime = SystemClock.uptimeMillis();
+        final MotionEvent trackBallEvent = MotionEvent.obtain(eventTime, eventTime,
                 MotionEvent.ACTION_DOWN, MOTION_X, MOTION_Y, 0);
 
         assertNull(d.trackballEvent);
@@ -636,7 +621,7 @@
         args = {android.view.WindowManager.LayoutParams.class}
     )
     public void testOnWindowAttributesChanged() throws Throwable {
-        popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+        startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
         final TestDialog d = (TestDialog) mActivity.getDialog();
 
         assertTrue(d.isOnWindowAttributesChangedCalled);
@@ -661,7 +646,7 @@
         args = {}
     )
     public void testOnContentChanged() throws Throwable {
-        popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+        startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
         final TestDialog d = (TestDialog) mActivity.getDialog();
         assertNotNull(d);
 
@@ -683,7 +668,7 @@
         args = {boolean.class}
     )
     public void testOnWindowFocusChanged() throws Throwable {
-        popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+        startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
         final TestDialog d = (TestDialog) mActivity.getDialog();
         assertTrue(d.isOnWindowFocusChangedCalled);
         d.isOnWindowFocusChangedCalled = false;
@@ -712,7 +697,7 @@
         )
     })
     public void testDispatchKeyEvent() {
-        popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+        startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
         final TestDialog d = (TestDialog) mActivity.getDialog();
 
         sendKeys(KeyEvent.KEYCODE_0);
@@ -748,149 +733,6 @@
 
     /*
      * Test point
-     * 1. First open a option menu will make onMenuOpened onCreatePanelView onCreatePanelMenu
-     * and onPreparePanel to be called.
-     * 2. When first open the option menu onCreatePanelMenu will calls through to
-     * the new onCreateOptionsMenu method.
-     * 3. When open the option menu onPreparePanel will calls through to
-     * the new onPrepareOptionsMenu method.
-     * 4. Closed option menu will make onPanelClosed to be called,
-     * and onPanelClosed will calls through to the new onPanelClosed method.
-     * 5. Every time open option menu will make onCreatePanelView and  onPreparePanel to be called.
-     * 6. Selected a item on the option menu will make onMenuItemSelected to be called,
-     * and onMenuItemSelected will calls through to the new onOptionsItemSelected method.
-     */
-    @TestTargets({
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "openOptionsMenu",
-            args = {}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "closeOptionsMenu",
-            args = {}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "onMenuOpened",
-            args = {int.class, android.view.Menu.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "onCreatePanelView",
-            args = {int.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "onCreatePanelMenu",
-            args = {int.class, android.view.Menu.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "onCreateOptionsMenu",
-            args = {android.view.Menu.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "onPreparePanel",
-            args = {int.class, android.view.View.class, android.view.Menu.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "onPrepareOptionsMenu",
-            args = {android.view.Menu.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.PARTIAL,
-            method = "onPanelClosed",
-            args = {int.class, android.view.Menu.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.PARTIAL,
-            notes = "onOptionsMenuClosed should be called when onPanelClosed Called.",
-            method = "onOptionsMenuClosed",
-            args = {android.view.Menu.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.PARTIAL,
-            method = "onMenuItemSelected",
-            args = {int.class, android.view.MenuItem.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.PARTIAL,
-            method = "onOptionsItemSelected",
-            args = {MenuItem.class}
-        )
-    })
-    @ToBeFixed(bug = "1716918", explanation = "As Javadoc of onMenuItemSelected() and "
-            + "onPanelClosed(), onOptionsItemSelected() and onContextItemSelected() should be "
-            + "called in onMenuItemSelected() source code, onOptionMenuClosed() and "
-            + "onContextMenuClosed() should be called in onPanelClosed() source code, "
-            + "but now onMenuItemSelected() and onPanelClosed() method are empty, is this a bug?")
-    public void testOptionMenu() throws Throwable {
-        popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
-        final TestDialog d = (TestDialog) mActivity.getDialog();
-        assertFalse(d.isOnMenuOpenedCalled);
-        assertFalse(d.isOnCreatePanelViewCalled);
-        assertFalse(d.isOnCreatePanelMenuCalled);
-        assertFalse(d.isOnCreateOptionsMenuCalled);
-        assertFalse(d.isOnPreparePanelCalled);
-        assertFalse(d.isOnPrepareOptionsMenuCalled);
-        // first open option menu
-        dialogOpenOptionMenu(d);
-
-        assertTrue(d.isOnMenuOpenedCalled);
-        assertTrue(d.isOnCreatePanelViewCalled);
-        assertTrue(d.isOnCreatePanelMenuCalled);
-        assertTrue(d.isOnCreateOptionsMenuCalled);
-        assertTrue(d.isOnPreparePanelCalled);
-        assertTrue(d.isOnPrepareOptionsMenuCalled);
-
-        assertFalse(d.isOnPanelClosedCalled);
-        // closed option menu
-        runTestOnUiThread(new Runnable() {
-            public void run() {
-                d.closeOptionsMenu();
-            }
-        });
-        mInstrumentation.waitForIdleSync();
-
-        assertTrue(d.isOnPanelClosedCalled);
-
-        d.isOnCreatePanelViewCalled = false;
-        d.isOnCreatePanelMenuCalled = false;
-        d.isOnPreparePanelCalled = false;
-        assertFalse(d.isOnOptionsMenuClosedCalled);
-        // open option menu again
-        dialogOpenOptionMenu(d);
-
-        assertTrue(d.isOnCreatePanelViewCalled);
-        assertFalse(d.isOnCreatePanelMenuCalled);
-        assertTrue(d.isOnPreparePanelCalled);
-        // Here isOnOptionsMenuClosedCalled should be true, see bug 1716918.
-        assertFalse(d.isOnOptionsMenuClosedCalled);
-
-        assertFalse(d.isOnMenuItemSelectedCalled);
-        assertFalse(d.isOnOptionsItemSelectedCalled);
-        // selected a item of option menu
-        sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
-        assertTrue(d.isOnMenuItemSelectedCalled);
-        // Here isOnOptionsItemSelectedCalled should be true, see bug 1716918.
-        assertFalse(d.isOnOptionsItemSelectedCalled);
-    }
-
-    private void dialogOpenOptionMenu(final Dialog d) throws Throwable {
-        runTestOnUiThread(new Runnable() {
-            public void run() {
-                d.openOptionsMenu();
-            }
-        });
-        mInstrumentation.waitForIdleSync();
-    }
-
-    /*
-     * Test point
      * 1. registerForContextMenu() will OnCreateContextMenuListener on the view to this activity,
      * so onCreateContextMenu() will be called when it is time to show the context menu.
      * 2. Close context menu will make onPanelClosed to be called,
@@ -943,7 +785,7 @@
             + "onContextMenuClosed() should be called in onPanelClosed() source code, "
             + "but now onMenuItemSelected() and onPanelClosed() method are empty, is this a bug?")
     public void testContextMenu() throws Throwable {
-        popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+        startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
         final TestDialog d = (TestDialog) mActivity.getDialog();
         final LinearLayout parent = new LinearLayout(mContext);
         final MockView v = new MockView(mContext);
@@ -1035,7 +877,7 @@
     @ToBeFixed(bug = "1695243",
             explanation = "It still get KeyEvent while set takeKeyEvents to false")
     public void testTakeKeyEvents() throws Throwable {
-        popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+        startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
         final TestDialog d = (TestDialog) mActivity.getDialog();
         final View v = d.getWindow().getDecorView();
         assertNull(d.getCurrentFocus());
@@ -1067,7 +909,7 @@
         args = {int.class}
     )
     public void testRequestWindowFeature() {
-        popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+        startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
         // called requestWindowFeature at TestDialog onCreate method
         assertTrue(((TestDialog) mActivity.getDialog()).isRequestWindowFeature);
     }
@@ -1080,7 +922,7 @@
         args = {int.class, int.class}
     )
     public void testSetFeatureDrawableResource() throws Throwable {
-        popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+        startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
         runTestOnUiThread(new Runnable() {
             public void run() {
                 mActivity.getDialog().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
@@ -1098,7 +940,7 @@
         args = {int.class, android.net.Uri.class}
     )
     public void testSetFeatureDrawableUri() {
-        popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+        startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
         mActivity.getDialog().setFeatureDrawableUri(0, Uri.parse("http://www.google.com"));
     }
 
@@ -1110,7 +952,7 @@
         args = {int.class, android.graphics.drawable.Drawable.class}
     )
     public void testSetFeatureDrawable() {
-        popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+        startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
         mActivity.getDialog().setFeatureDrawable(0, new MockDrawable());
     }
 
@@ -1122,7 +964,7 @@
         args = {int.class, int.class}
     )
     public void testSetFeatureDrawableAlpha() {
-        popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+        startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
         mActivity.getDialog().setFeatureDrawableAlpha(0, 0);
     }
 
@@ -1132,7 +974,7 @@
         args = {}
     )
     public void testGetLayoutInflater() {
-        popDialog(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+        startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
         final Dialog d = mActivity.getDialog();
         assertEquals(d.getWindow().getLayoutInflater(), d.getLayoutInflater());
     }
@@ -1142,17 +984,21 @@
         method = "setCancelable",
         args = {boolean.class}
     )
-    public void testSetCancelable() {
-        popDialog(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+    public void testSetCancelable_true() {
+        startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
         final Dialog d = mActivity.getDialog();
 
         d.setCancelable(true);
         assertTrue(d.isShowing());
         sendKeys(KeyEvent.KEYCODE_BACK);
         assertFalse(d.isShowing());
+    }
+
+    public void testSetCancellable_false() {
+        startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+        final Dialog d = mActivity.getDialog();
 
         d.setCancelable(false);
-        sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
         assertTrue(d.isShowing());
         sendKeys(KeyEvent.KEYCODE_BACK);
         assertTrue(d.isShowing());
@@ -1175,8 +1021,8 @@
             args = {android.content.DialogInterface.OnCancelListener.class}
         )
     })
-    public void testCancel() throws Throwable {
-        popDialog(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+    public void testCancel_listener() throws Throwable {
+        startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
         final Dialog d = mActivity.getDialog();
 
         assertTrue(d.isShowing());
@@ -1190,8 +1036,12 @@
 
         assertFalse(d.isShowing());
         assertTrue(mOnCancelListenerCalled);
+    }
 
-        sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
+    public void testCancel_noListener() throws Throwable {
+        startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+        final Dialog d = mActivity.getDialog();
+
         assertTrue(d.isShowing());
         mOnCancelListenerCalled = false;
         d.setOnCancelListener(null);
@@ -1209,7 +1059,7 @@
     )
     public void testSetCancelMessage() throws Exception {
         mCalledCallback = false;
-        popDialog(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+        startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
         final TestDialog d = (TestDialog) mActivity.getDialog();
         final HandlerThread ht = new HandlerThread("DialogTest");
         ht.start();
@@ -1239,9 +1089,9 @@
         method = "setOnDismissListener",
         args = {android.content.DialogInterface.OnDismissListener.class}
     )
-    public void testSetOnDismissListener() throws Throwable {
+    public void testSetOnDismissListener_listener() throws Throwable {
         mCalledCallback = false;
-        popDialog(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+        startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
         final Dialog d = mActivity.getDialog();
 
         d.setOnDismissListener(new OnDismissListener() {
@@ -1255,9 +1105,11 @@
         dialogDismiss(d);
         assertTrue(mCalledCallback);
         assertFalse(d.isShowing());
+    }
 
-        // show the dialog again
-        sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
+    public void testSetOnDismissListener_noListener() throws Throwable {
+        startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+        final Dialog d = mActivity.getDialog();
         assertTrue(d.isShowing());
         mCalledCallback = false;
         d.setOnDismissListener(null);
@@ -1273,7 +1125,7 @@
     )
     public void testSetDismissMessage() throws Throwable {
         mCalledCallback = false;
-        popDialog(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+        startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
         final Dialog d = mActivity.getDialog();
 
         final HandlerThread ht = new HandlerThread("DialogTest");
diff --git a/tests/tests/app/src/android/app/cts/InstrumentationTest.java b/tests/tests/app/src/android/app/cts/InstrumentationTest.java
index 1861ae2..6ab9ac6 100644
--- a/tests/tests/app/src/android/app/cts/InstrumentationTest.java
+++ b/tests/tests/app/src/android/app/cts/InstrumentationTest.java
@@ -16,7 +16,12 @@
 
 package android.app.cts;
 
-import java.util.List;
+import com.android.cts.stub.R;
+
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
 
 import android.app.Activity;
 import android.app.Application;
@@ -46,12 +51,7 @@
 import android.view.Window;
 import android.view.ViewGroup.LayoutParams;
 
-import com.android.cts.stub.R;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
+import java.util.List;
 
 @TestTargetClass(Instrumentation.class)
 public class InstrumentationTest extends InstrumentationTestCase {
@@ -73,8 +73,8 @@
         final long eventTime = SystemClock.uptimeMillis();
         // use coordinates for MotionEvent that do not include the status bar
         // TODO: is there a more deterministic way to get these values
-        final long x = 50;
-        final long y = 50;
+        final long x = 100;
+        final long y = 100;
         final int metaState = 0;
         mMotionEvent = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_DOWN, x, y,
                 metaState);
@@ -88,6 +88,7 @@
         mIntent = null;
         if (mActivity != null) {
             mActivity.finish();
+            mActivity = null;
         }
         super.tearDown();
     }
@@ -493,7 +494,7 @@
         assertEquals(text.length(), keyDownList.size());
         assertEquals(text.length(), keyUpList.size());
 
-        KeyCharacterMap kcm = KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD);
+        KeyCharacterMap kcm = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);
         KeyEvent[] keyEvents = kcm.getEvents(text.toCharArray());
 
         int i = 0;
@@ -508,10 +509,14 @@
         method = "callActivityOnSaveInstanceState",
         args = {Activity.class, Bundle.class}
     )
-    public void testCallActivityOnSaveInstanceState() {
+    public void testCallActivityOnSaveInstanceState() throws Throwable {
         final Bundle bundle = new Bundle();
         mActivity.setOnSaveInstanceState(false);
-        mInstrumentation.callActivityOnSaveInstanceState(mActivity, bundle);
+        runTestOnUiThread(new Runnable() {
+            public void run() {
+                mInstrumentation.callActivityOnSaveInstanceState(mActivity, bundle);
+            }
+        });
         mInstrumentation.waitForIdleSync();
 
         assertTrue(mActivity.isOnSaveInstanceState());
@@ -604,18 +609,6 @@
 
     @TestTargetNew(
         level = TestLevel.COMPLETE,
-        method = "callActivityOnDestroy",
-        args = {Activity.class}
-    )
-    public void testCallActivityOnDestroy() throws Exception {
-        mActivity.setOnDestroyCalled(false);
-        mInstrumentation.callActivityOnDestroy(mActivity);
-        mInstrumentation.waitForIdleSync();
-        assertTrue(mActivity.isOnDestroyCalled());
-    }
-
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
         method = "sendKeyDownUpSync",
         args = {int.class}
     )
@@ -849,6 +842,10 @@
             }
 
             @Override
+            public void alwaysReadCloseOnTouchAttr() {
+            }
+
+            @Override
             public View peekDecorView() {
                 return null;
             }
@@ -942,6 +939,11 @@
             }
 
             @Override
+            public boolean superDispatchKeyShortcutEvent(KeyEvent event) {
+                return false;
+            }
+
+            @Override
             public boolean superDispatchTouchEvent(MotionEvent event) {
                 return false;
             }
@@ -958,11 +960,15 @@
             @Override
             public void togglePanel(int featureId, KeyEvent event) {
             }
-            
+
+            @Override
+            public void invalidatePanelMenu(int featureId) {
+            }
+
             @Override
             public void takeSurface(SurfaceHolder.Callback2 callback) {
             }
-            
+
             @Override
             public void takeInputQueue(InputQueue.Callback queue) {
             }
diff --git a/tests/tests/app/src/android/app/cts/LocalActivityManagerTest.java b/tests/tests/app/src/android/app/cts/LocalActivityManagerTest.java
index efb5413..189a83f 100644
--- a/tests/tests/app/src/android/app/cts/LocalActivityManagerTest.java
+++ b/tests/tests/app/src/android/app/cts/LocalActivityManagerTest.java
@@ -112,7 +112,7 @@
     })
     public void testStartActivity() throws InterruptedException {
         LocalActivityManagerTestHelper.setResult(this);
-        setupActivity(LocalActivityManagerTestHelper.ACTION_START_ACTIIVTY);
+        setupActivity(LocalActivityManagerTestHelper.ACTION_START_ACTIVITY);
         waitForResult();
     }
 
diff --git a/tests/tests/app/src/android/app/cts/ServiceTest.java b/tests/tests/app/src/android/app/cts/ServiceTest.java
index 7f6fe94..0b2b767 100644
--- a/tests/tests/app/src/android/app/cts/ServiceTest.java
+++ b/tests/tests/app/src/android/app/cts/ServiceTest.java
@@ -16,6 +16,11 @@
 
 package android.app.cts;
 
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
+
 import android.app.Service;
 import android.content.ComponentName;
 import android.content.Context;
@@ -27,10 +32,6 @@
 import android.os.Parcel;
 import android.os.RemoteException;
 import android.test.suitebuilder.annotation.MediumTest;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
 
 @TestTargetClass(Service.class)
 public class ServiceTest extends ActivityTestsBase {
@@ -49,8 +50,8 @@
     private Intent mLocalService;
     private Intent mLocalDeniedService;
     private Intent mLocalGrantedService;
-    private Intent mLocalServiceGranted;
-    private Intent mLocalServiceDenied;
+    private Intent mLocalService_ApplicationHasPermission;
+    private Intent mLocalService_ApplicationDoesNotHavePermission;
 
     private IBinder mStateReceiver;
 
@@ -317,8 +318,8 @@
         mLocalService = new Intent(mContext, LocalService.class);
         mLocalDeniedService = new Intent(mContext, LocalDeniedService.class);
         mLocalGrantedService = new Intent(mContext, LocalGrantedService.class);
-        mLocalServiceGranted = new Intent(LocalService.SERVICE_LOCAL_GRANTED);
-        mLocalServiceDenied = new Intent(LocalService.SERVICE_LOCAL_DENIED);
+        mLocalService_ApplicationHasPermission = new Intent(LocalService.SERVICE_LOCAL_GRANTED);
+        mLocalService_ApplicationDoesNotHavePermission = new Intent(LocalService.SERVICE_LOCAL_DENIED);
         mStateReceiver = new MockBinder();
     }
 
@@ -388,7 +389,7 @@
         super.tearDown();
         mContext.stopService(mLocalService);
         mContext.stopService(mLocalGrantedService);
-        mContext.stopService(mLocalServiceGranted);
+        mContext.stopService(mLocalService_ApplicationHasPermission);
     }
 
     @TestTargets({
@@ -634,8 +635,9 @@
         )
     })
     @MediumTest
-    public void testLocalStartClassPermissionGranted() throws Exception {
+    public void testLocalStartClassPermissions() throws Exception {
         startExpectResult(mLocalGrantedService);
+        startExpectResult(mLocalDeniedService);
     }
 
     @TestTargets({
@@ -666,8 +668,9 @@
         )
     })
     @MediumTest
-    public void testLocalStartActionPermissionGranted() throws Exception {
-        startExpectResult(mLocalServiceGranted);
+    public void testLocalStartActionPermissions() throws Exception {
+        startExpectResult(mLocalService_ApplicationHasPermission);
+        startExpectResult(mLocalService_ApplicationDoesNotHavePermission);
     }
 
     @TestTargets({
@@ -698,8 +701,9 @@
         )
     })
     @MediumTest
-    public void testLocalBindClassPermissionGranted() throws Exception {
+    public void testLocalBindClassPermissions() throws Exception {
         bindExpectResult(mLocalGrantedService);
+        bindExpectResult(mLocalDeniedService);
     }
 
     @TestTargets({
@@ -730,8 +734,9 @@
         )
     })
     @MediumTest
-    public void testLocalBindActionPermissionGranted() throws Exception {
-        bindExpectResult(mLocalServiceGranted);
+    public void testLocalBindActionPermissions() throws Exception {
+        bindExpectResult(mLocalService_ApplicationHasPermission);
+        bindExpectResult(mLocalService_ApplicationDoesNotHavePermission);
     }
 
     @TestTargets({
@@ -795,135 +800,7 @@
     })
     @MediumTest
     public void testLocalBindAutoActionPermissionGranted() throws Exception {
-        bindAutoExpectResult(mLocalServiceGranted);
-    }
-
-    @TestTargets({
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "onStart",
-            args = {android.content.Intent.class, int.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "onDestroy",
-            args = {}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "onBind",
-            args = {android.content.Intent.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "onRebind",
-            args = {android.content.Intent.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "onUnbind",
-            args = {android.content.Intent.class}
-        )
-    })
-    @MediumTest
-    public void testLocalStartClassPermissionDenied() throws Exception {
-        startExpectNoPermission(mLocalDeniedService);
-    }
-
-    @TestTargets({
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "onStart",
-            args = {android.content.Intent.class, int.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "onDestroy",
-            args = {}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "onBind",
-            args = {android.content.Intent.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "onRebind",
-            args = {android.content.Intent.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "onUnbind",
-            args = {android.content.Intent.class}
-        )
-    })
-    @MediumTest
-    public void testLocalStartActionPermissionDenied() throws Exception {
-        startExpectNoPermission(mLocalServiceDenied);
-    }
-
-    @TestTargets({
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "onStart",
-            args = {android.content.Intent.class, int.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "onDestroy",
-            args = {}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "onBind",
-            args = {android.content.Intent.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "onRebind",
-            args = {android.content.Intent.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "onUnbind",
-            args = {android.content.Intent.class}
-        )
-    })
-    @MediumTest
-    public void testLocalBindClassPermissionDenied() throws Exception {
-        bindExpectNoPermission(mLocalDeniedService);
-    }
-
-    @TestTargets({
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "onStart",
-            args = {android.content.Intent.class, int.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "onDestroy",
-            args = {}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "onBind",
-            args = {android.content.Intent.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "onRebind",
-            args = {android.content.Intent.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "onUnbind",
-            args = {android.content.Intent.class}
-        )
-    })
-    @MediumTest
-    public void testLocalBindActionPermissionDenied() throws Exception {
-        bindExpectNoPermission(mLocalServiceDenied);
+        bindAutoExpectResult(mLocalService_ApplicationHasPermission);
     }
 
     @TestTargets({
@@ -957,7 +834,7 @@
     public void testLocalUnbindTwice() throws Exception {
         EmptyConnection conn = new EmptyConnection();
         mContext.bindService(
-                mLocalServiceGranted, conn, 0);
+                mLocalService_ApplicationHasPermission, conn, 0);
         mContext.unbindService(conn);
         try {
             mContext.unbindService(conn);
diff --git a/tests/tests/app/src/android/app/cts/TabActivityTest.java b/tests/tests/app/src/android/app/cts/TabActivityTest.java
index 649a56d..920ec11 100644
--- a/tests/tests/app/src/android/app/cts/TabActivityTest.java
+++ b/tests/tests/app/src/android/app/cts/TabActivityTest.java
@@ -30,7 +30,6 @@
 import android.content.Intent;
 import android.content.pm.ActivityInfo;
 import android.test.InstrumentationTestCase;
-import android.view.KeyEvent;
 import android.widget.TabHost;
 
 @TestTargetClass(TabActivity.class)
@@ -132,21 +131,6 @@
         final TabHost tabHost = mActivity.getTabHost();
         assertNotNull(tabHost);
         assertNotNull(tabHost.getTabWidget());
-
-        // Test onSaveInstanceState
-        assertFalse(mActivity.isOnSaveInstanceStateCalled);
-        final Intent embedded = new Intent(mInstrumentation.getTargetContext(),
-                ChildTabActivity.class);
-        mActivity.startActivity(embedded);
-        mInstrumentation.waitForIdleSync();
-        assertTrue(mActivity.isOnSaveInstanceStateCalled);
-
-        // Test onRestoreInstanceState
-        sendKeys(KeyEvent.KEYCODE_BACK);
-        mInstrumentation.waitForIdleSync();
-        assertFalse(MockTabActivity.isOnRestoreInstanceStateCalled);
-        OrientationTestUtils.toggleOrientationSync(mActivity, mInstrumentation);
-        assertTrue(MockTabActivity.isOnRestoreInstanceStateCalled);
     }
 
     @TestTargetNew(
diff --git a/tests/tests/app/src/android/app/cts/TimePickerDialogTest.java b/tests/tests/app/src/android/app/cts/TimePickerDialogTest.java
index 01f1ec9..417d046 100644
--- a/tests/tests/app/src/android/app/cts/TimePickerDialogTest.java
+++ b/tests/tests/app/src/android/app/cts/TimePickerDialogTest.java
@@ -26,7 +26,6 @@
 import android.content.Context;
 import android.os.Bundle;
 import android.test.ActivityInstrumentationTestCase2;
-import android.view.KeyEvent;
 import android.widget.TimePicker;
 
 /**
@@ -59,7 +58,6 @@
         super.setUp();
 
         mContext = getInstrumentation().getContext();
-        mActivity = getActivity();
         mOnTimeSetListener = new OnTimeSetListener(){
             public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                 mCallbackHour = hourOfDay;
@@ -131,7 +129,7 @@
     )
     public void testOnTimeChanged() throws Throwable {
         final int minute = 34;
-        popDialog(DialogStubActivity.TEST_TIMEPICKERDIALOG);
+        startDialogActivity(DialogStubActivity.TEST_TIMEPICKERDIALOG);
         final TimePickerDialog d = (TimePickerDialog) mActivity.getDialog();
 
         runTestOnUiThread(new Runnable() {
@@ -181,14 +179,7 @@
         assertFalse(b2.getBoolean(IS_24_HOUR));
     }
 
-    private void popDialog(int index) {
-        assertTrue(index > 0);
-
-        while (index != 0) {
-            sendKeys(KeyEvent.KEYCODE_DPAD_DOWN);
-            index--;
-        }
-
-        sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
+    private void startDialogActivity(int dialogNumber) {
+        mActivity = DialogStubActivity.startDialogActivity(this, dialogNumber);
     }
 }
diff --git a/tests/tests/content/src/android/content/cts/AvailableIntentsTest.java b/tests/tests/content/src/android/content/cts/AvailableIntentsTest.java
index bd8c260..b08e953 100644
--- a/tests/tests/content/src/android/content/cts/AvailableIntentsTest.java
+++ b/tests/tests/content/src/android/content/cts/AvailableIntentsTest.java
@@ -147,12 +147,9 @@
         args = {java.lang.String.class, android.net.Uri.class}
     )
     public void testDialPhoneNumber() {
-        PackageManager packageManager = mContext.getPackageManager();
-        if (packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
-            Uri uri = Uri.parse("tel:(212)5551212");
-            Intent intent = new Intent(Intent.ACTION_DIAL, uri);
-            assertCanBeHandled(intent);
-        }
+        Uri uri = Uri.parse("tel:(212)5551212");
+        Intent intent = new Intent(Intent.ACTION_DIAL, uri);
+        assertCanBeHandled(intent);
     }
 
     /**
@@ -164,11 +161,8 @@
         args = {java.lang.String.class, android.net.Uri.class}
     )
     public void testDialVoicemail() {
-        PackageManager packageManager = mContext.getPackageManager();
-        if (packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
-            Uri uri = Uri.parse("voicemail:");
-            Intent intent = new Intent(Intent.ACTION_DIAL, uri);
-            assertCanBeHandled(intent);
-        }
+        Uri uri = Uri.parse("voicemail:");
+        Intent intent = new Intent(Intent.ACTION_DIAL, uri);
+        assertCanBeHandled(intent);
     }
 }
diff --git a/tests/tests/content/src/android/content/cts/BroadcastReceiverTest.java b/tests/tests/content/src/android/content/cts/BroadcastReceiverTest.java
index 7fb403e..62d8724 100644
--- a/tests/tests/content/src/android/content/cts/BroadcastReceiverTest.java
+++ b/tests/tests/content/src/android/content/cts/BroadcastReceiverTest.java
@@ -77,33 +77,6 @@
     @TestTargets({
         @TestTargetNew(
             level = TestLevel.COMPLETE,
-            method = "abortBroadcast",
-            args = {}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "clearAbortBroadcast",
-            args = {}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "getAbortBroadcast",
-            args = {}
-        )
-    })
-    public void testAccessAbortBroadcast() {
-        MockReceiverInternal mockReceiver = new MockReceiverInternal();
-
-        mockReceiver.abortBroadcast();
-        assertTrue(mockReceiver.getAbortBroadcast());
-
-        mockReceiver.clearAbortBroadcast();
-        assertFalse(mockReceiver.getAbortBroadcast());
-    }
-
-    @TestTargets({
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
             method = "getDebugUnregister",
             args = {}
         ),
@@ -377,7 +350,7 @@
 
     static class MyServiceConnection implements ServiceConnection {
         private boolean serviceConnected;
-        
+
         public synchronized void onServiceConnected(ComponentName name, IBinder service) {
             serviceConnected = true;
             notifyAll();
@@ -385,7 +358,7 @@
 
         public synchronized void onServiceDisconnected(ComponentName name) {
         }
-        
+
         public synchronized boolean waitForService(long timeout) {
             if (!serviceConnected) {
                 try {
diff --git a/tests/tests/content/src/android/content/cts/ContentProviderTest.java b/tests/tests/content/src/android/content/cts/ContentProviderTest.java
index 0824e84..eabd470 100644
--- a/tests/tests/content/src/android/content/cts/ContentProviderTest.java
+++ b/tests/tests/content/src/android/content/cts/ContentProviderTest.java
@@ -394,6 +394,15 @@
             public Bundle call(String method, String request, Bundle args) {
                 return null;
             }
+            
+            public String[] getStreamTypes(Uri url, String mimeTypeFilter) throws RemoteException {
+                return null;
+            }
+
+            public AssetFileDescriptor openTypedAssetFile(Uri url, String mimeType, Bundle opts)
+                    throws RemoteException, FileNotFoundException {
+                return null;
+            }
         };
         assertNull(ContentProvider.coerceToLocalContentProvider(iContentProvider));
     }
diff --git a/tests/tests/content/src/android/content/cts/ContentResolverSyncTestCase.java b/tests/tests/content/src/android/content/cts/ContentResolverSyncTestCase.java
index 032f10a..4d7ca6d 100644
--- a/tests/tests/content/src/android/content/cts/ContentResolverSyncTestCase.java
+++ b/tests/tests/content/src/android/content/cts/ContentResolverSyncTestCase.java
@@ -93,7 +93,7 @@
     }
 
     private void addAccountAndVerifyInitSync(Account account, String password,
-            String authority, int latchTimeoutMs) {
+            String authority, int latchTimeoutMs, int accountIndex) {
 
         CountDownLatch latch = setNewLatch(new CountDownLatch(1));
 
@@ -109,7 +109,7 @@
         assertFalse(getMockSyncAdapter().isStartSync());
         assertFalse(getMockSyncAdapter().isCancelSync());
         assertTrue(getMockSyncAdapter().isInitialized());
-        assertEquals(account, getMockSyncAdapter().getAccount());
+        assertEquals(account, getMockSyncAdapter().getAccounts().get(accountIndex));
         assertEquals(authority, getMockSyncAdapter().getAuthority());
     }
 
@@ -159,8 +159,11 @@
         ContentResolver.setMasterSyncAutomatically(false);
         assertEquals(false, ContentResolver.getMasterSyncAutomatically());
 
-        addAccountAndVerifyInitSync(ACCOUNT, MockAccountAuthenticator.ACCOUNT_PASSWORD, AUTHORITY,
-                LATCH_TIMEOUT_MS);
+        addAccountAndVerifyInitSync(ACCOUNT,
+                MockAccountAuthenticator.ACCOUNT_PASSWORD,
+                AUTHORITY,
+                LATCH_TIMEOUT_MS,
+                0);
 
         getMockSyncAdapter().clearData();
 
@@ -174,7 +177,7 @@
         assertTrue(getMockSyncAdapter().isStartSync());
         assertFalse(getMockSyncAdapter().isCancelSync());
         assertFalse(getMockSyncAdapter().isInitialized());
-        assertEquals(ACCOUNT, getMockSyncAdapter().getAccount());
+        assertEquals(ACCOUNT, getMockSyncAdapter().getAccounts().get(0));
         assertEquals(AUTHORITY, getMockSyncAdapter().getAuthority());
     }
 
@@ -188,8 +191,11 @@
         ContentResolver.setMasterSyncAutomatically(false);
         assertEquals(false, ContentResolver.getMasterSyncAutomatically());
 
-        addAccountAndVerifyInitSync(ACCOUNT, MockAccountAuthenticator.ACCOUNT_PASSWORD, AUTHORITY,
-                LATCH_TIMEOUT_MS);
+        addAccountAndVerifyInitSync(ACCOUNT,
+                MockAccountAuthenticator.ACCOUNT_PASSWORD,
+                AUTHORITY,
+                LATCH_TIMEOUT_MS,
+                0);
 
         getMockSyncAdapter().clearData();
 
@@ -315,4 +321,35 @@
             //expected.
         }
     }
+
+    /**
+     * Test to verify that a SyncAdapter is called on all the accounts accounts
+     */
+    public void testCallMultipleAccounts() {
+        // Prevent auto sync
+        ContentResolver.setMasterSyncAutomatically(false);
+        assertEquals(false, ContentResolver.getMasterSyncAutomatically());
+
+        addAccountAndVerifyInitSync(ACCOUNT,
+                MockAccountAuthenticator.ACCOUNT_PASSWORD,
+                AUTHORITY,
+                LATCH_TIMEOUT_MS,
+                0);
+
+        getMockSyncAdapter().clearData();
+
+        setIsSyncable(ACCOUNT, AUTHORITY, true);
+        cancelSync(ACCOUNT, AUTHORITY, LATCH_TIMEOUT_MS);
+
+        getMockSyncAdapter().clearData();
+
+        requestSync(null /* all accounts */, AUTHORITY, LATCH_TIMEOUT_MS);
+
+        assertTrue(getMockSyncAdapter().isStartSync());
+        assertFalse(getMockSyncAdapter().isCancelSync());
+        assertFalse(getMockSyncAdapter().isInitialized());
+        assertEquals(ACCOUNT, getMockSyncAdapter().getAccounts().get(0));
+        assertEquals(AUTHORITY, getMockSyncAdapter().getAuthority());
+
+    }
 }
diff --git a/tests/tests/content/src/android/content/cts/ContextTest.java b/tests/tests/content/src/android/content/cts/ContextTest.java
index 3eac36a..b662162 100644
--- a/tests/tests/content/src/android/content/cts/ContextTest.java
+++ b/tests/tests/content/src/android/content/cts/ContextTest.java
@@ -16,7 +16,14 @@
 
 package android.content.cts;
 
-import java.io.IOException;
+import com.android.cts.stub.R;
+import com.android.internal.util.XmlUtils;
+
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
+import dalvik.annotation.ToBeFixed;
 
 import org.xmlpull.v1.XmlPullParserException;
 
@@ -28,14 +35,7 @@
 import android.util.AttributeSet;
 import android.util.Xml;
 
-import com.android.cts.stub.R;
-import com.android.internal.util.XmlUtils;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.ToBeFixed;
+import java.io.IOException;
 
 @TestTargetClass(Context.class)
 public class ContextTest extends AndroidTestCase {
@@ -132,7 +132,6 @@
             args = {android.util.AttributeSet.class, int[].class}
         )
     })
-    @ToBeFixed(bug=" ", explanation = "Wrong resource ID can not result in a exception.")
     public void testObtainStyledAttributes() {
         // Test obtainStyledAttributes(int[])
         TypedArray testTypedArray = mContext
@@ -165,17 +164,18 @@
         testTypedArray.recycle();
 
         // Test obtainStyledAttributes(AttributeSet, int[])
+        int[] attrs = android.R.styleable.DatePicker;
         testTypedArray = mContext.obtainStyledAttributes(getAttributeSet(R.layout.context_layout),
-                com.android.internal.R.styleable.DatePicker);
+                attrs);
         assertNotNull(testTypedArray);
-        assertEquals(2, testTypedArray.length());
+        assertEquals(attrs.length, testTypedArray.length());
         testTypedArray.recycle();
 
         // Test obtainStyledAttributes(AttributeSet, int[], int, int)
         testTypedArray = mContext.obtainStyledAttributes(getAttributeSet(R.layout.context_layout),
-                com.android.internal.R.styleable.DatePicker, 0, 0);
+                attrs, 0, 0);
         assertNotNull(testTypedArray);
-        assertEquals(2, testTypedArray.length());
+        assertEquals(attrs.length, testTypedArray.length());
         testTypedArray.recycle();
     }
 
diff --git a/tests/tests/content/src/android/content/cts/SharedPreferencesTest.java b/tests/tests/content/src/android/content/cts/SharedPreferencesTest.java
index bc81c4c..004fa9e 100644
--- a/tests/tests/content/src/android/content/cts/SharedPreferencesTest.java
+++ b/tests/tests/content/src/android/content/cts/SharedPreferencesTest.java
@@ -29,6 +29,7 @@
 import android.content.Context;
 import android.content.ContextWrapper;
 import android.content.SharedPreferences;
+import android.os.StrictMode;
 import android.preference.PreferenceManager;
 import android.test.AndroidTestCase;
 import android.util.Log;
@@ -317,4 +318,30 @@
         }
     }
 
+    public void testModeMultiProcess() {
+        // Pre-load it.
+        mContext.getSharedPreferences("multiprocessTest", 0);
+
+        final StrictMode.ThreadPolicy oldPolicy = StrictMode.getThreadPolicy();
+        try {
+            StrictMode.ThreadPolicy diskReadDeath =
+                    new StrictMode.ThreadPolicy.Builder().detectDiskReads().penaltyDeath().build();
+            StrictMode.setThreadPolicy(diskReadDeath);
+
+            // This shouldn't hit disk.  (it was already pre-loaded above)
+            mContext.getSharedPreferences("multiprocessTest", 0);
+
+            boolean didRead = false;
+            // This SHOULD hit disk.  (multi-process flag is set)
+            try {
+                mContext.getSharedPreferences("multiprocessTest", Context.MODE_MULTI_PROCESS);
+                fail();  // we shouldn't get here.
+            } catch (StrictMode.StrictModeViolation e) {
+                didRead = true;
+            }
+            assertTrue(didRead);
+        } finally {
+            StrictMode.setThreadPolicy(oldPolicy);
+        }
+    }
 }
diff --git a/tests/tests/content/src/android/content/res/cts/AssetFileDescriptor_AutoCloseInputStreamTest.java b/tests/tests/content/src/android/content/res/cts/AssetFileDescriptor_AutoCloseInputStreamTest.java
index 1ff3f49..de9f0e3 100644
--- a/tests/tests/content/src/android/content/res/cts/AssetFileDescriptor_AutoCloseInputStreamTest.java
+++ b/tests/tests/content/src/android/content/res/cts/AssetFileDescriptor_AutoCloseInputStreamTest.java
@@ -16,80 +16,252 @@
 
 package android.content.res.cts;
 
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-
-import android.content.res.AssetFileDescriptor;
-import android.os.ParcelFileDescriptor;
-import android.test.AndroidTestCase;
 import dalvik.annotation.TestLevel;
 import dalvik.annotation.TestTargetClass;
 import dalvik.annotation.TestTargetNew;
 import dalvik.annotation.TestTargets;
 
+import android.content.res.AssetFileDescriptor;
+import android.os.ParcelFileDescriptor;
+import android.test.AndroidTestCase;
+import android.test.MoreAsserts;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+
 @TestTargetClass(AssetFileDescriptor.AutoCloseInputStream.class)
 public class AssetFileDescriptor_AutoCloseInputStreamTest extends AndroidTestCase {
     private static final int FILE_END = -1;
-    private static final int FILE_LENGTH = 10;
     private static final String FILE_NAME = "testAssertFileDescriptorAutoCloseInputStream";
     private static final byte[] FILE_DATA = new byte[] {
             0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08
             };
-    private static final int OFFSET = 0;
-    private static final int READ_LENGTH = 1;
+    private static final int FILE_LENGTH = FILE_DATA.length;
 
     private File mFile;
-    private AssetFileDescriptor mAssetFileDes;
+    private AssetFileDescriptor mFd;
+    private AssetFileDescriptor.AutoCloseInputStream mInput;
 
     @Override
     protected void setUp() throws Exception {
         super.setUp();
         mFile = new File(getContext().getFilesDir(), FILE_NAME);
-        mFile.createNewFile();
+        FileOutputStream outputStream = new FileOutputStream(mFile);
+        outputStream.write(FILE_DATA);
+        outputStream.close();
     }
 
     @Override
     protected void tearDown() throws Exception {
         super.tearDown();
-        // As {@link AssetFileDescripter#createOutputStream()}
-        // and {@link AssetFileDescripter#createInputStream()} doc,
-        // the input and output stream will be auto closed when the AssetFileDescriptor closed.
-        // Here is no need to close AutoCloseInputStream, as AssetFileDescriptor will do it for us.
-        if (mAssetFileDes != null) {
-            mAssetFileDes.close();
+        if (mFd != null) {
+            mFd.close();
+            mFd = null;
         }
-        getContext().deleteFile(FILE_NAME);
+        mFile.delete();
     }
 
-    /*
-     * Test AutoInputStream life circle.
-     * Test point:
-     * 1. Test AutoInputStream read what we write into file.
-     */
     @TestTargets({
         @TestTargetNew(
-            level = TestLevel.COMPLETE,
+            level = TestLevel.PARTIAL_COMPLETE,
             method = "AssetFileDescriptor.AutoCloseInputStream",
             args = {AssetFileDescriptor.class}
         ),
         @TestTargetNew(
             level = TestLevel.COMPLETE,
+            method = "skip",
+            args = {long.class}
+        )
+    })
+    public void testSkip() throws IOException {
+        openInput(0, FILE_LENGTH);
+        assertEquals(FILE_DATA[0], mInput.read());
+        assertEquals(0, mInput.skip(0));
+        assertEquals(FILE_DATA[1], mInput.read());
+        assertEquals(3, mInput.skip(3));
+        assertEquals(FILE_DATA[5], mInput.read());
+        assertEquals(3, mInput.skip(10));
+        assertEquals(FILE_END, mInput.read());
+    }
+
+    @TestTargets({
+        @TestTargetNew(
+            level = TestLevel.PARTIAL_COMPLETE,
+            method = "AssetFileDescriptor.AutoCloseInputStream",
+            args = {AssetFileDescriptor.class}
+        ),
+        @TestTargetNew(
+            level = TestLevel.PARTIAL_COMPLETE,
             method = "read",
             args = {}
+        )
+    })
+    public void testRead() throws IOException {
+        openInput(0, FILE_LENGTH);
+        for (int i = 0; i < FILE_LENGTH; i++) {
+            assertEquals(FILE_DATA[i], mInput.read());
+        }
+        assertEquals(FILE_END, mInput.read());
+    }
+
+    @TestTargets({
+        @TestTargetNew(
+            level = TestLevel.PARTIAL_COMPLETE,
+            method = "AssetFileDescriptor.AutoCloseInputStream",
+            args = {AssetFileDescriptor.class}
         ),
         @TestTargetNew(
-            level = TestLevel.COMPLETE,
+            level = TestLevel.PARTIAL_COMPLETE,
             method = "read",
-            args = {byte[].class, int.class, int.class}
+            args = {}
+        )
+    })
+    public void testReadPartial() throws IOException {
+        long len = 6;
+        openInput(0, len);
+        for (int i = 0; i < len; i++) {
+            assertEquals(FILE_DATA[i], mInput.read());
+        }
+        assertEquals(FILE_END, mInput.read());
+    }
+
+    @TestTargets({
+        @TestTargetNew(
+            level = TestLevel.PARTIAL_COMPLETE,
+            method = "AssetFileDescriptor.AutoCloseInputStream",
+            args = {AssetFileDescriptor.class}
         ),
         @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "read",
-            args = {byte[].class}
+                level = TestLevel.COMPLETE,
+                method = "read",
+                args = {byte[].class, int.class, int.class}
+        )
+    })
+    public void testReadBufferLen() throws IOException {
+        openInput(0, FILE_LENGTH);
+        byte[] buf = new byte[FILE_LENGTH];
+        assertEquals(3, mInput.read(buf, 0, 3));
+        assertEquals(3, mInput.read(buf, 3, 3));
+        assertEquals(3, mInput.read(buf, 6, 4));
+        MoreAsserts.assertEquals(FILE_DATA, buf);
+        assertEquals(FILE_END, mInput.read(buf, 0, 4));
+    }
+
+    @TestTargets({
+        @TestTargetNew(
+            level = TestLevel.PARTIAL_COMPLETE,
+            method = "AssetFileDescriptor.AutoCloseInputStream",
+            args = {AssetFileDescriptor.class}
         ),
         @TestTargetNew(
+                level = TestLevel.PARTIAL_COMPLETE,
+                method = "read",
+                args = {byte[].class}
+        )
+    })
+    public void testReadBuffer() throws IOException {
+        openInput(0, FILE_LENGTH);
+        byte[] buf = new byte[6];
+        assertEquals(6, mInput.read(buf));
+        assertEquals(FILE_DATA[0], buf[0]);
+        assertEquals(3, mInput.read(buf));
+        assertEquals(FILE_DATA[6], buf[0]);
+        assertEquals(FILE_END, mInput.read(buf));
+    }
+
+    @TestTargets({
+        @TestTargetNew(
+            level = TestLevel.PARTIAL_COMPLETE,
+            method = "AssetFileDescriptor.AutoCloseInputStream",
+            args = {AssetFileDescriptor.class}
+        ),
+        @TestTargetNew(
+                level = TestLevel.PARTIAL_COMPLETE,
+                method = "read",
+                args = {byte[].class}
+        )
+    })
+    public void testReadBufferPartial() throws IOException {
+        long len = 8;
+        openInput(0, len);
+        byte[] buf = new byte[6];
+        assertEquals(6, mInput.read(buf));
+        assertEquals(FILE_DATA[0], buf[0]);
+        assertEquals(2, mInput.read(buf));
+        assertEquals(FILE_DATA[6], buf[0]);
+        assertEquals(FILE_END, mInput.read(buf));
+    }
+
+    @TestTargets({
+        @TestTargetNew(
+            level = TestLevel.PARTIAL_COMPLETE,
+            method = "AssetFileDescriptor.AutoCloseInputStream",
+            args = {AssetFileDescriptor.class}
+        ),
+        @TestTargetNew(
+                level = TestLevel.PARTIAL_COMPLETE,
+                method = "available",
+                args = {}
+        )
+    })
+    public void testAvailableRead() throws IOException {
+        openInput(0, FILE_LENGTH);
+        assertEquals(FILE_LENGTH, mInput.available());
+        assertEquals(FILE_DATA[0], mInput.read());
+        assertEquals(FILE_LENGTH -1 , mInput.available());
+    }
+
+    @TestTargets({
+        @TestTargetNew(
+            level = TestLevel.PARTIAL_COMPLETE,
+            method = "AssetFileDescriptor.AutoCloseInputStream",
+            args = {AssetFileDescriptor.class}
+        ),
+        @TestTargetNew(
+                level = TestLevel.PARTIAL_COMPLETE,
+                method = "available",
+                args = {}
+        )
+    })
+    public void testAvailableReadBuffer() throws IOException {
+        openInput(0, FILE_LENGTH);
+        byte[] buf = new byte[3];
+        assertEquals(FILE_LENGTH, mInput.available());
+        assertEquals(buf.length, mInput.read(buf));
+        assertEquals(FILE_LENGTH - buf.length, mInput.available());
+    }
+
+    @TestTargets({
+        @TestTargetNew(
+            level = TestLevel.PARTIAL_COMPLETE,
+            method = "AssetFileDescriptor.AutoCloseInputStream",
+            args = {AssetFileDescriptor.class}
+        ),
+        @TestTargetNew(
+                level = TestLevel.PARTIAL_COMPLETE,
+                method = "available",
+                args = {}
+        )
+    })
+    public void testAvailableReadBufferLen() throws IOException {
+        openInput(0, FILE_LENGTH);
+        byte[] buf = new byte[3];
+        assertEquals(FILE_LENGTH, mInput.available());
+        assertEquals(2, mInput.read(buf, 0, 2));
+        assertEquals(FILE_LENGTH - 2, mInput.available());
+    }
+
+    /*
+     * Tests that AutoInputStream doesn't support mark().
+     */
+    @TestTargets({
+        @TestTargetNew(
+                level = TestLevel.PARTIAL_COMPLETE,
+                method = "AssetFileDescriptor.AutoCloseInputStream",
+                args = {AssetFileDescriptor.class}
+         ),
+        @TestTargetNew(
             level = TestLevel.COMPLETE,
             method = "mark",
             args = {int.class}
@@ -103,57 +275,27 @@
             level = TestLevel.COMPLETE,
             method = "markSupported",
             args = {}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "skip",
-            args = {long.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "available",
-            args = {}
         )
     })
-    public void testInputStream() throws IOException {
-        initAssetFileDescriptor();
-        FileOutputStream outputStream = null;
-        outputStream = mAssetFileDes.createOutputStream();
-        outputStream.write(FILE_DATA);
-        mAssetFileDes.close();
-
-        initAssetFileDescriptor();
-        AssetFileDescriptor.AutoCloseInputStream inputStream = null;
-        inputStream = new AssetFileDescriptor.AutoCloseInputStream(mAssetFileDes);
-        assertEquals(FILE_LENGTH, inputStream.available());
-        assertEquals(FILE_DATA[0], inputStream.read());
-        byte[] readFromFile = new byte[2];
-        int readBytes = inputStream.read(readFromFile);
-        assertTrue(FILE_END != readBytes);
-        while (readBytes < readFromFile.length) {
-            readFromFile[readBytes] = (byte) inputStream.read();
-            readBytes++;
-        }
-        assertEquals(FILE_DATA[1], readFromFile[0]);
-        assertEquals(FILE_DATA[2], readFromFile[1]);
-        inputStream.mark(FILE_LENGTH);
-        assertEquals(5, inputStream.skip(5));
-        readBytes = inputStream.read(readFromFile, OFFSET, READ_LENGTH);
-        while (readBytes < READ_LENGTH) {
-            readFromFile[readBytes] = (byte) inputStream.read();
-            readBytes++;
-        }
-        assertEquals(FILE_DATA[8], readFromFile[0]);
-        assertEquals(FILE_END, inputStream.read());
-        inputStream.reset();
-        assertEquals(FILE_END, inputStream.read(readFromFile));
-        assertEquals(FILE_END, inputStream.read(readFromFile, 0, 1));
-        assertFalse(inputStream.markSupported());
+    public void testMark() throws IOException {
+        openInput(0, FILE_LENGTH);
+        assertFalse(mInput.markSupported());
+        assertEquals(FILE_DATA[0], mInput.read());
+        mInput.mark(FILE_LENGTH);  // should do nothing
+        assertEquals(FILE_DATA[1], mInput.read());
+        mInput.reset();  // should do nothing
+        assertEquals(FILE_DATA[2], mInput.read());
     }
 
-    private void initAssetFileDescriptor() throws FileNotFoundException {
+    private void openInput(long startOffset, long length)
+            throws IOException {
+        if (mFd != null) {
+            mFd.close();
+            mFd = null;
+        }
         ParcelFileDescriptor fd =
-            ParcelFileDescriptor.open(mFile, ParcelFileDescriptor.MODE_READ_WRITE);
-        mAssetFileDes = new AssetFileDescriptor(fd, 0, FILE_LENGTH);
+                ParcelFileDescriptor.open(mFile, ParcelFileDescriptor.MODE_READ_WRITE);
+        mFd = new AssetFileDescriptor(fd, startOffset, length);
+        mInput = new AssetFileDescriptor.AutoCloseInputStream(mFd);
     }
 }
diff --git a/tests/tests/database/src/android/database/cts/AbstractCursorTest.java b/tests/tests/database/src/android/database/cts/AbstractCursorTest.java
index 47c52ba..8f5fead 100644
--- a/tests/tests/database/src/android/database/cts/AbstractCursorTest.java
+++ b/tests/tests/database/src/android/database/cts/AbstractCursorTest.java
@@ -453,16 +453,9 @@
         method = "getUpdatedField",
         args = {int.class}
     )
-    @ToBeFixed(bug = "1569265", explanation = "All other updating-related methods are 'hide' and "
-        + "'deprecated.")
     public void testGetUpdatedField() {
         mTestAbstractCursor.moveToFirst();
-        try {
-            assertEquals("hello", mTestAbstractCursor.getUpdatedField(0));
-            fail("getUpdatedField should throws a NullPointerException here.");
-        } catch (NullPointerException e) {
-            // expected
-        }
+        assertNull(mTestAbstractCursor.getUpdatedField(0));
     }
 
     @TestTargetNew(
@@ -746,12 +739,6 @@
             return mRows.length;
         }
 
-        @Deprecated
-        @Override
-        public boolean deleteRow() {
-            return false;
-        }
-
         @Override
         public String[] getColumnNames() {
             return mColumnNames;
diff --git a/tests/tests/database/src/android/database/cts/CursorWrapperTest.java b/tests/tests/database/src/android/database/cts/CursorWrapperTest.java
index dba9784..df90237 100644
--- a/tests/tests/database/src/android/database/cts/CursorWrapperTest.java
+++ b/tests/tests/database/src/android/database/cts/CursorWrapperTest.java
@@ -750,7 +750,17 @@
 
     private void setupDatabase() {
         File dbDir = getContext().getDir("tests", Context.MODE_PRIVATE);
-        mDatabaseFile = new File(dbDir, "database_test.db");
+        /* don't use the same database name as the one in super class
+         * this class's setUp() method deletes a database file just opened by super.setUp().
+         * that can cause corruption in database in the following situation:
+         *    super.setUp() creates the database, inserts some data into it.
+         *    this class setUp() deletes just the database file but not the associated
+         *    database files such as wal, shm files.
+         * solution is to have this class delete the whole database directory.
+         * better yet, this class shouldn't extend DatabaseCursortest at all.
+         * TODO: fix this bogus cts class hierarchy
+         */
+        mDatabaseFile = new File(dbDir, "cursor_test.db");
         if (mDatabaseFile.exists()) {
             mDatabaseFile.delete();
         }
diff --git a/tests/tests/database/src/android/database/cts/DatabaseCursorTest.java b/tests/tests/database/src/android/database/cts/DatabaseCursorTest.java
index 4d0c6ac..7a8657d 100644
--- a/tests/tests/database/src/android/database/cts/DatabaseCursorTest.java
+++ b/tests/tests/database/src/android/database/cts/DatabaseCursorTest.java
@@ -103,43 +103,6 @@
     }
 
     @MediumTest
-    public void testCursorUpdate() {
-        mDatabase.execSQL("CREATE TABLE test (_id INTEGER PRIMARY KEY, d INTEGER, s INTEGER);");
-        for (int i = 0; i < 20; i++) {
-            mDatabase.execSQL("INSERT INTO test (d, s) VALUES (" + i + "," + i % 2 + ");");
-        }
-
-        Cursor testCursor = getTestCursor(mDatabase.query("test", null, "s = 0", null, null, null,
-                null));
-
-        int dCol = testCursor.getColumnIndexOrThrow("d");
-        int sCol = testCursor.getColumnIndexOrThrow("s");
-
-        int count = 0;
-        while (testCursor.moveToNext()) {
-            assertTrue(testCursor.updateInt(dCol, 3));
-            count++;
-        }
-        assertEquals(10, count);
-
-        assertTrue(testCursor.commitUpdates());
-
-        assertTrue(testCursor.requery());
-
-        count = 0;
-        while (testCursor.moveToNext()) {
-            assertEquals(3, testCursor.getInt(dCol));
-            count++;
-        }
-
-        assertEquals(10, count);
-        assertTrue(testCursor.moveToFirst());
-        assertTrue(testCursor.deleteRow());
-        assertEquals(9, testCursor.getCount());
-        testCursor.close();
-    }
-
-    @MediumTest
     public void testBlob() throws Exception {
         // create table
         mDatabase.execSQL(
@@ -178,23 +141,6 @@
         assertEquals(s, testCursor.getString(sCol));
         assertEquals((double) d, testCursor.getDouble(dCol));
         assertEquals((long) l, testCursor.getLong(lCol));
-
-        // new byte[]
-        byte[] newblob = new byte[1000];
-        value = 98;
-        Arrays.fill(blob, value);
-
-        testCursor.updateBlob(bCol, newblob);
-        cBlob = testCursor.getBlob(bCol);
-        assertTrue(Arrays.equals(newblob, cBlob));
-
-        // commit
-        assertTrue(testCursor.commitUpdates());
-        assertTrue(testCursor.requery());
-        testCursor.moveToNext();
-        cBlob = testCursor.getBlob(bCol);
-        assertTrue(Arrays.equals(newblob, cBlob));
-        testCursor.close();
     }
 
     @MediumTest
diff --git a/tests/tests/database/src/android/database/cts/DatabaseUtilsTest.java b/tests/tests/database/src/android/database/cts/DatabaseUtilsTest.java
index c47b65b..ae2a204 100644
--- a/tests/tests/database/src/android/database/cts/DatabaseUtilsTest.java
+++ b/tests/tests/database/src/android/database/cts/DatabaseUtilsTest.java
@@ -33,11 +33,15 @@
 import android.database.sqlite.SQLiteException;
 import android.database.sqlite.SQLiteStatement;
 import android.os.Parcel;
+import android.os.ParcelFileDescriptor;
 import android.test.AndroidTestCase;
+import android.test.MoreAsserts;
 
 import java.io.ByteArrayOutputStream;
 import java.io.File;
 import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
 import java.io.PrintStream;
 
 @TestTargetClass(android.database.DatabaseUtils.class)
@@ -64,6 +68,8 @@
         assertNotNull(mDatabase);
         mDatabase.execSQL("CREATE TABLE " + TABLE_NAME + " (_id INTEGER PRIMARY KEY, " +
                 "name TEXT, age INTEGER, address TEXT);");
+        mDatabase.execSQL(
+                "CREATE TABLE blob_test (_id INTEGER PRIMARY KEY, name TEXT, data BLOB)");
     }
 
     @Override
@@ -769,11 +775,98 @@
 
         args = new String[] { "1000" }; // NO people can be older than this.
         try {
-            DatabaseUtils.stringForQuery(statement, args);
+            DatabaseUtils.blobFileDescriptorForQuery(statement, args);
             fail("should throw SQLiteDoneException");
         } catch (SQLiteDoneException e) {
             // expected
         }
         statement.close();
     }
-}
\ No newline at end of file
+
+    @TestTargets({
+        @TestTargetNew(
+            level = TestLevel.COMPLETE,
+            method = "blobFileDescriptorForQuery",
+            args = {android.database.sqlite.SQLiteDatabase.class, java.lang.String.class,
+                    java.lang.String[].class}
+        ),
+        @TestTargetNew(
+            level = TestLevel.COMPLETE,
+            method = "blobFileDescriptorForQuery",
+            args = {android.database.sqlite.SQLiteStatement.class, java.lang.String[].class}
+        )
+    })
+    public void testBlobFileDescriptorForQuery() throws Exception {
+        String data1 = "5300FEFF";
+        String data2 = "DECAFBAD";
+        mDatabase.execSQL("INSERT INTO blob_test (name, data) VALUES ('Mike', X'" + data1 + "')");
+
+        String query = "SELECT data FROM blob_test";
+        assertFileDescriptorContent(parseBlob(data1),
+                        DatabaseUtils.blobFileDescriptorForQuery(mDatabase, query, null));
+
+        mDatabase.execSQL("INSERT INTO blob_test (name, data) VALUES ('Jack', X'" + data2 + "');");
+        query = "SELECT data FROM blob_test WHERE name = ?";
+        String[] args = new String[] { "Jack" };
+        assertFileDescriptorContent(parseBlob(data2),
+                DatabaseUtils.blobFileDescriptorForQuery(mDatabase, query, args));
+
+        args = new String[] { "No such name" };
+        try {
+            DatabaseUtils.stringForQuery(mDatabase, query, args);
+            fail("should throw SQLiteDoneException");
+        } catch (SQLiteDoneException e) {
+            // expected
+        }
+
+        query = "SELECT data FROM blob_test WHERE name = ?;";
+        SQLiteStatement statement = mDatabase.compileStatement(query);
+        args = new String[] { "Mike" };
+        assertFileDescriptorContent(parseBlob(data1),
+                DatabaseUtils.blobFileDescriptorForQuery(statement, args));
+
+        args = new String[] { "No such name" };
+        try {
+            DatabaseUtils.blobFileDescriptorForQuery(statement, args);
+            fail("should throw SQLiteDoneException");
+        } catch (SQLiteDoneException e) {
+            // expected
+        }
+        statement.close();
+    }
+
+    private static byte[] parseBlob(String src) {
+        int len = src.length();
+        byte[] result = new byte[len / 2];
+
+        for (int i = 0; i < len/2; i++) {
+            int val;
+            char c1 = src.charAt(i*2);
+            char c2 = src.charAt(i*2+1);
+            int val1 = Character.digit(c1, 16);
+            int val2 = Character.digit(c2, 16);
+            val = (val1 << 4) | val2;
+            result[i] = (byte)val;
+        }
+        return result;
+    }
+
+    private static void assertFileDescriptorContent(byte[] expected, ParcelFileDescriptor fd)
+            throws IOException {
+        assertInputStreamContent(expected, new ParcelFileDescriptor.AutoCloseInputStream(fd));
+    }
+
+    private static void assertInputStreamContent(byte[] expected, InputStream is)
+            throws IOException {
+        try {
+            byte[] observed = new byte[expected.length];
+            int count = is.read(observed);
+            assertEquals(expected.length, count);
+            assertEquals(-1, is.read());
+            MoreAsserts.assertEquals(expected, observed);
+        } finally {
+            is.close();
+        }
+    }
+
+}
diff --git a/tests/tests/database/src/android/database/sqlite/cts/SQLiteCursorTest.java b/tests/tests/database/src/android/database/sqlite/cts/SQLiteCursorTest.java
index ae5b9d4..c684a69 100644
--- a/tests/tests/database/src/android/database/sqlite/cts/SQLiteCursorTest.java
+++ b/tests/tests/database/src/android/database/sqlite/cts/SQLiteCursorTest.java
@@ -24,6 +24,7 @@
 
 import android.content.Context;
 import android.database.AbstractCursor;
+import android.database.Cursor;
 import android.database.CursorWindow;
 import android.database.DataSetObserver;
 import android.database.StaleDataException;
@@ -79,8 +80,8 @@
                 TEST_SQL, TABLE_NAME);
         try {
             new SQLiteCursor(mDatabase, cursorDriver, TABLE_NAME, null);
-            fail("constructor didn't throw NullPointerException when SQLiteQuery is null");
-        } catch (NullPointerException e) {
+            fail("constructor didn't throw IllegalArgumentException when SQLiteQuery is null");
+        } catch (IllegalArgumentException e) {
         }
 
         // get SQLiteCursor by querying database
@@ -221,6 +222,39 @@
     @TestTargets({
         @TestTargetNew(
             level = TestLevel.COMPLETE,
+            method = "requery",
+            args = {}
+        )
+    })
+    public void testRequery2() {
+        mDatabase.disableWriteAheadLogging();
+        mDatabase.execSQL("create table testRequery2 (i int);");
+        mDatabase.execSQL("insert into testRequery2 values(1);");
+        mDatabase.execSQL("insert into testRequery2 values(2);");
+        Cursor c = mDatabase.rawQuery("select * from testRequery2 order by i", null);
+        assertEquals(2, c.getCount());
+        assertTrue(c.moveToFirst());
+        assertEquals(1, c.getInt(0));
+        assertTrue(c.moveToNext());
+        assertEquals(2, c.getInt(0));
+        // add more data to the table and requery
+        mDatabase.execSQL("insert into testRequery2 values(3);");
+        assertTrue(c.requery());
+        assertEquals(3, c.getCount());
+        assertTrue(c.moveToFirst());
+        assertEquals(1, c.getInt(0));
+        assertTrue(c.moveToNext());
+        assertEquals(2, c.getInt(0));
+        assertTrue(c.moveToNext());
+        assertEquals(3, c.getInt(0));
+        // close the database and see if requery throws an exception
+        mDatabase.close();
+        assertFalse(c.requery());
+    }
+
+    @TestTargets({
+        @TestTargetNew(
+            level = TestLevel.COMPLETE,
             method = "getColumnIndex",
             args = {java.lang.String.class}
         ),
@@ -242,16 +276,6 @@
 
     @TestTargetNew(
         level = TestLevel.COMPLETE,
-        method = "getDatabase",
-        args = {}
-    )
-    public void testGetDatabase() {
-        SQLiteCursor cursor = getCursor();
-        assertSame(mDatabase, cursor.getDatabase());
-    }
-
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
         method = "setSelectionArguments",
         args = {java.lang.String[].class}
     )
diff --git a/tests/tests/database/src/android/database/sqlite/cts/SQLiteDatabaseTest.java b/tests/tests/database/src/android/database/sqlite/cts/SQLiteDatabaseTest.java
index 7a18cd8..4d2724a 100644
--- a/tests/tests/database/src/android/database/sqlite/cts/SQLiteDatabaseTest.java
+++ b/tests/tests/database/src/android/database/sqlite/cts/SQLiteDatabaseTest.java
@@ -18,10 +18,7 @@
 
 import java.io.File;
 import java.util.ArrayList;
-import java.util.Iterator;
 import java.util.Locale;
-import java.util.Map;
-import java.util.Set;
 
 import android.content.ContentValues;
 import android.database.Cursor;
@@ -37,6 +34,8 @@
 import android.database.sqlite.SQLiteTransactionListener;
 import android.test.AndroidTestCase;
 import android.test.MoreAsserts;
+import android.test.suitebuilder.annotation.LargeTest;
+import android.test.suitebuilder.annotation.SmallTest;
 import dalvik.annotation.TestTargets;
 import dalvik.annotation.TestTargetNew;
 import dalvik.annotation.TestLevel;
@@ -139,17 +138,8 @@
         assertNotNull(db);
         db.close();
 
-        try {
-            // do not allow to create file in the directory
-            SQLiteDatabase.openDatabase("/system/database.db", factory,
-                    SQLiteDatabase.CREATE_IF_NECESSARY);
-            fail("didn't throw SQLiteException when do not allow to create database file");
-        } catch (SQLiteException e) {
-        } finally {
-            db.close();
-        }
-
         File dbFile = new File(mDatabaseDir, "database_test12345678.db");
+        dbFile.delete();
         assertFalse(dbFile.exists());
         db = SQLiteDatabase.openOrCreateDatabase(dbFile.getPath(), factory);
         assertNotNull(db);
@@ -338,88 +328,6 @@
         }
     }
 
-    @SuppressWarnings("deprecation")
-    @TestTargets({
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            notes = "Test getSyncedTables()",
-            method = "getSyncedTables",
-            args = {}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            notes = "Test markTableSyncable(String, String)",
-            method = "markTableSyncable",
-            args = {java.lang.String.class, java.lang.String.class}
-        )
-    })
-    public void testGetSyncedTables() {
-        mDatabase.execSQL("CREATE TABLE people (_id INTEGER PRIMARY KEY, name TEXT, "
-                + "_sync_dirty INTEGER);");
-        mDatabase.execSQL("CREATE TABLE _delete_people (name TEXT);");
-        Map<String, String> tableMap = mDatabase.getSyncedTables();
-        assertEquals(0, tableMap.size());
-        mDatabase.markTableSyncable("people", "_delete_people");
-        tableMap = mDatabase.getSyncedTables();
-        assertEquals(1, tableMap.size());
-        Set<String> keys = tableMap.keySet();
-        Iterator<String> iterator = keys.iterator();
-        assertTrue(iterator.hasNext());
-        assertEquals("people", iterator.next());
-        assertEquals("_delete_people", tableMap.get("people"));
-        assertFalse(iterator.hasNext());
-
-        // test sync
-        mDatabase.execSQL("INSERT INTO people VALUES (0, \"foo\", 0);");
-        Cursor c = mDatabase.query("people", new String[] {"_id", "name" },
-                "_id = 0", null, null, null, null);
-        assertTrue(c.moveToFirst());
-        c.updateString(1, "updated");
-        c.commitUpdates();
-        c.close();
-        c = mDatabase.query("people", new String[] {"_id", "_sync_dirty" },
-                "_id = 0", null, null, null, null);
-        assertTrue(c.moveToFirst());
-        // _sync_dirty flag has been set
-        assertEquals(1, c.getInt(1));
-        c.close();
-    }
-
-    @SuppressWarnings("deprecation")
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "Test markTableSyncable(String, String, String)",
-        method = "markTableSyncable",
-        args = {java.lang.String.class, java.lang.String.class, java.lang.String.class}
-    )
-    public void testMarkTableSyncable() {
-        mDatabase.execSQL("CREATE TABLE phone (_id INTEGER PRIMARY KEY, _people_id INTEGER, " +
-                "name TEXT);");
-        mDatabase.execSQL("CREATE TABLE people (_id INTEGER PRIMARY KEY, " +
-                "name TEXT, _sync_dirty INTEGER);");
-        mDatabase.markTableSyncable("phone", "_people_id", "people");
-
-        Map<String, String> tableMap = mDatabase.getSyncedTables();
-        // since no delete table was given, there is no mapping
-        assertEquals(0, tableMap.size());
-
-        // test sync
-        mDatabase.execSQL("INSERT INTO people VALUES (13, \"foo\", 0);");
-        mDatabase.execSQL("INSERT INTO phone VALUES (0, 13, \"bar\");");
-        Cursor c = mDatabase.query("phone", new String[] {"_id", "name" },
-                "_id = 0", null, null, null, null);
-        assertTrue(c.moveToFirst());
-        c.updateString(1, "updated");
-        c.commitUpdates();
-        c.close();
-        c = mDatabase.query("people", new String[] {"_id", "_sync_dirty" },
-                "_id = 13", null, null, null, null);
-        assertTrue(c.moveToFirst());
-        // _sync_dirty flag has been set
-        assertEquals(1, c.getInt(1));
-        c.close();
-    }
-
     @TestTargets({
         @TestTargetNew(
             level = TestLevel.COMPLETE,
@@ -546,7 +454,8 @@
         mDatabase.execSQL("INSERT INTO test (name, age, address) VALUES ('Jim', 35, 'Chicago');");
 
         // delete one record.
-        mDatabase.delete(TABLE_NAME, "name = 'Mike'", null);
+        int count = mDatabase.delete(TABLE_NAME, "name = 'Mike'", null);
+        assertEquals(1, count);
 
         Cursor cursor = mDatabase.query(TABLE_NAME, TEST_PROJECTION, null,
                 null, null, null, null);
@@ -564,7 +473,8 @@
         cursor.close();
 
         // delete another record.
-        mDatabase.delete(TABLE_NAME, "name = ?", new String[] { "Jack" });
+        count = mDatabase.delete(TABLE_NAME, "name = ?", new String[] { "Jack" });
+        assertEquals(1, count);
 
         cursor = mDatabase.query(TABLE_NAME, TEST_PROJECTION, null, null, null,
                 null, null);
@@ -581,7 +491,8 @@
         mDatabase.execSQL("INSERT INTO test (name, age, address) VALUES ('Jack', 30, 'London');");
 
         // delete all records.
-        mDatabase.delete(TABLE_NAME, null, null);
+        count = mDatabase.delete(TABLE_NAME, null, null);
+        assertEquals(3, count);
 
         cursor = mDatabase.query(TABLE_NAME, TEST_PROJECTION, null, null, null, null, null);
         assertNotNull(cursor);
@@ -1594,4 +1505,128 @@
         assertEquals(1, cursor.getInt(0));
         assertEquals(2, cursor.getInt(1));
     }
+
+    @TestTargetNew(
+            level = TestLevel.COMPLETE,
+            notes = "test enableWriteAheadLogging",
+            method = "enableWriteAheadLogging",
+            args = {}
+        )
+    /**
+     * With sqlite's write-ahead-logging (WAL) enabled, readers get old version of data
+     * from the table that a writer is modifying at the same time.
+     * <p>
+     * This method does the following to test this sqlite3 feature
+     * <ol>
+     *   <li>creates a table in the database and populates it with 5 rows of data</li>
+     *   <li>do "select count(*) from this_table" and expect to receive 5</li>
+     *   <li>start a writer thread who BEGINs a transaction, INSERTs a single row
+     *   into this_table</li>
+     *   <li>writer stops the transaction at this point, kicks off a reader thread - which will
+     *       do  the above SELECT query: "select count(*) from this_table"</li>
+     *   <li>this query should return value 5 - because writer is still in transaction and
+     *    sqlite returns OLD version of the data</li>
+     *   <li>writer ends the transaction, thus making the extra row now visible to everyone</li>
+     *   <li>reader is kicked off again to do the same query. this time query should
+     *   return value = 6 which includes the newly inserted row into this_table.</li>
+     *</p>
+     * @throws InterruptedException
+     */
+    @LargeTest
+    public void testReaderGetsOldVersionOfDataWhenWriterIsInXact() throws InterruptedException {
+        // redo setup to create WAL enabled database
+        mDatabase.close();
+        new File(mDatabase.getPath()).delete();
+        mDatabase = SQLiteDatabase.openOrCreateDatabase(mDatabaseFile.getPath(), null, null);
+        boolean rslt = mDatabase.enableWriteAheadLogging();
+        assertTrue(rslt);
+        assertNotNull(mDatabase);
+
+        // create a new table and insert 5 records into it.
+        mDatabase.execSQL("CREATE TABLE t1 (i int, j int);");
+        mDatabase.beginTransaction();
+        for (int i = 0; i < 5; i++) {
+            mDatabase.execSQL("insert into t1 values(?,?);", new String[] {i+"", i+""});
+        }
+        mDatabase.setTransactionSuccessful();
+        mDatabase.endTransaction();
+
+        // make sure a reader can read the above data
+        ReaderQueryingData r1 = new ReaderQueryingData(5);
+        r1.start();
+        Thread.yield();
+        try {r1.join();} catch (Exception e) {}
+
+        WriterDoingSingleTransaction w = new WriterDoingSingleTransaction();
+        w.start();
+        w.join();
+    }
+
+    private class WriterDoingSingleTransaction extends Thread {
+        @Override public void run() {
+            // start a transaction
+            mDatabase.beginTransactionNonExclusive();
+            mDatabase.execSQL("insert into t1 values(?,?);", new String[] {"11", "11"});
+            assertTrue(mDatabase.isOpen());
+
+            // while the writer is in a transaction, start a reader and make sure it can still
+            // read 5 rows of data (= old data prior to the current transaction)
+            ReaderQueryingData r1 = new ReaderQueryingData(5);
+            r1.start();
+            try {r1.join();} catch (Exception e) {}
+
+            // now, have the writer do the select count(*)
+            // it should execute on the same connection as this transaction
+            // and count(*) should reflect the newly inserted row
+            Long l = DatabaseUtils.longForQuery(mDatabase, "select count(*) from t1", null);
+            assertEquals(6, l.intValue());
+
+            // end transaction
+            mDatabase.setTransactionSuccessful();
+            mDatabase.endTransaction();
+
+            // reader should now be able to read 6 rows = new data AFTER this transaction
+            r1 = new ReaderQueryingData(6);
+            r1.start();
+            try {r1.join();} catch (Exception e) {}
+        }
+    }
+
+    private class ReaderQueryingData extends Thread {
+        private int count;
+        /**
+         * constructor with a param to indicate the number of rows expected to be read
+         */
+        public ReaderQueryingData(int count) {
+            this.count = count;
+        }
+        @Override public void run() {
+            Long l = DatabaseUtils.longForQuery(mDatabase, "select count(*) from t1", null);
+            assertEquals(count, l.intValue());
+        }
+    }
+
+    @TestTargetNew(
+            level = TestLevel.COMPLETE,
+            notes = "test exceptions from enableWriteAheadLogging().",
+            method = "enableWriteAheadLogging",
+            args = {}
+        )
+    public void testExceptionsFromEnableWriteAheadLogging() {
+        // attach a database
+        // redo setup to create WAL enabled database
+        mDatabase.close();
+        new File(mDatabase.getPath()).delete();
+        mDatabase = SQLiteDatabase.openOrCreateDatabase(mDatabaseFile.getPath(), null, null);
+
+        // attach a database and call enableWriteAheadLogging - should not be allowed
+        mDatabase.execSQL("attach database ':memory:' as memoryDb");
+        boolean rslt = mDatabase.enableWriteAheadLogging();
+        assertFalse(rslt);
+        // enableWriteAheadLogging on memory database is not allowed
+        SQLiteDatabase db = SQLiteDatabase.create(null);
+        rslt = db.enableWriteAheadLogging();
+        assertFalse(rslt);
+        db.close();
+    }
 }
diff --git a/tests/tests/database/src/android/database/sqlite/cts/SQLiteProgramTest.java b/tests/tests/database/src/android/database/sqlite/cts/SQLiteProgramTest.java
index 89918a1..a9a3293 100644
--- a/tests/tests/database/src/android/database/sqlite/cts/SQLiteProgramTest.java
+++ b/tests/tests/database/src/android/database/sqlite/cts/SQLiteProgramTest.java
@@ -20,13 +20,13 @@
 import dalvik.annotation.TestTargetClass;
 import dalvik.annotation.TestTargetNew;
 import dalvik.annotation.TestTargets;
-import dalvik.annotation.ToBeFixed;
 
 import android.content.Context;
 import android.database.Cursor;
 import android.database.sqlite.SQLiteDatabase;
 import android.database.sqlite.SQLiteDoneException;
 import android.database.sqlite.SQLiteException;
+import android.database.sqlite.SQLiteQuery;
 import android.database.sqlite.SQLiteStatement;
 import android.test.AndroidTestCase;
 import android.test.MoreAsserts;
@@ -37,9 +37,6 @@
 
     private SQLiteDatabase mDatabase;
 
-    @ToBeFixed(bug="1448885", explanation="SQLiteProgram is an abstract class and its " +
-            "constructor is package private, so it can not be extended directly to test. " +
-            "For this reason, the test uses SQLiteStatement instead.")
     @Override
     protected void setUp() throws Exception {
         super.setUp();
@@ -57,79 +54,6 @@
         super.tearDown();
     }
 
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "Test getUniqueId()",
-        method = "getUniqueId",
-        args = {}
-    )
-    public void testGetUniqueId() {
-        mDatabase.execSQL("CREATE TABLE test (_id INTEGER PRIMARY KEY, text1 TEXT, text2 TEXT, " +
-                "num1 INTEGER, num2 INTEGER, image BLOB);");
-        final String statement = "DELETE FROM test WHERE _id=?;";
-        SQLiteStatement statementOne = mDatabase.compileStatement(statement);
-        SQLiteStatement statementTwo = mDatabase.compileStatement(statement);
-        // since the same compiled statement is being accessed at the same time by 2 different
-        // objects, they each get their own statement id
-        assertTrue(statementOne.getUniqueId() != statementTwo.getUniqueId());
-        statementOne.close();
-        statementTwo.close();
-        
-        statementOne = mDatabase.compileStatement(statement);
-        int n = statementOne.getUniqueId();
-        statementOne.close();
-        statementTwo = mDatabase.compileStatement(statement);
-        assertEquals(n, statementTwo.getUniqueId());
-        statementTwo.close();
-
-        // now try to compile 2 different statements and they should have different uniquerIds.
-        SQLiteStatement statement1 = mDatabase.compileStatement("DELETE FROM test WHERE _id=1;");
-        SQLiteStatement statement2 = mDatabase.compileStatement("DELETE FROM test WHERE _id=2;");
-        assertTrue(statement1.getUniqueId() != statement2.getUniqueId());
-        statement1.close();
-        statement2.close();
-    }
-
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "Test onAllReferencesReleased(). Since sql statements are always cached in " +
-        		"SQLiteDatabase, compiledSql should NOT be released " +
-        		"when onAllReferencesReleased() is called",
-        method = "onAllReferencesReleased",
-        args = {}
-    )
-    public void testOnAllReferencesReleased() {
-        mDatabase.execSQL("CREATE TABLE test (_id INTEGER PRIMARY KEY, text1 TEXT, text2 TEXT, " +
-                "num1 INTEGER, num2 INTEGER, image BLOB);");
-        final String statement = "DELETE FROM test WHERE _id=?;";
-        SQLiteStatement statementOne = mDatabase.compileStatement(statement);
-        assertTrue(statementOne.getUniqueId() > 0);
-        int nStatement = statementOne.getUniqueId();
-        statementOne.releaseReference();
-        assertTrue(statementOne.getUniqueId() == nStatement);
-        statementOne.close();
-    }
-
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "Test onAllReferencesReleasedFromContainer(). " +
-        		"Since sql statements are always cached in " +
-                "SQLiteDatabase, compiledSql should NOT be released " +
-                "when onAllReferencesReleasedFromContainer() is called",
-        args = {}
-    )
-    public void testOnAllReferencesReleasedFromContainer() {
-        mDatabase.execSQL("CREATE TABLE test (_id INTEGER PRIMARY KEY, text1 TEXT, text2 TEXT, " +
-                "num1 INTEGER, num2 INTEGER, image BLOB);");
-        final String statement = "DELETE FROM test WHERE _id=?;";
-        SQLiteStatement statementOne = mDatabase.compileStatement(statement);
-        assertTrue(statementOne.getUniqueId() > 0);
-        int nStatement = statementOne.getUniqueId();
-        statementOne.releaseReferenceFromContainer();
-        assertTrue(statementOne.getUniqueId() == nStatement);
-        statementOne.close();
-    }
-
     @TestTargets({
         @TestTargetNew(
             level = TestLevel.COMPLETE,
@@ -195,39 +119,36 @@
         }
         statement.close();
 
-        statement = mDatabase.compileStatement("SELECT text1 FROM test;");
+        Cursor cursor = null;
         try {
-            statement.bindString(1, "foo");
+            cursor = mDatabase.query("test", new String[]{"text1"}, "where text1='a'",
+                    new String[]{"foo"}, null, null, null);
             fail("Should throw exception (no value to bind)");
         } catch (SQLiteException expected) {
             // expected
-        }
-
-        statement =
-            mDatabase.compileStatement("SELECT text1 FROM test WHERE text2 = ? AND num2 = ?;");
-
-        try {
-            statement.bindString(0, "Jack");
-            fail("Should throw exception (index is 0)");
-        } catch (SQLiteException expected) {
-            // expected
+        } finally {
+            if (cursor != null) {
+                cursor.close();
+            }
         }
         try {
-            statement.bindLong(-1, 30);
-            fail("Should throw exception (index is negative)");
-        } catch (SQLiteException expected) {
-            // expected
-        }
-        try {
-            statement.bindDouble(3, 589.0);
+            cursor = mDatabase.query("test", new String[]{"text1"}, "where text1='a'",
+                    new String[]{"foo", "bar"}, null, null, null);
             fail("Should throw exception (index too large)");
         } catch (SQLiteException expected) {
             // expected
+        } finally {
+            if (cursor != null) {
+                cursor.close();
+            }
         }
         // test positive case
+        statement = mDatabase.compileStatement(
+                "SELECT text1 FROM test WHERE text2 = ? AND num2 = ?;");
         statement.bindString(1, "Jack");
         statement.bindLong(2, 30);
         assertEquals("Mike", statement.simpleQueryForString());
+        statement.close();
     }
 
     @TestTargetNew(
@@ -303,64 +224,4 @@
         MoreAsserts.assertEquals(blob, value);
         cursor.close();
     }
-
-    @TestTargets({
-        @TestTargetNew(
-            level = TestLevel.NOT_FEASIBLE,
-            method = "onAllReferencesReleased",
-            args = {}
-        ),
-        @TestTargetNew(
-            level = TestLevel.NOT_FEASIBLE,
-            method = "onAllReferencesReleasedFromContainer",
-            args = {}
-        ),
-        @TestTargetNew(
-            level = TestLevel.NOT_FEASIBLE,
-            method = "compile",
-            args = {java.lang.String.class, boolean.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.NOT_FEASIBLE,
-            method = "native_bind_blob",
-            args = {int.class, byte[].class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.NOT_FEASIBLE,
-            method = "native_bind_double",
-            args = {int.class, double.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.NOT_FEASIBLE,
-            method = "native_bind_long",
-            args = {int.class, long.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.NOT_FEASIBLE,
-            method = "native_bind_null",
-            args = {int.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.NOT_FEASIBLE,
-            method = "native_compile",
-            args = {java.lang.String.class}
-        )
-    })
-    @ToBeFixed(bug = "1448885", explanation = "Cannot test protected methods, since constructor" +
-        " is private.")
-    public void testProtectedMethods() {
-        // cannot test
-    }
-
-    private void closeDatabaseWithOrphanedStatement(){
-        try {
-            mDatabase.close();
-        } catch (SQLiteException e) {
-            // A SQLiteException is thrown if there are some unfinialized exceptions
-            // This is expected as some tests explicitly leave statements in this state
-            if (!e.getMessage().equals("Unable to close due to unfinalised statements")) {
-                throw e;
-            }
-        }
-    }
 }
diff --git a/tests/tests/database/src/android/database/sqlite/cts/SQLiteStatementTest.java b/tests/tests/database/src/android/database/sqlite/cts/SQLiteStatementTest.java
index ec6b79a..b568b8c 100644
--- a/tests/tests/database/src/android/database/sqlite/cts/SQLiteStatementTest.java
+++ b/tests/tests/database/src/android/database/sqlite/cts/SQLiteStatementTest.java
@@ -21,19 +21,35 @@
 import dalvik.annotation.TestTargetNew;
 import dalvik.annotation.TestTargets;
 
+import android.content.ContentValues;
 import android.content.Context;
 import android.database.Cursor;
+import android.database.DatabaseUtils;
 import android.database.SQLException;
 import android.database.sqlite.SQLiteDatabase;
 import android.database.sqlite.SQLiteDoneException;
 import android.database.sqlite.SQLiteStatement;
+import android.os.ParcelFileDescriptor;
 import android.test.AndroidTestCase;
+import android.test.MoreAsserts;
+
+import java.io.IOException;
+import java.io.InputStream;
 
 @TestTargetClass(android.database.sqlite.SQLiteStatement.class)
 public class SQLiteStatementTest extends AndroidTestCase {
     private static final String STRING1 = "this is a test";
     private static final String STRING2 = "another test";
 
+    private static final byte[][] BLOBS = new byte [][] {
+        parseBlob("86FADCF1A820666AEBD0789F47932151A2EF734269E8AC4E39630AB60519DFD8"),
+        new byte[1],
+        null,
+        parseBlob("00"),
+        parseBlob("FF"),
+        parseBlob("D7B500FECF25F7A4D83BF823D3858690790F2526013DE6CAE9A69170E2A1E47238"),
+    };
+
     private static final String DATABASE_NAME = "database_test.db";
 
     private static final int CURRENT_DATABASE_VERSION = 42;
@@ -60,40 +76,62 @@
         mDatabase.execSQL("CREATE TABLE test (_id INTEGER PRIMARY KEY, data TEXT);");
     }
 
+    private void populateBlobTable() {
+        mDatabase.execSQL("CREATE TABLE blob_test (_id INTEGER PRIMARY KEY, data BLOB)");
+        for (int i = 0; i < BLOBS.length; i++) {
+            ContentValues values = new ContentValues();
+            values.put("_id", i);
+            values.put("data", BLOBS[i]);
+            mDatabase.insert("blob_test", null, values);
+        }
+    }
+
     @TestTargetNew(
         level = TestLevel.COMPLETE,
-        method = "execute",
+        method = "executeUpdateDelete",
         args = {}
     )
     public void testExecute() {
+        mDatabase.disableWriteAheadLogging();
         populateDefaultTable();
 
-        Cursor c = mDatabase.query("test", null, null, null, null, null, null);
-        assertEquals(0, c.getCount());
+        assertEquals(0, DatabaseUtils.longForQuery(mDatabase, "select count(*) from test", null));
 
-        // test insert
-        SQLiteStatement statement = mDatabase.compileStatement(
-                "INSERT INTO test (data) VALUES ('" + STRING1 + "')");
-        statement.execute();
+        // test update
+        // insert 2 rows and then update them.
+        SQLiteStatement statement1 = mDatabase.compileStatement(
+                "INSERT INTO test (data) VALUES ('" + STRING2 + "')");
+        assertEquals(1, statement1.executeInsert());
+        assertEquals(2, statement1.executeInsert());
+        SQLiteStatement statement2 =
+                mDatabase.compileStatement("UPDATE test set data = 'a' WHERE _id > 0");
+        assertEquals(2, statement2.executeUpdateDelete());
+        statement2.close();
+        // should still have 2 rows in the table
+        assertEquals(2, DatabaseUtils.longForQuery(mDatabase, "select count(*) from test", null));
 
-        c = mDatabase.query("test", null, null, null, null, null, null);
-        assertEquals(1, c.getCount());
+        // test delete
+        // insert 2 more rows and delete 3 of them
+        assertEquals(3, statement1.executeInsert());
+        assertEquals(4, statement1.executeInsert());
+        statement1.close();
+        statement2 = mDatabase.compileStatement("DELETE from test WHERE _id < 4");
+        assertEquals(3, statement2.executeUpdateDelete());
+        statement2.close();
+        // should still have 1 row1 in the table
+        assertEquals(1, DatabaseUtils.longForQuery(mDatabase, "select count(*) from test", null));
 
-        c.moveToFirst();
-        assertEquals(STRING1, c.getString(c.getColumnIndex("data")));
-
-        // invalid SQL statement
-        statement = mDatabase.compileStatement(
-                "SELECT * FROM test WHERE data=\"" + STRING1 + "\"");
+        // if the SQL statement is something that causes rows of data to
+        // be returned, executeUpdateDelete() (and execute()) throw an exception.
+        statement2 = mDatabase.compileStatement("SELECT count(*) FROM test");
         try {
-            statement.execute();
-            fail("There should be a SQLException thrown out.");
+            statement2.executeUpdateDelete();
+            fail("exception expected");
         } catch (SQLException e) {
-            // expected.
+            // expected
+        } finally {
+            statement2.close();
         }
-
-        c.deactivate();
-        statement.close();
     }
 
     @TestTargets({
@@ -118,25 +156,33 @@
         SQLiteStatement statement = mDatabase.compileStatement(
                 "INSERT INTO test (data) VALUES ('" + STRING2 + "')");
         assertEquals(1, statement.executeInsert());
+        statement.close();
+
+        // try to insert another row with the same id. last inserted rowid should be -1
+        statement = mDatabase.compileStatement("insert or ignore into test values(1, 1);");
+        assertEquals(-1, statement.executeInsert());
+        statement.close();
 
         c = mDatabase.query("test", null, null, null, null, null, null);
         assertEquals(1, c.getCount());
 
         c.moveToFirst();
         assertEquals(STRING2, c.getString(c.getColumnIndex("data")));
+        c.close();
 
-        // invalid SQL statement
+        // if the sql statement is something that causes rows of data to
+        // be returned, executeInsert() throws an exception
         statement = mDatabase.compileStatement(
                 "SELECT * FROM test WHERE data=\"" + STRING2 + "\"");
         try {
             statement.executeInsert();
-            fail("There should be a SQLException thrown out.");
+            fail("exception expected");
         } catch (SQLException e) {
-            // expected.
-        }
+            // expected
+        } finally {
+            statement.close();
 
-        c.deactivate();
-        statement.close();
+        }
     }
 
     @TestTargetNew(
@@ -196,4 +242,177 @@
 
         statement.close();
     }
+
+    @TestTargetNew(
+        level = TestLevel.PARTIAL_COMPLETE,
+        method = "simpleQueryForBlobFileDescriptor",
+        args = {}
+    )
+    public void testSimpleQueryForBlobFileDescriptorSuccessNormal() throws IOException {
+        doTestSimpleQueryForBlobFileDescriptorSuccess(0);
+    }
+
+    @TestTargetNew(
+        level = TestLevel.PARTIAL_COMPLETE,
+        method = "simpleQueryForBlobFileDescriptor",
+        args = {}
+    )
+    public void testSimpleQueryForBlobFileDescriptorSuccessEmpty() throws IOException {
+        doTestSimpleQueryForBlobFileDescriptorSuccess(1);
+    }
+
+    @TestTargetNew(
+        level = TestLevel.PARTIAL_COMPLETE,
+        method = "simpleQueryForBlobFileDescriptor",
+        args = {}
+    )
+    public void testSimpleQueryForBlobFileDescriptorSuccessNull() {
+        populateBlobTable();
+
+        String sql = "SELECT data FROM blob_test WHERE _id = " + 2;
+        SQLiteStatement stm = mDatabase.compileStatement(sql);
+        assertNull(stm.simpleQueryForBlobFileDescriptor());
+    }
+
+    @TestTargetNew(
+        level = TestLevel.PARTIAL_COMPLETE,
+        method = "simpleQueryForBlobFileDescriptor",
+        args = {}
+    )
+    public void testSimpleQueryForBlobFileDescriptorSuccess00() throws IOException {
+        doTestSimpleQueryForBlobFileDescriptorSuccess(3);
+    }
+
+    @TestTargetNew(
+        level = TestLevel.PARTIAL_COMPLETE,
+        method = "simpleQueryForBlobFileDescriptor",
+        args = {}
+    )
+    public void testSimpleQueryForBlobFileDescriptorSuccessFF() throws IOException {
+        doTestSimpleQueryForBlobFileDescriptorSuccess(4);
+    }
+
+    @TestTargetNew(
+        level = TestLevel.PARTIAL_COMPLETE,
+        method = "simpleQueryForBlobFileDescriptor",
+        args = {}
+    )
+    public void testSimpleQueryForBlobFileDescriptorSuccessEmbeddedNul() throws IOException {
+        doTestSimpleQueryForBlobFileDescriptorSuccess(5);
+    }
+
+    private void doTestSimpleQueryForBlobFileDescriptorSuccess(int i) throws IOException {
+        populateBlobTable();
+
+        String sql = "SELECT data FROM blob_test WHERE _id = " + i;
+        SQLiteStatement stm = mDatabase.compileStatement(sql);
+        ParcelFileDescriptor fd = stm.simpleQueryForBlobFileDescriptor();
+        assertFileDescriptorContent(BLOBS[i], fd);
+    }
+
+    @TestTargetNew(
+        level = TestLevel.PARTIAL_COMPLETE,
+        method = "simpleQueryForBlobFileDescriptor",
+        args = {}
+    )
+    public void testSimpleQueryForBlobFileDescriptorSuccessParam() throws IOException {
+        populateBlobTable();
+
+        String sql = "SELECT data FROM blob_test WHERE _id = ?";
+        SQLiteStatement stm = mDatabase.compileStatement(sql);
+        stm.bindLong(1, 0);
+        ParcelFileDescriptor fd = stm.simpleQueryForBlobFileDescriptor();
+        assertFileDescriptorContent(BLOBS[0], fd);
+    }
+
+    @TestTargetNew(
+        level = TestLevel.PARTIAL_COMPLETE,
+        method = "simpleQueryForBlobFileDescriptor",
+        args = {}
+    )
+    public void testGetBlobFailureNoParam() throws Exception {
+        populateBlobTable();
+
+        String sql = "SELECT data FROM blob_test WHERE _id = 100";
+        SQLiteStatement stm = mDatabase.compileStatement(sql);
+        ParcelFileDescriptor fd = null;
+        SQLiteDoneException expectedException = null;
+        try {
+            fd = stm.simpleQueryForBlobFileDescriptor();
+        } catch (SQLiteDoneException ex) {
+            expectedException = ex;
+        } finally {
+            if (fd != null) {
+                fd.close();
+                fd = null;
+            }
+        }
+        assertNotNull("Should have thrown SQLiteDoneException", expectedException);
+    }
+
+    @TestTargetNew(
+        level = TestLevel.PARTIAL_COMPLETE,
+        method = "simpleQueryForBlobFileDescriptor",
+        args = {}
+    )
+    public void testGetBlobFailureParam() throws Exception {
+        populateBlobTable();
+
+        String sql = "SELECT data FROM blob_test WHERE _id = ?";
+        SQLiteStatement stm = mDatabase.compileStatement(sql);
+        stm.bindLong(1, 100);
+        ParcelFileDescriptor fd = null;
+        SQLiteDoneException expectedException = null;
+        try {
+            fd = stm.simpleQueryForBlobFileDescriptor();
+        } catch (SQLiteDoneException ex) {
+            expectedException = ex;
+        } finally {
+            if (fd != null) {
+                fd.close();
+                fd = null;
+            }
+        }
+        assertNotNull("Should have thrown SQLiteDoneException", expectedException);
+    }
+
+    /*
+     * Convert string of hex digits to byte array.
+     * Results are undefined for poorly formed string.
+     *
+     * @param src hex string
+     */
+    private static byte[] parseBlob(String src) {
+        int len = src.length();
+        byte[] result = new byte[len / 2];
+
+        for (int i = 0; i < len/2; i++) {
+            int val;
+            char c1 = src.charAt(i*2);
+            char c2 = src.charAt(i*2+1);
+            int val1 = Character.digit(c1, 16);
+            int val2 = Character.digit(c2, 16);
+            val = (val1 << 4) | val2;
+            result[i] = (byte)val;
+        }
+        return result;
+    }
+
+    private static void assertFileDescriptorContent(byte[] expected, ParcelFileDescriptor fd)
+            throws IOException {
+        assertInputStreamContent(expected, new ParcelFileDescriptor.AutoCloseInputStream(fd));
+    }
+
+    private static void assertInputStreamContent(byte[] expected, InputStream is)
+            throws IOException {
+        try {
+            byte[] observed = new byte[expected.length];
+            int count = is.read(observed);
+            assertEquals(expected.length, count);
+            assertEquals(-1, is.read());
+            MoreAsserts.assertEquals(expected, observed);
+        } finally {
+            is.close();
+        }
+    }
 }
diff --git a/tests/tests/graphics/src/android/graphics/cts/CanvasTest.java b/tests/tests/graphics/src/android/graphics/cts/CanvasTest.java
index 07612d4..b00a383 100644
--- a/tests/tests/graphics/src/android/graphics/cts/CanvasTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/CanvasTest.java
@@ -96,7 +96,6 @@
     )
     public void testCanvas1() {
         final Canvas c = new Canvas();
-        assertNull(c.getGL());
     }
 
     @TestTargetNew(
@@ -128,36 +127,6 @@
         new Canvas(mMutableBitmap);
     }
 
-    @TestTargets({
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "Canvas",
-            args = {javax.microedition.khronos.opengles.GL.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "getGL",
-            args = {}
-        )
-    })
-    public void testCanvas3() {
-        Canvas c = new Canvas();
-        assertNull(c.getGL());
-        final MyGL myGL = new MyGL();
-        c = new Canvas(myGL);
-        assertTrue(myGL.equals(c.getGL()));
-    }
-
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        method = "freeGlCaches",
-        args = {}
-    )
-    public void testFreeGlCaches() {
-        // can't get the changed state
-        Canvas.freeGlCaches();
-    }
-
     @TestTargetNew(
         level = TestLevel.COMPLETE,
         method = "setBitmap",
@@ -173,16 +142,6 @@
             // expected
         }
 
-        // abnormal case: GL not null
-        final Canvas c = new Canvas(new MyGL());
-        try {
-            c.setBitmap(mMutableBitmap);
-            fail("should throw out RuntimeException when setting MutableBitmap to Canvas "
-                    + "when the Canvas is created with GL");
-        } catch (RuntimeException e) {
-            // expected
-        }
-
         // abnormal case: bitmap to be set has been recycled
         mMutableBitmap.recycle();
         try {
@@ -199,39 +158,6 @@
         assertEquals(31, mCanvas.getHeight());
     }
 
-    @TestTargets({
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "setViewport",
-            args = {int.class, int.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "getWidth",
-            args = {}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "getHeight",
-            args = {}
-        )
-    })
-    public void testSetViewport() {
-        assertEquals(BITMAP_WIDTH, mCanvas.getWidth());
-        assertEquals(BITMAP_HEIGHT, mCanvas.getHeight());
-
-        // set viewport has no effect for bitmap based canvas
-        mCanvas.setViewport(BITMAP_HEIGHT, BITMAP_WIDTH);
-        assertEquals(BITMAP_WIDTH, mCanvas.getWidth());
-        assertEquals(BITMAP_HEIGHT, mCanvas.getHeight());
-
-        // only GL based canvas that can set viewport
-        mCanvas = new Canvas(new MyGL());
-        mCanvas.setViewport(BITMAP_HEIGHT, BITMAP_WIDTH);
-        assertEquals(BITMAP_HEIGHT, mCanvas.getWidth());
-        assertEquals(BITMAP_WIDTH, mCanvas.getHeight());
-    }
-
     @TestTargetNew(
         level = TestLevel.COMPLETE,
         method = "isOpaque",
@@ -2266,8 +2192,4 @@
         assertEquals(0.0f, values[7]);
         assertEquals(1.0f, values[8]);
     }
-
-    private class MyGL implements GL {
-        //do nothing
-    }
 }
diff --git a/tests/tests/graphics/src/android/graphics/cts/PorterDuff_ModeTest.java b/tests/tests/graphics/src/android/graphics/cts/PorterDuff_ModeTest.java
deleted file mode 100644
index 170992d..0000000
--- a/tests/tests/graphics/src/android/graphics/cts/PorterDuff_ModeTest.java
+++ /dev/null
@@ -1,85 +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 android.graphics.PorterDuff;
-import android.graphics.PorterDuff.Mode;
-import android.test.AndroidTestCase;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(PorterDuff.Mode.class)
-public class PorterDuff_ModeTest extends AndroidTestCase {
-
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        method = "valueOf",
-        args = {java.lang.String.class}
-    )
-    public void testValueOf() {
-        assertEquals(Mode.CLEAR, Mode.valueOf("CLEAR"));
-        assertEquals(Mode.SRC, Mode.valueOf("SRC"));
-        assertEquals(Mode.DST, Mode.valueOf("DST"));
-        assertEquals(Mode.SRC_OVER, Mode.valueOf("SRC_OVER"));
-        assertEquals(Mode.DST_OVER, Mode.valueOf("DST_OVER"));
-        assertEquals(Mode.SRC_IN, Mode.valueOf("SRC_IN"));
-        assertEquals(Mode.DST_IN, Mode.valueOf("DST_IN"));
-        assertEquals(Mode.SRC_OUT, Mode.valueOf("SRC_OUT"));
-        assertEquals(Mode.DST_OUT, Mode.valueOf("DST_OUT"));
-        assertEquals(Mode.SRC_ATOP, Mode.valueOf("SRC_ATOP"));
-        assertEquals(Mode.DST_ATOP, Mode.valueOf("DST_ATOP"));
-        assertEquals(Mode.XOR, Mode.valueOf("XOR"));
-        assertEquals(Mode.DARKEN, Mode.valueOf("DARKEN"));
-        assertEquals(Mode.LIGHTEN, Mode.valueOf("LIGHTEN"));
-        assertEquals(Mode.MULTIPLY, Mode.valueOf("MULTIPLY"));
-        assertEquals(Mode.SCREEN, Mode.valueOf("SCREEN"));
-        // Every Mode element will be tested in other test cases.
-    }
-
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        method = "values",
-        args = {}
-    )
-    public void testValues() {
-        // set the expected value
-        Mode[] expected = {
-                Mode.CLEAR,
-                Mode.SRC,
-                Mode.DST,
-                Mode.SRC_OVER,
-                Mode.DST_OVER,
-                Mode.SRC_IN,
-                Mode.DST_IN,
-                Mode.SRC_OUT,
-                Mode.DST_OUT,
-                Mode.SRC_ATOP,
-                Mode.DST_ATOP,
-                Mode.XOR,
-                Mode.DARKEN,
-                Mode.LIGHTEN,
-                Mode.MULTIPLY,
-                Mode.SCREEN};
-        Mode[] actual = Mode.values();
-        assertEquals(expected.length, actual.length);
-        for (int i = 0; i < actual.length; i ++) {
-            assertEquals(expected[i], actual[i]);
-        }
-    }
-
-}
diff --git a/tests/tests/graphics/src/android/graphics/drawable/cts/DrawableContainerStateTest.java b/tests/tests/graphics/src/android/graphics/drawable/cts/DrawableContainerStateTest.java
index 15ae0b6..bfe3ec7 100644
--- a/tests/tests/graphics/src/android/graphics/drawable/cts/DrawableContainerStateTest.java
+++ b/tests/tests/graphics/src/android/graphics/drawable/cts/DrawableContainerStateTest.java
@@ -241,8 +241,8 @@
     })
     public void testConstantHeightsAndWidths() {
         assertEquals(0, mDrawableContainerState.getChildCount());
-        assertEquals(0, mDrawableContainerState.getConstantHeight());
-        assertEquals(0, mDrawableContainerState.getConstantWidth());
+        assertEquals(-1, mDrawableContainerState.getConstantHeight());
+        assertEquals(-1, mDrawableContainerState.getConstantWidth());
         assertEquals(0, mDrawableContainerState.getConstantMinimumHeight());
         assertEquals(0, mDrawableContainerState.getConstantMinimumWidth());
 
diff --git a/tests/tests/graphics/src/android/graphics/drawable/cts/LayerDrawableTest.java b/tests/tests/graphics/src/android/graphics/drawable/cts/LayerDrawableTest.java
index b47d906..604f1e24 100644
--- a/tests/tests/graphics/src/android/graphics/drawable/cts/LayerDrawableTest.java
+++ b/tests/tests/graphics/src/android/graphics/drawable/cts/LayerDrawableTest.java
@@ -283,9 +283,6 @@
 
         assertFalse(layerDrawable.setDrawableByLayerId(30, d1));
 
-        layerDrawable.setDrawableByLayerId(20, null);
-        assertEquals(null, layerDrawable.getDrawable(1));
-
         try {
             layerDrawable.getDrawable(layerDrawable.getNumberOfLayers());
             fail("Should throw IndexOutOfBoundsException");
diff --git a/tests/tests/graphics/src/android/graphics/drawable/shapes/cts/RoundRectShapeTest.java b/tests/tests/graphics/src/android/graphics/drawable/shapes/cts/RoundRectShapeTest.java
index fa164e3..ada9d69 100644
--- a/tests/tests/graphics/src/android/graphics/drawable/shapes/cts/RoundRectShapeTest.java
+++ b/tests/tests/graphics/src/android/graphics/drawable/shapes/cts/RoundRectShapeTest.java
@@ -62,11 +62,7 @@
         } catch (ArrayIndexOutOfBoundsException e) {
         }
 
-        try {
-            new RoundRectShape(null, new RectF(), new float[8]);
-            fail("Should throw NullPointerException");
-        } catch (NullPointerException e) {
-        }
+        new RoundRectShape(null, new RectF(), new float[8]);
 
         try {
             new RoundRectShape(new float[8], new RectF(), new float[7]);
diff --git a/tests/tests/hardware/src/android/hardware/cts/CameraTest.java b/tests/tests/hardware/src/android/hardware/cts/CameraTest.java
index a261914..944de6c 100644
--- a/tests/tests/hardware/src/android/hardware/cts/CameraTest.java
+++ b/tests/tests/hardware/src/android/hardware/cts/CameraTest.java
@@ -31,6 +31,7 @@
 import android.hardware.Camera.PictureCallback;
 import android.hardware.Camera.ShutterCallback;
 import android.hardware.Camera.Size;
+import android.media.CamcorderProfile;
 import android.media.ExifInterface;
 import android.media.MediaRecorder;
 import android.os.ConditionVariable;
@@ -595,6 +596,10 @@
         // If camera supports flash, the default flash mode must be off.
         String flashMode = parameters.getFlashMode();
         assertTrue(flashMode == null || flashMode.equals(parameters.FLASH_MODE_OFF));
+        String wb = parameters.getWhiteBalance();
+        assertTrue(wb == null || wb.equals(parameters.WHITE_BALANCE_AUTO));
+        String effect = parameters.getColorEffect();
+        assertTrue(effect == null || effect.equals(parameters.EFFECT_NONE));
 
         // Some parameters must be supported.
         List<Size> previewSizes = parameters.getSupportedPreviewSizes();
@@ -689,6 +694,45 @@
         assertTrue(paramActual.getPreviewFrameRate() > 0);
 
         checkExposureCompensation(parameters);
+        checkPreferredPreviewSizeForVideo(parameters);
+    }
+
+    private void checkPreferredPreviewSizeForVideo(Parameters parameters) {
+        List<Size> videoSizes = parameters.getSupportedVideoSizes();
+        Size preferredPreviewSize = parameters.getPreferredPreviewSizeForVideo();
+
+        // If getSupportedVideoSizes() returns null,
+        // getPreferredPreviewSizeForVideo() will return null;
+        // otherwise, if getSupportedVideoSizes() does not return null,
+        // getPreferredPreviewSizeForVideo() will not return null.
+        if (videoSizes == null) {
+            assertNull(preferredPreviewSize);
+        } else {
+            assertNotNull(preferredPreviewSize);
+        }
+
+        // If getPreferredPreviewSizeForVideo() returns null,
+        // getSupportedVideoSizes() will return null;
+        // otherwise, if getPreferredPreviewSizeForVideo() does not return null,
+        // getSupportedVideoSizes() will not return null.
+        if (preferredPreviewSize == null) {
+            assertNull(videoSizes);
+        } else {
+            assertNotNull(videoSizes);
+        }
+
+        if (videoSizes != null) {  // implies: preferredPreviewSize != null
+            // If getSupportedVideoSizes() does not return null,
+            // the returned list will contain at least one size.
+            assertTrue(videoSizes.size() > 0);
+
+            // In addition, getPreferredPreviewSizeForVideo() returns a size
+            // that is among the supported preview sizes.
+            List<Size> previewSizes = parameters.getSupportedPreviewSizes();
+            assertNotNull(previewSizes);
+            assertTrue(previewSizes.size() > 0);
+            assertTrue(previewSizes.contains(preferredPreviewSize));
+        }
     }
 
     private void checkExposureCompensation(Parameters parameters) {
@@ -805,25 +849,10 @@
         assertEquals(focalLength, exifFocalLength, 0.001);
 
         // Test gps exif tags.
-        mCamera.startPreview();
-        parameters.setGpsLatitude(37.736071);
-        parameters.setGpsLongitude(-122.441983);
-        parameters.setGpsAltitude(21);
-        parameters.setGpsTimestamp(1199145600);
-        String thirtyTwoCharacters = "GPS NETWORK HYBRID ARE ALL FINE.";
-        parameters.setGpsProcessingMethod(thirtyTwoCharacters);
-        mCamera.setParameters(parameters);
-        mCamera.takePicture(mShutterCallback, mRawPictureCallback, mJpegPictureCallback);
-        waitForSnapshotDone();
-        exif = new ExifInterface(JPEG_PATH);
-        assertNotNull(exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE));
-        assertNotNull(exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE));
-        assertNotNull(exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF));
-        assertNotNull(exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF));
-        assertNotNull(exif.getAttribute(ExifInterface.TAG_GPS_TIMESTAMP));
-        assertNotNull(exif.getAttribute(ExifInterface.TAG_GPS_DATESTAMP));
-        assertEquals(thirtyTwoCharacters,
-                exif.getAttribute(ExifInterface.TAG_GPS_PROCESSING_METHOD));
+        testGpsExifValues(parameters, 37.736071, -122.441983, 21, 1199145600,
+            "GPS NETWORK HYBRID ARE ALL FINE.");
+        testGpsExifValues(parameters, 0.736071, 0.441983, 1, 1199145601, "GPS");
+        testGpsExifValues(parameters, -89.736071, -179.441983, 100000, 1199145602, "NETWORK");
 
         // Test gps tags do not exist after calling removeGpsData.
         mCamera.startPreview();
@@ -836,6 +865,33 @@
         terminateMessageLooper();
     }
 
+    private void testGpsExifValues(Parameters parameters, double latitude,
+            double longitude, double altitude, long timestamp, String method)
+            throws IOException {
+        mCamera.startPreview();
+        parameters.setGpsLatitude(latitude);
+        parameters.setGpsLongitude(longitude);
+        parameters.setGpsAltitude(altitude);
+        parameters.setGpsTimestamp(timestamp);
+        parameters.setGpsProcessingMethod(method);
+        mCamera.setParameters(parameters);
+        mCamera.takePicture(mShutterCallback, mRawPictureCallback, mJpegPictureCallback);
+        waitForSnapshotDone();
+        ExifInterface exif = new ExifInterface(JPEG_PATH);
+        assertNotNull(exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE));
+        assertNotNull(exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE));
+        assertNotNull(exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF));
+        assertNotNull(exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF));
+        assertNotNull(exif.getAttribute(ExifInterface.TAG_GPS_TIMESTAMP));
+        assertNotNull(exif.getAttribute(ExifInterface.TAG_GPS_DATESTAMP));
+        assertEquals(method, exif.getAttribute(ExifInterface.TAG_GPS_PROCESSING_METHOD));
+        float[] latLong = new float[2];
+        assertTrue(exif.getLatLong(latLong));
+        assertEquals((float)latitude, latLong[0], 0.0001f);
+        assertEquals((float)longitude, latLong[1], 0.0001f);
+        assertEquals(altitude, exif.getAltitude(-1), 1);
+    }
+
     private void checkGpsDataNull(ExifInterface exif) {
         assertNull(exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE));
         assertNull(exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE));
@@ -872,13 +928,31 @@
         Camera.Parameters parameters = mCamera.getParameters();
         SurfaceHolder surfaceHolder;
         surfaceHolder = getActivity().getSurfaceView().getHolder();
-        Size size = parameters.getPreviewSize();
+        CamcorderProfile profile = CamcorderProfile.get(cameraId,
+                CamcorderProfile.QUALITY_LOW);
+
+        // Set the preview size.
+        if (parameters.getSupportedVideoSizes() == null) {
+            parameters.setPreviewSize(profile.videoFrameWidth,
+                    profile.videoFrameHeight);
+        } else {  // Driver supports separates outputs for preview and video.
+            List<Size> sizes = parameters.getSupportedPreviewSizes();
+            Size preferred = parameters.getPreferredPreviewSizeForVideo();
+            int product = preferred.width * preferred.height;
+            for (Size size: sizes) {
+                if (size.width * size.height <= product) {
+                    parameters.setPreviewSize(size.width, size.height);
+                    break;
+                }
+            }
+        }
+
         mCamera.setParameters(parameters);
         mCamera.setPreviewDisplay(surfaceHolder);
         mCamera.startPreview();
         mCamera.lock();  // Locking again from the same process has no effect.
         try {
-            recordVideo(size, surfaceHolder);
+            recordVideo(profile, surfaceHolder);
             fail("Recording should not succeed because camera is locked.");
         } catch (Exception e) {
             // expected
@@ -892,26 +966,25 @@
             // expected
         }
 
-        try {
-            recordVideo(size, surfaceHolder);
-        } catch (Exception e) {
-            fail("Should not throw exception");
-        }
+        recordVideo(profile, surfaceHolder);  // should not throw exception
+        // Media recorder already releases the camera so the test application
+        // can lock and use the camera now.
         mCamera.lock();  // should not fail
         mCamera.setParameters(parameters);  // should not fail
         terminateMessageLooper();
     }
 
-    private void recordVideo(Size size, SurfaceHolder surfaceHolder) throws Exception {
+    private void recordVideo(CamcorderProfile profile,
+            SurfaceHolder holder) throws Exception {
         MediaRecorder recorder = new MediaRecorder();
         try {
+            // Pass the camera from the test application to media recorder.
             recorder.setCamera(mCamera);
+            recorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
             recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
-            recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
+            recorder.setProfile(profile);
             recorder.setOutputFile("/dev/null");
-            recorder.setVideoSize(size.width, size.height);
-            recorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
-            recorder.setPreviewDisplay(surfaceHolder.getSurface());
+            recorder.setPreviewDisplay(holder.getSurface());
             recorder.prepare();
             recorder.start();
             Thread.sleep(5000);
@@ -1111,10 +1184,12 @@
         // It should not generate callbacks if zoom value is not changed.
         mCamera.startSmoothZoom(0);
         assertFalse(zoomListener.mZoomDone.block(500));
+        assertEquals(0, mCamera.getParameters().getZoom());
 
         // Test startSmoothZoom.
         mCamera.startSmoothZoom(maxZoom);
         assertEquals(true, zoomListener.mZoomDone.block(5000));
+        assertEquals(maxZoom, mCamera.getParameters().getZoom());
         assertEquals(maxZoom, zoomListener.mValues.size());
         for(int i = 0; i < maxZoom; i++) {
             // Make sure we get all the callbacks in order.
@@ -1129,6 +1204,7 @@
             zoomListener.mZoomDone.close();
             mCamera.startSmoothZoom(maxZoom / 2);
             assertTrue(zoomListener.mZoomDone.block(5000));
+            assertEquals(maxZoom / 2, mCamera.getParameters().getZoom());
             assertEquals(maxZoom - (maxZoom / 2), zoomListener.mValues.size());
             int i = maxZoom - 1;
             for(Integer value: zoomListener.mValues) {
@@ -1155,6 +1231,7 @@
         mCamera.startSmoothZoom(maxZoom);
         mCamera.stopSmoothZoom();
         assertTrue(zoomListener.mZoomDone.block(5000));
+        assertEquals(zoomListener.mValues.size(), mCamera.getParameters().getZoom());
         for(int i = 0; i < zoomListener.mValues.size() - 1; i++) {
             // Make sure we get all the callbacks in order (except the last).
             assertEquals(i + 1, zoomListener.mValues.get(i).intValue());
@@ -1169,7 +1246,6 @@
 
         public void onZoomChange(int value, boolean stopped, Camera camera) {
             mValues.add(value);
-            assertEquals(value, camera.getParameters().getZoom());
             assertFalse(mStopped);
             mStopped = stopped;
             if (stopped) {
@@ -1650,4 +1726,164 @@
                     Character.isLetter(c) && c != 'x');
         }
     }
+
+    @UiThreadTest
+    public void testSceneMode() throws Exception {
+        int nCameras = Camera.getNumberOfCameras();
+        for (int id = 0; id < nCameras; id++) {
+            Log.v(TAG, "Camera id=" + id);
+            testSceneModeByCamera(id);
+        }
+    }
+
+    private class SceneModeSettings {
+        public String mScene, mFlash, mFocus, mWhiteBalance;
+        public List<String> mSupportedFlash, mSupportedFocus, mSupportedWhiteBalance;
+
+        public SceneModeSettings(Parameters parameters) {
+            mScene = parameters.getSceneMode();
+            mFlash = parameters.getFlashMode();
+            mFocus = parameters.getFocusMode();
+            mWhiteBalance = parameters.getWhiteBalance();
+            mSupportedFlash = parameters.getSupportedFlashModes();
+            mSupportedFocus = parameters.getSupportedFocusModes();
+            mSupportedWhiteBalance = parameters.getSupportedWhiteBalance();
+        }
+    }
+
+    private void testSceneModeByCamera(int cameraId) throws Exception {
+        initializeMessageLooper(cameraId);
+        Parameters parameters = mCamera.getParameters();
+        List<String> supportedSceneModes = parameters.getSupportedSceneModes();
+        if (supportedSceneModes != null) {
+            assertEquals(Parameters.SCENE_MODE_AUTO, parameters.getSceneMode());
+            SceneModeSettings autoSceneMode = new SceneModeSettings(parameters);
+
+            // Store all scene mode affected settings.
+            SceneModeSettings[] settings = new SceneModeSettings[supportedSceneModes.size()];
+            for (int i = 0; i < supportedSceneModes.size(); i++) {
+                parameters.setSceneMode(supportedSceneModes.get(i));
+                mCamera.setParameters(parameters);
+                parameters = mCamera.getParameters();
+                settings[i] = new SceneModeSettings(parameters);
+            }
+
+            // Make sure scene mode settings are consistent before preview and
+            // after preview.
+            mCamera.setPreviewDisplay(getActivity().getSurfaceView().getHolder());
+            mCamera.startPreview();
+            waitForPreviewDone();
+            for (int i = 0; i < supportedSceneModes.size(); i++) {
+                String sceneMode = supportedSceneModes.get(i);
+                parameters.setSceneMode(sceneMode);
+                mCamera.setParameters(parameters);
+                parameters = mCamera.getParameters();
+
+                // In auto scene mode, camera HAL will not remember the previous
+                // flash, focus, and white-balance. It will just take values set
+                // by parameters. But the supported flash, focus, and
+                // white-balance should still be restored in auto scene mode.
+                if (!Parameters.SCENE_MODE_AUTO.equals(sceneMode)) {
+                    assertEquals("Flash is inconsistent in scene mode " + sceneMode,
+                            settings[i].mFlash, parameters.getFlashMode());
+                    assertEquals("Focus is inconsistent in scene mode " + sceneMode,
+                            settings[i].mFocus, parameters.getFocusMode());
+                    assertEquals("White balance is inconsistent in scene mode " + sceneMode,
+                            settings[i].mWhiteBalance, parameters.getWhiteBalance());
+                }
+                assertEquals("Suppported flash modes are inconsistent in scene mode " + sceneMode,
+                        settings[i].mSupportedFlash, parameters.getSupportedFlashModes());
+                assertEquals("Suppported focus modes are inconsistent in scene mode " + sceneMode,
+                        settings[i].mSupportedFocus, parameters.getSupportedFocusModes());
+                assertEquals("Suppported white balance are inconsistent in scene mode " + sceneMode,
+                        settings[i].mSupportedWhiteBalance, parameters.getSupportedWhiteBalance());
+            }
+
+            for (int i = 0; i < settings.length; i++) {
+                if (Parameters.SCENE_MODE_AUTO.equals(settings[i].mScene)) continue;
+
+                // If the scene mode overrides the flash mode, it should also override
+                // the supported flash modes.
+                if (autoSceneMode.mSupportedFlash != null) {
+                    if (!autoSceneMode.mFlash.equals(settings[i].mFlash)) {
+                        assertEquals(1, settings[i].mSupportedFlash.size());
+                        assertTrue(settings[i].mSupportedFlash.contains(settings[i].mFlash));
+                    }
+                }
+
+                // If the scene mode overrides the focus mode, it should also override
+                // the supported focus modes.
+                if (autoSceneMode.mSupportedFocus != null) {
+                    if (!autoSceneMode.mFocus.equals(settings[i].mFocus)) {
+                        assertEquals(1, settings[i].mSupportedFocus.size());
+                        assertTrue(settings[i].mSupportedFocus.contains(settings[i].mFocus));
+                    }
+                }
+
+                // If the scene mode overrides the white balance, it should also override
+                // the supported white balance.
+                if (autoSceneMode.mSupportedWhiteBalance != null) {
+                    if (!autoSceneMode.mWhiteBalance.equals(settings[i].mWhiteBalance)) {
+                        assertEquals(1, settings[i].mSupportedWhiteBalance.size());
+                        assertTrue(settings[i].mSupportedWhiteBalance.contains(settings[i].mWhiteBalance));
+                    }
+                }
+            }
+        }
+        terminateMessageLooper();
+    }
+
+    @UiThreadTest
+    public void testInvalidParameters() throws Exception {
+        int nCameras = Camera.getNumberOfCameras();
+        for (int id = 0; id < nCameras; id++) {
+            Log.v(TAG, "Camera id=" + id);
+            testInvalidParametersByCamera(id);
+        }
+    }
+
+    private void testInvalidParametersByCamera(int cameraId) throws Exception {
+        initializeMessageLooper(cameraId);
+        // Test flash mode.
+        Parameters parameters = mCamera.getParameters();
+        List<String> list = parameters.getSupportedFlashModes();
+        if (list != null && list.size() > 0) {
+            String original = parameters.getFlashMode();
+            parameters.setFlashMode("invalid");
+            try {
+                mCamera.setParameters(parameters);
+                fail("Should throw exception for invalid parameters");
+            } catch (RuntimeException e) {
+                // expected
+            }
+            parameters = mCamera.getParameters();
+            assertEquals(original, parameters.getFlashMode());
+        }
+
+        // Test focus mode.
+        String originalFocus = parameters.getFocusMode();
+        parameters.setFocusMode("invalid");
+        try {
+            mCamera.setParameters(parameters);
+            fail("Should throw exception for invalid parameters");
+        } catch (RuntimeException e) {
+            // expected
+        }
+        parameters = mCamera.getParameters();
+        assertEquals(originalFocus, parameters.getFocusMode());
+
+        // Test preview size.
+        Size originalSize = parameters.getPreviewSize();
+        parameters.setPreviewSize(-1, -1);
+        try {
+            mCamera.setParameters(parameters);
+            fail("Should throw exception for invalid parameters");
+        } catch (RuntimeException e) {
+            // expected
+        }
+        parameters = mCamera.getParameters();
+        assertEquals(originalSize, parameters.getPreviewSize());
+
+        terminateMessageLooper();
+    }
 }
diff --git a/tests/tests/media/src/android/media/cts/AudioManagerTest.java b/tests/tests/media/src/android/media/cts/AudioManagerTest.java
index b4053cf..4b68540 100644
--- a/tests/tests/media/src/android/media/cts/AudioManagerTest.java
+++ b/tests/tests/media/src/android/media/cts/AudioManagerTest.java
@@ -22,6 +22,7 @@
 import static android.media.AudioManager.FLAG_ALLOW_RINGER_MODES;
 import static android.media.AudioManager.FLAG_SHOW_UI;
 import static android.media.AudioManager.MODE_IN_CALL;
+import static android.media.AudioManager.MODE_IN_COMMUNICATION;
 import static android.media.AudioManager.MODE_NORMAL;
 import static android.media.AudioManager.MODE_RINGTONE;
 import static android.media.AudioManager.RINGER_MODE_NORMAL;
@@ -199,6 +200,8 @@
         assertEquals(MODE_RINGTONE, mAudioManager.getMode());
         mAudioManager.setMode(MODE_IN_CALL);
         assertEquals(MODE_IN_CALL, mAudioManager.getMode());
+        mAudioManager.setMode(MODE_IN_COMMUNICATION);
+        assertEquals(MODE_IN_COMMUNICATION, mAudioManager.getMode());
         mAudioManager.setMode(MODE_NORMAL);
         assertEquals(MODE_NORMAL, mAudioManager.getMode());
     }
@@ -260,25 +263,30 @@
         assertEquals(AudioManager.MODE_CURRENT, mAudioManager.getRouting(MODE_RINGTONE));
         assertEquals(AudioManager.MODE_CURRENT, mAudioManager.getRouting(MODE_NORMAL));
         assertEquals(AudioManager.MODE_CURRENT, mAudioManager.getRouting(MODE_IN_CALL));
+        assertEquals(AudioManager.MODE_CURRENT, mAudioManager.getRouting(MODE_IN_COMMUNICATION));
 
         mAudioManager.setBluetoothScoOn(true);
         assertTrue(mAudioManager.isBluetoothScoOn());
         assertEquals(AudioManager.MODE_CURRENT, mAudioManager.getRouting(MODE_RINGTONE));
         assertEquals(AudioManager.MODE_CURRENT, mAudioManager.getRouting(MODE_NORMAL));
         assertEquals(AudioManager.MODE_CURRENT, mAudioManager.getRouting(MODE_IN_CALL));
+        assertEquals(AudioManager.MODE_CURRENT, mAudioManager.getRouting(MODE_IN_COMMUNICATION));
 
         mAudioManager.setBluetoothScoOn(false);
         assertFalse(mAudioManager.isBluetoothScoOn());
         assertEquals(AudioManager.MODE_CURRENT, mAudioManager.getRouting(MODE_RINGTONE));
         assertEquals(AudioManager.MODE_CURRENT, mAudioManager.getRouting(MODE_NORMAL));
         assertEquals(AudioManager.MODE_CURRENT, mAudioManager.getRouting(MODE_IN_CALL));
+        assertEquals(AudioManager.MODE_CURRENT, mAudioManager.getRouting(MODE_IN_COMMUNICATION));
 
         mAudioManager.setSpeakerphoneOn(true);
         assertTrue(mAudioManager.isSpeakerphoneOn());
         assertEquals(AudioManager.MODE_CURRENT, mAudioManager.getRouting(MODE_IN_CALL));
+        assertEquals(AudioManager.MODE_CURRENT, mAudioManager.getRouting(MODE_IN_COMMUNICATION));
         mAudioManager.setSpeakerphoneOn(false);
         assertFalse(mAudioManager.isSpeakerphoneOn());
         assertEquals(AudioManager.MODE_CURRENT, mAudioManager.getRouting(MODE_IN_CALL));
+        assertEquals(AudioManager.MODE_CURRENT, mAudioManager.getRouting(MODE_IN_COMMUNICATION));
     }
 
     @TestTargets({
@@ -525,44 +533,27 @@
                 assertEquals(k - 1, mAudioManager.getStreamVolume(streams[i]));
             }
 
+            // test ringer modes changes
             mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
             assertEquals(RINGER_MODE_NORMAL, mAudioManager.getRingerMode());
             mAudioManager.setStreamVolume(streams[i], 1, FLAG_SHOW_UI);
             assertEquals(1, mAudioManager.getStreamVolume(streams[i]));
-            if (streams[i] == AudioManager.STREAM_RING) {
-                mAudioManager.adjustStreamVolume(streams[i], ADJUST_LOWER, FLAG_SHOW_UI);
-                assertEquals(0, mAudioManager.getStreamVolume(streams[i]));
-                // adjusting the volume to zero should result in either silent or vibrate mode
-                assertTrue(mAudioManager.getRingerMode() == RINGER_MODE_VIBRATE ||
-                        mAudioManager.getRingerMode() == RINGER_MODE_SILENT);
-                mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
-                assertEquals(RINGER_MODE_NORMAL, mAudioManager.getRingerMode());
-                assertEquals(1, mAudioManager.getStreamVolume(streams[i]));
-            } else {
-                mAudioManager.adjustStreamVolume(streams[i], ADJUST_LOWER, FLAG_SHOW_UI);
-                assertEquals(0, mAudioManager.getStreamVolume(streams[i]));
-                // lowering the volume should NOT have changed the ringer mode
-                assertEquals(RINGER_MODE_NORMAL, mAudioManager.getRingerMode());
-                // API quirk: volume must be decremented from 1 to get ringer mode change
-                mAudioManager.setStreamVolume(streams[i], 1, FLAG_SHOW_UI);
-                mAudioManager.adjustStreamVolume(streams[i], ADJUST_LOWER, FLAG_ALLOW_RINGER_MODES);
-                // lowering the volume should have changed the ringer mode
-                assertTrue(mAudioManager.getRingerMode() == RINGER_MODE_VIBRATE ||
-                        mAudioManager.getRingerMode() == RINGER_MODE_SILENT);
-                mAudioManager.adjustStreamVolume(streams[i], ADJUST_LOWER, FLAG_ALLOW_RINGER_MODES);
-                // adjusting the volume to zero should result in either silent or vibrate mode
-                assertTrue(mAudioManager.getRingerMode() == RINGER_MODE_VIBRATE ||
-                        mAudioManager.getRingerMode() == RINGER_MODE_SILENT);
-                mAudioManager.adjustStreamVolume(streams[i], ADJUST_RAISE, FLAG_ALLOW_RINGER_MODES);
-                // There are two possible ways the device may work. It may have a silent/vibrate
-                // mode or it may have distinct silent and vibrate modes.
-                assertTrue(mAudioManager.getRingerMode() == RINGER_MODE_NORMAL ||
-                        mAudioManager.getRingerMode() == RINGER_MODE_VIBRATE);
-                // Increase the volume one more time to get out of the vibrate mode which may
-                // be separate from silent mode.
-                mAudioManager.adjustStreamVolume(streams[i], ADJUST_RAISE, FLAG_ALLOW_RINGER_MODES);
-                assertEquals(RINGER_MODE_NORMAL, mAudioManager.getRingerMode());
-            }
+
+            // decreasing the volume from 1 to 0 shouldn't change ringer modes
+            adjustStreamVolumeAndRingerMode(streams[i], ADJUST_LOWER);
+            assertEquals("Stream: " + i, 0, mAudioManager.getStreamVolume(streams[i]));
+            assertEquals("Stream: " + i, RINGER_MODE_NORMAL, mAudioManager.getRingerMode());
+
+            // decreasing the volume from 0 should change ringer modes
+            adjustStreamVolumeAndRingerMode(streams[i], ADJUST_LOWER);
+            assertEquals("Stream: " + i, 0, mAudioManager.getStreamVolume(streams[i]));
+            assertTrue("Stream: " + i, mAudioManager.getRingerMode() == RINGER_MODE_VIBRATE
+                    || mAudioManager.getRingerMode() == RINGER_MODE_SILENT);
+
+            // increasing the volume from 0 should change back to normal
+            adjustStreamVolumeAndRingerMode(streams[i], ADJUST_RAISE);
+            assertEquals("Stream: " + i, 0, mAudioManager.getStreamVolume(streams[i]));
+            assertTrue("Stream: " + i, mAudioManager.getRingerMode() == RINGER_MODE_NORMAL);
 
             // volume raise
             mAudioManager.setStreamVolume(streams[i], 0, FLAG_SHOW_UI);
@@ -617,6 +608,17 @@
         assertFalse(mAudioManager.isMusicActive());
     }
 
+    /**
+     * Imitate how pressing the volume key adjusts the volume either up or down and releasing the
+     * key causes an ADJUST_SAME direction afterwards.
+     */
+    private void adjustStreamVolumeAndRingerMode(int streamType, int direction) {
+        mAudioManager.adjustStreamVolume(streamType, direction,
+                FLAG_SHOW_UI | FLAG_ALLOW_RINGER_MODES);
+        mAudioManager.adjustStreamVolume(streamType, ADJUST_SAME,
+                FLAG_SHOW_UI | FLAG_ALLOW_RINGER_MODES);
+    }
+
     public void setResult(int resultCode) {
         mSync.notifyResult();
         mResultCode = resultCode;
diff --git a/tests/tests/media/src/android/media/cts/AudioRecordTest.java b/tests/tests/media/src/android/media/cts/AudioRecordTest.java
index 5f6fc2c..74b0952 100644
--- a/tests/tests/media/src/android/media/cts/AudioRecordTest.java
+++ b/tests/tests/media/src/android/media/cts/AudioRecordTest.java
@@ -18,6 +18,7 @@
 
 import java.nio.ByteBuffer;
 
+import android.content.pm.PackageManager;
 import android.media.AudioFormat;
 import android.media.AudioRecord;
 import android.media.MediaRecorder;
@@ -40,6 +41,7 @@
     private boolean mIsOnPeriodicNotificationCalled;
     private boolean mIsHandleMessageCalled;
     private Looper mLooper;
+    private int MAX_RECORD_START_TIME_MS = 100;
 
     @Override
     protected void setUp() throws Exception {
@@ -228,6 +230,9 @@
         final int RECORD_TIME = 10000;
         assertEquals(AudioRecord.STATE_INITIALIZED, mAudioRecord.getState());
 
+        PackageManager pm = getContext().getPackageManager();
+        boolean isLowLatency = pm.hasSystemFeature(PackageManager.FEATURE_AUDIO_LOW_LATENCY);
+
         int markerInFrames = mAudioRecord.getSampleRate() / 2;
         assertEquals(AudioRecord.SUCCESS,
                 mAudioRecord.setNotificationMarkerPosition(markerInFrames));
@@ -253,6 +258,10 @@
         byte[] byteData = new byte[BUFFER_SIZE];
         long time = System.currentTimeMillis();
         mAudioRecord.startRecording();
+        if (isLowLatency) {
+            assertTrue("Record start time too long",
+                    (System.currentTimeMillis() - time) < MAX_RECORD_START_TIME_MS);
+        }
         assertEquals(AudioRecord.RECORDSTATE_RECORDING, mAudioRecord.getRecordingState());
         while (System.currentTimeMillis() - time < RECORD_TIME) {
             Thread.sleep(SLEEP_TIME);
diff --git a/tests/tests/media/src/android/media/cts/AudioTrackTest.java b/tests/tests/media/src/android/media/cts/AudioTrackTest.java
index 4adc582..12cfcad 100644
--- a/tests/tests/media/src/android/media/cts/AudioTrackTest.java
+++ b/tests/tests/media/src/android/media/cts/AudioTrackTest.java
@@ -29,7 +29,7 @@
 @TestTargetClass(AudioTrack.class)
 public class AudioTrackTest extends AndroidTestCase {
     private String TAG = "AudioTrackTest";
-    private final long WAIT_MSEC = 200;
+    private final long WAIT_MSEC = 100;
     private final int OFFSET_DEFAULT = 0;
     private final int OFFSET_NEGATIVE = -10;
 
@@ -2620,4 +2620,4 @@
         }
     }
 
-}
+}
\ No newline at end of file
diff --git a/tests/tests/media/src/android/media/cts/CamcorderProfileTest.java b/tests/tests/media/src/android/media/cts/CamcorderProfileTest.java
index b94da11..03566d3 100644
--- a/tests/tests/media/src/android/media/cts/CamcorderProfileTest.java
+++ b/tests/tests/media/src/android/media/cts/CamcorderProfileTest.java
@@ -22,6 +22,8 @@
 import dalvik.annotation.TestTargets;
 
 import android.hardware.Camera;
+import android.hardware.Camera.Parameters;
+import android.hardware.Camera.Size;
 import android.media.CamcorderProfile;
 import android.test.AndroidTestCase;
 import android.util.Log;
@@ -33,7 +35,16 @@
 
     private static final String TAG = "CamcorderProfileTest";
 
-    private void checkProfile(CamcorderProfile profile) {
+    // Uses get without id if cameraId == -1 and get with id otherwise.
+    private CamcorderProfile getWithOptionalId(int quality, int cameraId) {
+        if (cameraId == -1) {
+            return CamcorderProfile.get(quality);
+        } else {
+            return CamcorderProfile.get(cameraId, quality);
+        }
+    }
+
+    private void checkProfile(CamcorderProfile profile, List<Size> videoSizes) {
         Log.v(TAG, String.format("profile: duration=%d, quality=%d, " +
             "fileFormat=%d, videoCodec=%d, videoBitRate=%d, videoFrameRate=%d, " +
             "videoFrameWidth=%d, videoFrameHeight=%d, audioCodec=%d, " +
@@ -52,7 +63,19 @@
             profile.audioChannels));
         assertTrue(profile.duration > 0);
         assertTrue(profile.quality == CamcorderProfile.QUALITY_LOW ||
-                   profile.quality == CamcorderProfile.QUALITY_HIGH);
+                   profile.quality == CamcorderProfile.QUALITY_HIGH ||
+                   profile.quality == CamcorderProfile.QUALITY_QCIF ||
+                   profile.quality == CamcorderProfile.QUALITY_CIF ||
+                   profile.quality == CamcorderProfile.QUALITY_480P ||
+                   profile.quality == CamcorderProfile.QUALITY_720P ||
+                   profile.quality == CamcorderProfile.QUALITY_1080P ||
+                   profile.quality == CamcorderProfile.QUALITY_TIME_LAPSE_LOW ||
+                   profile.quality == CamcorderProfile.QUALITY_TIME_LAPSE_HIGH ||
+                   profile.quality == CamcorderProfile.QUALITY_TIME_LAPSE_QCIF ||
+                   profile.quality == CamcorderProfile.QUALITY_TIME_LAPSE_CIF ||
+                   profile.quality == CamcorderProfile.QUALITY_TIME_LAPSE_480P ||
+                   profile.quality == CamcorderProfile.QUALITY_TIME_LAPSE_720P ||
+                   profile.quality == CamcorderProfile.QUALITY_TIME_LAPSE_1080P);
         assertTrue(profile.videoBitRate > 0);
         assertTrue(profile.videoFrameRate > 0);
         assertTrue(profile.videoFrameWidth > 0);
@@ -60,6 +83,146 @@
         assertTrue(profile.audioBitRate > 0);
         assertTrue(profile.audioSampleRate > 0);
         assertTrue(profile.audioChannels > 0);
+        assertTrue(isSizeSupported(profile.videoFrameWidth,
+                                   profile.videoFrameHeight,
+                                   videoSizes));
+    }
+
+    private void assertProfileEquals(CamcorderProfile expectedProfile,
+            CamcorderProfile actualProfile) {
+        assertEquals(expectedProfile.duration, actualProfile.duration);
+        assertEquals(expectedProfile.fileFormat, actualProfile.fileFormat);
+        assertEquals(expectedProfile.videoCodec, actualProfile.videoCodec);
+        assertEquals(expectedProfile.videoBitRate, actualProfile.videoBitRate);
+        assertEquals(expectedProfile.videoFrameRate, actualProfile.videoFrameRate);
+        assertEquals(expectedProfile.videoFrameWidth, actualProfile.videoFrameWidth);
+        assertEquals(expectedProfile.videoFrameHeight, actualProfile.videoFrameHeight);
+        assertEquals(expectedProfile.audioCodec, actualProfile.audioCodec);
+        assertEquals(expectedProfile.audioBitRate, actualProfile.audioBitRate);
+        assertEquals(expectedProfile.audioSampleRate, actualProfile.audioSampleRate);
+        assertEquals(expectedProfile.audioChannels, actualProfile.audioChannels);
+    }
+
+    private void checkSpecificProfileDimensions(CamcorderProfile profile, int quality) {
+        Log.v(TAG, String.format("specific profile: quality=%d, width = %d, height = %d",
+                    profile.quality, profile.videoFrameWidth, profile.videoFrameHeight));
+
+        switch (quality) {
+            case CamcorderProfile.QUALITY_QCIF:
+            case CamcorderProfile.QUALITY_TIME_LAPSE_QCIF:
+                assertEquals(176, profile.videoFrameWidth);
+                assertEquals(144, profile.videoFrameHeight);
+                break;
+
+            case CamcorderProfile.QUALITY_CIF:
+            case CamcorderProfile.QUALITY_TIME_LAPSE_CIF:
+                assertEquals(352, profile.videoFrameWidth);
+                assertEquals(288, profile.videoFrameHeight);
+                break;
+
+            case CamcorderProfile.QUALITY_480P:
+            case CamcorderProfile.QUALITY_TIME_LAPSE_480P:
+                assertTrue(720 == profile.videoFrameWidth ||  // SMPTE 293M/ITU-R Rec. 601
+                           640 == profile.videoFrameWidth ||  // ATSC/NTSC (square sampling)
+                           704 == profile.videoFrameWidth);   // ATSC/NTSC (non-square sampling)
+                assertEquals(480, profile.videoFrameHeight);
+                break;
+
+            case CamcorderProfile.QUALITY_720P:
+            case CamcorderProfile.QUALITY_TIME_LAPSE_720P:
+                assertEquals(1280, profile.videoFrameWidth);
+                assertEquals(720, profile.videoFrameHeight);
+                break;
+
+            case CamcorderProfile.QUALITY_1080P:
+            case CamcorderProfile.QUALITY_TIME_LAPSE_1080P:
+                assertEquals(1920, profile.videoFrameWidth);
+                assertEquals(1088, profile.videoFrameHeight);
+                break;
+        }
+    }
+
+    // Checks if the existing specific profiles have the correct dimensions.
+    // Also checks that the mimimum quality specific profile matches the low profile and
+    // similarly that the maximum quality specific profile matches the high profile.
+    private void checkSpecificProfiles(
+            int cameraId,
+            CamcorderProfile low,
+            CamcorderProfile high,
+            int[] specificQualities,
+            List<Size> videoSizes) {
+
+        CamcorderProfile minProfile = null;
+        CamcorderProfile maxProfile = null;
+
+        for (int i = 0; i < specificQualities.length; i++) {
+            int quality = specificQualities[i];
+            if ((cameraId != -1 && CamcorderProfile.hasProfile(cameraId, quality)) ||
+                (cameraId == -1 && CamcorderProfile.hasProfile(quality))) {
+                CamcorderProfile profile = getWithOptionalId(quality, cameraId);
+                checkSpecificProfileDimensions(profile, quality);
+
+                assertTrue(isSizeSupported(profile.videoFrameWidth,
+                                           profile.videoFrameHeight,
+                                           videoSizes));
+
+                if (minProfile == null) {
+                    minProfile = profile;
+                }
+                maxProfile = profile;
+            }
+        }
+
+        assertNotNull(minProfile);
+        assertNotNull(maxProfile);
+
+        Log.v(TAG, String.format("min profile: quality=%d, width = %d, height = %d",
+                    minProfile.quality, minProfile.videoFrameWidth, minProfile.videoFrameHeight));
+        Log.v(TAG, String.format("max profile: quality=%d, width = %d, height = %d",
+                    maxProfile.quality, maxProfile.videoFrameWidth, maxProfile.videoFrameHeight));
+
+        assertProfileEquals(low, minProfile);
+        assertProfileEquals(high, maxProfile);
+
+    }
+
+    private void checkGet(int cameraId) {
+        Log.v(TAG, (cameraId == -1)
+                   ? "Checking get without id"
+                   : "Checking get with id = " + cameraId);
+
+        final List<Size> videoSizes = getSupportedVideoSizes(cameraId);
+
+        CamcorderProfile lowProfile =
+            getWithOptionalId(CamcorderProfile.QUALITY_LOW, cameraId);
+        CamcorderProfile highProfile =
+            getWithOptionalId(CamcorderProfile.QUALITY_HIGH, cameraId);
+        checkProfile(lowProfile, videoSizes);
+        checkProfile(highProfile, videoSizes);
+
+        CamcorderProfile lowTimeLapseProfile =
+            getWithOptionalId(CamcorderProfile.QUALITY_TIME_LAPSE_LOW, cameraId);
+        CamcorderProfile highTimeLapseProfile =
+            getWithOptionalId(CamcorderProfile.QUALITY_TIME_LAPSE_HIGH, cameraId);
+        checkProfile(lowTimeLapseProfile, null);
+        checkProfile(highTimeLapseProfile, null);
+
+        int[] specificProfileQualities = {CamcorderProfile.QUALITY_QCIF,
+                                          CamcorderProfile.QUALITY_CIF,
+                                          CamcorderProfile.QUALITY_480P,
+                                          CamcorderProfile.QUALITY_720P,
+                                          CamcorderProfile.QUALITY_1080P};
+
+        int[] specificTimeLapseProfileQualities = {CamcorderProfile.QUALITY_TIME_LAPSE_QCIF,
+                                                   CamcorderProfile.QUALITY_TIME_LAPSE_CIF,
+                                                   CamcorderProfile.QUALITY_TIME_LAPSE_480P,
+                                                   CamcorderProfile.QUALITY_TIME_LAPSE_720P,
+                                                   CamcorderProfile.QUALITY_TIME_LAPSE_1080P};
+
+        checkSpecificProfiles(cameraId, lowProfile, highProfile,
+                specificProfileQualities, videoSizes);
+        checkSpecificProfiles(cameraId, lowTimeLapseProfile, highTimeLapseProfile,
+                specificTimeLapseProfileQualities, null);
     }
 
     @TestTargets({
@@ -70,10 +233,7 @@
         )
     })
     public void testGet() {
-        CamcorderProfile lowProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_LOW);
-        CamcorderProfile highProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
-        checkProfile(lowProfile);
-        checkProfile(highProfile);
+        checkGet(-1);
     }
 
     @TestTargets({
@@ -85,13 +245,31 @@
     })
     public void testGetWithId() {
         int nCamera = Camera.getNumberOfCameras();
-        for (int id = 0; id < nCamera; id++) {
-            CamcorderProfile lowProfile = CamcorderProfile.get(id,
-                    CamcorderProfile.QUALITY_LOW);
-            CamcorderProfile highProfile = CamcorderProfile.get(id,
-                    CamcorderProfile.QUALITY_HIGH);
-            checkProfile(lowProfile);
-            checkProfile(highProfile);
+        for (int cameraId = 0; cameraId < nCamera; cameraId++) {
+            checkGet(cameraId);
         }
     }
+
+    private List<Size> getSupportedVideoSizes(int cameraId) {
+        Camera camera = (cameraId == -1)? Camera.open(): Camera.open(cameraId);
+        Parameters parameters = camera.getParameters();
+        List<Size> videoSizes = parameters.getSupportedVideoSizes();
+        if (videoSizes == null) {
+            videoSizes = parameters.getSupportedPreviewSizes();
+            assertNotNull(videoSizes);
+        }
+        camera.release();
+        return videoSizes;
+    }
+
+    private boolean isSizeSupported(int width, int height, List<Size> sizes) {
+        if (sizes == null) return true;
+
+        for (Size size: sizes) {
+            if (size.width == width && size.height == height) {
+                return true;
+            }
+        }
+        return false;
+    }
 }
diff --git a/tests/tests/net/src/android/net/wifi/cts/WifiInfoTest.java b/tests/tests/net/src/android/net/wifi/cts/WifiInfoTest.java
index 3b1a6c1..42243c8 100644
--- a/tests/tests/net/src/android/net/wifi/cts/WifiInfoTest.java
+++ b/tests/tests/net/src/android/net/wifi/cts/WifiInfoTest.java
@@ -20,6 +20,7 @@
 import dalvik.annotation.TestTargetClass;
 import dalvik.annotation.TestTargetNew;
 import dalvik.annotation.TestTargets;
+import dalvik.annotation.ToBeFixed;
 
 import android.content.BroadcastReceiver;
 import android.content.Context;
@@ -167,6 +168,8 @@
             args = {}
         )
     })
+    @ToBeFixed(bug="1871573", explanation="android.net.wifi.WifiInfo#getNetworkId() return -1 when"
+        + " there is wifi connection")
     public void testWifiInfoProperties() throws Exception {
         // this test case should in Wifi environment
         WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
@@ -186,7 +189,6 @@
         Thread.sleep(DURATION);
         wifiInfo = mWifiManager.getConnectionInfo();
         assertEquals(-1, wifiInfo.getNetworkId());
-        assertEquals(WifiManager.WIFI_STATE_DISABLED, mWifiManager.getWifiState());
     }
 
 }
diff --git a/tests/tests/os/src/android/os/cts/BuildVersionTest.java b/tests/tests/os/src/android/os/cts/BuildVersionTest.java
index 8855492..af42553 100644
--- a/tests/tests/os/src/android/os/cts/BuildVersionTest.java
+++ b/tests/tests/os/src/android/os/cts/BuildVersionTest.java
@@ -32,8 +32,8 @@
 
     private static final String LOG_TAG = "BuildVersionTest";
     private static final Set<String> EXPECTED_RELEASES =
-        new HashSet<String>(Arrays.asList("2.3", "2.3.1", "2.3.2"));
-    private static final int EXPECTED_SDK = 9;
+        new HashSet<String>(Arrays.asList("3.0"));
+    private static final int EXPECTED_SDK = 11;
 
     public void testReleaseVersion() {
         // Applications may rely on the exact release version
diff --git a/tests/tests/os/src/android/os/cts/ParcelFileDescriptorTest.java b/tests/tests/os/src/android/os/cts/ParcelFileDescriptorTest.java
index ce6658f..3974b6c 100644
--- a/tests/tests/os/src/android/os/cts/ParcelFileDescriptorTest.java
+++ b/tests/tests/os/src/android/os/cts/ParcelFileDescriptorTest.java
@@ -28,9 +28,14 @@
 import android.os.Parcelable;
 import android.os.ParcelFileDescriptor.AutoCloseInputStream;
 import android.test.AndroidTestCase;
+import android.test.MoreAsserts;
 
 import java.io.File;
+import java.io.FileDescriptor;
+import java.io.FileInputStream;
 import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
 import java.io.OutputStream;
 import java.net.InetAddress;
 import java.net.ServerSocket;
@@ -110,6 +115,72 @@
     }
 
     @TestTargetNew(
+            level = TestLevel.PARTIAL_COMPLETE,
+            method = "fromData",
+            args = {byte[].class}
+    )
+    public void testFromData() throws IOException {
+        assertNull(ParcelFileDescriptor.fromData(null, null));
+        byte[] data = new byte[] { 0 };
+        assertFileDescriptorContent(data, ParcelFileDescriptor.fromData(data, null));
+        data = new byte[] { 0, 1, 2, 3 };
+        assertFileDescriptorContent(data, ParcelFileDescriptor.fromData(data, null));
+        data = new byte[0];
+        assertFileDescriptorContent(data, ParcelFileDescriptor.fromData(data, null));
+
+        // Check that modifying the data does not modify the data in the FD
+        data = new byte[] { 0, 1, 2, 3 };
+        ParcelFileDescriptor pfd = ParcelFileDescriptor.fromData(data, null);
+        data[1] = 42;
+        assertFileDescriptorContent(new byte[] { 0, 1, 2, 3 }, pfd);
+    }
+
+    private static void assertFileDescriptorContent(byte[] expected, ParcelFileDescriptor fd)
+        throws IOException {
+        assertInputStreamContent(expected, new ParcelFileDescriptor.AutoCloseInputStream(fd));
+    }
+
+    private static void assertInputStreamContent(byte[] expected, InputStream is)
+            throws IOException {
+        try {
+            byte[] observed = new byte[expected.length];
+            int count = is.read(observed);
+            assertEquals(expected.length, count);
+            assertEquals(-1, is.read());
+            MoreAsserts.assertEquals(expected, observed);
+        } finally {
+            is.close();
+        }
+    }
+
+    @TestTargetNew(
+            level = TestLevel.PARTIAL_COMPLETE,
+            notes = "Tests that skip() works on FDs returned by fromData()",
+            method = "fromData",
+            args = {byte[].class}
+    )
+    public void testFromDataSkip() throws IOException {
+        byte[] data = new byte[] { 40, 41, 42, 43, 44, 45, 46 };
+        ParcelFileDescriptor pfd = ParcelFileDescriptor.fromData(data, null);
+        assertNotNull(pfd);
+        FileDescriptor fd = pfd.getFileDescriptor();
+        assertNotNull(fd);
+        assertTrue(fd.valid());
+        FileInputStream is = new FileInputStream(fd);
+        try {
+            assertEquals(1, is.skip(1));
+            assertEquals(41, is.read());
+            assertEquals(42, is.read());
+            assertEquals(2, is.skip(2));
+            assertEquals(45, is.read());
+            assertEquals(46, is.read());
+            assertEquals(-1, is.read());
+        } finally {
+            is.close();
+        }
+    }
+
+    @TestTargetNew(
         level = TestLevel.COMPLETE,
         method = "toString",
         args = {}
diff --git a/tests/tests/permission/src/android/permission/cts/NoActivityRelatedPermissionTest.java b/tests/tests/permission/src/android/permission/cts/NoActivityRelatedPermissionTest.java
index a645424..fab9cf6 100644
--- a/tests/tests/permission/src/android/permission/cts/NoActivityRelatedPermissionTest.java
+++ b/tests/tests/permission/src/android/permission/cts/NoActivityRelatedPermissionTest.java
@@ -20,9 +20,13 @@
 
 import android.app.Activity;
 import android.app.ActivityManager;
+import android.app.AlertDialog;
 import android.content.Context;
 import android.test.ActivityInstrumentationTestCase2;
 import android.test.suitebuilder.annotation.MediumTest;
+import android.test.suitebuilder.annotation.Suppress;
+import android.view.WindowManager;
+import android.view.WindowManager.BadTokenException;
 
 /**
  * Verify the Activity related operations require specific permissions.
diff --git a/tests/tests/permission2/src/android/permission2/cts/NoReceiveSmsPermissionTest.java b/tests/tests/permission2/src/android/permission2/cts/NoReceiveSmsPermissionTest.java
index f34e380..f0f4b6f 100755
--- a/tests/tests/permission2/src/android/permission2/cts/NoReceiveSmsPermissionTest.java
+++ b/tests/tests/permission2/src/android/permission2/cts/NoReceiveSmsPermissionTest.java
@@ -52,11 +52,6 @@
      * Note: this test requires that the device under test reports a valid phone number
      */
     public void testReceiveTextMessage() {
-        PackageManager packageManager = mContext.getPackageManager();
-        if (!packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
-            return;
-        }
-
         // register our test receiver to receive SMSs. This won't throw a SecurityException,
         // so test needs to wait to determine if it actual receives an SMS
         // admittedly, this is a weak verification
@@ -77,9 +72,15 @@
                 Log.w(LOG_TAG, "wait for sms interrupted");
             }
         }
-        assertTrue("Sms not sent successfully, test environment problem?",
-                receiver.isMessageSent());
-        assertFalse("Sms received without proper permissions", receiver.isSmsReceived());
+
+        PackageManager packageManager = getContext().getPackageManager();
+        if (packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            assertTrue("Sms not sent successfully, test environment problem?",
+                    receiver.isMessageSent());
+            assertFalse("Sms received without proper permissions", receiver.isSmsReceived());
+        } else {
+            assertFalse(receiver.isMessageSent());
+        }
     }
 
     private void sendSMSToSelf() {
diff --git a/tests/tests/provider/src/android/provider/cts/BrowserTest.java b/tests/tests/provider/src/android/provider/cts/BrowserTest.java
index 2486efa..9eb5b82 100644
--- a/tests/tests/provider/src/android/provider/cts/BrowserTest.java
+++ b/tests/tests/provider/src/android/provider/cts/BrowserTest.java
@@ -28,8 +28,10 @@
 import android.provider.Browser;
 import android.provider.Browser.BookmarkColumns;
 import android.provider.Browser.SearchColumns;
+import android.provider.BrowserContract;
+import android.provider.BrowserContract.Bookmarks;
+import android.provider.BrowserContract.History;
 import android.test.ActivityInstrumentationTestCase2;
-import android.webkit.WebIconDatabase;
 import dalvik.annotation.TestTargets;
 import dalvik.annotation.TestTargetNew;
 import dalvik.annotation.TestLevel;
@@ -70,20 +72,29 @@
         mBookmarksBackup = new ArrayList<ContentValues>();
         mSearchesBackup = new ArrayList<ContentValues>();
 
-        // backup the current contents in database
-        Cursor cursor = mProvider.query(Browser.BOOKMARKS_URI, null, null, null, null);
+        // backup the current contents in database (_id=1 is a fixed id root)
+        Cursor cursor = mProvider.query(Bookmarks.CONTENT_URI, null, "_id != 1", null, null);
         if (cursor.moveToFirst()) {
+            String[] colNames = cursor.getColumnNames();
             while (!cursor.isAfterLast()) {
                 ContentValues value = new ContentValues();
 
-                value.put(BookmarkColumns._ID, cursor.getInt(0));
-                value.put(BookmarkColumns.TITLE, cursor.getString(1));
-                value.put(BookmarkColumns.URL, cursor.getString(2));
-                value.put(BookmarkColumns.VISITS, cursor.getInt(3));
-                value.put(BookmarkColumns.DATE, cursor.getLong(4));
-                value.put(BookmarkColumns.CREATED, cursor.getLong(5));
-                value.put(BookmarkColumns.BOOKMARK, cursor.getInt(7));
-                value.put(BookmarkColumns.FAVICON, cursor.getBlob(8));
+                for (int i = 0; i < colNames.length; i++) {
+                    switch (cursor.getType(i)) {
+                    case Cursor.FIELD_TYPE_BLOB:
+                        value.put(colNames[i], cursor.getBlob(i));
+                        break;
+                    case Cursor.FIELD_TYPE_FLOAT:
+                        value.put(colNames[i], cursor.getFloat(i));
+                        break;
+                    case Cursor.FIELD_TYPE_INTEGER:
+                        value.put(colNames[i], cursor.getLong(i));
+                        break;
+                    case Cursor.FIELD_TYPE_STRING:
+                        value.put(colNames[i], cursor.getString(i));
+                        break;
+                    }
+                }
                 mBookmarksBackup.add(value);
 
                 cursor.moveToNext();
@@ -106,28 +117,37 @@
         }
         cursor.close();
 
-        mProvider.delete(Browser.BOOKMARKS_URI, null, null);
+        Uri uri = Bookmarks.CONTENT_URI.buildUpon()
+                .appendQueryParameter(BrowserContract.CALLER_IS_SYNCADAPTER, "true")
+                .build();
+        mProvider.delete(uri, null, null);
         mProvider.delete(Browser.SEARCHES_URI, null, null);
+        mProvider.delete(History.CONTENT_URI, null, null);
 
         mActivity = getActivity();
     }
 
     @Override
     protected void tearDown() throws Exception {
-        // clear all new contents added in test cases.
-        mProvider.delete(Browser.BOOKMARKS_URI, null, null);
-        mProvider.delete(Browser.SEARCHES_URI, null, null);
+        try {
+            // clear all new contents added in test cases.
+            Uri uri = Bookmarks.CONTENT_URI.buildUpon()
+                .appendQueryParameter(BrowserContract.CALLER_IS_SYNCADAPTER, "true")
+                .build();
+            mProvider.delete(uri, null, null);
+            mProvider.delete(Browser.SEARCHES_URI, null, null);
 
-        // recover the old backup contents
-        for (ContentValues value : mBookmarksBackup) {
-            mProvider.insert(Browser.BOOKMARKS_URI, value);
+            // recover the old backup contents
+            for (ContentValues value : mBookmarksBackup) {
+                mProvider.insert(Bookmarks.CONTENT_URI, value);
+            }
+
+            for (ContentValues value : mSearchesBackup) {
+                mProvider.insert(Browser.SEARCHES_URI, value);
+            }
+        } finally {
+            super.tearDown();
         }
-
-        for (ContentValues value : mSearchesBackup) {
-            mProvider.insert(Browser.SEARCHES_URI, value);
-        }
-
-        super.tearDown();
     }
 
     @TestTargets({
@@ -305,7 +325,7 @@
             assertEquals(1, cursor.getCount());
             cursor.moveToFirst();
             assertEquals(visitedHistoryUrl, cursor.getString(Browser.HISTORY_PROJECTION_URL_INDEX));
-            assertEquals(visitedHistoryUrl, 
+            assertEquals(visitedHistoryUrl,
                     cursor.getString(Browser.HISTORY_PROJECTION_TITLE_INDEX));
             assertEquals(0, cursor.getInt(Browser.HISTORY_PROJECTION_BOOKMARK_INDEX));
             assertEquals(1, cursor.getInt(Browser.HISTORY_PROJECTION_VISITS_INDEX));
@@ -320,7 +340,7 @@
             assertEquals(1, cursor.getCount());
             cursor.moveToFirst();
             assertEquals(visitedHistoryUrl, cursor.getString(Browser.HISTORY_PROJECTION_URL_INDEX));
-            assertEquals(visitedHistoryUrl, 
+            assertEquals(visitedHistoryUrl,
                     cursor.getString(Browser.HISTORY_PROJECTION_TITLE_INDEX));
             assertEquals(0, cursor.getInt(Browser.HISTORY_PROJECTION_BOOKMARK_INDEX));
             assertEquals(2, cursor.getInt(Browser.HISTORY_PROJECTION_VISITS_INDEX));
@@ -450,7 +470,7 @@
             int historyCountAfterDelete = cursor.getCount();
             assertEquals(historyCountBeforeDelete - 1, historyCountAfterDelete);
             cursor.moveToLast();
-            assertEquals(MAX_HISTORY_COUNT - 1, 
+            assertEquals(MAX_HISTORY_COUNT - 1,
                     cursor.getLong(Browser.HISTORY_PROJECTION_DATE_INDEX));
             cursor.close();
 
@@ -541,7 +561,7 @@
         level = TestLevel.COMPLETE,
         notes = "test requestAllIcons(ContentResolver, String, WebIconDatabase.IconListener).",
         method = "requestAllIcons",
-        args = {android.content.ContentResolver.class, java.lang.String.class, 
+        args = {android.content.ContentResolver.class, java.lang.String.class,
                 android.webkit.WebIconDatabase.IconListener.class}
     )
     public void testRequestAllIcons() {
diff --git a/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_PlaylistsTest.java b/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_PlaylistsTest.java
index e50abf4..48ae5d7 100644
--- a/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_PlaylistsTest.java
+++ b/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_PlaylistsTest.java
@@ -30,6 +30,8 @@
 import android.provider.MediaStore.Audio.Playlists;
 import android.test.InstrumentationTestCase;
 
+import java.util.regex.Pattern;
+
 @TestTargetClass(Playlists.class)
 public class MediaStore_Audio_PlaylistsTest extends InstrumentationTestCase {
     private ContentResolver mContentResolver;
@@ -74,9 +76,8 @@
         ContentValues values = new ContentValues();
         values.put(Playlists.NAME, "My favourites");
         values.put(Playlists.DATA, externalPlaylistPath);
-        long dateAdded = System.currentTimeMillis();
-        values.put(Playlists.DATE_ADDED, dateAdded);
-        long dateModified = System.currentTimeMillis();
+        long dateAdded = System.currentTimeMillis() / 1000;
+        long dateModified = System.currentTimeMillis() / 1000;
         values.put(Playlists.DATE_MODIFIED, dateModified);
         // insert
         Uri uri = mContentResolver.insert(Playlists.EXTERNAL_CONTENT_URI, values);
@@ -91,7 +92,8 @@
             assertEquals(externalPlaylistPath,
                     c.getString(c.getColumnIndex(Playlists.DATA)));
 
-            assertEquals(dateAdded, c.getLong(c.getColumnIndex(Playlists.DATE_ADDED)));
+            long realDateAdded = c.getLong(c.getColumnIndex(Playlists.DATE_ADDED));
+            assertTrue(realDateAdded >= dateAdded);
             assertEquals(dateModified, c.getLong(c.getColumnIndex(Playlists.DATE_MODIFIED)));
             assertTrue(c.getLong(c.getColumnIndex(Playlists._ID)) > 0);
             c.close();
@@ -108,7 +110,7 @@
             assertEquals(externalPlaylistPath,
                     c.getString(c.getColumnIndex(Playlists.DATA)));
 
-            assertEquals(dateAdded, c.getLong(c.getColumnIndex(Playlists.DATE_ADDED)));
+            assertEquals(realDateAdded, c.getLong(c.getColumnIndex(Playlists.DATE_ADDED)));
             assertEquals(dateModified, c.getLong(c.getColumnIndex(Playlists.DATE_MODIFIED)));
             c.close();
         } finally {
@@ -117,7 +119,6 @@
     }
 
     public void testStoreAudioPlaylistsInternal() {
-        // the internal database does not have play lists
         ContentValues values = new ContentValues();
         values.put(Playlists.NAME, "My favourites");
         values.put(Playlists.DATA, "/data/data/com.android.cts.stub/files/my_favorites.pl");
@@ -126,6 +127,8 @@
         long dateModified = System.currentTimeMillis();
         values.put(Playlists.DATE_MODIFIED, dateModified);
         Uri uri = mContentResolver.insert(Playlists.INTERNAL_CONTENT_URI, values);
-        assertNull(uri);
+        assertNotNull(uri);
+        assertTrue(Pattern.matches("content://media/internal/audio/playlists/\\d+",
+                uri.toString()));
     }
 }
diff --git a/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_Playlists_MembersTest.java b/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_Playlists_MembersTest.java
index 12d080e..c53393f 100644
--- a/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_Playlists_MembersTest.java
+++ b/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_Playlists_MembersTest.java
@@ -31,6 +31,8 @@
 import android.provider.cts.MediaStoreAudioTestHelper.Audio2;
 import android.test.InstrumentationTestCase;
 
+import java.util.regex.Pattern;
+
 @TestTargetClass(Members.class)
 public class MediaStore_Audio_Playlists_MembersTest extends InstrumentationTestCase {
     private String[] mAudioProjection = {
@@ -247,7 +249,6 @@
     }
 
     public void testStoreAudioPlaylistsMembersInternal() {
-        // the internal database does not have play lists
         ContentValues values = new ContentValues();
         values.put(Playlists.NAME, "My favourites");
         values.put(Playlists.DATA, "/data/data/com.android.cts.stub/files/my_favorites.pl");
@@ -256,6 +257,8 @@
         long dateModified = System.currentTimeMillis();
         values.put(Playlists.DATE_MODIFIED, dateModified);
         Uri uri = mContentResolver.insert(Playlists.INTERNAL_CONTENT_URI, values);
-        assertNull(uri);
+        assertNotNull(uri);
+        assertTrue(Pattern.matches("content://media/internal/audio/playlists/\\d+",
+                uri.toString()));
     }
 }
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 2de72c8..8e8d650 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
@@ -35,10 +35,10 @@
 import android.provider.MediaStore.Images.Media;
 import android.provider.MediaStore.Images.Thumbnails;
 import android.test.InstrumentationTestCase;
-import android.util.Log;
 
 import java.io.File;
 import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
 import java.io.IOException;
 import java.util.ArrayList;
 
@@ -247,11 +247,15 @@
         assertNull(mContentResolver.query(Media.getContentUri(volume), null, null, null, null));
     }
 
-    public void testStoreImagesMediaExternal() {
+    public void testStoreImagesMediaExternal() throws Exception {
         final String externalPath = Environment.getExternalStorageDirectory().getPath() +
                 "/testimage.jpg";
         final String externalPath2 = Environment.getExternalStorageDirectory().getPath() +
                 "/testimage1.jpg";
+
+        int numBytes = 1337;
+        FileCopyHelper.createFile(new File(externalPath), numBytes);
+
         ContentValues values = new ContentValues();
         values.put(Media.ORIENTATION, 0);
         values.put(Media.PICASA_ID, 0);
@@ -265,11 +269,11 @@
         values.put(Media.DATA, externalPath);
         values.put(Media.DISPLAY_NAME, "testimage");
         values.put(Media.MIME_TYPE, "image/jpeg");
-        values.put(Media.SIZE, 86853);
+        values.put(Media.SIZE, numBytes);
         values.put(Media.TITLE, "testimage");
-        long dateAdded = System.currentTimeMillis();
+        long dateAdded = System.currentTimeMillis() / 1000;
         values.put(Media.DATE_ADDED, dateAdded);
-        long dateModified = System.currentTimeMillis();
+        long dateModified = System.currentTimeMillis() / 1000;
         values.put(Media.DATE_MODIFIED, dateModified);
 
         // insert
@@ -296,9 +300,9 @@
             assertEquals("testimage", c.getString(c.getColumnIndex(Media.DISPLAY_NAME)));
             assertEquals("image/jpeg", c.getString(c.getColumnIndex(Media.MIME_TYPE)));
             assertEquals("testimage", c.getString(c.getColumnIndex(Media.TITLE)));
-            assertEquals(86853, c.getInt(c.getColumnIndex(Media.SIZE)));
+            assertEquals(numBytes, c.getInt(c.getColumnIndex(Media.SIZE)));
             long realDateAdded = c.getLong(c.getColumnIndex(Media.DATE_ADDED));
-            assertTrue(realDateAdded > 0);
+            assertTrue(realDateAdded >= dateAdded);
             assertEquals(dateModified, c.getLong(c.getColumnIndex(Media.DATE_MODIFIED)));
             c.close();
 
@@ -318,7 +322,7 @@
             values.put(Media.MIME_TYPE, "image/jpeg");
             values.put(Media.SIZE, 86854);
             values.put(Media.TITLE, "testimage1");
-            dateModified = System.currentTimeMillis();
+            dateModified = System.currentTimeMillis() / 1000;
             values.put(Media.DATE_MODIFIED, dateModified);
             assertEquals(1, mContentResolver.update(uri, values, null, null));
 
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 9a720e5..6f7842c 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
@@ -29,6 +29,8 @@
 import android.provider.MediaStore.Video.Media;
 import android.test.InstrumentationTestCase;
 
+import java.io.File;
+
 @TestTargetClass(MediaStore.Video.Media.class)
 public class MediaStore_Video_MediaTest extends InstrumentationTestCase {
     private ContentResolver mContentResolver;
@@ -56,11 +58,15 @@
         assertNull(mContentResolver.query(Media.getContentUri(volume), null, null, null, null));
     }
 
-    public void testStoreVideoMediaExternal() {
+    public void testStoreVideoMediaExternal() throws Exception {
         final String externalVideoPath = Environment.getExternalStorageDirectory().getPath() +
                  "/video/testvideo.3gp";
         final String externalVideoPath2 = Environment.getExternalStorageDirectory().getPath() +
                 "/video/testvideo1.3gp";
+
+        int numBytes = 1337;
+        FileCopyHelper.createFile(new File(externalVideoPath), numBytes);
+
         ContentValues values = new ContentValues();
         values.put(Media.ALBUM, "cts");
         values.put(Media.ARTIST, "cts team");
@@ -79,11 +85,11 @@
         values.put(Media.DATA, externalVideoPath);
         values.put(Media.DISPLAY_NAME, "testvideo");
         values.put(Media.MIME_TYPE, "video/3gpp");
-        values.put(Media.SIZE, 86853);
+        values.put(Media.SIZE, numBytes);
         values.put(Media.TITLE, "testvideo");
-        long dateAdded = System.currentTimeMillis();
+        long dateAdded = System.currentTimeMillis() / 1000;
         values.put(Media.DATE_ADDED, dateAdded);
-        long dateModified = System.currentTimeMillis();
+        long dateModified = System.currentTimeMillis() / 1000;
         values.put(Media.DATE_MODIFIED, dateModified);
 
         // insert
@@ -115,9 +121,9 @@
             assertEquals("testvideo.3gp", c.getString(c.getColumnIndex(Media.DISPLAY_NAME)));
             assertEquals("video/3gpp", c.getString(c.getColumnIndex(Media.MIME_TYPE)));
             assertEquals("testvideo", c.getString(c.getColumnIndex(Media.TITLE)));
-            assertEquals(86853, c.getInt(c.getColumnIndex(Media.SIZE)));
+            assertEquals(numBytes, c.getInt(c.getColumnIndex(Media.SIZE)));
             long realDateAdded = c.getLong(c.getColumnIndex(Media.DATE_ADDED));
-            assertTrue(realDateAdded > 0);
+            assertTrue(realDateAdded >= dateAdded);
             assertEquals(dateModified, c.getLong(c.getColumnIndex(Media.DATE_MODIFIED)));
             c.close();
 
diff --git a/tests/tests/provider/src/android/provider/cts/SearchRecentSuggestionsTest.java b/tests/tests/provider/src/android/provider/cts/SearchRecentSuggestionsTest.java
new file mode 100644
index 0000000..1395de1
--- /dev/null
+++ b/tests/tests/provider/src/android/provider/cts/SearchRecentSuggestionsTest.java
@@ -0,0 +1,244 @@
+/*
+ * 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.provider.cts;
+
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
+
+import android.content.ContentResolver;
+import android.content.ContentValues;
+import android.content.Context;
+import android.database.Cursor;
+import android.net.Uri;
+import android.provider.SearchRecentSuggestions;
+import android.test.ProviderTestCase2;
+import android.view.animation.cts.DelayedCheck;
+
+@TestTargetClass(android.provider.SearchRecentSuggestions.class)
+public class SearchRecentSuggestionsTest extends
+        ProviderTestCase2<TestSearchRecentSuggestionsProvider> {
+    private final static String AUTHORITY_HEAD = "content://"
+            + TestSearchRecentSuggestionsProvider.AUTHORITY;
+
+    private Uri mTestUri;
+    private TestSearchRecentSuggestionsProvider mTestSRSProvider;
+    private Context mContext;
+
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
+        mTestUri = Uri.parse(AUTHORITY_HEAD + "/suggestions");
+        mTestSRSProvider = getProvider();
+        mContext = mTestSRSProvider.getContext();
+    }
+
+    public SearchRecentSuggestionsTest() {
+        super(TestSearchRecentSuggestionsProvider.class,
+                TestSearchRecentSuggestionsProvider.AUTHORITY);
+    }
+
+    @TestTargetNew(
+        level = TestLevel.COMPLETE,
+        method = "SearchRecentSuggestions",
+        args = {android.content.Context.class, java.lang.String.class, int.class}
+    )
+    public void testConstructor() {
+        new SearchRecentSuggestions(mContext, TestSearchRecentSuggestionsProvider.AUTHORITY,
+                TestSearchRecentSuggestionsProvider.MODE);
+    }
+
+    @TestTargets({
+        @TestTargetNew(
+            level = TestLevel.COMPLETE,
+            method = "SearchRecentSuggestions",
+            args = {android.content.Context.class, java.lang.String.class, int.class}
+        ),
+        @TestTargetNew(
+            level = TestLevel.COMPLETE,
+            method = "saveRecentQuery",
+            args = {java.lang.String.class, java.lang.String.class}
+        ),
+        @TestTargetNew(
+            level = TestLevel.COMPLETE,
+            method = "clearHistory",
+            args = {}
+        ),
+        @TestTargetNew(
+            level = TestLevel.COMPLETE,
+            method = "truncateHistory",
+            args = {android.content.ContentResolver.class, int.class}
+        )
+    })
+    public void testSearchRecentSuggestions() {
+        MySearchRecentSuggestions srs = new MySearchRecentSuggestions(mContext,
+                TestSearchRecentSuggestionsProvider.AUTHORITY,
+                TestSearchRecentSuggestionsProvider.MODE);
+        Cursor c = mTestSRSProvider.query(mTestUri, null, null, null, null);
+
+        try {
+            assertNotNull(c);
+            assertEquals(0, c.getCount());
+            c.close();
+
+            // insert three rows
+            String query1 = "query1";
+            String line1 = "line1";
+            srs.saveRecentQuery(query1, line1);
+
+            waitForCursorCount(mTestUri, SearchRecentSuggestions.QUERIES_PROJECTION_2LINE, 1);
+
+            c = mTestSRSProvider.query(mTestUri, SearchRecentSuggestions.QUERIES_PROJECTION_2LINE,
+                    null, null, null);
+            c.moveToFirst();
+            assertEquals(query1, c
+                    .getString(SearchRecentSuggestions.QUERIES_PROJECTION_QUERY_INDEX));
+            assertEquals(line1, c
+                    .getString(SearchRecentSuggestions.QUERIES_PROJECTION_DISPLAY2_INDEX));
+            c.close();
+
+            String query2 = "query2";
+            String line2 = "line2";
+            srs.saveRecentQuery(query2, line2);
+            waitForCursorCount(mTestUri, null, 2);
+
+            String query3 = "query3";
+            String line3 = "line3";
+            srs.saveRecentQuery(query3, line3);
+            waitForCursorCount(mTestUri, null, 3);
+
+            // truncateHistory will delete the oldest one record
+            ContentResolver cr = mContext.getContentResolver();
+            srs.truncateHistory(cr, 2);
+
+            waitForCursorCount(mTestUri, SearchRecentSuggestions.QUERIES_PROJECTION_2LINE, 2);
+
+            c = mTestSRSProvider.query(mTestUri, SearchRecentSuggestions.QUERIES_PROJECTION_2LINE,
+                    null, null, null);
+
+            // and the left two should be: test2 and test3, test1 should be delete
+            c.moveToFirst();
+            assertEquals(query2, c
+                    .getString(SearchRecentSuggestions.QUERIES_PROJECTION_QUERY_INDEX));
+            assertEquals(line2, c
+                    .getString(SearchRecentSuggestions.QUERIES_PROJECTION_DISPLAY2_INDEX));
+            c.moveToNext();
+            assertEquals(query3, c
+                    .getString(SearchRecentSuggestions.QUERIES_PROJECTION_QUERY_INDEX));
+            assertEquals(line3, c
+                    .getString(SearchRecentSuggestions.QUERIES_PROJECTION_DISPLAY2_INDEX));
+            c.close();
+
+            // clear all history
+            srs.clearHistory();
+            waitForCursorCount(mTestUri, null, 0);
+        } finally {
+            c.close();
+        }
+    }
+
+    public void testSuggestionsTable() {
+        String insertDisplay1 = "display1_insert";
+        String insertDisplay2 = "display2_insert";
+        String insertQuery = "query_insert";
+
+        String updateDisplay1 = "display1_update";
+        String updateDisplay2 = "display2_update";
+        String updateQuery = "query_update";
+
+        // Test: insert
+        ContentValues value = new ContentValues();
+        value.put("display1", insertDisplay1);
+        value.put("display2", insertDisplay2);
+        value.put("query", insertQuery);
+        value.put("date", 1);
+
+        mTestSRSProvider.insert(mTestUri, value);
+
+        Cursor cursor = mTestSRSProvider.query(mTestUri,
+                SearchRecentSuggestions.QUERIES_PROJECTION_2LINE,
+                "display1=\"" + insertDisplay1 + "\"", null, null);
+        try {
+            assertNotNull(cursor);
+            assertEquals(1, cursor.getCount());
+            assertTrue(cursor.moveToFirst());
+            assertEquals(insertDisplay2, cursor
+                    .getString(SearchRecentSuggestions.QUERIES_PROJECTION_DISPLAY2_INDEX));
+            assertEquals(insertQuery, cursor
+                    .getString(SearchRecentSuggestions.QUERIES_PROJECTION_QUERY_INDEX));
+            assertEquals(1, cursor.getInt(SearchRecentSuggestions.QUERIES_PROJECTION_DATE_INDEX));
+            cursor.close();
+
+            // Test: update
+            /**
+             * SearchRecentSuggestionsProvider.update is not implement, always
+             * throw an UnsupportedOperationException.
+             */
+            value.clear();
+            value.put("display1", updateDisplay1);
+            value.put("display2", updateDisplay2);
+            value.put("query", updateQuery);
+            value.put("date", 2);
+
+            try {
+                mTestSRSProvider.update(mTestUri, value, "display1=\"" + insertDisplay1 + "\"",
+                        null);
+                fail("There should be an UnsupportedOperationException thrown out.");
+            } catch (UnsupportedOperationException e) {
+                // expected, test success.
+            }
+
+            // Test: delete
+            mTestSRSProvider.delete(mTestUri, "display1=\"" + insertDisplay1 + "\"", null);
+            cursor = mTestSRSProvider.query(mTestUri,
+                    SearchRecentSuggestions.QUERIES_PROJECTION_2LINE, "display1=\""
+                            + insertDisplay1 + "\"", null, null);
+            assertNotNull(cursor);
+            assertEquals(0, cursor.getCount());
+        } finally {
+            cursor.close();
+        }
+    }
+
+    private class MySearchRecentSuggestions extends SearchRecentSuggestions {
+        public MySearchRecentSuggestions(Context context, String authority, int mode) {
+            super(context, authority, mode);
+        }
+
+        protected void truncateHistory(ContentResolver cr, int maxEntries) {
+            super.truncateHistory(cr, maxEntries);
+        }
+    }
+
+    private void waitForCursorCount(final Uri uri, final String[] projection,
+            final int expectedCount) {
+        new DelayedCheck() {
+            protected boolean check() {
+                Cursor cursor = null;
+                try {
+                    cursor = mTestSRSProvider.query(uri, projection, null, null, null);
+                    return cursor != null && cursor.getCount() == expectedCount;
+                } finally {
+                    if (cursor != null) {
+                        cursor.close();
+                    }
+                }
+            }
+        }.run();
+    }
+}
diff --git a/tests/tests/provider/src/android/provider/cts/Settings_SecureTest.java b/tests/tests/provider/src/android/provider/cts/Settings_SecureTest.java
index 6ce4157..8c02419 100644
--- a/tests/tests/provider/src/android/provider/cts/Settings_SecureTest.java
+++ b/tests/tests/provider/src/android/provider/cts/Settings_SecureTest.java
@@ -116,11 +116,10 @@
         } catch (SecurityException expected) {
         }
 
-        // TODO: Should be fixed to throw SettingNotFoundException.
         try {
             Secure.getFloat(cr, NO_SUCH_SETTING);
-            fail("NullPointerException should have been thrown!");
-        } catch (NullPointerException expected) {
+            fail("SettingNotFoundException should have been thrown!");
+        } catch (SettingNotFoundException expected) {
         }
 
         try {
diff --git a/tests/tests/telephony/src/android/telephony/cts/SmsManagerTest.java b/tests/tests/telephony/src/android/telephony/cts/SmsManagerTest.java
index 3177d89..4811a93 100644
--- a/tests/tests/telephony/src/android/telephony/cts/SmsManagerTest.java
+++ b/tests/tests/telephony/src/android/telephony/cts/SmsManagerTest.java
@@ -128,7 +128,7 @@
         )
     })
     public void testSendMessages() throws InterruptedException {
-        PackageManager packageManager = mContext.getPackageManager();
+        PackageManager packageManager = getContext().getPackageManager();
         if (!packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
             return;
         }
diff --git a/tests/tests/telephony/src/android/telephony/cts/SmsMessageTest.java b/tests/tests/telephony/src/android/telephony/cts/SmsMessageTest.java
index 515f8b5..8c6ad01 100644
--- a/tests/tests/telephony/src/android/telephony/cts/SmsMessageTest.java
+++ b/tests/tests/telephony/src/android/telephony/cts/SmsMessageTest.java
@@ -22,6 +22,7 @@
 import dalvik.annotation.TestTargets;
 
 import android.content.Context;
+import android.content.pm.PackageManager;
 import android.telephony.SmsMessage;
 import android.telephony.TelephonyManager;
 import android.test.AndroidTestCase;
@@ -30,6 +31,7 @@
 public class SmsMessageTest extends AndroidTestCase{
 
     private TelephonyManager mTelephonyManager;
+    private PackageManager mPackageManager;
 
     private static final String DISPLAY_MESSAGE_BODY = "test subject /test body";
     private static final String DMB = "{ testBody[^~\\] }";
@@ -69,7 +71,7 @@
         super.setUp();
         mTelephonyManager =
             (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);
-        assertNotNull(mTelephonyManager);
+        mPackageManager = getContext().getPackageManager();
     }
 
     @SuppressWarnings("deprecation")
@@ -171,10 +173,12 @@
         )
     })
     public void testCreateFromPdu() throws Exception {
-        if (mTelephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)
+                || mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_CDMA)) {
             // TODO: temp workaround, need to adjust test to use CDMA pdus
             return;
         }
+
         String pdu = "07916164260220F0040B914151245584F600006060605130308A04D4F29C0E";
         SmsMessage sms = SmsMessage.createFromPdu(hexStringToByteArray(pdu));
         assertEquals(SCA1, sms.getServiceCenterAddress());
@@ -254,7 +258,8 @@
         )
     })
     public void testCPHSVoiceMail() throws Exception {
-        if (mTelephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)
+                || mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_CDMA)) {
             // TODO: temp workaround, need to adjust test to use CDMA pdus
             return;
         }
@@ -302,7 +307,8 @@
         )
     })
     public void testGetUserData() throws Exception {
-        if (mTelephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)
+                || mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_CDMA)) {
             // TODO: temp workaround, need to adjust test to use CDMA pdus
             return;
         }
@@ -331,6 +337,10 @@
         )
     })
     public void testGetSubmitPdu() throws Exception {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            return;
+        }
+
         String scAddress = null, destinationAddress = null;
         String message = null;
         boolean statusReportRequested = false;
@@ -403,10 +413,12 @@
         )
     })
     public void testEmailGateway() throws Exception {
-        if (mTelephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)
+                || mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_CDMA)) {
             // TODO: temp workaround, need to adjust test to use CDMA pdus
             return;
         }
+
         String pdu = "07914151551512f204038105f300007011103164638a28e6f71b50c687db" +
                          "7076d9357eb7412f7a794e07cdeb6275794c07bde8e5391d247e93f3";
 
diff --git a/tests/tests/telephony/src/android/telephony/cts/TelephonyManagerTest.java b/tests/tests/telephony/src/android/telephony/cts/TelephonyManagerTest.java
index 4cfddb1..603c725 100644
--- a/tests/tests/telephony/src/android/telephony/cts/TelephonyManagerTest.java
+++ b/tests/tests/telephony/src/android/telephony/cts/TelephonyManagerTest.java
@@ -296,7 +296,6 @@
                 break;
 
             case TelephonyManager.PHONE_TYPE_NONE:
-                assertNull(deviceId);
                 assertSerialNumber();
                 assertMacAddressReported();
                 break;
diff --git a/tests/tests/telephony/src/android/telephony/gsm/cts/SmsMessageTest.java b/tests/tests/telephony/src/android/telephony/gsm/cts/SmsMessageTest.java
deleted file mode 100644
index 8b26880..0000000
--- a/tests/tests/telephony/src/android/telephony/gsm/cts/SmsMessageTest.java
+++ /dev/null
@@ -1,468 +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.telephony.gsm.cts;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-
-import android.content.Context;
-import android.telephony.TelephonyManager;
-import android.telephony.gsm.SmsMessage;
-import android.test.AndroidTestCase;
-
-@SuppressWarnings("deprecation")
-@TestTargetClass(SmsMessage.class)
-public class SmsMessageTest extends AndroidTestCase{
-
-    private TelephonyManager mTelephonyManager;
-
-    private static final String DISPLAY_MESSAGE_BODY = "test subject /test body";
-    private static final String DMB = "{ testBody[^~\\] }";
-    private static final String EMAIL_ADD = "foo@example.com";
-    private static final String EMAIL_FROM = "foo@example.com";
-    private static final String MB = DMB;
-    private static final String MESSAGE_BODY1 = "Test";
-    private static final String MESSAGE_BODY2 = "(Subject)Test";
-    private static final String MESSAGE_BODY3 = "\u2122\u00a9\u00aehello";
-    private static final String MESSAGE_BODY4 = " ";
-    private static final String MESSAGE_BODY5 = " ";
-    private static final String OA = "foo@example.com";
-    private static final String OA1 = "+14154255486";
-    private static final String OA2 = "+15122977683";
-    private static final String OA3 = "_@";
-    private static final String OA4 = "\u0394@";
-    // pseudo subject will always be empty
-    private static final String PSEUDO_SUBJECT = "";
-    private static final String SCA1 = "+16466220020";
-    private static final String SCA2 = "+12063130012";
-    private static final String SCA3 = "+14155551212";
-    private static final String SCA4 = "+14155551212";
-    private static final int NOT_CREATE_FROM_SIM = -1;
-    private static final int PROTOCOL_IDENTIFIER = 0;
-    private static final int SMS_NUMBER1 = 1;
-    private static final int SMS_NUMBER2 = 1;
-    private static final int SMS_NUMBER3 = 1;
-    private static final int STATUS = 0;
-    private static final int STATUS_ON_SIM_DEF = -1;
-    private static final int TPLAYER_LENGTH_FOR_PDU = 23;
-    private static final long TIMESTAMP_MILLIS = 1149631383000l;
-
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
-        mTelephonyManager =
-            (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);
-        assertNotNull(mTelephonyManager);
-    }
-
-    @TestTargets({
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "createFromPdu",
-            args = {byte[].class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "getServiceCenterAddress",
-            args = {}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "getOriginatingAddress",
-            args = {}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "getTPLayerLengthForPDU",
-            args = {String.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "getMessageBody",
-            args = {}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "calculateLength",
-            args = {CharSequence.class, boolean.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "calculateLength",
-            args = {String.class, boolean.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "getPdu",
-            args = {}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "isEmail",
-            args = {}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "isCphsMwiMessage",
-            args = {}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "isMwiDontStore",
-            args = {}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "isReplyPathPresent",
-            args = {}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "isStatusReportMessage",
-            args = {}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "getProtocolIdentifier",
-            args = {}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "getIndexOnSim",
-            args = {}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "getMessageClass",
-            args = {}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "getStatus",
-            args = {}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "getStatusOnSim",
-            args = {}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "getTimestampMillis",
-            args = {}
-        )
-    })
-    public void testCreateFromPdu() throws Exception {
-        if (mTelephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
-            // TODO: temp workaround, need to adjust test to use CDMA pdus
-            return;
-        }
-
-        String pdu = "07916164260220F0040B914151245584F600006060605130308A04D4F29C0E";
-        SmsMessage sms = SmsMessage.createFromPdu(hexStringToByteArray(pdu));
-        assertEquals(SCA1, sms.getServiceCenterAddress());
-        assertEquals(OA1, sms.getOriginatingAddress());
-        assertEquals(MESSAGE_BODY1, sms.getMessageBody());
-        assertEquals(TPLAYER_LENGTH_FOR_PDU, SmsMessage.getTPLayerLengthForPDU(pdu));
-        int[] result = SmsMessage.calculateLength(sms.getMessageBody(), true);
-        assertEquals(SMS_NUMBER1, result[0]);
-        assertEquals(sms.getMessageBody().length(), result[1]);
-        assertEquals(SmsMessage.MAX_USER_DATA_SEPTETS - sms.getMessageBody().length(), result[2]);
-        assertEquals(SmsMessage.ENCODING_7BIT, result[3]);
-        assertEquals(pdu, toHexString(sms.getPdu()));
-
-        assertEquals(NOT_CREATE_FROM_SIM, sms.getIndexOnSim());
-        assertEquals(PROTOCOL_IDENTIFIER, sms.getProtocolIdentifier());
-        assertFalse(sms.isEmail());
-        assertFalse(sms.isReplyPathPresent());
-        assertFalse(sms.isStatusReportMessage());
-        assertFalse(sms.isCphsMwiMessage());
-        assertEquals(SmsMessage.MessageClass.UNKNOWN, sms.getMessageClass());
-        assertEquals(STATUS, sms.getStatus());
-        assertEquals(STATUS_ON_SIM_DEF, sms.getStatusOnSim());
-        assertEquals(TIMESTAMP_MILLIS, sms.getTimestampMillis());
-
-        // Test create from null Pdu
-        sms = SmsMessage.createFromPdu(null);
-        assertNotNull(sms);
-
-        //Test create from long Pdu
-        pdu = "07912160130310F2040B915121927786F300036060924180008A0DA"
-            + "8695DAC2E8FE9296A794E07";
-        sms = SmsMessage.createFromPdu(hexStringToByteArray(pdu));
-        assertEquals(SCA2, sms.getServiceCenterAddress());
-        assertEquals(OA2, sms.getOriginatingAddress());
-        assertEquals(MESSAGE_BODY2, sms.getMessageBody());
-        CharSequence msgBody = (CharSequence) sms.getMessageBody();
-        result = SmsMessage.calculateLength(msgBody, false);
-        assertEquals(SMS_NUMBER2, result[0]);
-        assertEquals(sms.getMessageBody().length(), result[1]);
-        assertEquals(SmsMessage.MAX_USER_DATA_SEPTETS - sms.getMessageBody().length(), result[2]);
-        assertEquals(SmsMessage.ENCODING_7BIT, result[3]);
-
-        // Test createFromPdu Ucs to Sms
-        pdu = "07912160130300F4040B914151245584"
-            + "F600087010807121352B10212200A900AE00680065006C006C006F";
-        sms = SmsMessage.createFromPdu(hexStringToByteArray(pdu));
-        assertEquals(MESSAGE_BODY3, sms.getMessageBody());
-        result = SmsMessage.calculateLength(sms.getMessageBody(), true);
-        assertEquals(SMS_NUMBER3, result[0]);
-        assertEquals(sms.getMessageBody().length(), result[1]);
-        assertEquals(SmsMessage.MAX_USER_DATA_SEPTETS - sms.getMessageBody().length(), result[2]);
-        assertEquals(SmsMessage.ENCODING_7BIT, result[3]);
-    }
-
-    @TestTargets({
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "isReplace",
-            args = {}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "isMWISetMessage",
-            args = {}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "isMWIClearMessage",
-            args = {}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "isMwiDontStore",
-            args = {}
-        )
-    })
-    public void testCPHSVoiceMail() throws Exception {
-        if (mTelephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
-            // TODO: temp workaround, need to adjust test to use CDMA pdus
-            return;
-        }
-
-        // "set MWI flag"
-        String pdu = "07912160130310F20404D0110041006060627171118A0120";
-        SmsMessage sms = SmsMessage.createFromPdu(hexStringToByteArray(pdu));
-        assertTrue(sms.isReplace());
-        assertEquals(OA3, sms.getOriginatingAddress());
-        assertEquals(MESSAGE_BODY4, sms.getMessageBody());
-        assertTrue(sms.isMWISetMessage());
-
-        // "clear mwi flag"
-        pdu = "07912160130310F20404D0100041006021924193352B0120";
-        sms = SmsMessage.createFromPdu(hexStringToByteArray(pdu));
-        assertTrue(sms.isMWIClearMessage());
-
-        // "clear MWI flag"
-        pdu = "07912160130310F20404D0100041006060627161058A0120";
-        sms = SmsMessage.createFromPdu(hexStringToByteArray(pdu));
-        assertTrue(sms.isReplace());
-        assertEquals(OA4, sms.getOriginatingAddress());
-        assertEquals(MESSAGE_BODY5, sms.getMessageBody());
-        assertTrue(sms.isMWIClearMessage());
-
-        // "set MWI flag"
-        pdu = "07912180958750F84401800500C87020026195702B06040102000200";
-        sms = SmsMessage.createFromPdu(hexStringToByteArray(pdu));
-        assertTrue(sms.isMWISetMessage());
-        assertTrue(sms.isMwiDontStore());
-
-        // "clear mwi flag"
-        pdu = "07912180958750F84401800500C07020027160112B06040102000000";
-        sms = SmsMessage.createFromPdu(hexStringToByteArray(pdu));
-
-        assertTrue(sms.isMWIClearMessage());
-        assertTrue(sms.isMwiDontStore());
-    }
-
-    @TestTargets({
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "getUserData",
-            args = {}
-        )
-    })
-    public void testGetUserData() throws Exception {
-        if (mTelephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
-            // TODO: temp workaround, need to adjust test to use CDMA pdus
-            return;
-        }
-
-        String pdu = "07914140279510F6440A8111110301003BF56080207130138A8C0B05040B8423F"
-            + "000032A02010106276170706C69636174696F6E2F766E642E7761702E6D6D732D"
-            + "6D65737361676500AF848D0185B4848C8298524E453955304A6D7135514141426"
-            + "66C414141414D7741414236514141414141008D908918802B3135313232393737"
-            + "3638332F545950453D504C4D4E008A808E022B918805810306977F83687474703"
-            + "A2F2F36";
-        SmsMessage sms = SmsMessage.createFromPdu(hexStringToByteArray(pdu));
-        byte[] userData = sms.getUserData();
-        assertNotNull(userData);
-    }
-
-    @TestTargets({
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "getSubmitPdu",
-            args = {String.class, String.class, String.class, boolean.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "getSubmitPdu",
-            args = {String.class, String.class, short.class, byte[].class, boolean.class}
-        )
-    })
-    public void testGetSubmitPdu() throws Exception {
-        String scAddress = null, destinationAddress = null;
-        String message = null;
-        boolean statusReportRequested = false;
-
-        try {
-            // null message, null destination
-            SmsMessage.getSubmitPdu(scAddress, destinationAddress, message, statusReportRequested);
-            fail("Should throw NullPointerException");
-        } catch (NullPointerException expected) {
-            // expected
-        }
-
-        message = "This is a test message";
-        try {
-            // non-null message
-            SmsMessage.getSubmitPdu(scAddress, destinationAddress, message, statusReportRequested);
-            fail("Should throw NullPointerException");
-        } catch (NullPointerException expected) {
-            // expected
-        }
-
-        if (mTelephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
-            // TODO: temp workaround, OCTET encoding for EMS not properly supported
-            return;
-        }
-
-        scAddress = "1650253000";
-        destinationAddress = "18004664411";
-        message = "This is a test message";
-        statusReportRequested = false;
-        SmsMessage.SubmitPdu smsPdu =
-            SmsMessage.getSubmitPdu(scAddress, destinationAddress, message, statusReportRequested);
-        assertNotNull(smsPdu);
-
-        smsPdu = SmsMessage.getSubmitPdu(scAddress, destinationAddress, (short)80,
-                message.getBytes(), statusReportRequested);
-        assertNotNull(smsPdu);
-    }
-
-    @TestTargets({
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "getEmailBody",
-            args = {}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "getEmailFrom",
-            args = {}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "getDisplayMessageBody",
-            args = {}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "getPseudoSubject",
-            args = {}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "getDisplayOriginatingAddress",
-            args = {}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "isEmail",
-            args = {}
-        )
-    })
-    public void testEmailGateway() throws Exception {
-        if (mTelephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
-            // TODO: temp workaround, need to adjust test to use CDMA pdus
-            return;
-        }
-        String pdu = "07914151551512f204038105f300007011103164638a28e6f71b50c687db" +
-                         "7076d9357eb7412f7a794e07cdeb6275794c07bde8e5391d247e93f3";
-
-        SmsMessage sms = SmsMessage.createFromPdu(hexStringToByteArray(pdu));
-        assertEquals(SCA4, sms.getServiceCenterAddress());
-        assertTrue(sms.isEmail());
-        assertEquals(EMAIL_ADD, sms.getEmailFrom());
-        assertEquals(EMAIL_ADD, sms.getDisplayOriginatingAddress());
-        assertEquals(PSEUDO_SUBJECT, sms.getPseudoSubject());
-
-        assertEquals(DISPLAY_MESSAGE_BODY, sms.getDisplayMessageBody());
-        assertEquals(DISPLAY_MESSAGE_BODY, sms.getEmailBody());
-
-        pdu = "07914151551512f204038105f400007011103105458a29e6f71b50c687db" +
-                        "7076d9357eb741af0d0a442fcfe9c23739bfe16d289bdee6b5f1813629";
-        sms = SmsMessage.createFromPdu(hexStringToByteArray(pdu));
-        assertEquals(SCA3, sms.getServiceCenterAddress());
-        assertTrue(sms.isEmail());
-        assertEquals(OA, sms.getDisplayOriginatingAddress());
-        assertEquals(EMAIL_FROM, sms.getEmailFrom());
-        assertEquals(DMB, sms.getDisplayMessageBody());
-        assertEquals(MB, sms.getEmailBody());
-    }
-
-    private final static char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
-            'A', 'B', 'C', 'D', 'E', 'F' };
-
-    public static String toHexString(byte[] array) {
-        int length = array.length;
-        char[] buf = new char[length * 2];
-
-        int bufIndex = 0;
-        for (int i = 0 ; i < length; i++)
-        {
-            byte b = array[i];
-            buf[bufIndex++] = HEX_DIGITS[(b >>> 4) & 0x0F];
-            buf[bufIndex++] = HEX_DIGITS[b & 0x0F];
-        }
-
-        return new String(buf);
-    }
-
-    private static int toByte(char c) {
-        if (c >= '0' && c <= '9') return (c - '0');
-        if (c >= 'A' && c <= 'F') return (c - 'A' + 10);
-        if (c >= 'a' && c <= 'f') return (c - 'a' + 10);
-
-        throw new RuntimeException ("Invalid hex char '" + c + "'");
-    }
-
-    private static byte[] hexStringToByteArray(String hexString) {
-        int length = hexString.length();
-        byte[] buffer = new byte[length / 2];
-
-        for (int i = 0 ; i < length ; i += 2) {
-            buffer[i / 2] =
-                (byte)((toByte(hexString.charAt(i)) << 4) | toByte(hexString.charAt(i+1)));
-        }
-
-        return buffer;
-    }
-}
diff --git a/tests/tests/text/src/android/text/cts/LayoutTest.java b/tests/tests/text/src/android/text/cts/LayoutTest.java
index 4c305bb..60bac35 100644
--- a/tests/tests/text/src/android/text/cts/LayoutTest.java
+++ b/tests/tests/text/src/android/text/cts/LayoutTest.java
@@ -21,12 +21,7 @@
 import dalvik.annotation.TestTargetNew;
 import dalvik.annotation.ToBeFixed;
 
-import android.graphics.Bitmap;
-import android.graphics.Canvas;
-import android.graphics.Paint;
-import android.graphics.Path;
 import android.graphics.Rect;
-import android.graphics.Bitmap.Config;
 import android.test.AndroidTestCase;
 import android.text.Layout;
 import android.text.Spannable;
@@ -82,53 +77,6 @@
 
     @TestTargetNew(
         level = TestLevel.COMPLETE,
-        method = "draw",
-        args = {android.graphics.Canvas.class}
-    )
-    @ToBeFixed(bug = "1386429", explanation = "can not get the" +
-            " package protected class Directions")
-    public void testDraw1() {
-        Layout layout = new MockLayout(LAYOUT_TEXT, mTextPaint, mWidth,
-                mAlign, mSpacingmult, mSpacingadd);
-        layout.draw(new Canvas());
-
-        try {
-            layout.draw(new Canvas(Bitmap.createBitmap(200, 200, Config.ARGB_4444)));
-            fail("should throw NullPointerException here");
-        } catch (NullPointerException e) {
-        }
-    }
-
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        method = "draw",
-        args = {android.graphics.Canvas.class, android.graphics.Path.class,
-                android.graphics.Paint.class, int.class}
-    )
-    @ToBeFixed(bug = "1386429", explanation = "can not get the" +
-            " package protected class Directions")
-    public void testDraw2() {
-        Layout layout = new MockLayout(LAYOUT_TEXT, mTextPaint, mWidth,
-                mAlign, mSpacingmult, mSpacingadd);
-        layout.draw(new Canvas(), null, null, 0);
-
-        try {
-            Bitmap bitmap = Bitmap.createBitmap(200, 200,Config.ARGB_4444);
-            layout.draw(new Canvas(bitmap), null, null, 0);
-            fail("should throw NullPointerException here");
-        } catch (NullPointerException e) {
-        }
-
-        try {
-            Bitmap bitmap = Bitmap.createBitmap(200, 200, null);
-            layout.draw(new Canvas(bitmap), new Path(), new Paint(), 2);
-            fail("should throw NullPointerException here");
-        } catch (NullPointerException e) {
-        }
-    }
-
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
         method = "getText",
         args = {}
     )
@@ -280,66 +228,6 @@
 
     @TestTargetNew(
         level = TestLevel.COMPLETE,
-        method = "getPrimaryHorizontal",
-        args = {int.class}
-    )
-    @ToBeFixed(bug = "1386429", explanation = "can not get the" +
-            " package protected class Directions")
-    public void testGetPrimaryHorizontal() {
-        Layout layout = new MockLayout(LAYOUT_TEXT, mTextPaint, mWidth,
-                mAlign, mSpacingmult, mSpacingadd);
-        try {
-            layout.getPrimaryHorizontal(0);
-            fail("should throw NullPointerException here");
-        } catch (NullPointerException e) {
-        }
-    }
-
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        method = "getSecondaryHorizontal",
-        args = {int.class}
-    )
-    @ToBeFixed(bug = "1386429", explanation = "can not get the" +
-            " package protected class Directions")
-    public void testGetSecondaryHorizontal() {
-        Layout layout = new MockLayout(LAYOUT_TEXT, mTextPaint, mWidth,
-                mAlign, mSpacingmult, mSpacingadd);
-        try {
-            layout.getSecondaryHorizontal(0);
-            fail("should throw NullPointerException here");
-        } catch (NullPointerException e) {
-        }
-    }
-
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        method = "getLineLeft",
-        args = {int.class}
-    )
-    public void testGetLineLeft() {
-        Layout layout = new MockLayout(LAYOUT_TEXT, mTextPaint, mWidth,
-                mAlign, mSpacingmult, mSpacingadd);
-        assertEquals(2.0f, layout.getLineLeft(0));
-        assertEquals(4.0f, layout.getLineLeft(1));
-        assertEquals(1.0f, layout.getLineLeft(2));
-    }
-
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        method = "getLineRight",
-        args = {int.class}
-    )
-    public void testGetLineRight() {
-        Layout layout = new MockLayout(LAYOUT_TEXT, mTextPaint, mWidth,
-                mAlign, mSpacingmult, mSpacingadd);
-        assertEquals(9.0f, layout.getLineRight(0));
-        assertEquals(7.0f, layout.getLineRight(1));
-        assertEquals(10.0f, layout.getLineRight(2));
-    }
-
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
         method = "getLineForVertical",
         args = {int.class}
     )
@@ -368,23 +256,6 @@
 
     @TestTargetNew(
         level = TestLevel.COMPLETE,
-        method = "getOffsetForHorizontal",
-        args = {int.class, float.class}
-    )
-    @ToBeFixed(bug = "1386429", explanation = "can not get the" +
-            " package protected class Directions")
-    public void testGetOffsetForHorizontal() {
-        Layout layout = new MockLayout(LAYOUT_TEXT, mTextPaint, mWidth,
-                mAlign, mSpacingmult, mSpacingadd);
-        try {
-            layout.getOffsetForHorizontal(0, 0);
-            fail("should throw NullPointerException here");
-        } catch (NullPointerException e) {
-        }
-    }
-
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
         method = "getLineEnd",
         args = {int.class}
     )
@@ -450,84 +321,6 @@
 
     @TestTargetNew(
         level = TestLevel.COMPLETE,
-        method = "getOffsetToLeftOf",
-        args = {int.class}
-    )
-    @ToBeFixed(bug = "1386429", explanation = "can not get the" +
-            " package protected class Directions")
-    public void testGetOffsetToLeftOf() {
-        Layout layout = new MockLayout(LAYOUT_TEXT, mTextPaint, mWidth,
-                mAlign, mSpacingmult, mSpacingadd);
-        try {
-            layout.getOffsetToLeftOf(0);
-            fail("should throw NullPointerException here");
-        } catch (NullPointerException e) {
-        }
-    }
-
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        method = "getOffsetToRightOf",
-        args = {int.class}
-    )
-    @ToBeFixed(bug = "1386429", explanation = "can not get the" +
-            " package protected class Directions")
-    public void testGetOffsetToRightOf() {
-        Layout layout = new MockLayout(LAYOUT_TEXT, mTextPaint, mWidth,
-                mAlign, mSpacingmult, mSpacingadd);
-        try {
-            layout.getOffsetToRightOf(0);
-            fail("should throw NullPointerException here");
-        } catch (NullPointerException e) {
-        }
-    }
-
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        method = "getCursorPath",
-        args = {int.class, android.graphics.Path.class, java.lang.CharSequence.class}
-    )
-    @ToBeFixed(bug = "1386429", explanation = "can not get the" +
-            " package protected class Directions")
-    public void testGetCursorPath() {
-        Layout layout = new MockLayout(LAYOUT_TEXT, mTextPaint, mWidth,
-                mAlign, mSpacingmult, mSpacingadd);
-        try {
-            layout.getCursorPath(0, new Path(), "test");
-            fail("should throw NullPointerException here");
-        } catch (NullPointerException e) {
-        }
-    }
-
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        method = "getSelectionPath",
-        args = {int.class, int.class, android.graphics.Path.class}
-    )
-    @ToBeFixed(bug = "1386429", explanation = "can not get the" +
-            " package protected class Directions")
-    public void testGetSelectionPath() {
-        Layout layout = new MockLayout(LAYOUT_TEXT, mTextPaint, mWidth,
-                mAlign, mSpacingmult, mSpacingadd);
-        Path path = new Path();
-
-        layout.getSelectionPath(0, 0, path);
-
-        try {
-            layout.getSelectionPath(1, 0, path);
-            fail("should throw NullPointerException here");
-        } catch (NullPointerException e) {
-        }
-
-        try {
-            layout.getSelectionPath(0, 1, path);
-            fail("should throw NullPointerException here");
-        } catch (NullPointerException e) {
-        }
-    }
-
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
         method = "getParagraphAlignment",
         args = {int.class}
     )
diff --git a/tests/tests/text/src/android/text/cts/SelectionTest.java b/tests/tests/text/src/android/text/cts/SelectionTest.java
index 11ba854..4fc3386 100644
--- a/tests/tests/text/src/android/text/cts/SelectionTest.java
+++ b/tests/tests/text/src/android/text/cts/SelectionTest.java
@@ -16,15 +16,16 @@
 
 package android.text.cts;
 
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.ToBeFixed;
+
 import android.test.AndroidTestCase;
 import android.text.Selection;
 import android.text.SpannableStringBuilder;
 import android.text.StaticLayout;
 import android.text.TextPaint;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.ToBeFixed;
 
 @TestTargetClass(Selection.class)
 public class SelectionTest extends AndroidTestCase {
@@ -106,12 +107,6 @@
             fail("should throw IndexOutOfBoundsException");
         } catch (IndexOutOfBoundsException e) {
         }
-
-        try {
-            Selection.setSelection(null, 3, 6);
-            fail("should throw NullPointerException");
-        } catch (NullPointerException e) {
-        }
     }
 
     @TestTargetNew(
@@ -145,12 +140,6 @@
             fail("should throw IndexOutOfBoundsException");
         } catch (IndexOutOfBoundsException e) {
         }
-
-        try {
-            Selection.setSelection(null, 3);
-            fail("should throw NullPointerException");
-        } catch (NullPointerException e) {
-        }
     }
 
     @TestTargetNew(
@@ -158,7 +147,6 @@
         method = "removeSelection",
         args = {android.text.Spannable.class}
     )
-    @ToBeFixed(bug = "1371108",explanation = "throw unexpected NullPointerException")
     public void testRemoveSelection() {
         CharSequence text = "hello, world";
         SpannableStringBuilder builder = new SpannableStringBuilder(text);
@@ -176,12 +164,6 @@
         Selection.removeSelection(builder);
         assertEquals(-1, Selection.getSelectionStart(builder));
         assertEquals(-1, Selection.getSelectionEnd(builder));
-
-        try {
-            Selection.removeSelection(null);
-            fail("should throw NullPointerException");
-        } catch (NullPointerException e) {
-        }
     }
 
     @TestTargetNew(
@@ -189,7 +171,6 @@
         method = "selectAll",
         args = {android.text.Spannable.class}
     )
-    @ToBeFixed(bug = "1371108",explanation = "throw unexpected NullPointerException")
     public void testSelectAll() {
         CharSequence text = "hello, world";
         SpannableStringBuilder builder = new SpannableStringBuilder(text);
@@ -214,12 +195,6 @@
         Selection.selectAll(empty);
         assertEquals(0, Selection.getSelectionStart(empty));
         assertEquals(0, Selection.getSelectionEnd(empty));
-
-        try {
-            Selection.selectAll(null);
-            fail("should throw NullPointerException");
-        } catch (NullPointerException e) {
-        }
     }
 
     @TestTargetNew(
@@ -227,8 +202,6 @@
         method = "moveLeft",
         args = {android.text.Spannable.class, android.text.Layout.class}
     )
-    @ToBeFixed(bug = "1417734",explanation = "throw unexpected IndexOutOfBoundsException" +
-            "and NullPointerException")
     public void testMoveLeft() {
         CharSequence text = "hello\nworld";
         SpannableStringBuilder builder = new SpannableStringBuilder(text);
@@ -236,12 +209,6 @@
         assertEquals(-1, Selection.getSelectionStart(builder));
         assertEquals(-1, Selection.getSelectionEnd(builder));
 
-        try {
-            Selection.moveLeft(builder, layout);
-            fail("should throw IndexOutOfBoundsException");
-        } catch (IndexOutOfBoundsException e) {
-        }
-
         Selection.setSelection(builder, 6, 8);
         assertTrue(Selection.moveLeft(builder, layout));
         assertEquals(6, Selection.getSelectionStart(builder));
@@ -260,24 +227,6 @@
         assertTrue(Selection.moveLeft(builder, layout));
         assertEquals(0, Selection.getSelectionStart(builder));
         assertEquals(0, Selection.getSelectionEnd(builder));
-
-        try {
-            Selection.moveLeft(new SpannableStringBuilder(), layout);
-            fail("should throw IndexOutOfBoundsException");
-        } catch (IndexOutOfBoundsException e) {
-        }
-
-        try {
-            Selection.moveLeft(null, layout);
-            fail("should throw IndexOutOfBoundsException");
-        } catch (IndexOutOfBoundsException e) {
-        }
-
-        try {
-            Selection.moveLeft(builder, null);
-            fail("should throw NullPointerException");
-        } catch (NullPointerException e) {
-        }
     }
 
     @TestTargetNew(
@@ -285,8 +234,6 @@
         method = "moveRight",
         args = {android.text.Spannable.class, android.text.Layout.class}
     )
-    @ToBeFixed(bug = "1417734",explanation = "throw unexpected IndexOutOfBoundsException" +
-            "and NullPointerException")
     public void testMoveRight() {
         CharSequence text = "hello\nworld";
         SpannableStringBuilder builder = new SpannableStringBuilder(text);
@@ -294,12 +241,6 @@
         assertEquals(-1, Selection.getSelectionStart(builder));
         assertEquals(-1, Selection.getSelectionEnd(builder));
 
-        try {
-            Selection.moveRight(builder, layout);
-            fail("should throw IndexOutOfBoundsException");
-        } catch (IndexOutOfBoundsException e) {
-        }
-
         Selection.setSelection(builder,1, 5);
         assertTrue(Selection.moveRight(builder, layout));
         assertEquals(5, Selection.getSelectionStart(builder));
@@ -322,24 +263,6 @@
         assertTrue(Selection.moveRight(builder, layout));
         assertEquals(text.length(), Selection.getSelectionStart(builder));
         assertEquals(text.length(), Selection.getSelectionEnd(builder));
-
-        try {
-            Selection.moveRight(null, layout);
-            fail("should throw IndexOutOfBoundsException");
-        } catch (IndexOutOfBoundsException e) {
-        }
-
-        try {
-            Selection.moveRight(builder, null);
-            fail("should throw NullPointerException");
-        } catch (NullPointerException e) {
-        }
-
-        try {
-            Selection.moveRight(new SpannableStringBuilder(), layout);
-            fail("should throw IndexOutOfBoundsException");
-        } catch (IndexOutOfBoundsException e) {
-        }
     }
 
     @TestTargetNew(
@@ -347,7 +270,6 @@
         method = "moveUp",
         args = {android.text.Spannable.class, android.text.Layout.class}
     )
-    @ToBeFixed(bug = "1371108",explanation = "throw unexpected NullPointerException")
     public void testMoveUp() {
         CharSequence text = "Google\nhello,world";
         SpannableStringBuilder builder = new SpannableStringBuilder(text);
@@ -380,14 +302,6 @@
         assertFalse(Selection.moveUp(builder, layout));
         assertEquals(5, Selection.getSelectionStart(builder));
         assertEquals(5, Selection.getSelectionEnd(builder));
-
-        try {
-            Selection.moveUp(builder, null);
-            fail("should throw NullPointerException");
-        } catch (NullPointerException e) {
-        }
-
-        Selection.moveUp(null, layout);
     }
 
     @TestTargetNew(
@@ -395,8 +309,6 @@
         method = "moveDown",
         args = {android.text.Spannable.class, android.text.Layout.class}
     )
-    @ToBeFixed(bug = "1417734",explanation = "throw unexpected IndexOutOfBoundsException" +
-            "and NullPointerException")
     public void testMoveDown() {
         CharSequence text = "hello,world\nGoogle";
         SpannableStringBuilder builder = new SpannableStringBuilder(text);
@@ -404,12 +316,6 @@
         assertEquals(-1, Selection.getSelectionStart(builder));
         assertEquals(-1, Selection.getSelectionEnd(builder));
 
-        try {
-            Selection.moveDown(builder, layout);
-            fail("should throw IndexOutOfBoundsException");
-        } catch (IndexOutOfBoundsException e) {
-        }
-
         Selection.setSelection(builder, 1, 3);
         assertTrue(Selection.moveDown(builder, layout));
         assertEquals(3, Selection.getSelectionStart(builder));
@@ -433,18 +339,6 @@
         Selection.moveDown(builder, layout);
         assertEquals(18, Selection.getSelectionStart(builder));
         assertEquals(18, Selection.getSelectionEnd(builder));
-
-        try {
-            Selection.moveDown(builder, null);
-            fail("should throw NullPointerException");
-        } catch (NullPointerException e) {
-        }
-
-        try {
-            Selection.moveDown(null, layout);
-            fail("should throw IndexOutOfBoundsException");
-        } catch (IndexOutOfBoundsException e) {
-        }
     }
 
     @TestTargetNew(
@@ -452,8 +346,6 @@
         method = "extendSelection",
         args = {android.text.Spannable.class, int.class}
     )
-    @ToBeFixed(bug = "1417734",explanation = "throw unexpected IndexOutOfBoundsException" +
-            "and NullPointerException")
     public void testExtendSelection() {
         CharSequence text = "hello, world";
         SpannableStringBuilder builder = new SpannableStringBuilder(text);
@@ -505,8 +397,6 @@
         method = "extendLeft",
         args = {android.text.Spannable.class, android.text.Layout.class}
     )
-    @ToBeFixed(bug = "1417734",explanation = "throw unexpected IndexOutOfBoundsException" +
-            "and NullPointerException")
     public void testExtendLeft() {
         CharSequence text = "Google\nhello, world";
         SpannableStringBuilder builder = new SpannableStringBuilder(text);
@@ -514,12 +404,6 @@
         assertEquals(-1, Selection.getSelectionStart(builder));
         assertEquals(-1, Selection.getSelectionEnd(builder));
 
-        try {
-            Selection.extendLeft(builder, layout);
-            fail("should throw IndexOutOfBoundsException");
-        } catch (IndexOutOfBoundsException e) {
-        }
-
         Selection.setSelection(builder, 7, 8);
         assertTrue(Selection.extendLeft(builder, layout));
         assertEquals(7, Selection.getSelectionStart(builder));
@@ -537,24 +421,6 @@
         assertTrue(Selection.extendLeft(builder, layout));
         assertEquals(0, Selection.getSelectionStart(builder));
         assertEquals(0, Selection.getSelectionEnd(builder));
-
-        try {
-            Selection.extendLeft(builder, null);
-            fail("should throw NullPointerException");
-        } catch (NullPointerException e) {
-        }
-
-        try {
-            Selection.extendLeft(null, layout);
-            fail("should throw IndexOutOfBoundsException");
-        } catch (IndexOutOfBoundsException e) {
-        }
-
-        try {
-            Selection.extendLeft(new SpannableStringBuilder(), layout);
-            fail("should throw IndexOutOfBoundsException");
-        } catch (IndexOutOfBoundsException e) {
-        }
     }
 
     @TestTargetNew(
@@ -562,8 +428,6 @@
         method = "extendRight",
         args = {android.text.Spannable.class, android.text.Layout.class}
     )
-    @ToBeFixed(bug = "1417734",explanation = "throw unexpected IndexOutOfBoundsException" +
-            "and NullPointerException")
     public void testExtendRight() {
         CharSequence text = "Google\nhello, world";
         SpannableStringBuilder builder = new SpannableStringBuilder(text);
@@ -571,12 +435,6 @@
         assertEquals(-1, Selection.getSelectionStart(builder));
         assertEquals(-1, Selection.getSelectionEnd(builder));
 
-        try {
-            Selection.extendRight(builder, layout);
-            fail("should throw IndexOutOfBoundsException");
-        } catch (IndexOutOfBoundsException e) {
-        }
-
         Selection.setSelection(builder, 1, 6);
         assertTrue(Selection.extendRight(builder, layout));
         assertEquals(1, Selection.getSelectionStart(builder));
@@ -590,24 +448,6 @@
         assertTrue(Selection.extendRight(builder, layout));
         assertEquals(12, Selection.getSelectionStart(builder));
         assertEquals(text.length(), Selection.getSelectionEnd(builder));
-
-        try {
-            Selection.extendRight(new SpannableStringBuilder(), layout);
-            fail("should throw IndexOutOfBoundsException");
-        } catch (IndexOutOfBoundsException e) {
-        }
-
-        try {
-            Selection.extendRight(builder, null);
-            fail("should throw NullPointerException");
-        } catch (NullPointerException e) {
-        }
-
-        try {
-            Selection.extendRight(null, layout);
-            fail("should throw IndexOutOfBoundsException");
-        } catch (IndexOutOfBoundsException e) {
-        }
     }
 
     @TestTargetNew(
@@ -615,7 +455,6 @@
         method = "extendUp",
         args = {android.text.Spannable.class, android.text.Layout.class}
     )
-    @ToBeFixed(bug = "1371108",explanation = "throw unexpected NullPointerException")
     public void testExtendUp() {
         CharSequence text = "Google\nhello, world";
         SpannableStringBuilder builder = new SpannableStringBuilder(text);
@@ -640,18 +479,6 @@
         assertEquals(8, Selection.getSelectionStart(builder));
         assertEquals(0, Selection.getSelectionEnd(builder));
 
-        try {
-            Selection.extendUp(builder, null);
-            fail("should throw NullPointerException");
-        } catch (NullPointerException e) {
-        }
-
-        try {
-            Selection.extendUp(null, layout);
-            fail("should throw NullPointerException");
-        } catch (NullPointerException e) {
-        }
-
         builder = new SpannableStringBuilder();
         assertTrue(Selection.extendUp(builder, layout));
         assertEquals(-1, Selection.getSelectionStart(builder));
@@ -663,8 +490,6 @@
         method = "extendDown",
         args = {android.text.Spannable.class, android.text.Layout.class}
     )
-    @ToBeFixed(bug = "1417734",explanation = "throw unexpected IndexOutOfBoundsException" +
-            "and NullPointerException")
     public void testExtendDown() {
         CharSequence text = "Google\nhello, world";
         SpannableStringBuilder builder = new SpannableStringBuilder(text);
@@ -672,12 +497,6 @@
         assertEquals(-1, Selection.getSelectionStart(builder));
         assertEquals(-1, Selection.getSelectionEnd(builder));
 
-        try {
-            Selection.extendDown(builder, layout);
-            fail("should throw IndexOutOfBoundsException");
-        } catch (IndexOutOfBoundsException e) {
-        }
-
         Selection.setSelection(builder, 1, 3);
         assertTrue(Selection.extendDown(builder, layout));
         assertEquals(1, Selection.getSelectionStart(builder));
@@ -690,24 +509,6 @@
         assertTrue(Selection.extendDown(builder, layout));
         assertEquals(1, Selection.getSelectionStart(builder));
         assertEquals(text.length(), Selection.getSelectionEnd(builder));
-
-        try {
-            Selection.extendDown(new SpannableStringBuilder(), layout);
-            fail("should throw IndexOutOfBoundsException");
-        } catch (IndexOutOfBoundsException e) {
-        }
-
-        try {
-            Selection.extendDown(builder, null);
-            fail("should throw NullPointerException");
-        } catch (NullPointerException e) {
-        }
-
-        try {
-            Selection.extendDown(null, layout);
-            fail("should throw IndexOutOfBoundsException");
-        } catch (IndexOutOfBoundsException e) {
-        }
     }
 
     @TestTargetNew(
@@ -715,7 +516,6 @@
         method = "extendToLeftEdge",
         args = {android.text.Spannable.class, android.text.Layout.class}
     )
-    @ToBeFixed(bug = "1371108",explanation = "throw unexpected NullPointerException")
     public void testExtendToLeftEdge() {
         CharSequence text = "hello\nworld";
         SpannableStringBuilder builder = new SpannableStringBuilder(text);
@@ -742,18 +542,6 @@
         assertEquals(2, Selection.getSelectionStart(builder));
         assertEquals(0, Selection.getSelectionEnd(builder));
 
-        try {
-            Selection.extendToLeftEdge(new SpannableStringBuilder(), null);
-            fail("should throw NullPointerException");
-        } catch (NullPointerException e) {
-        }
-
-        try {
-            Selection.extendToLeftEdge(null, layout);
-            fail("should throw NullPointerException");
-        } catch (NullPointerException e) {
-        }
-
         builder = new SpannableStringBuilder();
         assertEquals(-1, Selection.getSelectionStart(builder));
         assertEquals(-1, Selection.getSelectionEnd(builder));
@@ -768,8 +556,6 @@
         method = "extendToRightEdge",
         args = {android.text.Spannable.class, android.text.Layout.class}
     )
-    @ToBeFixed(bug = "1417734",explanation = "throw unexpected IndexOutOfBoundsException" +
-            "and NullPointerException")
     public void testExtendToRightEdge() {
         CharSequence text = "hello\nworld";
         SpannableStringBuilder builder = new SpannableStringBuilder(text);
@@ -794,24 +580,6 @@
         assertTrue(Selection.extendToRightEdge(builder, layout));
         assertEquals(1, Selection.getSelectionStart(builder));
         assertEquals(text.length(), Selection.getSelectionEnd(builder));
-
-        try {
-            Selection.extendToRightEdge(new SpannableStringBuilder(), layout);
-            fail("should throw IndexOutOfBoundsException");
-        } catch (IndexOutOfBoundsException e) {
-        }
-
-        try {
-            Selection.extendToRightEdge(builder, null);
-            fail("should throw NullPointerException");
-        } catch (NullPointerException e) {
-        }
-
-        try {
-            Selection.extendToRightEdge(null, layout);
-            fail("should throw NullPointerException");
-        } catch (NullPointerException e) {
-        }
     }
 
     @TestTargetNew(
@@ -819,7 +587,6 @@
         method = "moveToLeftEdge",
         args = {android.text.Spannable.class, android.text.Layout.class}
     )
-    @ToBeFixed(bug = "1371108",explanation = "throw unexpected NullPointerException")
     public void testMoveToLeftEdge() {
         CharSequence text = "hello\nworld";
         SpannableStringBuilder builder = new SpannableStringBuilder(text);
@@ -845,18 +612,6 @@
         assertEquals(0, Selection.getSelectionStart(builder));
         assertEquals(0, Selection.getSelectionEnd(builder));
 
-        try {
-            Selection.moveToLeftEdge(builder, null);
-            fail("should throw NullPointerException");
-        } catch (NullPointerException e) {
-        }
-
-        try {
-            Selection.moveToLeftEdge(null, layout);
-            fail("should throw NullPointerException");
-        } catch (NullPointerException e) {
-        }
-
         builder = new SpannableStringBuilder();
         assertTrue(Selection.moveToLeftEdge(builder, layout));
         assertEquals(0, Selection.getSelectionStart(builder));
@@ -868,8 +623,6 @@
         method = "moveToRightEdge",
         args = {android.text.Spannable.class, android.text.Layout.class}
     )
-    @ToBeFixed(bug = "1417734",explanation = "throw unexpected IndexOutOfBoundsException" +
-            "and NullPointerException")
     public void testMoveToRightEdge() {
         CharSequence text = "hello\nworld";
         SpannableStringBuilder builder = new SpannableStringBuilder(text);
@@ -894,23 +647,5 @@
         assertTrue(Selection.moveToRightEdge(builder, layout));
         assertEquals(text.length(), Selection.getSelectionStart(builder));
         assertEquals(text.length(), Selection.getSelectionEnd(builder));
-
-        try {
-            Selection.moveToRightEdge(builder, null);
-            fail("should throw NullPointerException");
-        } catch (NullPointerException e) {
-        }
-
-        try {
-            Selection.moveToRightEdge(null, layout);
-            fail("should throw NullPointerException");
-        } catch (NullPointerException e) {
-        }
-
-        try {
-            Selection.moveToRightEdge(new SpannableStringBuilder(), layout);
-            fail("should throw IndexOutOfBoundsException");
-        } catch (IndexOutOfBoundsException e) {
-        }
     }
 }
diff --git a/tests/tests/text/src/android/text/cts/SpannableStringBuilderTest.java b/tests/tests/text/src/android/text/cts/SpannableStringBuilderTest.java
index 26ebfb5..f8b4336 100644
--- a/tests/tests/text/src/android/text/cts/SpannableStringBuilderTest.java
+++ b/tests/tests/text/src/android/text/cts/SpannableStringBuilderTest.java
@@ -16,6 +16,12 @@
 
 package android.text.cts;
 
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
+import dalvik.annotation.ToBeFixed;
+
 import android.test.AndroidTestCase;
 import android.text.InputFilter;
 import android.text.SpannableString;
@@ -24,11 +30,6 @@
 import android.text.style.StrikethroughSpan;
 import android.text.style.TabStopSpan;
 import android.text.style.UnderlineSpan;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.ToBeFixed;
 
 /**
  * Test {@link SpannableStringBuilder}.
@@ -250,6 +251,28 @@
         builder.replace(0, 5, text, 0, text.length());
         assertEquals("ahiabc, world", builder.toString());
 
+        // Replacing by an empty string (identical target indexes)
+        builder = new SpannableStringBuilder("hello, world");
+        builder.replace(4, 6, "", 0, 0);
+        assertEquals("hell world", builder.toString());
+
+        builder = new SpannableStringBuilder("hello, world");
+        builder.replace(4, 6, "any string", 5, 5);
+        assertEquals("hell world", builder.toString());
+
+        // Inserting in place (no deletion)
+        builder = new SpannableStringBuilder("hello, world");
+        builder.replace(3, 3, "any string", 0, 0);
+        assertEquals("hello, world", builder.toString());
+
+        builder = new SpannableStringBuilder("hello, world");
+        builder.replace(7, 7, "nice ", 0, 5);
+        assertEquals("hello, nice world", builder.toString());
+
+        builder = new SpannableStringBuilder("hello, world");
+        builder.replace(0, 0, "say ", 1, 4);
+        assertEquals("ay hello, world", builder.toString());
+
         try {
             builder.replace(0, 5, text, 10, 3);
             fail("should throw IndexOutOfBoundsException here");
diff --git a/tests/tests/text/src/android/text/cts/TextUtilsTest.java b/tests/tests/text/src/android/text/cts/TextUtilsTest.java
index 04f9366..b432c1d 100644
--- a/tests/tests/text/src/android/text/cts/TextUtilsTest.java
+++ b/tests/tests/text/src/android/text/cts/TextUtilsTest.java
@@ -139,14 +139,6 @@
         } catch (NullPointerException e) {
             // issue 1688347, not clear what is supposed to happen if TextPaint is null.
         }
-
-        try {
-            TextUtils.commaEllipsize(text, p, textWidth, "plus 1", null);
-            fail("Should throw NullPointerException");
-        } catch (NullPointerException e) {
-            // issue 1688347, not clear what is supposed to happen
-            // if the string for "%d more" in the current locale is null.
-        }
     }
 
     @TestTargetNew(
@@ -365,11 +357,11 @@
             "   In other methods, MARQUEE is equivalent to END, except for the first line.")
     public void testEllipsize() {
         TextPaint p = new TextPaint();
-        
+
         // turn off kerning. with kerning enabled, different methods of measuring the same text
         // produce different results.
         p.setFlags(p.getFlags() & ~p.DEV_KERN_TEXT_FLAG);
-        
+
         CharSequence text = "long string to truncate";
 
         float textWidth = p.measureText(mEllipsis + "uncate");
@@ -391,16 +383,14 @@
                 TextUtils.ellipsize(text, p, textWidth, TruncateAt.MARQUEE).toString());
 
         textWidth = p.measureText(mEllipsis);
-        assertEquals(mEllipsis, TextUtils.ellipsize(text, p, textWidth, TruncateAt.END).toString());
+        assertEquals("", TextUtils.ellipsize(text, p, textWidth, TruncateAt.END).toString());
         assertEquals("", TextUtils.ellipsize(text, p, textWidth - 1, TruncateAt.END).toString());
         assertEquals("", TextUtils.ellipsize(text, p, -1f, TruncateAt.END).toString());
         assertEquals(text,
                 TextUtils.ellipsize(text, p, Float.MAX_VALUE, TruncateAt.END).toString());
 
-        assertEquals(mEllipsis,
-                TextUtils.ellipsize(text, p, textWidth, TruncateAt.START).toString());
-        assertEquals(mEllipsis,
-                TextUtils.ellipsize(text, p, textWidth, TruncateAt.MIDDLE).toString());
+        assertEquals("", TextUtils.ellipsize(text, p, textWidth, TruncateAt.START).toString());
+        assertEquals("", TextUtils.ellipsize(text, p, textWidth, TruncateAt.MIDDLE).toString());
 
         try {
             TextUtils.ellipsize(text, null, textWidth, TruncateAt.MIDDLE);
@@ -436,7 +426,7 @@
         // turn off kerning. with kerning enabled, different methods of measuring the same text
         // produce different results.
         p.setFlags(p.getFlags() & ~p.DEV_KERN_TEXT_FLAG);
-        
+
         TextUtils.EllipsizeCallback callback = new TextUtils.EllipsizeCallback() {
             public void ellipsized(final int start, final int end) {
                 mStart = start;
@@ -523,14 +513,14 @@
 
         // avail is long enough for ELLIPSIS, and preserveLength is specified.
         resetRange();
-        assertEquals(getBlankString(true, text.length()),
+        assertEquals(getBlankString(false, text.length()),
                 TextUtils.ellipsize(text, p, textWidth, TruncateAt.END, true, callback).toString());
         assertEquals(0, mStart);
         assertEquals(text.length(), mEnd);
 
         // avail is long enough for ELLIPSIS, and preserveLength doesn't be specified.
         resetRange();
-        assertEquals(mEllipsis,
+        assertEquals("",
                 TextUtils.ellipsize(text, p, textWidth, TruncateAt.END, false,
                         callback).toString());
         assertEquals(0, mStart);
diff --git a/tests/tests/text/src/android/text/method/cts/ArrowKeyMovementMethodTest.java b/tests/tests/text/src/android/text/method/cts/ArrowKeyMovementMethodTest.java
index 1d6c109..a92f323 100644
--- a/tests/tests/text/src/android/text/method/cts/ArrowKeyMovementMethodTest.java
+++ b/tests/tests/text/src/android/text/method/cts/ArrowKeyMovementMethodTest.java
@@ -247,7 +247,8 @@
         Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
         pressBothShiftAlt();
         assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
-                KeyEvent.KEYCODE_DPAD_UP, null));
+                KeyEvent.KEYCODE_DPAD_UP, new KeyEvent(KeyEvent.ACTION_DOWN,
+                        KeyEvent.KEYCODE_DPAD_UP)));
         // |first line
         // second |line
         // last line
@@ -256,7 +257,8 @@
         Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
         pressShift();
         assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
-                KeyEvent.KEYCODE_DPAD_UP, null));
+                KeyEvent.KEYCODE_DPAD_UP, new KeyEvent(KeyEvent.ACTION_DOWN,
+                        KeyEvent.KEYCODE_DPAD_UP)));
         // first lin|e
         // second |line
         // last line
@@ -267,7 +269,8 @@
 
         pressShift();
         assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
-                KeyEvent.KEYCODE_DPAD_UP, null));
+                KeyEvent.KEYCODE_DPAD_UP, new KeyEvent(KeyEvent.ACTION_DOWN,
+                        KeyEvent.KEYCODE_DPAD_UP)));
         // |first line
         // second |line
         // last line
@@ -276,7 +279,8 @@
         Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
         pressAlt();
         assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
-                KeyEvent.KEYCODE_DPAD_UP, null));
+                KeyEvent.KEYCODE_DPAD_UP, new KeyEvent(KeyEvent.ACTION_DOWN,
+                        KeyEvent.KEYCODE_DPAD_UP)));
         // |first line
         // second line
         // last line
@@ -285,14 +289,16 @@
         Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
         MetaKeyKeyListener.resetMetaState(mEditable);
         assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
-                KeyEvent.KEYCODE_DPAD_UP, null));
+                KeyEvent.KEYCODE_DPAD_UP, new KeyEvent(KeyEvent.ACTION_DOWN,
+                        KeyEvent.KEYCODE_DPAD_UP)));
         // first lin|e
         // second line
         // last line
         assertSelection(correspondingIn1stLine);
 
         assertFalse(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
-                KeyEvent.KEYCODE_DPAD_UP, null));
+                KeyEvent.KEYCODE_DPAD_UP, new KeyEvent(KeyEvent.ACTION_DOWN,
+                        KeyEvent.KEYCODE_DPAD_UP)));
         // first lin|e
         // second line
         // last line
@@ -316,7 +322,8 @@
         Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
         pressBothShiftAlt();
         assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
-                KeyEvent.KEYCODE_DPAD_DOWN, null));
+                KeyEvent.KEYCODE_DPAD_DOWN, new KeyEvent(KeyEvent.ACTION_DOWN,
+                        KeyEvent.KEYCODE_DPAD_DOWN)));
         // first line
         // second |line
         // last line|
@@ -325,7 +332,8 @@
         Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
         pressShift();
         assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
-                KeyEvent.KEYCODE_DPAD_DOWN, null));
+                KeyEvent.KEYCODE_DPAD_DOWN, new KeyEvent(KeyEvent.ACTION_DOWN,
+                        KeyEvent.KEYCODE_DPAD_DOWN)));
         // first line
         // second |line
         // last lin|e
@@ -336,7 +344,8 @@
 
         pressShift();
         assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
-                KeyEvent.KEYCODE_DPAD_DOWN, null));
+                KeyEvent.KEYCODE_DPAD_DOWN, new KeyEvent(KeyEvent.ACTION_DOWN,
+                        KeyEvent.KEYCODE_DPAD_DOWN)));
         // first line
         // second |line
         // last line|
@@ -345,7 +354,8 @@
         Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
         pressAlt();
         assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
-                KeyEvent.KEYCODE_DPAD_DOWN, null));
+                KeyEvent.KEYCODE_DPAD_DOWN, new KeyEvent(KeyEvent.ACTION_DOWN,
+                        KeyEvent.KEYCODE_DPAD_DOWN)));
         // first line
         // second line
         // last line|
@@ -354,14 +364,16 @@
         Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
         MetaKeyKeyListener.resetMetaState(mEditable);
         assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
-                KeyEvent.KEYCODE_DPAD_DOWN, null));
+                KeyEvent.KEYCODE_DPAD_DOWN, new KeyEvent(KeyEvent.ACTION_DOWN,
+                        KeyEvent.KEYCODE_DPAD_DOWN)));
         // first line
         // second line
         // last lin|e
         assertSelection(correspondingIn3rdLine);
 
         assertFalse(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
-                KeyEvent.KEYCODE_DPAD_DOWN, null));
+                KeyEvent.KEYCODE_DPAD_DOWN, new KeyEvent(KeyEvent.ACTION_DOWN,
+                        KeyEvent.KEYCODE_DPAD_DOWN)));
         // first line
         // second line
         // last lin|e
@@ -385,7 +397,8 @@
         Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
         pressBothShiftAlt();
         assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
-                KeyEvent.KEYCODE_DPAD_LEFT, null));
+                KeyEvent.KEYCODE_DPAD_LEFT, new KeyEvent(KeyEvent.ACTION_DOWN,
+                        KeyEvent.KEYCODE_DPAD_LEFT)));
         // first line
         // |second |line
         // last line
@@ -393,7 +406,8 @@
 
         pressBothShiftAlt();
         assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
-                KeyEvent.KEYCODE_DPAD_LEFT, null));
+                KeyEvent.KEYCODE_DPAD_LEFT, new KeyEvent(KeyEvent.ACTION_DOWN,
+                        KeyEvent.KEYCODE_DPAD_LEFT)));
         // first line
         // |second |line
         // last line
@@ -402,7 +416,8 @@
         Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
         pressShift();
         assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
-                KeyEvent.KEYCODE_DPAD_LEFT, null));
+                KeyEvent.KEYCODE_DPAD_LEFT, new KeyEvent(KeyEvent.ACTION_DOWN,
+                        KeyEvent.KEYCODE_DPAD_LEFT)));
         // first line
         // second| |line
         // last line
@@ -410,7 +425,8 @@
 
         pressShift();
         assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
-                KeyEvent.KEYCODE_DPAD_LEFT, null));
+                KeyEvent.KEYCODE_DPAD_LEFT, new KeyEvent(KeyEvent.ACTION_DOWN,
+                        KeyEvent.KEYCODE_DPAD_LEFT)));
         // first line
         // secon|d |line
         // last line
@@ -419,7 +435,8 @@
         Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
         pressAlt();
         assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
-                KeyEvent.KEYCODE_DPAD_LEFT, null));
+                KeyEvent.KEYCODE_DPAD_LEFT, new KeyEvent(KeyEvent.ACTION_DOWN,
+                        KeyEvent.KEYCODE_DPAD_LEFT)));
         // first line
         // |second line
         // last line
@@ -427,7 +444,8 @@
 
         pressAlt();
         assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
-                KeyEvent.KEYCODE_DPAD_LEFT, null));
+                KeyEvent.KEYCODE_DPAD_LEFT, new KeyEvent(KeyEvent.ACTION_DOWN,
+                        KeyEvent.KEYCODE_DPAD_LEFT)));
         // first line
         // |second line
         // last line
@@ -436,7 +454,8 @@
         Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
         MetaKeyKeyListener.resetMetaState(mEditable);
         assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
-                KeyEvent.KEYCODE_DPAD_LEFT, null));
+                KeyEvent.KEYCODE_DPAD_LEFT, new KeyEvent(KeyEvent.ACTION_DOWN,
+                        KeyEvent.KEYCODE_DPAD_LEFT)));
         // first line
         // second| line
         // last line
@@ -447,7 +466,8 @@
         // |second line
         // last line
         assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
-                KeyEvent.KEYCODE_DPAD_LEFT, null));
+                KeyEvent.KEYCODE_DPAD_LEFT, new KeyEvent(KeyEvent.ACTION_DOWN,
+                        KeyEvent.KEYCODE_DPAD_LEFT)));
         // first line|
         // second line
         // last line
@@ -471,7 +491,8 @@
         Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
         pressBothShiftAlt();
         assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
-                KeyEvent.KEYCODE_DPAD_RIGHT, null));
+                KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(KeyEvent.ACTION_DOWN,
+                        KeyEvent.KEYCODE_DPAD_RIGHT)));
         // first line
         // second |line|
         // last line
@@ -479,7 +500,8 @@
 
         pressBothShiftAlt();
         assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
-                KeyEvent.KEYCODE_DPAD_RIGHT, null));
+                KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(KeyEvent.ACTION_DOWN,
+                        KeyEvent.KEYCODE_DPAD_RIGHT)));
         // first line
         // second |line|
         // last line
@@ -488,7 +510,8 @@
         Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
         pressShift();
         assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
-                KeyEvent.KEYCODE_DPAD_RIGHT, null));
+                KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(KeyEvent.ACTION_DOWN,
+                        KeyEvent.KEYCODE_DPAD_RIGHT)));
         // first line
         // second |l|ine
         // last line
@@ -496,7 +519,8 @@
 
         pressShift();
         assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
-                KeyEvent.KEYCODE_DPAD_RIGHT, null));
+                KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(KeyEvent.ACTION_DOWN,
+                        KeyEvent.KEYCODE_DPAD_RIGHT)));
         // first line
         // second |li|ne
         // last line
@@ -505,7 +529,8 @@
         Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
         pressAlt();
         assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
-                KeyEvent.KEYCODE_DPAD_RIGHT, null));
+                KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(KeyEvent.ACTION_DOWN,
+                        KeyEvent.KEYCODE_DPAD_RIGHT)));
         // first line
         // second line|
         // last line
@@ -513,7 +538,8 @@
 
         pressAlt();
         assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
-                KeyEvent.KEYCODE_DPAD_RIGHT, null));
+                KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(KeyEvent.ACTION_DOWN,
+                        KeyEvent.KEYCODE_DPAD_RIGHT)));
         // first line
         // second line|
         // last line
@@ -522,7 +548,8 @@
         Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
         MetaKeyKeyListener.resetMetaState(mEditable);
         assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
-                KeyEvent.KEYCODE_DPAD_RIGHT, null));
+                KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(KeyEvent.ACTION_DOWN,
+                        KeyEvent.KEYCODE_DPAD_RIGHT)));
         // first line
         // second l|ine
         // last line
@@ -533,7 +560,8 @@
         // second line|
         // last line
         assertTrue(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
-                KeyEvent.KEYCODE_DPAD_RIGHT, null));
+                KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(KeyEvent.ACTION_DOWN,
+                        KeyEvent.KEYCODE_DPAD_RIGHT)));
         // first line
         // second line
         // |last line
@@ -624,43 +652,15 @@
         Selection.setSelection(mEditable, SPACE_IN_2ND_LINE);
 
         assertFalse(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
-                KeyEvent.KEYCODE_DPAD_CENTER, null));
+                KeyEvent.KEYCODE_DPAD_CENTER, new KeyEvent(KeyEvent.ACTION_DOWN,
+                        KeyEvent.KEYCODE_DPAD_CENTER)));
         assertFalse(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
-                KeyEvent.KEYCODE_0, null));
+                KeyEvent.KEYCODE_0, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_0)));
         assertFalse(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
-                KeyEvent.KEYCODE_E, null));
+                KeyEvent.KEYCODE_E, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_E)));
         assertFalse(mArrowKeyMovementMethod.onKeyDown(mTextView, mEditable,
-                KeyEvent.KEYCODE_UNKNOWN, null));
-    }
-
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "Test {@link ArrowKeyMovementMethod#onKeyDown(TextView, Spannable, int, "
-                + "KeyEvent)}. Test the method with null parameters.",
-        method = "onKeyDown",
-        args = {TextView.class, Spannable.class, int.class, KeyEvent.class}
-    )
-    @ToBeFixed(bug = "1695243", explanation = "Android API javadocs are incomplete. @throws clause "
-            + "should be added into javadoc of ArrowKeyMovementMethod#onKeyDown(TextView, "
-            + "Spannable, int, KeyEvent)} when the params view or buffer is null")
-    public void testOnKeyDownWithNullParameters() {
-        initTextViewWithNullLayout();
-        mEditable = (Editable) mTextView.getText();
-        try {
-            mArrowKeyMovementMethod.onKeyDown(null, mEditable, KeyEvent.KEYCODE_DPAD_RIGHT,
-                    new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_RIGHT));
-            fail("The method did not throw NullPointerException when param textView is null.");
-        } catch (NullPointerException e) {
-            // expected
-        }
-
-        try {
-            mArrowKeyMovementMethod.onKeyDown(mTextView, null, KeyEvent.KEYCODE_DPAD_RIGHT,
-                    new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_RIGHT));
-            fail("The method did not throw NullPointerException when param spannable is null.");
-        } catch (NullPointerException e) {
-            // expected
-        }
+                KeyEvent.KEYCODE_UNKNOWN, new KeyEvent(KeyEvent.ACTION_DOWN,
+                        KeyEvent.KEYCODE_UNKNOWN)));
     }
 
     @TestTargetNew(
diff --git a/tests/tests/text/src/android/text/method/cts/BaseKeyListenerTest.java b/tests/tests/text/src/android/text/method/cts/BaseKeyListenerTest.java
index 2f8cbfd..0383463 100644
--- a/tests/tests/text/src/android/text/method/cts/BaseKeyListenerTest.java
+++ b/tests/tests/text/src/android/text/method/cts/BaseKeyListenerTest.java
@@ -62,117 +62,89 @@
         mTextView = (TextView) mActivity.findViewById(R.id.keylistener_textview);
     }
 
-    /**
-     * Check point:
-     * 1. Set the cursor and press DEL key, the character before cursor is deleted.
-     * 2. Set a selection and press DEL key, the selection is deleted.
-     * 3. Press ALT+DEL key, the whole content of TextView is deleted.
-     * 4. when there is no any selections and press DEL key, an IndexOutOfBoundsException occurs
-     * 5. ALT+DEL does not delete everything where there is a selection
-     * 6. DEL key does not take effect when text view does not have BaseKeyListener.
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        method = "backspace",
-        args = {View.class, Editable.class, int.class, KeyEvent.class}
-    )
-    @ToBeFixed(bug = "1695243", explanation = "1. when there is no any selections, " +
-            "an IndexOutOfBoundsException occurs. " +
-            "2. ALT+DEL does not delete everything where there is a selection, " +
-            "javadoc does not explain this situation")
     public void testBackspace() {
-        Editable content;
+        final Editable content = Editable.Factory.getInstance().newEditable(TEST_STRING);
+        setTextViewText(content);
+
+        // Nothing to delete when the cursor is at the beginning.
         final MockBaseKeyListener baseKeyListener = new MockBaseKeyListener();
         KeyEvent delKeyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL);
-
-        content = Editable.Factory.getInstance().newEditable(TEST_STRING);
         Selection.setSelection(content, 0, 0);
         baseKeyListener.backspace(mTextView, content, KeyEvent.KEYCODE_DEL, delKeyEvent);
         assertEquals("123456", content.toString());
 
-        content = Editable.Factory.getInstance().newEditable(TEST_STRING);
+        // Delete the first three letters using a selection.
+        setTextViewText(content);
         Selection.setSelection(content, 0, 3);
         baseKeyListener.backspace(mTextView, content, KeyEvent.KEYCODE_DEL, delKeyEvent);
         assertEquals("456", content.toString());
 
-        content = Editable.Factory.getInstance().newEditable(TEST_STRING);
-        try {
-            baseKeyListener.backspace(mTextView, content, KeyEvent.KEYCODE_DEL,delKeyEvent);
-            fail("did not throw IndexOutOfBoundsException when there is no selections");
-        } catch (IndexOutOfBoundsException e) {
-            // expected.
-        }
+        // Delete the entire line wit ALT + DEL
+        setTextViewText(content);
+        KeyEvent altDelKeyEvent = new KeyEvent(0, 0, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL,
+                0, KeyEvent.META_ALT_ON);
+        Selection.setSelection(content, 0, 0);
+        baseKeyListener.backspace(mTextView, content, KeyEvent.KEYCODE_DEL, altDelKeyEvent);
+        assertEquals("", content.toString());
+    }
 
-        final String str = "123456";
+    private void setTextViewText(final CharSequence content) {
         mActivity.runOnUiThread(new Runnable() {
             public void run() {
-                mTextView.setText(str, BufferType.EDITABLE);
-                mTextView.setKeyListener(baseKeyListener);
-                mTextView.requestFocus();
-                Selection.setSelection((Editable) mTextView.getText(), 1, 1);
+                mTextView.setText(content, BufferType.EDITABLE);
             }
         });
         mInstrumentation.waitForIdleSync();
-        assertEquals(str, mTextView.getText().toString());
-        // delete the first character '1'
+    }
+
+    public void testBackspace_withSendKeys() {
+        final MockBaseKeyListener baseKeyListener = new MockBaseKeyListener();
+        final String str = "123456";
+
+        // Delete the first character '1'
+        prepareTextView(str, baseKeyListener, 1, 1);
         sendKeys(KeyEvent.KEYCODE_DEL);
         assertEquals("23456", mTextView.getText().toString());
 
-        mActivity.runOnUiThread(new Runnable() {
-            public void run() {
-                mTextView.setText(str, BufferType.EDITABLE);
-                mTextView.requestFocus();
-                Selection.setSelection((Editable) mTextView.getText(), 1, 3);
-            }
-        });
-        mInstrumentation.waitForIdleSync();
-        assertEquals(str, mTextView.getText().toString());
-        // delete character '2' and '3'
+        // Delete character '2' and '3'
+        prepareTextView(str, baseKeyListener, 1, 3);
         sendKeys(KeyEvent.KEYCODE_DEL);
         assertEquals("1456", mTextView.getText().toString());
 
-        mActivity.runOnUiThread(new Runnable() {
-            public void run() {
-                mTextView.setText(str, BufferType.EDITABLE);
-                mTextView.requestFocus();
-                Selection.setSelection((Editable) mTextView.getText(), 0, 0);
-            }
-        });
-        mInstrumentation.waitForIdleSync();
-        assertEquals(str, mTextView.getText().toString());
-        // delete everything on the line the cursor is on.
-        sendKeys(KeyEvent.KEYCODE_ALT_LEFT);
-        sendKeys(KeyEvent.KEYCODE_DEL);
+        // Delete everything on the line the cursor is on.
+        prepareTextView(str, baseKeyListener, 0, 0);
+        sendAltDelete();
         assertEquals("", mTextView.getText().toString());
 
-        mActivity.runOnUiThread(new Runnable() {
-            public void run() {
-                mTextView.setText(str, BufferType.EDITABLE);
-                mTextView.requestFocus();
-                Selection.setSelection((Editable) mTextView.getText(), 2, 4);
-            }
-        });
-        mInstrumentation.waitForIdleSync();
-        assertEquals(str, mTextView.getText().toString());
         // ALT+DEL deletes the selection only.
-        sendKeys(KeyEvent.KEYCODE_ALT_LEFT);
-        sendKeys(KeyEvent.KEYCODE_DEL);
+        prepareTextView(str, baseKeyListener, 2, 4);
+        sendAltDelete();
         assertEquals("1256", mTextView.getText().toString());
 
-        // text view does not have BaseKeyListener
+        // DEL key does not take effect when TextView does not have BaseKeyListener.
+        prepareTextView(str, null, 1, 1);
+        sendKeys(KeyEvent.KEYCODE_DEL);
+        assertEquals(str, mTextView.getText().toString());
+    }
+
+    private void prepareTextView(final CharSequence content, final BaseKeyListener keyListener,
+            final int selectionStart, final int selectionEnd) {
         mActivity.runOnUiThread(new Runnable() {
             public void run() {
-                mTextView.setText(str, BufferType.EDITABLE);
-                mTextView.setKeyListener(null);
+                mTextView.setText(content, BufferType.EDITABLE);
+                mTextView.setKeyListener(keyListener);
                 mTextView.requestFocus();
-                Selection.setSelection((Editable) mTextView.getText(), 1, 1);
+                Selection.setSelection((Editable) mTextView.getText(), selectionStart,
+                        selectionEnd);
             }
         });
         mInstrumentation.waitForIdleSync();
-        assertEquals(str, mTextView.getText().toString());
-        // DEL key does not take effect
+    }
+
+    private void sendAltDelete() {
+        mInstrumentation.sendKeySync(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ALT_LEFT));
         sendKeys(KeyEvent.KEYCODE_DEL);
-        assertEquals(str, mTextView.getText().toString());
+        mInstrumentation.sendKeySync(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ALT_LEFT));
     }
 
     /**
diff --git a/tests/tests/text/src/android/text/method/cts/MetaKeyKeyListenerTest.java b/tests/tests/text/src/android/text/method/cts/MetaKeyKeyListenerTest.java
index 32a98e9..6a67a5c 100644
--- a/tests/tests/text/src/android/text/method/cts/MetaKeyKeyListenerTest.java
+++ b/tests/tests/text/src/android/text/method/cts/MetaKeyKeyListenerTest.java
@@ -29,6 +29,7 @@
 import android.text.Spanned;
 import android.text.method.DateKeyListener;
 import android.text.method.MetaKeyKeyListener;
+import android.view.KeyCharacterMap;
 import android.view.KeyEvent;
 import android.view.View;
 import android.widget.ImageView;
@@ -426,9 +427,10 @@
         args = {long.class, int.class, KeyEvent.class}
     )
     public void testHandleKeyDown() {
+        KeyEvent fullEvent = new KeyEvent(0, 0, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SHIFT_LEFT,
+                0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0);
         long state = MetaKeyKeyListener.handleKeyDown(MetaKeyKeyListener.META_CAP_LOCKED,
-                KeyEvent.KEYCODE_SHIFT_LEFT,
-                new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SHIFT_LEFT));
+                KeyEvent.KEYCODE_SHIFT_LEFT, fullEvent);
         assertEquals(0, state);
     }
 
@@ -438,10 +440,11 @@
         args = {long.class, int.class, KeyEvent.class}
     )
     public void testHandleKeyUp() {
+        KeyEvent fullEvent = new KeyEvent(0, 0, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_SHIFT_LEFT,
+                0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0);
         long state = MetaKeyKeyListener.handleKeyUp(MetaKeyKeyListener.META_CAP_LOCKED,
-                KeyEvent.KEYCODE_SHIFT_LEFT,
-                new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_SHIFT_LEFT));
-        assertEquals(MetaKeyKeyListener.META_CAP_LOCKED, state);
+                KeyEvent.KEYCODE_SHIFT_LEFT, fullEvent);
+        assertEquals(0, state);
     }
 
     private class MockMetaKeyKeyListener extends MetaKeyKeyListener {
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 9968bda..cdb1409 100644
--- a/tests/tests/text/src/android/text/method/cts/ScrollingMovementMethodTest.java
+++ b/tests/tests/text/src/android/text/method/cts/ScrollingMovementMethodTest.java
@@ -486,8 +486,9 @@
         int previousScrollX = mTextView.getScrollX();
         runActionOnUiThread(new Runnable() {
             public void run() {
-                method.onKeyDown(mTextView, null, KeyEvent.KEYCODE_DPAD_RIGHT,
-                        new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_RIGHT));
+                method.onKeyDown(mTextView, (Spannable) mTextView.getText(),
+                        KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(KeyEvent.ACTION_DOWN,
+                                KeyEvent.KEYCODE_DPAD_RIGHT));
             }
         });
         assertTrue(mTextView.getScrollX() > previousScrollX);
@@ -495,8 +496,9 @@
         previousScrollX = mTextView.getScrollX();
         runActionOnUiThread(new Runnable() {
             public void run() {
-                method.onKeyDown(mTextView, null, KeyEvent.KEYCODE_DPAD_LEFT,
-                        new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_LEFT));
+                method.onKeyDown(mTextView, (Spannable) mTextView.getText(),
+                        KeyEvent.KEYCODE_DPAD_LEFT, new KeyEvent(KeyEvent.ACTION_DOWN,
+                                KeyEvent.KEYCODE_DPAD_LEFT));
             }
         });
         assertTrue(mTextView.getScrollX() < previousScrollX);
@@ -505,7 +507,8 @@
         assertVisibleLineInTextView(0);
         runActionOnUiThread(new Runnable() {
             public void run() {
-                assertFalse(method.onKeyDown(mTextView, mSpannable, 0, null));
+                assertFalse(method.onKeyDown(mTextView, mSpannable, 0,
+                        new KeyEvent(KeyEvent.ACTION_DOWN, 0)));
             }
         });
         assertEquals(previousScrollX, mTextView.getScrollX());
diff --git a/tests/tests/text/src/android/text/method/cts/TouchTest.java b/tests/tests/text/src/android/text/method/cts/TouchTest.java
index e5275af..22a5515 100644
--- a/tests/tests/text/src/android/text/method/cts/TouchTest.java
+++ b/tests/tests/text/src/android/text/method/cts/TouchTest.java
@@ -39,6 +39,9 @@
     private Activity mActivity;
     private static final String LONG_TEXT = "Scrolls the specified widget to the specified " +
             "coordinates, except constrains the X scrolling position to the horizontal regions " +
+            "of the text that will be visible after scrolling to the specified Y position." +
+            "Scrolls the specified widget to the specified " +
+            "coordinates, except constrains the X scrolling position to the horizontal regions " +
             "of the text that will be visible after scrolling to the specified Y position.";
     private boolean mReturnFromTouchEvent;
 
diff --git a/tests/tests/util/src/android/util/cts/EventLogTest.java b/tests/tests/util/src/android/util/cts/EventLogTest.java
index c803174..43d1b02 100644
--- a/tests/tests/util/src/android/util/cts/EventLogTest.java
+++ b/tests/tests/util/src/android/util/cts/EventLogTest.java
@@ -163,8 +163,8 @@
 
     private long getTime() throws InterruptedException {
         // The precision of currentTimeMillis is poor compared to event timestamps
-        Thread.sleep(20);
-        return System.currentTimeMillis() - 10;
+        Thread.sleep(40);
+        return System.currentTimeMillis() - 20;
     }
 
     private ArrayList<EventLog.Event> getEventsSince(long since, int[] tags) throws IOException {
diff --git a/tests/tests/view/src/android/view/cts/AccessibilityEventTest.java b/tests/tests/view/src/android/view/cts/AccessibilityEventTest.java
index 731784a..f7c1e7a 100644
--- a/tests/tests/view/src/android/view/cts/AccessibilityEventTest.java
+++ b/tests/tests/view/src/android/view/cts/AccessibilityEventTest.java
@@ -202,8 +202,7 @@
         TestCase.assertEquals("fromIndex not properly recycled", 0, event.getFromIndex());
         TestCase.assertEquals("itemCount not properly recycled", 0, event.getItemCount());
         TestCase.assertNull("packageName not properly recycled", event.getPackageName());
-        // This will fail and is fixed in Gingerbread Bug: 2593810
-        // TestCase.assertNull("parcelableData not properly recycled", event.getParcelableData());
+        TestCase.assertNull("parcelableData not properly recycled", event.getParcelableData());
         TestCase.assertEquals("removedCount not properly recycled", 0, event.getRemovedCount());
         TestCase.assertTrue("text not properly recycled", event.getText().isEmpty());
     }
diff --git a/tests/tests/view/src/android/view/cts/KeyCharacterMapTest.java b/tests/tests/view/src/android/view/cts/KeyCharacterMapTest.java
index 4ab38df..156dc49 100644
--- a/tests/tests/view/src/android/view/cts/KeyCharacterMapTest.java
+++ b/tests/tests/view/src/android/view/cts/KeyCharacterMapTest.java
@@ -16,17 +16,17 @@
 
 package android.view.cts;
 
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
+
 import android.test.AndroidTestCase;
 import android.text.TextUtils;
 import android.view.KeyCharacterMap;
 import android.view.KeyEvent;
 import android.view.KeyCharacterMap.KeyData;
 
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-
 @TestTargetClass(KeyCharacterMap.class)
 public class KeyCharacterMapTest extends AndroidTestCase {
 
@@ -36,7 +36,7 @@
     @Override
     protected void setUp() throws Exception {
         super.setUp();
-        mKeyCharacterMap = KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD);
+        mKeyCharacterMap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);
     }
 
     @TestTargetNew(
@@ -113,6 +113,7 @@
         assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SHIFT_RIGHT));
         assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_TAB));
         assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SPACE));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SYM));
         assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUM));
         assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_EXPLORER));
         assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_ENVELOPE));
@@ -133,11 +134,131 @@
         assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUM));
         assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_HEADSETHOOK));
 
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_FOCUS));
         assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_PLUS));
-
         assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MENU));
         assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NOTIFICATION));
         assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SEARCH));
+
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MEDIA_STOP));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MEDIA_NEXT));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MEDIA_PREVIOUS));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MEDIA_REWIND));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MEDIA_FAST_FORWARD));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MUTE));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_PAGE_UP));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_PAGE_DOWN));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_PICTSYMBOLS));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SWITCH_CHARSET));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BUTTON_A));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BUTTON_B));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BUTTON_C));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BUTTON_X));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BUTTON_Y));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BUTTON_Z));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BUTTON_L1));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BUTTON_R1));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BUTTON_L2));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BUTTON_R2));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BUTTON_THUMBL));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BUTTON_THUMBR));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BUTTON_START));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BUTTON_SELECT));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BUTTON_MODE));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_ESCAPE));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_FORWARD_DEL));
+
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_CTRL_LEFT));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_CTRL_RIGHT));
+
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_CAPS_LOCK));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SCROLL_LOCK));
+
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_META_LEFT));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_META_RIGHT));
+
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_FUNCTION));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SYSRQ));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BREAK));
+
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MOVE_HOME));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MOVE_END));
+
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_INSERT));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_FORWARD));
+
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MEDIA_PLAY));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MEDIA_PAUSE));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MEDIA_CLOSE));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MEDIA_EJECT));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_MEDIA_RECORD));
+
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_F1));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_F2));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_F3));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_F4));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_F5));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_F6));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_F7));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_F8));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_F9));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_F10));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_F11));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_F12));
+
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUM_LOCK));
+
+        assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_0));
+        assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_1));
+        assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_2));
+        assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_3));
+        assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_4));
+        assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_5));
+        assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_6));
+        assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_7));
+        assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_8));
+        assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_9));
+        assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_DIVIDE));
+        assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_MULTIPLY));
+        assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_SUBTRACT));
+        assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_ADD));
+        assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_DOT));
+        assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_COMMA));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_ENTER));
+        assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_EQUALS));
+        assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_LEFT_PAREN));
+        assertTrue(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_NUMPAD_RIGHT_PAREN));
+
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_VOLUME_MUTE));
+
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_INFO));
+
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_CHANNEL_UP));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_CHANNEL_DOWN));
+
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_ZOOM_IN));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_ZOOM_OUT));
+
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_TV));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_WINDOW));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_GUIDE));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_DVR));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_BOOKMARK));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_CAPTIONS));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_SETTINGS));
+
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_TV_POWER));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_TV_INPUT));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_STB_POWER));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_STB_INPUT));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_AVR_POWER));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_AVR_INPUT));
+
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_PROG_RED));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_PROG_GREEN));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_PROG_YELLOW));
+        assertFalse(mKeyCharacterMap.isPrintingKey(KeyEvent.KEYCODE_PROG_BLUE));
     }
 
     @TestTargetNew(
diff --git a/tests/tests/view/src/android/view/cts/KeyEventTest.java b/tests/tests/view/src/android/view/cts/KeyEventTest.java
index dc1696c6..6689ca4 100644
--- a/tests/tests/view/src/android/view/cts/KeyEventTest.java
+++ b/tests/tests/view/src/android/view/cts/KeyEventTest.java
@@ -31,6 +31,8 @@
 import android.view.KeyCharacterMap.KeyData;
 import android.view.KeyEvent.Callback;
 
+import junit.framework.Assert;
+
 /**
  * Test {@link KeyEvent}.
  */
@@ -183,23 +185,16 @@
         args = {android.view.KeyCharacterMap.KeyData.class}
     )
     public void testGetKeyData() {
+        KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_Z);
         KeyData keyData = new KeyData();
-        char origDisplayLabel = keyData.displayLabel;
-        char origNumber = keyData.number;
-        char[] origMeta = new char[KeyData.META_LENGTH];
-        origMeta[0] = keyData.meta[0];
-        origMeta[1] = keyData.meta[1];
-        origMeta[2] = keyData.meta[2];
-        origMeta[3] = keyData.meta[3];
+        assertTrue(keyEvent.getKeyData(keyData));
 
-        assertTrue(mKeyEvent.getKeyData(keyData));
-        // check whether KeyData has been updated.
-        assertTrue(keyData.displayLabel != origDisplayLabel);
-        assertTrue(keyData.number != origNumber);
-        assertTrue(keyData.meta[0] != origMeta[0]);
-        assertTrue(keyData.meta[1] != origMeta[1]);
-        assertTrue(keyData.meta[2] != origMeta[2]);
-        assertTrue(keyData.meta[3] != origMeta[3]);
+        assertEquals('Z', keyData.displayLabel);
+        assertEquals(0, keyData.number);
+        assertEquals('z', keyData.meta[0]);
+        assertEquals('Z', keyData.meta[1]);
+        assertEquals(0, keyData.meta[2]);
+        assertEquals(0, keyData.meta[3]);
     }
 
     @TestTargetNew(
@@ -295,6 +290,7 @@
     public void testGetUnicodeChar1() {
         // 48 is Unicode character of '0'
         assertEquals(48, mKeyEvent.getUnicodeChar());
+
         mKeyEvent = new KeyEvent(mDownTime, mEventTime, KeyEvent.ACTION_DOWN,
                 KeyEvent.KEYCODE_9, 5, 0);
         // 57 is Unicode character of '9'
@@ -317,6 +313,7 @@
         assertEquals(48, mKeyEvent.getUnicodeChar(MetaKeyKeyListener.META_CAP_LOCKED));
         mKeyEvent = new KeyEvent(mDownTime, mEventTime, KeyEvent.ACTION_DOWN,
                 KeyEvent.KEYCODE_9, 5, 0);
+
         // 57 is Unicode character of '9'
         assertEquals(57, mKeyEvent.getUnicodeChar(0));
 
@@ -397,21 +394,205 @@
         assertFalse(mKeyEvent.isAltPressed());
     }
 
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "Test {@link KeyEvent#isModifierKey(int)}",
-        method = "isModifierKey",
-        args = {int.class}
-    )
+    public void testGetModifierMetaStateMask() {
+        int mask = KeyEvent.getModifierMetaStateMask();
+        assertTrue((mask & KeyEvent.META_SHIFT_ON) != 0);
+        assertTrue((mask & KeyEvent.META_SHIFT_LEFT_ON) != 0);
+        assertTrue((mask & KeyEvent.META_SHIFT_RIGHT_ON) != 0);
+        assertTrue((mask & KeyEvent.META_ALT_ON) != 0);
+        assertTrue((mask & KeyEvent.META_ALT_LEFT_ON) != 0);
+        assertTrue((mask & KeyEvent.META_ALT_RIGHT_ON) != 0);
+        assertTrue((mask & KeyEvent.META_CTRL_ON) != 0);
+        assertTrue((mask & KeyEvent.META_CTRL_LEFT_ON) != 0);
+        assertTrue((mask & KeyEvent.META_CTRL_RIGHT_ON) != 0);
+        assertTrue((mask & KeyEvent.META_META_ON) != 0);
+        assertTrue((mask & KeyEvent.META_META_LEFT_ON) != 0);
+        assertTrue((mask & KeyEvent.META_META_RIGHT_ON) != 0);
+        assertTrue((mask & KeyEvent.META_SYM_ON) != 0);
+        assertTrue((mask & KeyEvent.META_FUNCTION_ON) != 0);
+
+        assertFalse((mask & KeyEvent.META_CAPS_LOCK_ON) != 0);
+        assertFalse((mask & KeyEvent.META_NUM_LOCK_ON) != 0);
+        assertFalse((mask & KeyEvent.META_SCROLL_LOCK_ON) != 0);
+    }
+
     public void testIsModifierKey() {
         assertTrue(KeyEvent.isModifierKey(KeyEvent.KEYCODE_SHIFT_LEFT));
         assertTrue(KeyEvent.isModifierKey(KeyEvent.KEYCODE_SHIFT_RIGHT));
         assertTrue(KeyEvent.isModifierKey(KeyEvent.KEYCODE_ALT_LEFT));
         assertTrue(KeyEvent.isModifierKey(KeyEvent.KEYCODE_ALT_RIGHT));
+        assertTrue(KeyEvent.isModifierKey(KeyEvent.KEYCODE_CTRL_LEFT));
+        assertTrue(KeyEvent.isModifierKey(KeyEvent.KEYCODE_CTRL_RIGHT));
+        assertTrue(KeyEvent.isModifierKey(KeyEvent.KEYCODE_META_LEFT));
+        assertTrue(KeyEvent.isModifierKey(KeyEvent.KEYCODE_META_RIGHT));
         assertTrue(KeyEvent.isModifierKey(KeyEvent.KEYCODE_SYM));
+        assertTrue(KeyEvent.isModifierKey(KeyEvent.KEYCODE_NUM));
+        assertTrue(KeyEvent.isModifierKey(KeyEvent.KEYCODE_FUNCTION));
+
         assertFalse(KeyEvent.isModifierKey(KeyEvent.KEYCODE_0));
     }
 
+    private static final int UNDEFINED_META_STATE = 0x80000000;
+
+    public void testNormalizeMetaState() {
+        // Already normalized values.
+        assertEquals(0, KeyEvent.normalizeMetaState(0));
+        assertEquals(KeyEvent.getModifierMetaStateMask(),
+                KeyEvent.normalizeMetaState(KeyEvent.getModifierMetaStateMask()));
+
+        // Values that require normalization.
+        assertEquals(KeyEvent.META_SHIFT_LEFT_ON | KeyEvent.META_SHIFT_ON,
+                KeyEvent.normalizeMetaState(KeyEvent.META_SHIFT_LEFT_ON));
+        assertEquals(KeyEvent.META_SHIFT_RIGHT_ON | KeyEvent.META_SHIFT_ON,
+                KeyEvent.normalizeMetaState(KeyEvent.META_SHIFT_RIGHT_ON));
+        assertEquals(KeyEvent.META_ALT_LEFT_ON | KeyEvent.META_ALT_ON,
+                KeyEvent.normalizeMetaState(KeyEvent.META_ALT_LEFT_ON));
+        assertEquals(KeyEvent.META_ALT_RIGHT_ON | KeyEvent.META_ALT_ON,
+                KeyEvent.normalizeMetaState(KeyEvent.META_ALT_RIGHT_ON));
+        assertEquals(KeyEvent.META_CTRL_LEFT_ON | KeyEvent.META_CTRL_ON,
+                KeyEvent.normalizeMetaState(KeyEvent.META_CTRL_LEFT_ON));
+        assertEquals(KeyEvent.META_CTRL_RIGHT_ON | KeyEvent.META_CTRL_ON,
+                KeyEvent.normalizeMetaState(KeyEvent.META_CTRL_RIGHT_ON));
+        assertEquals(KeyEvent.META_META_LEFT_ON | KeyEvent.META_META_ON,
+                KeyEvent.normalizeMetaState(KeyEvent.META_META_LEFT_ON));
+        assertEquals(KeyEvent.META_META_RIGHT_ON | KeyEvent.META_META_ON,
+                KeyEvent.normalizeMetaState(KeyEvent.META_META_RIGHT_ON));
+        assertEquals(KeyEvent.META_CAPS_LOCK_ON,
+                KeyEvent.normalizeMetaState(MetaKeyKeyListener.META_CAP_LOCKED));
+        assertEquals(KeyEvent.META_ALT_ON,
+                KeyEvent.normalizeMetaState(MetaKeyKeyListener.META_ALT_LOCKED));
+        assertEquals(KeyEvent.META_SYM_ON,
+                KeyEvent.normalizeMetaState(MetaKeyKeyListener.META_SYM_LOCKED));
+        assertEquals(KeyEvent.META_SHIFT_ON,
+                KeyEvent.normalizeMetaState(KeyEvent.META_SHIFT_ON | UNDEFINED_META_STATE));
+    }
+
+    public void testMetaStateHasNoModifiers() {
+        assertTrue(KeyEvent.metaStateHasNoModifiers(0));
+        assertTrue(KeyEvent.metaStateHasNoModifiers(KeyEvent.META_CAPS_LOCK_ON));
+        assertTrue(KeyEvent.metaStateHasNoModifiers(KeyEvent.META_NUM_LOCK_ON));
+        assertTrue(KeyEvent.metaStateHasNoModifiers(KeyEvent.META_SCROLL_LOCK_ON));
+
+        assertFalse(KeyEvent.metaStateHasNoModifiers(KeyEvent.META_SHIFT_ON));
+        assertFalse(KeyEvent.metaStateHasNoModifiers(KeyEvent.META_SHIFT_LEFT_ON));
+        assertFalse(KeyEvent.metaStateHasNoModifiers(KeyEvent.META_SHIFT_RIGHT_ON));
+        assertFalse(KeyEvent.metaStateHasNoModifiers(KeyEvent.META_ALT_ON));
+        assertFalse(KeyEvent.metaStateHasNoModifiers(KeyEvent.META_ALT_LEFT_ON));
+        assertFalse(KeyEvent.metaStateHasNoModifiers(KeyEvent.META_ALT_RIGHT_ON));
+        assertFalse(KeyEvent.metaStateHasNoModifiers(KeyEvent.META_CTRL_ON));
+        assertFalse(KeyEvent.metaStateHasNoModifiers(KeyEvent.META_CTRL_LEFT_ON));
+        assertFalse(KeyEvent.metaStateHasNoModifiers(KeyEvent.META_CTRL_RIGHT_ON));
+        assertFalse(KeyEvent.metaStateHasNoModifiers(KeyEvent.META_META_ON));
+        assertFalse(KeyEvent.metaStateHasNoModifiers(KeyEvent.META_META_LEFT_ON));
+        assertFalse(KeyEvent.metaStateHasNoModifiers(KeyEvent.META_META_RIGHT_ON));
+        assertFalse(KeyEvent.metaStateHasNoModifiers(KeyEvent.META_SYM_ON));
+        assertFalse(KeyEvent.metaStateHasNoModifiers(KeyEvent.META_FUNCTION_ON));
+    }
+
+    public void testMetaStateHasModifiers() {
+        assertTrue(KeyEvent.metaStateHasModifiers(0, 0));
+        assertTrue(KeyEvent.metaStateHasModifiers(
+                KeyEvent.META_NUM_LOCK_ON | KeyEvent.META_CAPS_LOCK_ON
+                        | KeyEvent.META_SCROLL_LOCK_ON, 0));
+        assertTrue(KeyEvent.metaStateHasModifiers(
+                KeyEvent.META_SHIFT_ON | KeyEvent.META_SHIFT_LEFT_ON,
+                KeyEvent.META_SHIFT_LEFT_ON));
+        assertTrue(KeyEvent.metaStateHasModifiers(
+                KeyEvent.META_SHIFT_LEFT_ON | KeyEvent.META_SHIFT_RIGHT_ON,
+                KeyEvent.META_SHIFT_LEFT_ON | KeyEvent.META_SHIFT_RIGHT_ON));
+        assertTrue(KeyEvent.metaStateHasModifiers(
+                KeyEvent.META_SHIFT_LEFT_ON,
+                KeyEvent.META_SHIFT_LEFT_ON));
+        assertTrue(KeyEvent.metaStateHasModifiers(
+                KeyEvent.META_NUM_LOCK_ON | KeyEvent.META_CAPS_LOCK_ON
+                        | KeyEvent.META_SCROLL_LOCK_ON | KeyEvent.META_SHIFT_LEFT_ON,
+                KeyEvent.META_SHIFT_LEFT_ON));
+        assertTrue(KeyEvent.metaStateHasModifiers(
+                KeyEvent.META_SHIFT_ON | KeyEvent.META_SHIFT_LEFT_ON,
+                KeyEvent.META_SHIFT_ON));
+        assertTrue(KeyEvent.metaStateHasModifiers(
+                KeyEvent.META_ALT_ON | KeyEvent.META_ALT_RIGHT_ON,
+                KeyEvent.META_ALT_ON));
+        assertTrue(KeyEvent.metaStateHasModifiers(
+                KeyEvent.META_ALT_LEFT_ON | KeyEvent.META_SHIFT_LEFT_ON,
+                KeyEvent.META_ALT_ON | KeyEvent.META_SHIFT_ON));
+        assertTrue(KeyEvent.metaStateHasModifiers(
+                KeyEvent.META_CTRL_RIGHT_ON | KeyEvent.META_META_LEFT_ON,
+                KeyEvent.META_CTRL_RIGHT_ON | KeyEvent.META_META_ON));
+        assertTrue(KeyEvent.metaStateHasModifiers(
+                KeyEvent.META_SYM_ON | KeyEvent.META_FUNCTION_ON | KeyEvent.META_CAPS_LOCK_ON,
+                KeyEvent.META_SYM_ON | KeyEvent.META_FUNCTION_ON));
+
+        assertFalse(KeyEvent.metaStateHasModifiers(0, KeyEvent.META_SHIFT_ON));
+        assertFalse(KeyEvent.metaStateHasModifiers(
+                KeyEvent.META_ALT_ON | KeyEvent.META_SHIFT_LEFT_ON,
+                KeyEvent.META_SHIFT_ON));
+        assertFalse(KeyEvent.metaStateHasModifiers(
+                KeyEvent.META_ALT_LEFT_ON | KeyEvent.META_SHIFT_LEFT_ON,
+                KeyEvent.META_SHIFT_ON));
+        assertFalse(KeyEvent.metaStateHasModifiers(
+                KeyEvent.META_ALT_LEFT_ON,
+                KeyEvent.META_ALT_RIGHT_ON));
+        assertFalse(KeyEvent.metaStateHasModifiers(
+                KeyEvent.META_ALT_LEFT_ON,
+                KeyEvent.META_CTRL_LEFT_ON));
+
+        final int[] invalidModifiers = new int[] {
+                KeyEvent.META_CAPS_LOCK_ON,
+                KeyEvent.META_NUM_LOCK_ON,
+                KeyEvent.META_SCROLL_LOCK_ON,
+                MetaKeyKeyListener.META_CAP_LOCKED,
+                MetaKeyKeyListener.META_ALT_LOCKED,
+                MetaKeyKeyListener.META_SYM_LOCKED,
+                KeyEvent.META_SHIFT_ON | KeyEvent.META_SHIFT_LEFT_ON,
+                KeyEvent.META_SHIFT_ON | KeyEvent.META_SHIFT_RIGHT_ON,
+                KeyEvent.META_SHIFT_ON | KeyEvent.META_SHIFT_LEFT_ON| KeyEvent.META_SHIFT_RIGHT_ON,
+                KeyEvent.META_ALT_ON | KeyEvent.META_ALT_LEFT_ON,
+                KeyEvent.META_ALT_ON | KeyEvent.META_ALT_RIGHT_ON,
+                KeyEvent.META_ALT_ON | KeyEvent.META_ALT_LEFT_ON| KeyEvent.META_ALT_RIGHT_ON,
+                KeyEvent.META_CTRL_ON | KeyEvent.META_CTRL_LEFT_ON,
+                KeyEvent.META_CTRL_ON | KeyEvent.META_CTRL_RIGHT_ON,
+                KeyEvent.META_CTRL_ON | KeyEvent.META_CTRL_LEFT_ON| KeyEvent.META_CTRL_RIGHT_ON,
+                KeyEvent.META_META_ON | KeyEvent.META_META_LEFT_ON,
+                KeyEvent.META_META_ON | KeyEvent.META_META_RIGHT_ON,
+                KeyEvent.META_META_ON | KeyEvent.META_META_LEFT_ON| KeyEvent.META_META_RIGHT_ON,
+        };
+        for (int modifiers : invalidModifiers) {
+            try {
+                KeyEvent.metaStateHasModifiers(0, modifiers);
+                Assert.fail("Expected IllegalArgumentException");
+            } catch (IllegalArgumentException ex) {
+            }
+        }
+
+        assertFalse(KeyEvent.metaStateHasModifiers(0, UNDEFINED_META_STATE));
+    }
+
+    public void testHasNoModifiers() {
+        KeyEvent ev = new KeyEvent(0, 0, KeyEvent.ACTION_DOWN,
+                KeyEvent.KEYCODE_A, 0, KeyEvent.META_CAPS_LOCK_ON);
+        assertTrue(ev.hasNoModifiers());
+
+        ev = new KeyEvent(0, 0, KeyEvent.ACTION_DOWN,
+                KeyEvent.KEYCODE_A, 0, KeyEvent.META_CAPS_LOCK_ON | KeyEvent.META_SHIFT_ON);
+        assertFalse(ev.hasNoModifiers());
+    }
+
+    public void testHasModifiers() {
+        KeyEvent ev = new KeyEvent(0, 0, KeyEvent.ACTION_DOWN,
+                KeyEvent.KEYCODE_A, 0, KeyEvent.META_CAPS_LOCK_ON);
+        assertTrue(ev.hasModifiers(0));
+
+        ev = new KeyEvent(0, 0, KeyEvent.ACTION_DOWN,
+                KeyEvent.KEYCODE_A, 0, KeyEvent.META_CAPS_LOCK_ON | KeyEvent.META_SHIFT_ON);
+        assertTrue(ev.hasModifiers(KeyEvent.META_SHIFT_ON));
+
+        ev = new KeyEvent(0, 0, KeyEvent.ACTION_DOWN,
+                KeyEvent.KEYCODE_A, 0,
+                KeyEvent.META_CAPS_LOCK_ON | KeyEvent.META_SHIFT_ON | KeyEvent.META_SHIFT_RIGHT_ON);
+        assertFalse(ev.hasModifiers(KeyEvent.META_SHIFT_LEFT_ON));
+    }
+
     @TestTargetNew(
         level = TestLevel.COMPLETE,
         notes = "Test {@link KeyEvent#getDisplayLabel()}",
@@ -509,8 +690,6 @@
         method = "getMatch",
         args = {char[].class}
     )
-    @ToBeFixed(bug = "1695243", explanation = "Android API javadocs are incomplete, " +
-            "should add NPE description in javadoc.")
     public void testGetMatch1() {
         char[] codes1 = new char[] { '0', '1', '2' };
         assertEquals('0', mKeyEvent.getMatch(codes1));
@@ -521,13 +700,6 @@
         char[] codes3 = { '2', 'S' };
         mKeyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_S);
         assertEquals('S', mKeyEvent.getMatch(codes3));
-
-        try {
-            mKeyEvent.getMatch(null);
-            fail("Should throw NullPointerException");
-        } catch (NullPointerException e) {
-            // empty
-        }
     }
 
     @TestTargetNew(
@@ -742,7 +914,7 @@
         public boolean onKeyLongPress(int keyCode, KeyEvent event) {
             return false;
         }
-        
+
         public boolean onKeyMultiple(int keyCode, int count, KeyEvent event) {
             mIsMultiple = true;
             mKeyCode = keyCode;
diff --git a/tests/tests/view/src/android/view/cts/LayoutInflaterTest.java b/tests/tests/view/src/android/view/cts/LayoutInflaterTest.java
index 6f637fc..f5bd8f4 100644
--- a/tests/tests/view/src/android/view/cts/LayoutInflaterTest.java
+++ b/tests/tests/view/src/android/view/cts/LayoutInflaterTest.java
@@ -16,6 +16,14 @@
 
 package android.view.cts;
 
+import com.android.cts.stub.R;
+import com.android.internal.util.XmlUtils;
+
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
+
 import org.xmlpull.v1.XmlPullParser;
 
 import android.app.cts.MockActivity;
@@ -23,6 +31,7 @@
 import android.content.Context;
 import android.content.pm.ActivityInfo;
 import android.content.pm.PackageManager;
+import android.content.res.Resources;
 import android.content.res.XmlResourceParser;
 import android.test.AndroidTestCase;
 import android.util.AttributeSet;
@@ -35,21 +44,13 @@
 import android.view.LayoutInflater.Factory;
 import android.view.LayoutInflater.Filter;
 import android.widget.LinearLayout;
-import com.android.cts.stub.R;
-
-import com.android.internal.util.XmlUtils;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
 
 @TestTargetClass(LayoutInflater.class)
 public class LayoutInflaterTest extends AndroidTestCase {
 
     private LayoutInflater mLayoutInflater;
     private Context mContext;
-    private Factory mFactory = new Factory() {
+    private final Factory mFactory = new Factory() {
         public View onCreateView(String name, Context context,
                 AttributeSet attrs) {
 
@@ -57,7 +58,7 @@
         }
     };
     private boolean isOnLoadClass;
-    private Filter mFilter = new Filter() {
+    private final Filter mFilter = new Filter() {
 
         @SuppressWarnings("unchecked")
         public boolean onLoadClass(Class clazz) {
@@ -172,7 +173,7 @@
             }
             String nodeName = parser.getName();
             if (!"alias".equals(nodeName)) {
-                throw new RuntimeException();
+                throw new InflateException();
             }
             int outerDepth = parser.getDepth();
             while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
@@ -296,8 +297,7 @@
         try {
             view = mLayoutInflater.inflate(-1, null);
             fail("should throw exception");
-        } catch (RuntimeException e) {
-
+        } catch (Resources.NotFoundException e) {
         }
         LinearLayout mLayout;
         mLayout = new LinearLayout(mContext);
@@ -335,7 +335,7 @@
         try {
             view = mLayoutInflater.inflate(-1, null, false);
             fail("should throw exception");
-        } catch (RuntimeException e) {
+        } catch (Resources.NotFoundException e) {
 
         }
         LinearLayout mLayout;
@@ -381,7 +381,7 @@
         try {
             view = mLayoutInflater.inflate(null, null);
             fail("should throw exception");
-        } catch (RuntimeException e) {
+        } catch (NullPointerException e) {
         }
         LinearLayout mLayout;
         mLayout = new LinearLayout(mContext);
@@ -395,7 +395,7 @@
         try {
             view = mLayoutInflater.inflate(parser, mLayout);
             fail("should throw exception");
-        } catch (RuntimeException e) {
+        } catch (NullPointerException e) {
         }
         parser = getContext().getResources().getLayout(
                 R.layout.inflater_layout);
@@ -440,7 +440,7 @@
        try {
            view = mLayoutInflater.inflate(null, null, false);
            fail("should throw exception");
-       } catch (RuntimeException e) {
+       } catch (NullPointerException e) {
        }
        LinearLayout mLayout;
        mLayout = new LinearLayout(mContext);
@@ -454,7 +454,7 @@
        try {
            view = mLayoutInflater.inflate(parser, mLayout, false);
            fail("should throw exception");
-       } catch (RuntimeException e) {
+       } catch (NullPointerException e) {
        }
        parser = getContext().getResources().getLayout(
                R.layout.inflater_layout);
@@ -475,7 +475,7 @@
        try {
            view = mLayoutInflater.inflate(parser, mLayout, false);
            fail("should throw exception");
-       } catch (RuntimeException e) {
+       } catch (InflateException e) {
        }
 
        parser = null;
@@ -497,6 +497,7 @@
             super(original, newContext);
         }
 
+        @Override
         public View onCreateView(String name, AttributeSet attrs)
                 throws ClassNotFoundException {
             return super.onCreateView(name, attrs);
diff --git a/tests/tests/view/src/android/view/cts/MotionEventTest.java b/tests/tests/view/src/android/view/cts/MotionEventTest.java
index e4df594..f8a14e6 100644
--- a/tests/tests/view/src/android/view/cts/MotionEventTest.java
+++ b/tests/tests/view/src/android/view/cts/MotionEventTest.java
@@ -22,12 +22,15 @@
 import dalvik.annotation.TestTargets;
 import dalvik.annotation.ToBeFixed;
 
+import android.graphics.Matrix;
 import android.os.Parcel;
 import android.os.Parcelable;
 import android.os.SystemClock;
 import android.test.AndroidTestCase;
+import android.view.InputDevice;
 import android.view.KeyEvent;
 import android.view.MotionEvent;
+import android.view.MotionEvent.PointerCoords;
 
 /**
  * Test {@link MotionEvent}.
@@ -497,4 +500,103 @@
         
         mMotionEvent2 = null; // since it was recycled, don't try to recycle again in tear down
     }
+
+    @TestTargetNew(
+            level = TestLevel.COMPLETE,
+            method = "transform",
+            args = {}
+        )
+    public void testTransformShouldThrowWhenMatrixIsNull() {
+        try {
+            mMotionEvent1.transform(null);
+            fail("transform() should throw an exception when matrix is null.");
+        } catch (IllegalArgumentException ex) {
+        }
+    }
+
+    @TestTargetNew(
+            level = TestLevel.COMPLETE,
+            method = "transform",
+            args = {}
+        )
+    public void testTransformShouldApplyMatrixToPointsAndPreserveRawPosition() {
+        // Generate some points on a circle.
+        // Each point 'i' is a point on a circle of radius ROTATION centered at (3,2) at an angle
+        // of ARC * i degrees clockwise relative to the Y axis.
+        // The geometrical representation is irrelevant to the test, it's just easy to generate
+        // and check rotation.  We set the orientation to the same angle.
+        // Coordinate system: down is increasing Y, right is increasing X.
+        final float PI_180 = (float) (Math.PI / 180);
+        final float RADIUS = 10;
+        final float ARC = 36;
+        final float ROTATION = ARC * 2;
+
+        final int pointerCount = 11;
+        final int[] pointerIds = new int[pointerCount];
+        final PointerCoords[] pointerCoords = new PointerCoords[pointerCount];
+        for (int i = 0; i < pointerCount; i++) {
+            final PointerCoords c = new PointerCoords();
+            final float angle = (float) (i * ARC * PI_180);
+            pointerIds[i] = i;
+            pointerCoords[i] = c;
+            c.x = (float) (Math.sin(angle) * RADIUS + 3);
+            c.y = (float) (- Math.cos(angle) * RADIUS + 2);
+            c.orientation = angle;
+        }
+        final MotionEvent event = MotionEvent.obtain(0, 0, MotionEvent.ACTION_MOVE,
+                pointerCount, pointerIds, pointerCoords, 0, 0, 0, 0, 0, 0, 0);
+        final float originalRawX = 0 + 3;
+        final float originalRawY = - RADIUS + 2;
+        dump("Original points.", event);
+
+        // Check original raw X and Y assumption.
+        assertEquals(originalRawX, event.getRawX(), 0.001);
+        assertEquals(originalRawY, event.getRawY(), 0.001);
+
+        // Now translate the motion event so the circle's origin is at (0,0).
+        event.offsetLocation(-3, -2);
+        dump("Translated points.", event);
+
+        // Offsetting the location should preserve the raw X and Y of the first point.
+        assertEquals(originalRawX, event.getRawX(), 0.001);
+        assertEquals(originalRawY, event.getRawY(), 0.001);
+
+        // Apply a rotation about the origin by ROTATION degrees clockwise.
+        Matrix matrix = new Matrix();
+        matrix.setRotate(ROTATION);
+        event.transform(matrix);
+        dump("Rotated points.", event);
+
+        // Check the points.
+        for (int i = 0; i < pointerCount; i++) {
+            final PointerCoords c = pointerCoords[i];
+            event.getPointerCoords(i, c);
+
+            final float angle = (float) ((i * ARC + ROTATION) * PI_180);
+            assertEquals(Math.sin(angle) * RADIUS, c.x, 0.001);
+            assertEquals(- Math.cos(angle) * RADIUS, c.y, 0.001);
+            assertEquals(Math.tan(angle), Math.tan(c.orientation), 0.1);
+        }
+
+        // Applying the transformation should preserve the raw X and Y of the first point.
+        assertEquals(originalRawX, event.getRawX(), 0.001);
+        assertEquals(originalRawY, event.getRawY(), 0.001);
+    }
+
+    private void dump(String label, MotionEvent ev) {
+        if (false) {
+            StringBuilder msg = new StringBuilder();
+            msg.append(label).append("\n");
+
+            msg.append("  Raw: (").append(ev.getRawX()).append(",").append(ev.getRawY()).append(")\n");
+            int pointerCount = ev.getPointerCount();
+            for (int i = 0; i < pointerCount; i++) {
+                msg.append("  Pointer[").append(i).append("]: (")
+                        .append(ev.getX(i)).append(",").append(ev.getY(i)).append("), orientation=")
+                        .append(ev.getOrientation(i) * 180 / Math.PI).append(" deg\n");
+            }
+
+            android.util.Log.i("TEST", msg.toString());
+        }
+    }
 }
diff --git a/tests/tests/view/src/android/view/cts/ViewGroupTest.java b/tests/tests/view/src/android/view/cts/ViewGroupTest.java
index ebcee54..2498700 100644
--- a/tests/tests/view/src/android/view/cts/ViewGroupTest.java
+++ b/tests/tests/view/src/android/view/cts/ViewGroupTest.java
@@ -16,7 +16,13 @@
 
 package android.view.cts;
 
-import java.util.ArrayList;
+import com.android.internal.util.XmlUtils;
+
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
+import dalvik.annotation.ToBeFixed;
 
 import android.app.cts.CTSResult;
 import android.content.Context;
@@ -55,13 +61,7 @@
 import android.widget.TextView;
 import android.widget.cts.ViewGroupStubActivity;
 
-import com.android.internal.util.XmlUtils;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.ToBeFixed;
+import java.util.ArrayList;
 
 @TestTargetClass(ViewGroup.class)
 public class ViewGroupTest extends InstrumentationTestCase implements CTSResult{
@@ -1557,20 +1557,6 @@
         assertTrue(vg.isOnRequestFocusInDescendantsCalled);
     }
 
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        method = "recomputeViewAttributes",
-        args = {android.view.View.class}
-    )
-    public void testRecomputeViewAttributes() {
-        MockViewGroup father = new MockViewGroup(mContext);
-        MockViewGroup son = new MockViewGroup(mContext);
-        father.addView(son);
-
-        son.recomputeViewAttributes(null);
-        assertTrue(father.isRecomputeViewAttributesCalled);
-    }
-
     @TestTargets({
         @TestTargetNew(
             level = TestLevel.COMPLETE,
@@ -1948,6 +1934,7 @@
         public int mBottom;
 
         public MockCanvas() {
+            super(Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888));
         }
 
         public MockCanvas(Bitmap bitmap) {
diff --git a/tests/tests/view/src/android/view/cts/ViewTest.java b/tests/tests/view/src/android/view/cts/ViewTest.java
index e07e105..f3d449b 100644
--- a/tests/tests/view/src/android/view/cts/ViewTest.java
+++ b/tests/tests/view/src/android/view/cts/ViewTest.java
@@ -46,6 +46,7 @@
 import android.util.Log;
 import android.util.SparseArray;
 import android.util.Xml;
+import android.view.ActionMode;
 import android.view.ContextMenu;
 import android.view.Display;
 import android.view.HapticFeedbackConstants;
@@ -2028,10 +2029,6 @@
         view.setMeasuredDimensionWrapper(20, 30);
         assertEquals(20, view.getMeasuredWidth());
         assertEquals(30, view.getMeasuredHeight());
-
-        view.setMeasuredDimensionWrapper(-20, -30);
-        assertEquals(-20, view.getMeasuredWidth());
-        assertEquals(-30, view.getMeasuredHeight());
     }
 
     @TestTargets({
@@ -2680,8 +2677,11 @@
         runTestOnUiThread(new Runnable() {
             public void run() {
                 view.setFocusable(true);
+                view.requestFocus();
             }
         });
+        getInstrumentation().waitForIdleSync();
+        assertTrue(view.isFocused());
 
         KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MENU);
         getInstrumentation().sendKeySync(event);
@@ -3081,8 +3081,11 @@
         runTestOnUiThread(new Runnable() {
             public void run() {
                 view.setFocusable(true);
+                view.requestFocus();
             }
         });
+        getInstrumentation().waitForIdleSync();
+        assertTrue(view.isFocused());
 
         KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_0);
         getInstrumentation().sendKeySync(event);
@@ -4010,8 +4013,6 @@
             args = {}
         )
     })
-    @ToBeFixed(bug = "", explanation = "when scrollbar is with INSET style, the bottom padding" +
-            "should be increased.")
     @UiThreadTest
     public void testScrollbarStyle() {
         MockView view = (MockView) mActivity.findViewById(R.id.mock_view);
@@ -4036,8 +4037,7 @@
         view.setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET);
         assertEquals(View.SCROLLBARS_INSIDE_INSET, view.getScrollBarStyle());
         assertEquals(verticalScrollBarWidth, view.getPaddingRight());
-        // issue, mockView.getPaddingBottom() is expected to equal horizontalScrollBarHeight.
-        assertEquals(0, view.getPaddingBottom());
+        assertEquals(horizontalScrollBarHeight, view.getPaddingBottom());
 
         view.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
         assertEquals(View.SCROLLBARS_OUTSIDE_OVERLAY, view.getScrollBarStyle());
@@ -4047,8 +4047,7 @@
         view.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_INSET);
         assertEquals(View.SCROLLBARS_OUTSIDE_INSET, view.getScrollBarStyle());
         assertEquals(verticalScrollBarWidth, view.getPaddingRight());
-        // issue, mockView.getPaddingBottom() is expected to equal horizontalScrollBarHeight.
-        assertEquals(0, view.getPaddingBottom());
+        assertEquals(horizontalScrollBarHeight, view.getPaddingBottom());
 
         // TODO: how to get the position of the Scrollbar to assert it is inside or outside.
     }
@@ -4145,30 +4144,25 @@
     @UiThreadTest
     public void testScrolling() {
         MockView view = (MockView) mActivity.findViewById(R.id.mock_view);
-
         view.reset();
         assertEquals(0, view.getScrollX());
         assertEquals(0, view.getScrollY());
         assertFalse(view.hasCalledOnScrollChanged());
-        assertFalse(view.hasCalledInvalidate());
 
         view.scrollTo(0, 0);
         assertEquals(0, view.getScrollX());
         assertEquals(0, view.getScrollY());
         assertFalse(view.hasCalledOnScrollChanged());
-        assertFalse(view.hasCalledInvalidate());
 
         view.scrollBy(0, 0);
         assertEquals(0, view.getScrollX());
         assertEquals(0, view.getScrollY());
         assertFalse(view.hasCalledOnScrollChanged());
-        assertFalse(view.hasCalledInvalidate());
 
         view.scrollTo(10, 100);
         assertEquals(10, view.getScrollX());
         assertEquals(100, view.getScrollY());
         assertTrue(view.hasCalledOnScrollChanged());
-        assertTrue(view.hasCalledInvalidate());
 
         view.reset();
         assertFalse(view.hasCalledOnScrollChanged());
@@ -4176,7 +4170,6 @@
         assertEquals(0, view.getScrollX());
         assertEquals(0, view.getScrollY());
         assertTrue(view.hasCalledOnScrollChanged());
-        assertTrue(view.hasCalledInvalidate());
 
         view.reset();
         assertFalse(view.hasCalledOnScrollChanged());
@@ -4184,7 +4177,6 @@
         assertEquals(-1, view.getScrollX());
         assertEquals(-2, view.getScrollY());
         assertTrue(view.hasCalledOnScrollChanged());
-        assertTrue(view.hasCalledInvalidate());
     }
 
     @TestTargets({
@@ -4606,6 +4598,11 @@
             return false;
         }
 
+        public ActionMode startActionModeForChild(View originalView,
+                ActionMode.Callback callback) {
+            return null;
+        }
+
         public boolean hasShowContextMenuForChild() {
             return mHasShowContextMenuForChild;
         }
diff --git a/tests/tests/view/src/android/view/cts/View_UsingViewsTest.java b/tests/tests/view/src/android/view/cts/View_UsingViewsTest.java
index 2ea05c4..7bdcfd2 100644
--- a/tests/tests/view/src/android/view/cts/View_UsingViewsTest.java
+++ b/tests/tests/view/src/android/view/cts/View_UsingViewsTest.java
@@ -344,6 +344,8 @@
          * setDuplicateParentStateEnabled
          */
         TextView v = new TextView(mActivity);
+        v.setSingleLine(); // otherwise the multiline state interferes with theses tests
+        v.setEnabled(false);
         v.setText("Test setDuplicateParentStateEnabled");
 
         v.setDuplicateParentStateEnabled(false);
@@ -482,13 +484,14 @@
         mSymbolTextView.setText(ARGENTINA_SYMBOL);
         mWarningTextView.setVisibility(View.VISIBLE);
 
+        assertTrue(mEditText.requestFocus());
         assertTrue(mEditText.hasFocus());
         assertFalse(mButtonOk.hasFocus());
         assertFalse(mButtonCancel.hasFocus());
         assertFalse(mSymbolTextView.hasFocus());
         assertFalse(mWarningTextView.hasFocus());
 
-        assertFalse(editListener.hasFocus());
+        assertTrue(editListener.hasFocus());
         assertFalse(okListener.hasFocus());
         assertFalse(cancelListener.hasFocus());
         assertFalse(symbolListener.hasFocus());
diff --git a/tests/tests/view/src/android/view/cts/WindowManager_LayoutParamsTest.java b/tests/tests/view/src/android/view/cts/WindowManager_LayoutParamsTest.java
index 00b18c1..e2775d0 100644
--- a/tests/tests/view/src/android/view/cts/WindowManager_LayoutParamsTest.java
+++ b/tests/tests/view/src/android/view/cts/WindowManager_LayoutParamsTest.java
@@ -16,6 +16,11 @@
 
 package android.view.cts;
 
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
+
 import android.graphics.PixelFormat;
 import android.os.Binder;
 import android.os.IBinder;
@@ -24,10 +29,6 @@
 import android.text.SpannedString;
 import android.view.Gravity;
 import android.view.WindowManager;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
 
 @TestTargetClass(WindowManager.LayoutParams.class)
 public class WindowManager_LayoutParamsTest extends AndroidTestCase {
@@ -167,18 +168,15 @@
         params.setTitle(PARAMS_TITLE);
         params.alpha = ALPHA - 0.5f;
         params.windowAnimations = WINDOW_ANIMATIONS;
-        params.memoryType = WindowManager.LayoutParams.MEMORY_TYPE_HARDWARE;
         params.dimAmount = DIM_AMOUNT - 1.0f;
         mLayoutParams = new WindowManager.LayoutParams();
         assertEquals(WindowManager.LayoutParams.TITLE_CHANGED
                 | WindowManager.LayoutParams.ALPHA_CHANGED
-                | WindowManager.LayoutParams.MEMORY_TYPE_CHANGED
                 | WindowManager.LayoutParams.ANIMATION_CHANGED
                 | WindowManager.LayoutParams.DIM_AMOUNT_CHANGED,
                 mLayoutParams.copyFrom(params));
         assertEquals(params.getTitle(), mLayoutParams.getTitle());
         assertEquals(params.alpha, mLayoutParams.alpha);
-        assertEquals(params.memoryType, mLayoutParams.memoryType);
         assertEquals(params.dimAmount, mLayoutParams.dimAmount);
 
         params = new WindowManager.LayoutParams();
diff --git a/tests/tests/view/src/android/view/cts/WindowTest.java b/tests/tests/view/src/android/view/cts/WindowTest.java
index 0e31888..f7cdbac 100644
--- a/tests/tests/view/src/android/view/cts/WindowTest.java
+++ b/tests/tests/view/src/android/view/cts/WindowTest.java
@@ -37,7 +37,7 @@
 import android.os.Bundle;
 import android.test.ActivityInstrumentationTestCase2;
 import android.util.DisplayMetrics;
-import android.view.accessibility.AccessibilityEvent;
+import android.view.ActionMode;
 import android.view.Gravity;
 import android.view.InputQueue;
 import android.view.KeyEvent;
@@ -50,6 +50,7 @@
 import android.view.ViewGroup;
 import android.view.Window;
 import android.view.WindowManager;
+import android.view.accessibility.AccessibilityEvent;
 import android.widget.TextView;
 
 @TestTargetClass(Window.class)
@@ -312,69 +313,6 @@
     public void testCloseAllPanels() throws Throwable {
     }
 
-    @TestTargets({
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "closePanel",
-            args = {int.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            method = "openPanel",
-            args = {int.class, android.view.KeyEvent.class}
-        )
-    })
-    public void testOpPanel() throws Throwable {
-        runTestOnUiThread(new Runnable() {
-            public void run() {
-                mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null);
-                assertTrue(mActivity.isOnCreateOptionsMenuCalled());
-                mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);
-                assertTrue(mActivity.isOnOptionsMenuClosedCalled());
-            }
-        });
-        mInstrumentation.waitForIdleSync();
-    }
-
-    /**
-     * togglePanel: When the panel is closing, open it; when open, close it.
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        method = "togglePanel",
-        args = {int.class, android.view.KeyEvent.class}
-    )
-    public void testTogglePanelClose() throws Throwable {
-        runTestOnUiThread(new Runnable() {
-            public void run() {
-                mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null);
-                assertTrue(mActivity.isOnCreateOptionsMenuCalled());
-                // close panel
-                mWindow.togglePanel(Window.FEATURE_OPTIONS_PANEL, null);
-                assertTrue(mActivity.isOnOptionsMenuClosedCalled());
-            }
-        });
-        mInstrumentation.waitForIdleSync();
-    }
-
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        method = "togglePanel",
-        args = {int.class, android.view.KeyEvent.class}
-    )
-    public void testTogglePanelOpen() throws Throwable {
-        runTestOnUiThread(new Runnable() {
-            public void run() {
-                // open panel
-                mWindow.togglePanel(Window.FEATURE_OPTIONS_PANEL, null);
-                assertTrue(mActivity.isOnCreateOptionsMenuCalled());
-                mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);
-                assertTrue(mActivity.isOnOptionsMenuClosedCalled());
-            }
-        });
-        mInstrumentation.waitForIdleSync();
-    }
-
     /**
      * getCurrentFocus: Return the view in this Window that currently has focus, or null if
      *                  there are none.
@@ -443,7 +381,7 @@
         int screenWidth = dm.widthPixels;
         int screenHeight = dm.heightPixels;
         assertEquals(screenWidth, decor.getWidth());
-        assertEquals(screenHeight, decor.getHeight());
+        assertTrue(screenHeight > decor.getHeight());
         assertSame(mWindow.getContext(), decor.getContext());
     }
 
@@ -563,29 +501,6 @@
         assertFalse(mWindow.isFloating());
     }
 
-    /**
-     * isShortcutKey: check if a key is the shortcut key for this window
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "We set 'q' & 'a' key as shortcut key in WindowStubActivity.java,"
-              + " other keys are not shortcut key",
-        method = "isShortcutKey",
-        args = {int.class, android.view.KeyEvent.class}
-    )
-    public void testIsShortcutKey() throws Throwable {
-        runTestOnUiThread(new Runnable() {
-            public void run() {
-                mActivity.openOptionsMenu();
-            }
-        });
-        mInstrumentation.waitForIdleSync();
-        assertTrue(mWindow.isShortcutKey(KeyEvent.KEYCODE_Q, new KeyEvent(KeyEvent.ACTION_DOWN,
-                KeyEvent.KEYCODE_Q)));
-        assertFalse(mWindow.isShortcutKey(KeyEvent.KEYCODE_F, new KeyEvent(KeyEvent.ACTION_DOWN,
-                KeyEvent.KEYCODE_F)));
-    }
-
     @TestTargets({
         @TestTargetNew(
             level = TestLevel.NOT_NECESSARY,
@@ -1148,6 +1063,9 @@
         public void togglePanel(int featureId, KeyEvent event) {
         }
 
+        public void invalidatePanelMenu(int featureId) {
+        }
+
         public boolean performPanelShortcut(int featureId, int keyCode, KeyEvent event, int flags) {
             return true;
         }
@@ -1192,6 +1110,10 @@
             return true;
         }
 
+        public boolean superDispatchKeyShortcutEvent(KeyEvent event) {
+            return false;
+        }
+
         public boolean superDispatchTouchEvent(MotionEvent event) {
             return true;
         }
@@ -1204,6 +1126,9 @@
             return null;
         }
 
+        public void alwaysReadCloseOnTouchAttr() {
+        }
+
         public View peekDecorView() {
             return null;
         }
@@ -1245,11 +1170,11 @@
         public void setDefaultWindowFormat(int format) {
             super.setDefaultWindowFormat(format);
         }
-        
+
         @Override
         public void takeSurface(SurfaceHolder.Callback2 callback) {
         }
-        
+
         @Override
         public void takeInputQueue(InputQueue.Callback callback) {
         }
@@ -1263,6 +1188,10 @@
             return true;
         }
 
+        public boolean dispatchKeyShortcutEvent(KeyEvent event) {
+            return false;
+        }
+
         public boolean dispatchTouchEvent(MotionEvent event) {
             return true;
         }
@@ -1270,7 +1199,7 @@
         public boolean dispatchTrackballEvent(MotionEvent event) {
             return true;
         }
-        
+
         public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
             return true;
         }
@@ -1326,5 +1255,15 @@
         public boolean onSearchRequested() {
             return false;
         }
+
+        public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) {
+            return null;
+        }
+
+        public void onActionModeStarted(ActionMode mode) {
+        }
+
+        public void onActionModeFinished(ActionMode mode) {
+        }
     }
 }
diff --git a/tests/tests/view/src/android/view/inputmethod/cts/BaseInputConnectionTest.java b/tests/tests/view/src/android/view/inputmethod/cts/BaseInputConnectionTest.java
index f5f2286..6241a1e 100644
--- a/tests/tests/view/src/android/view/inputmethod/cts/BaseInputConnectionTest.java
+++ b/tests/tests/view/src/android/view/inputmethod/cts/BaseInputConnectionTest.java
@@ -224,7 +224,7 @@
             args = {int.class, int.class}
         )
     })
-    public void testOpTextMethods() {
+    public void testOpTextMethods() throws Throwable {
         // return is an default Editable instance with empty source
         final Editable text = mConnection.getEditable();
         assertNotNull(text);
@@ -249,6 +249,13 @@
         assertEquals(expected.toString(), mConnection.getTextAfterCursor(offLength,
                 BaseInputConnection.GET_TEXT_WITH_STYLES).toString());
 
+        runTestOnUiThread(new Runnable() {
+            public void run() {
+                assertTrue(mView.requestFocus());
+                assertTrue(mView.isFocused());
+            }
+        });
+
         // dummy mode
         BaseInputConnection dummyConnection = new BaseInputConnection(mView, false);
         dummyConnection.commitText(inputText, inputText.length());
@@ -291,7 +298,7 @@
             args = {CharSequence.class, int.class}
         )
     })
-    public void testFinishComposingText() {
+    public void testFinishComposingText() throws Throwable {
         CharSequence str = "TestFinish";
         Editable inputText = Editable.Factory.getInstance().newEditable(str);
         mConnection.commitText(inputText, inputText.length());
@@ -303,6 +310,14 @@
         mConnection.finishComposingText();
         assertTrue(BaseInputConnection.getComposingSpanStart(text) == -1);
         assertTrue(BaseInputConnection.getComposingSpanEnd(text) == -1);
+
+        runTestOnUiThread(new Runnable() {
+            public void run() {
+                assertTrue(mView.requestFocus());
+                assertTrue(mView.isFocused());
+            }
+        });
+
         // dummy mode
         BaseInputConnection dummyConnection = new BaseInputConnection(mView, false);
         dummyConnection.setComposingText(str, str.length());
@@ -324,7 +339,14 @@
         method = "sendKeyEvent",
         args = {KeyEvent.class}
     )
-    public void testSendKeyEvent() {
+    public void testSendKeyEvent() throws Throwable {
+        runTestOnUiThread(new Runnable() {
+            public void run() {
+                assertTrue(mView.requestFocus());
+                assertTrue(mView.isFocused());
+            }
+        });
+
         mConnection.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_Q));
         new DelayedCheck() {
             @Override
diff --git a/tests/tests/view/src/android/view/inputmethod/cts/InputConnectionWrapperTest.java b/tests/tests/view/src/android/view/inputmethod/cts/InputConnectionWrapperTest.java
index bdee05a..10abe4a 100644
--- a/tests/tests/view/src/android/view/inputmethod/cts/InputConnectionWrapperTest.java
+++ b/tests/tests/view/src/android/view/inputmethod/cts/InputConnectionWrapperTest.java
@@ -26,6 +26,7 @@
 import android.text.TextUtils;
 import android.view.KeyEvent;
 import android.view.inputmethod.CompletionInfo;
+import android.view.inputmethod.CorrectionInfo;
 import android.view.inputmethod.EditorInfo;
 import android.view.inputmethod.ExtractedText;
 import android.view.inputmethod.ExtractedTextRequest;
@@ -164,6 +165,8 @@
         assertTrue(inputConnection.isClearMetaKeyStatesCalled);
         wrapper.commitCompletion(new CompletionInfo(1, 1, "testText"));
         assertTrue(inputConnection.isCommitCompletionCalled);
+        wrapper.commitCorrection(new CorrectionInfo(0, "oldText", "newText"));
+        assertTrue(inputConnection.isCommitCorrectionCalled);
         wrapper.commitText("Text", 1);
         assertTrue(inputConnection.isCommitTextCalled);
         wrapper.deleteSurroundingText(10, 100);
@@ -204,6 +207,7 @@
         public boolean isBeginBatchEditCalled;
         public boolean isClearMetaKeyStatesCalled;
         public boolean isCommitCompletionCalled;
+        public boolean isCommitCorrectionCalled;
         public boolean isCommitTextCalled;
         public boolean isDeleteSurroundingTextCalled;
         public boolean isEndBatchEditCalled;
@@ -237,6 +241,11 @@
             return false;
         }
 
+        public boolean commitCorrection(CorrectionInfo info) {
+            isCommitCorrectionCalled = true;
+            return false;
+        }
+
         public boolean commitText(CharSequence text, int newCursorPosition) {
             isCommitTextCalled = true;
             return false;
diff --git a/tests/tests/view/src/android/view/inputmethod/cts/InputMethodManagerTest.java b/tests/tests/view/src/android/view/inputmethod/cts/InputMethodManagerTest.java
index 5b7940f..92ef3fef 100755
--- a/tests/tests/view/src/android/view/inputmethod/cts/InputMethodManagerTest.java
+++ b/tests/tests/view/src/android/view/inputmethod/cts/InputMethodManagerTest.java
@@ -150,6 +150,8 @@
     public void testInputMethodManager() {
         Window window = mActivity.getWindow();
         EditText view = (EditText) window.findViewById(R.id.entry);
+        assertTrue(view.requestFocus());
+        assertTrue(view.isFocused());
 
         BaseInputConnection connection = new BaseInputConnection(view, false);
         Context context = mInstrumentation.getTargetContext();
diff --git a/tests/tests/webkit/src/android/webkit/cts/CacheManagerTest.java b/tests/tests/webkit/src/android/webkit/cts/CacheManagerTest.java
index 3e9a073..5e0fca5 100644
--- a/tests/tests/webkit/src/android/webkit/cts/CacheManagerTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/CacheManagerTest.java
@@ -125,10 +125,8 @@
         args = {}
     )
     public void testCacheDisabled() {
+        // The cache should always be enabled.
         assertFalse(CacheManager.cacheDisabled());
-
-        // Because setCacheDisabled is package private, we can not call it.
-        // cacheDisabled() always return false. How to let it return true?
     }
 
     private void loadUrl(String url){
diff --git a/tests/tests/webkit/src/android/webkit/cts/CookieManagerTest.java b/tests/tests/webkit/src/android/webkit/cts/CookieManagerTest.java
index ca1b76f..712d641 100755
--- a/tests/tests/webkit/src/android/webkit/cts/CookieManagerTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/CookieManagerTest.java
@@ -107,6 +107,7 @@
         )
     })
     public void testAcceptCookie() throws Exception {
+        mCookieManager.removeAllCookie();
         mCookieManager.setAcceptCookie(false);
         assertFalse(mCookieManager.acceptCookie());
         assertFalse(mCookieManager.hasCookies());
@@ -286,4 +287,14 @@
             }
         }.run();
     }
+
+    public void testb3167208() throws Exception {
+        String uri = "http://host.android.com/path/";
+        // note the space after the domain=
+        String problemCookie = "foo=bar; domain= .android.com; path=/";
+        mCookieManager.setCookie(uri, problemCookie);
+        String cookie = mCookieManager.getCookie(uri);
+        assertNotNull(cookie);
+        assertTrue(cookie.contains("foo=bar"));
+    }
 }
diff --git a/tests/tests/webkit/src/android/webkit/cts/CookieSyncManagerTest.java b/tests/tests/webkit/src/android/webkit/cts/CookieSyncManagerTest.java
index 2f4c35a..ef4d0dc 100644
--- a/tests/tests/webkit/src/android/webkit/cts/CookieSyncManagerTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/CookieSyncManagerTest.java
@@ -62,21 +62,27 @@
         assertSame(csm1, csm2);
 
         final CookieManager cookieManager = CookieManager.getInstance();
-        assertFalse(cookieManager.hasCookies());
+
+        // Remove all cookies from the database.
+        cookieManager.removeAllCookie();
+        new DelayedCheck(30000) {
+            @Override
+            protected boolean check() {
+                return !cookieManager.hasCookies();
+            }
+        }.run();
 
         cookieManager.setAcceptCookie(true);
         assertTrue(cookieManager.acceptCookie());
 
-        String cookieValue = "a = b";
-        cookieManager.setCookie(TestHtmlConstants.HELLO_WORLD_URL, cookieValue);
-        assertEquals(cookieValue, cookieManager.getCookie(TestHtmlConstants.HELLO_WORLD_URL));
-
-        // Cookie is stored in RAM but not in the database.
-        assertFalse(cookieManager.hasCookies());
+        String url = TestHtmlConstants.getFileUrl(TestHtmlConstants.HELLO_WORLD_URL);
+        String cookieValue = "a=b";
+        cookieManager.setCookie(url, cookieValue);
+        assertEquals(cookieValue, cookieManager.getCookie(url));
 
         // Store the cookie to the database.
         csm1.sync();
-        new DelayedCheck(10000) {
+        new DelayedCheck(30000) {
             @Override
             protected boolean check() {
                 return cookieManager.hasCookies();
@@ -85,7 +91,7 @@
 
         // Remove all cookies from the database.
         cookieManager.removeAllCookie();
-        new DelayedCheck(10000) {
+        new DelayedCheck(30000) {
             @Override
             protected boolean check() {
                 return !cookieManager.hasCookies();
diff --git a/tests/tests/webkit/src/android/webkit/cts/CookieTest.java b/tests/tests/webkit/src/android/webkit/cts/CookieTest.java
index a95cd90..14a14d0 100644
--- a/tests/tests/webkit/src/android/webkit/cts/CookieTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/CookieTest.java
@@ -211,24 +211,16 @@
     public void testEmptyValue() {
         String url = "http://www.foobar.com";
 
-        mCookieManager.setCookie(url, "foo;");
-        String cookie = mCookieManager.getCookie(url);
-        assertTrue(cookie.equals("foo"));
-
-        mCookieManager.setCookie(url, "bar");
-        cookie = mCookieManager.getCookie(url);
-        assertTrue(cookie.equals("bar; foo"));
-
         mCookieManager.setCookie(url, "bar=");
-        cookie = mCookieManager.getCookie(url);
-        assertTrue(cookie.equals("bar=; bar; foo"));
+        String cookie = mCookieManager.getCookie(url);
+        assertTrue(cookie.equals("bar="));
 
         mCookieManager.setCookie(url, "foobar=;");
         cookie = mCookieManager.getCookie(url);
-        assertTrue(cookie.equals("bar=; foobar=; bar; foo"));
+        assertTrue(cookie.equals("bar=; foobar="));
 
         mCookieManager.setCookie(url, "baz=; path=/wee");
         cookie = mCookieManager.getCookie(url + "/wee");
-        assertTrue(cookie.equals("baz=; bar=; foobar=; bar; foo"));
+        assertTrue(cookie.equals("baz=; bar=; foobar="));
     }
 }
diff --git a/tests/tests/webkit/src/android/webkit/cts/HttpAuthHandlerTest.java b/tests/tests/webkit/src/android/webkit/cts/HttpAuthHandlerTest.java
index e51f574..8721326 100644
--- a/tests/tests/webkit/src/android/webkit/cts/HttpAuthHandlerTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/HttpAuthHandlerTest.java
@@ -90,7 +90,7 @@
 
         assertLoadUrlSuccessfully(url);
         assertEquals(CtsTestServer.AUTH_REALM, client.realm);
-        assertEquals(CtsTestServer.getReasonString(HttpStatus.SC_FORBIDDEN), mWebView.getTitle());
+        assertEquals(CtsTestServer.getReasonString(HttpStatus.SC_UNAUTHORIZED), mWebView.getTitle());
         assertTrue(client.useHttpAuthUsernamePassword);
 
         // missing credentials
@@ -148,6 +148,7 @@
         private boolean mProceed;
         private String mUser;
         private String mPassword;
+        private int mAuthCount;
 
         MyWebViewClient(boolean proceed, String user, String password) {
             mProceed = proceed;
@@ -157,6 +158,11 @@
 
         public void onReceivedHttpAuthRequest(WebView view,
                 HttpAuthHandler handler, String host, String realm) {
+            ++mAuthCount;
+            if (mAuthCount > 1) {
+                handler.cancel();
+                return;
+            }
             this.realm = realm;
             this.useHttpAuthUsernamePassword = handler.useHttpAuthUsernamePassword();
             if (mProceed) {
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebSettingsTest.java b/tests/tests/webkit/src/android/webkit/cts/WebSettingsTest.java
index 6b9f9dc..9f4f8d0 100644
--- a/tests/tests/webkit/src/android/webkit/cts/WebSettingsTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebSettingsTest.java
@@ -90,9 +90,9 @@
     public void testUserAgentString_default() {
         final String actualUserAgentString = mSettings.getUserAgentString();
         Log.i(LOG_TAG, String.format("Checking user agent string %s", actualUserAgentString));
-        final String patternString = "Mozilla/5\\.0 \\(Linux; U; Android (.+); (\\w+)-(\\w+);" +
-            " (.+) Build/(.+)\\) AppleWebKit/533\\.1 \\(KHTML, like Gecko\\) Version/4\\.0" +
-            " Mobile Safari/533\\.1";
+        final String patternString = "Mozilla/5\\.0 \\(Linux; U; Android (.+); (\\w+)-(\\w+);\\s?" +
+            "(.*)\\sBuild/(.+)\\) AppleWebKit/(\\d+)\\.(\\d+) \\(KHTML, like Gecko\\) Version/4\\.0" +
+            "( Mobile)? Safari/(\\d+)\\.(\\d+)";
         Log.i(LOG_TAG, String.format("Trying to match pattern %s", patternString));
         final Pattern userAgentExpr = Pattern.compile(patternString);
         Matcher patternMatcher = userAgentExpr.matcher(actualUserAgentString);
@@ -103,7 +103,9 @@
         Locale currentLocale = Locale.getDefault();
         assertEquals(currentLocale.getLanguage().toLowerCase(), patternMatcher.group(2));
         assertEquals(currentLocale.getCountry().toLowerCase(), patternMatcher.group(3));
-        assertEquals(Build.MODEL, patternMatcher.group(4));
+        // Model is only added in release builds
+        if ("REL".equals(Build.VERSION.CODENAME))
+            assertEquals(Build.MODEL, patternMatcher.group(4));
         assertEquals(Build.ID, patternMatcher.group(5));
     }
 
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java b/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java
index 0de14e7..5344339 100644
--- a/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java
@@ -31,8 +31,7 @@
 import android.webkit.WebSettings;
 import android.webkit.WebView;
 import android.webkit.WebViewClient;
-import android.webkit.WebChromeClient;
- 
+
 @TestTargetClass(android.webkit.WebViewClient.class)
 public class WebViewClientTest extends ActivityInstrumentationTestCase2<WebViewStubActivity> {
     private static final long TEST_TIMEOUT = 5000;
@@ -48,7 +47,6 @@
     protected void setUp() throws Exception {
         super.setUp();
         mWebView = getActivity().getWebView();
-        mWebView.setWebChromeClient(new WebChromeClient());
     }
 
     @Override
@@ -195,7 +193,7 @@
         mWebServer = new CtsTestServer(getActivity());
 
         assertFalse(webViewClient.hasOnReceivedHttpAuthRequestCalled());
-        String url = mWebServer.getAuthAssetUrl(TestHtmlConstants.HELLO_WORLD_URL);
+        String url = mWebServer.getAuthAssetUrl(TestHtmlConstants.EMBEDDED_IMG_URL);
         assertLoadUrlSuccessfully(mWebView, url);
         assertTrue(webViewClient.hasOnReceivedHttpAuthRequestCalled());
     }
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java b/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java
index b9d054f..6f62cb9 100644
--- a/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java
@@ -47,6 +47,7 @@
 import android.view.View;
 import android.view.animation.cts.DelayedCheck;
 import android.webkit.CacheManager;
+import android.webkit.CacheManager.CacheResult;
 import android.webkit.DownloadListener;
 import android.webkit.SslErrorHandler;
 import android.webkit.WebBackForwardList;
@@ -336,56 +337,15 @@
         )
     })
     public void testScrollBarOverlay() throws Throwable {
-        DisplayMetrics metrics = mWebView.getContext().getResources().getDisplayMetrics();
-        int dimension = 2 * Math.max(metrics.widthPixels, metrics.heightPixels);
-
-        String p = "<p style=\"height:" + dimension + "px;" +
-                "width:" + dimension + "px;margin:0px auto;\">Test scroll bar overlay.</p>";
-        mWebView.loadData("<html><body>" + p + "</body></html>", "text/html", "UTF-8");
-        waitForLoadComplete(mWebView, TEST_TIMEOUT);
+        mWebView.setHorizontalScrollbarOverlay(true);
+        mWebView.setVerticalScrollbarOverlay(false);
         assertTrue(mWebView.overlayHorizontalScrollbar());
         assertFalse(mWebView.overlayVerticalScrollbar());
-        int startX = mWebView.getScrollX();
-        int startY = mWebView.getScrollY();
-
-        final int bigVelocity = 10000;
-        // fling to the max and wait for ending scroll
-        runTestOnUiThread(new Runnable() {
-            public void run() {
-                mWebView.flingScroll(bigVelocity, bigVelocity);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-
-        int overlayOffsetX = mWebView.getScrollX() - startX;
-        int insetOffsetY = mWebView.getScrollY() - startY;
-
-        // scroll back
-        runTestOnUiThread(new Runnable() {
-            public void run() {
-                mWebView.flingScroll(-bigVelocity, -bigVelocity);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
 
         mWebView.setHorizontalScrollbarOverlay(false);
         mWebView.setVerticalScrollbarOverlay(true);
         assertFalse(mWebView.overlayHorizontalScrollbar());
         assertTrue(mWebView.overlayVerticalScrollbar());
-
-        // fling to the max and wait for ending scroll
-        runTestOnUiThread(new Runnable() {
-            public void run() {
-                mWebView.flingScroll(bigVelocity, bigVelocity);
-            }
-        });
-        getInstrumentation().waitForIdleSync();
-
-        int insetOffsetX = mWebView.getScrollX() - startX;
-        int overlayOffsetY = mWebView.getScrollY() - startY;
-
-        assertTrue(overlayOffsetY > insetOffsetY);
-        assertTrue(overlayOffsetX > insetOffsetX);
     }
 
     @TestTargets({
@@ -577,6 +537,108 @@
         }.run();
     }
 
+    @TestTargetNew(
+        level = TestLevel.COMPLETE,
+        method = "addJavascriptInterface",
+        args = {Object.class, String.class}
+    )
+    public void testAddJavascriptInterfaceNullObject() throws Exception {
+        WebSettings settings = mWebView.getSettings();
+        settings.setJavaScriptEnabled(true);
+        String setTitleToPropertyTypeHtml = "<html><head></head>" +
+                "<body onload=\"document.title = typeof window.injectedObject;\"></body></html>";
+
+        // Test that the property is initially undefined.
+        mWebView.loadData(setTitleToPropertyTypeHtml, "text/html", "UTF-8");
+        waitForLoadComplete(mWebView, TEST_TIMEOUT);
+        assertEquals("undefined", mWebView.getTitle());
+
+        // Test that adding a null object has no effect.
+        mWebView.addJavascriptInterface(null, "injectedObject");
+        mWebView.loadData(setTitleToPropertyTypeHtml, "text/html", "UTF-8");
+        waitForLoadComplete(mWebView, TEST_TIMEOUT);
+        assertEquals("undefined", mWebView.getTitle());
+
+        // Test that adding an object gives an object type.
+        final DummyJavaScriptInterface obj = new DummyJavaScriptInterface();
+        mWebView.addJavascriptInterface(obj, "injectedObject");
+        mWebView.loadData(setTitleToPropertyTypeHtml, "text/html", "UTF-8");
+        waitForLoadComplete(mWebView, TEST_TIMEOUT);
+        assertEquals("object", mWebView.getTitle());
+
+        // Test that trying to replace with a null object has no effect.
+        mWebView.addJavascriptInterface(null, "injectedObject");
+        mWebView.loadData(setTitleToPropertyTypeHtml, "text/html", "UTF-8");
+        waitForLoadComplete(mWebView, TEST_TIMEOUT);
+        assertEquals("object", mWebView.getTitle());
+    }
+
+    @TestTargets({
+        @TestTargetNew(
+            level = TestLevel.COMPLETE,
+            method = "addJavascriptInterface",
+            args = {Object.class, String.class}
+        ),
+        @TestTargetNew(
+            level = TestLevel.COMPLETE,
+            method = "removeJavascriptInterface",
+            args = {String.class}
+        )
+    })
+    public void testAddJavascriptInterfaceOddName() throws Exception {
+        WebSettings settings = mWebView.getSettings();
+        settings.setJavaScriptEnabled(true);
+        final DummyJavaScriptInterface obj = new DummyJavaScriptInterface();
+
+        // We should be able to use any character other than a single quote.
+        // TODO: We currently fail when the name contains '#', '\', '\n' or '\r'.
+        // See b/3279426
+        //String oddNames[] = {" x y ", "`!\"$%^&*()-=_+[]{};#:@~\\|,./<>?\n\r ", " ", "\n", ""};
+        String oddNames[] = {" x y ", "`!\"$%^&*()-=_+[]{};:@~|,./<>? ", " ", ""};
+        for (String name : oddNames) {
+            String setTitleToPropertyTypeHtml = "<html><head>" +
+                    "<script>function updateTitle() { document.title = typeof window['" +
+                    name +
+                    "']; }</script>" +
+                    "</head><body onload=\"updateTitle();\"></body></html>";
+
+            mWebView.addJavascriptInterface(obj, name);
+            mWebView.loadData(setTitleToPropertyTypeHtml, "text/html", "UTF-8");
+            waitForLoadComplete(mWebView, TEST_TIMEOUT);
+            assertEquals("object", mWebView.getTitle());
+
+            mWebView.removeJavascriptInterface(name);
+            mWebView.loadData(setTitleToPropertyTypeHtml, "text/html", "UTF-8");
+            waitForLoadComplete(mWebView, TEST_TIMEOUT);
+            assertEquals("undefined", mWebView.getTitle());
+        }
+    }
+
+    @TestTargetNew(
+        level = TestLevel.COMPLETE,
+        method = "removeJavascriptInterface",
+        args = {String.class}
+    )
+    public void testRemoveJavascriptInterface() throws Exception {
+        WebSettings settings = mWebView.getSettings();
+        settings.setJavaScriptEnabled(true);
+        String setTitleToPropertyTypeHtml = "<html><head></head>" +
+                "<body onload=\"document.title = typeof window.injectedObject;\"></body></html>";
+
+        // Test that adding an object gives an object type.
+        final DummyJavaScriptInterface obj = new DummyJavaScriptInterface();
+        mWebView.addJavascriptInterface(obj, "injectedObject");
+        mWebView.loadData(setTitleToPropertyTypeHtml, "text/html", "UTF-8");
+        waitForLoadComplete(mWebView, TEST_TIMEOUT);
+        assertEquals("object", mWebView.getTitle());
+
+        // Test that removing the object leaves the property undefined.
+        mWebView.removeJavascriptInterface("injectedObject");
+        mWebView.loadData(setTitleToPropertyTypeHtml, "text/html", "UTF-8");
+        waitForLoadComplete(mWebView, TEST_TIMEOUT);
+        assertEquals("undefined", mWebView.getTitle());
+    }
+
     @TestTargets({
         @TestTargetNew(
             level = TestLevel.COMPLETE,
@@ -1149,8 +1211,16 @@
         assertEquals(0, cacheFileBaseDir.list().length);
 
         startWebServer(false);
-        mWebView.loadUrl(mWebServer.getAssetUrl(TestHtmlConstants.HELLO_WORLD_URL));
+        final String url = mWebServer.getAssetUrl(TestHtmlConstants.HELLO_WORLD_URL);
+        mWebView.loadUrl(url);
         waitForLoadComplete(mWebView, TEST_TIMEOUT);
+        new DelayedCheck(TEST_TIMEOUT) {
+            @Override
+            protected boolean check() {
+                CacheResult result = CacheManager.getCacheFile(url, null);
+                return result != null;
+            }
+        }.run();
         int cacheFileCount = cacheFileBaseDir.list().length;
         assertTrue(cacheFileCount > 0);
 
diff --git a/tests/tests/widget/src/android/widget/cts/AbsListViewTest.java b/tests/tests/widget/src/android/widget/cts/AbsListViewTest.java
index 4bf19d2..0995f28 100644
--- a/tests/tests/widget/src/android/widget/cts/AbsListViewTest.java
+++ b/tests/tests/widget/src/android/widget/cts/AbsListViewTest.java
@@ -199,6 +199,55 @@
         });
         mInstrumentation.waitForIdleSync();
     }
+    @TestTargetNew(
+        level = TestLevel.COMPLETE,
+        method = "setOnScrollListener",
+        args = {android.widget.AbsListView.OnScrollListener.class}
+    )
+    public void testSetOnScrollListener() throws Throwable {
+        MockOnScrollListener onScrollListener = new MockOnScrollListener();
+
+        assertNull(onScrollListener.getView());
+        assertEquals(0, onScrollListener.getFirstVisibleItem());
+        assertEquals(0, onScrollListener.getVisibleItemCount());
+        assertEquals(0, onScrollListener.getTotalItemCount());
+        assertEquals(-1, onScrollListener.getScrollState());
+
+        assertFalse(onScrollListener.isOnScrollCalled());
+        assertFalse(onScrollListener.isOnScrollStateChangedCalled());
+
+        mListView.setOnScrollListener(onScrollListener);
+        assertSame(mListView, onScrollListener.getView());
+        assertEquals(0, onScrollListener.getFirstVisibleItem());
+        assertEquals(0, onScrollListener.getVisibleItemCount());
+        assertEquals(0, onScrollListener.getTotalItemCount());
+        assertEquals(-1, onScrollListener.getScrollState());
+
+        assertTrue(onScrollListener.isOnScrollCalled());
+        assertFalse(onScrollListener.isOnScrollStateChangedCalled());
+        onScrollListener.reset();
+
+        setAdapter();
+
+        assertSame(mListView, onScrollListener.getView());
+        assertEquals(0, onScrollListener.getFirstVisibleItem());
+        assertEquals(mListView.getChildCount(), onScrollListener.getVisibleItemCount());
+        assertEquals(mCountryList.length, onScrollListener.getTotalItemCount());
+        assertEquals(-1, onScrollListener.getScrollState());
+
+        assertTrue(onScrollListener.isOnScrollCalled());
+        assertFalse(onScrollListener.isOnScrollStateChangedCalled());
+        onScrollListener.reset();
+
+        TouchUtils.scrollToBottom(this, mActivity, mListView);
+        assertSame(mListView, onScrollListener.getView());
+        assertEquals(mListView.getChildCount(), onScrollListener.getVisibleItemCount());
+        assertEquals(mCountryList.length, onScrollListener.getTotalItemCount());
+        assertEquals(OnScrollListener.SCROLL_STATE_IDLE, onScrollListener.getScrollState());
+
+        assertTrue(onScrollListener.isOnScrollCalled());
+        assertTrue(onScrollListener.isOnScrollStateChangedCalled());
+    }
 
     @TestTargetNew(
         level = TestLevel.COMPLETE,
diff --git a/tests/tests/widget/src/android/widget/cts/AdapterViewTest.java b/tests/tests/widget/src/android/widget/cts/AdapterViewTest.java
old mode 100755
new mode 100644
index 12815b2..97a5753
--- a/tests/tests/widget/src/android/widget/cts/AdapterViewTest.java
+++ b/tests/tests/widget/src/android/widget/cts/AdapterViewTest.java
@@ -310,9 +310,8 @@
         setArrayAdapter(mAdapterView);
 
         // LastVisiblePosition should be adapter's getCount - 1,by mocking method
-        float density = mActivity.getResources().getDisplayMetrics().density;
-        int bottom = (int) (LAYOUT_HEIGHT * density);
-        mAdapterView.layout(0, 0, LAYOUT_WIDTH, bottom);
+        // TODO: the +50 is a gross hack
+        mAdapterView.layout(0, 0, LAYOUT_WIDTH, LAYOUT_HEIGHT+50);
         assertEquals(FRUIT.length - 1, mAdapterView.getLastVisiblePosition());
     }
 
diff --git a/tests/tests/widget/src/android/widget/cts/AutoCompleteTextViewTest.java b/tests/tests/widget/src/android/widget/cts/AutoCompleteTextViewTest.java
index a8c9ae0..27a285a 100644
--- a/tests/tests/widget/src/android/widget/cts/AutoCompleteTextViewTest.java
+++ b/tests/tests/widget/src/android/widget/cts/AutoCompleteTextViewTest.java
@@ -16,7 +16,13 @@
 
 package android.widget.cts;
 
-import java.io.IOException;
+import com.android.cts.stub.R;
+
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
+import dalvik.annotation.ToBeFixed;
 
 import org.xmlpull.v1.XmlPullParser;
 import org.xmlpull.v1.XmlPullParserException;
@@ -39,13 +45,7 @@
 import android.widget.Filterable;
 import android.widget.AutoCompleteTextView.Validator;
 
-import com.android.cts.stub.R;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.ToBeFixed;
+import java.io.IOException;
 
 @TestTargetClass(AutoCompleteTextView.class)
 public class AutoCompleteTextViewTest extends
@@ -499,8 +499,6 @@
         // Set Threshold to 4 characters
         mAutoCompleteTextView.setThreshold(4);
 
-        inflatePopup();
-        assertTrue(mAutoCompleteTextView.isPopupShowing());
         String testString = "tes";
         // Test the filter if the input string is not long enough to threshold
         runTestOnUiThread(new Runnable() {
@@ -515,8 +513,6 @@
         // onFilterComplete will close the popup.
         assertFalse(mAutoCompleteTextView.isPopupShowing());
 
-        inflatePopup();
-        assertTrue(mAutoCompleteTextView.isPopupShowing());
         testString = "that";
         mInstrumentation.sendStringSync(testString);
         assertFalse(mAutoCompleteTextView.isPopupShowing());
@@ -555,11 +551,16 @@
             public void run() {
                 mAutoCompleteTextView.setAdapter(mAdapter);
                 mAutoCompleteTextView.setValidator(mValidator);
-                mAutoCompleteTextView.setAdapter(mAdapter);
+
+                mAutoCompleteTextView.setText("test");
+                mAutoCompleteTextView.setFocusable(true);
+                mAutoCompleteTextView.requestFocus();
+                mAutoCompleteTextView.showDropDown();
             }
         });
-        inflatePopup();
+        mInstrumentation.waitForIdleSync();
         assertTrue(mAutoCompleteTextView.isPopupShowing());
+
         mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
         // KeyBack will close the popup.
         assertFalse(mAutoCompleteTextView.isPopupShowing());
@@ -974,18 +975,6 @@
         }
     }
 
-    private void inflatePopup() throws Throwable {
-        runTestOnUiThread(new Runnable() {
-            public void run() {
-                mAutoCompleteTextView.setText("");
-                mAutoCompleteTextView.setFocusable(true);
-                mAutoCompleteTextView.requestFocus();
-                mAutoCompleteTextView.showDropDown();
-            }
-        });
-        mInstrumentation.waitForIdleSync();
-    }
-
     private static class MockFilter extends Filter {
         private String mFilterResult;
 
diff --git a/tests/tests/widget/src/android/widget/cts/CompoundButtonTest.java b/tests/tests/widget/src/android/widget/cts/CompoundButtonTest.java
index 27c967d..cf15efd 100644
--- a/tests/tests/widget/src/android/widget/cts/CompoundButtonTest.java
+++ b/tests/tests/widget/src/android/widget/cts/CompoundButtonTest.java
@@ -317,9 +317,9 @@
         // compoundButton is checked, append R.attr.state_checked to state array.
         compoundButton.setChecked(true);
         int[] checkedState = compoundButton.onCreateDrawableState(0);
-        assertEquals(2, checkedState.length);
         assertEquals(state[0], checkedState[0]);
-        assertEquals(com.android.internal.R.attr.state_checked, checkedState[1]);
+        assertEquals(com.android.internal.R.attr.state_checked,
+                checkedState[checkedState.length - 1]);
 
         // compoundButton is not checked again.
         compoundButton.setChecked(false);
@@ -339,7 +339,8 @@
         int drawableHeight;
         Rect bounds;
         Drawable drawable;
-        Canvas canvas = new Canvas();
+        Canvas canvas = new Canvas(android.graphics.Bitmap.createBitmap(100, 100,
+                android.graphics.Bitmap.Config.ARGB_8888));
         MockCompoundButton compoundButton;
 
         // onDraw when there is no drawable
diff --git a/tests/tests/widget/src/android/widget/cts/DialerFilterTest.java b/tests/tests/widget/src/android/widget/cts/DialerFilterTest.java
index 0b436b2..8d8e4c28 100644
--- a/tests/tests/widget/src/android/widget/cts/DialerFilterTest.java
+++ b/tests/tests/widget/src/android/widget/cts/DialerFilterTest.java
@@ -113,10 +113,13 @@
         mInstrumentation.runOnMainSync(new Runnable() {
             public void run() {
                 mDialerFilter.setMode(DialerFilter.DIGITS_ONLY);
+                mDialerFilter.requestFocus();
             }
         });
         mInstrumentation.waitForIdleSync();
 
+        assertTrue(mDialerFilter.hasFocus());
+
         mInstrumentation.sendStringSync("123");
         assertEquals("", mDialerFilter.getLetters().toString());
         assertEquals("123", mDialerFilter.getDigits().toString());
diff --git a/tests/tests/widget/src/android/widget/cts/ExpandableListTester.java b/tests/tests/widget/src/android/widget/cts/ExpandableListTester.java
new file mode 100644
index 0000000..8175807
--- /dev/null
+++ b/tests/tests/widget/src/android/widget/cts/ExpandableListTester.java
@@ -0,0 +1,241 @@
+/*
+ * Copyright (C) 2007 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 android.app.Instrumentation;
+import android.test.ActivityInstrumentationTestCase2;
+import android.view.KeyEvent;
+import android.view.View;
+import android.widget.ExpandableListAdapter;
+import android.widget.ExpandableListView;
+import android.widget.cts.util.ExpandableListScenario;
+import android.widget.cts.util.ListUtil;
+
+import junit.framework.Assert;
+
+public class ExpandableListTester {
+    private final ExpandableListView mExpandableListView;
+    private final ExpandableListAdapter mAdapter;
+    private final ListUtil mListUtil;
+
+    private final ActivityInstrumentationTestCase2<? extends ExpandableListScenario>
+        mActivityInstrumentation;
+
+    Instrumentation mInstrumentation;
+
+    public ExpandableListTester(
+            ExpandableListView expandableListView,
+            ActivityInstrumentationTestCase2<? extends ExpandableListScenario>
+            activityInstrumentation) {
+        mExpandableListView = expandableListView;
+        Instrumentation instrumentation = activityInstrumentation.getInstrumentation();
+        mListUtil = new ListUtil(mExpandableListView, instrumentation);
+        mAdapter = mExpandableListView.getExpandableListAdapter();
+        mActivityInstrumentation = activityInstrumentation;
+        mInstrumentation = mActivityInstrumentation.getInstrumentation();
+    }
+
+    private void expandGroup(final int groupIndex, int flatPosition) {
+        Assert.assertFalse("Group is already expanded", mExpandableListView
+                .isGroupExpanded(groupIndex));
+        mListUtil.arrowScrollToSelectedPosition(flatPosition);
+        mInstrumentation.waitForIdleSync();
+        mActivityInstrumentation.sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
+        mActivityInstrumentation.getInstrumentation().waitForIdleSync();
+        Assert.assertTrue("Group did not expand " + groupIndex, 
+                mExpandableListView.isGroupExpanded(groupIndex));
+    }
+
+    void testContextMenus() {
+        // Add a position tester ContextMenu listener to the ExpandableListView
+        PositionTesterContextMenuListener menuListener = new PositionTesterContextMenuListener();
+        mExpandableListView.setOnCreateContextMenuListener(menuListener);
+
+        int index = 0;
+
+        // Scrolling on header elements should trigger an AdapterContextMenu
+        for (int i=0; i<mExpandableListView.getHeaderViewsCount(); i++) {
+            // Check group index in context menu
+            menuListener.expectAdapterContextMenu(i);
+            // Make sure the group is visible so that getChild finds it
+            mListUtil.arrowScrollToSelectedPosition(index);
+            View headerChild = mExpandableListView.getChildAt(index
+                    - mExpandableListView.getFirstVisiblePosition());
+            mExpandableListView.showContextMenuForChild(headerChild);
+            mInstrumentation.waitForIdleSync();
+            Assert.assertNull(menuListener.getErrorMessage(), menuListener.getErrorMessage());
+            index++;
+        }
+
+        int groupCount = mAdapter.getGroupCount();
+        for (int groupIndex = 0; groupIndex < groupCount; groupIndex++) {
+
+            // Expand group
+            expandGroup(groupIndex, index);
+
+            // Check group index in context menu
+            menuListener.expectGroupContextMenu(groupIndex);
+            // Make sure the group is visible so that getChild finds it
+            mListUtil.arrowScrollToSelectedPosition(index);
+            View groupChild = mExpandableListView.getChildAt(index
+                    - mExpandableListView.getFirstVisiblePosition());
+            mExpandableListView.showContextMenuForChild(groupChild);
+            mInstrumentation.waitForIdleSync();
+            Assert.assertNull(menuListener.getErrorMessage(), menuListener.getErrorMessage());
+            index++;
+
+            final int childrenCount = mAdapter.getChildrenCount(groupIndex);
+            for (int childIndex = 0; childIndex < childrenCount; childIndex++) {
+                // Check child index in context menu
+                mListUtil.arrowScrollToSelectedPosition(index);
+                menuListener.expectChildContextMenu(groupIndex, childIndex);
+                View child = mExpandableListView.getChildAt(index
+                        - mExpandableListView.getFirstVisiblePosition());
+                mExpandableListView.showContextMenuForChild(child);
+                mInstrumentation.waitForIdleSync();
+                Assert.assertNull(menuListener.getErrorMessage(), menuListener.getErrorMessage());
+                index++;
+            }
+        }
+
+        // Scrolling on footer elements should trigger an AdapterContextMenu
+        for (int i=0; i<mExpandableListView.getFooterViewsCount(); i++) {
+            // Check group index in context menu
+            menuListener.expectAdapterContextMenu(index);
+            // Make sure the group is visible so that getChild finds it
+            mListUtil.arrowScrollToSelectedPosition(index);
+            View footerChild = mExpandableListView.getChildAt(index
+                    - mExpandableListView.getFirstVisiblePosition());
+            mExpandableListView.showContextMenuForChild(footerChild);
+            mInstrumentation.waitForIdleSync();
+            Assert.assertNull(menuListener.getErrorMessage(), menuListener.getErrorMessage());
+            index++;
+        }
+
+        // Cleanup: remove the listener we added.
+        mExpandableListView.setOnCreateContextMenuListener(null);
+    }
+
+    private int expandAGroup() {
+        final int groupIndex = 2;
+        final int headerCount = mExpandableListView.getHeaderViewsCount();
+        Assert.assertTrue("Not enough groups", groupIndex < mAdapter.getGroupCount());
+        expandGroup(groupIndex, groupIndex + headerCount);
+        return groupIndex;
+    }
+
+    // This method assumes that NO group is expanded when called
+    void testConvertionBetweenFlatAndPackedOnGroups() {
+        final int headerCount = mExpandableListView.getHeaderViewsCount();
+
+        for (int i=0; i<headerCount; i++) {
+            Assert.assertEquals("Non NULL position for header item",
+                    ExpandableListView.PACKED_POSITION_VALUE_NULL,
+                    mExpandableListView.getExpandableListPosition(i));
+        }
+
+        // Test all (non expanded) groups
+        final int groupCount = mAdapter.getGroupCount();
+        for (int groupIndex = 0; groupIndex < groupCount; groupIndex++) {
+            int expectedFlatPosition = headerCount + groupIndex;
+            long packedPositionForGroup = ExpandableListView.getPackedPositionForGroup(groupIndex);
+            Assert.assertEquals("Group not found at flat position " + expectedFlatPosition,
+                    packedPositionForGroup,
+                    mExpandableListView.getExpandableListPosition(expectedFlatPosition));
+
+            Assert.assertEquals("Wrong flat position for group " + groupIndex,
+                    expectedFlatPosition,
+                    mExpandableListView.getFlatListPosition(packedPositionForGroup));
+        }
+
+        for (int i=0; i<mExpandableListView.getFooterViewsCount(); i++) {
+            Assert.assertEquals("Non NULL position for header item",
+                    ExpandableListView.PACKED_POSITION_VALUE_NULL,
+                    mExpandableListView.getExpandableListPosition(headerCount + groupCount + i));
+        }
+    }
+
+    // This method assumes that NO group is expanded when called
+    void testConvertionBetweenFlatAndPackedOnChildren() {
+        // Test with an expanded group
+        final int headerCount = mExpandableListView.getHeaderViewsCount();
+        final int groupIndex = expandAGroup();
+
+        final int childrenCount = mAdapter.getChildrenCount(groupIndex);
+        for (int childIndex = 0; childIndex < childrenCount; childIndex++) {
+            int expectedFlatPosition = headerCount + groupIndex + 1 + childIndex;
+            long childPos = ExpandableListView.getPackedPositionForChild(groupIndex, childIndex);
+
+            Assert.assertEquals("Wrong flat position for child ",
+                    childPos,
+                    mExpandableListView.getExpandableListPosition(expectedFlatPosition));
+
+            Assert.assertEquals("Wrong flat position for child ",
+                    expectedFlatPosition,
+                    mExpandableListView.getFlatListPosition(childPos));
+        }
+    }
+
+    // This method assumes that NO group is expanded when called
+    void testSelectedPositionOnGroups() {
+        int index = 0;
+
+        // Scrolling on header elements should not give a valid selected position.
+        for (int i=0; i<mExpandableListView.getHeaderViewsCount(); i++) {
+            mListUtil.arrowScrollToSelectedPosition(index);
+            Assert.assertEquals("Header item is selected",
+                    ExpandableListView.PACKED_POSITION_VALUE_NULL,
+                    mExpandableListView.getSelectedPosition());
+            index++;
+        }
+
+        // Check selection on group items
+        final int groupCount = mAdapter.getGroupCount();
+        for (int groupIndex = 0; groupIndex < groupCount; groupIndex++) {
+            mListUtil.arrowScrollToSelectedPosition(index);
+            Assert.assertEquals("Group item is not selected",
+                    ExpandableListView.getPackedPositionForGroup(groupIndex),
+                    mExpandableListView.getSelectedPosition());
+            index++;
+        }
+
+        // Scrolling on footer elements should not give a valid selected position.
+        for (int i=0; i<mExpandableListView.getFooterViewsCount(); i++) {
+            mListUtil.arrowScrollToSelectedPosition(index);
+            Assert.assertEquals("Footer item is selected",
+                    ExpandableListView.PACKED_POSITION_VALUE_NULL,
+                    mExpandableListView.getSelectedPosition());
+            index++;
+        }
+    }
+
+    // This method assumes that NO group is expanded when called
+    void testSelectedPositionOnChildren() {
+        // Test with an expanded group
+        final int headerCount = mExpandableListView.getHeaderViewsCount();
+        final int groupIndex = expandAGroup();
+
+        final int childrenCount = mAdapter.getChildrenCount(groupIndex);
+        for (int childIndex = 0; childIndex < childrenCount; childIndex++) {
+            int childFlatPosition = headerCount + groupIndex + 1 + childIndex;
+            mListUtil.arrowScrollToSelectedPosition(childFlatPosition);
+            Assert.assertEquals("Group item is not selected",
+                    ExpandableListView.getPackedPositionForChild(groupIndex, childIndex),
+                    mExpandableListView.getSelectedPosition());
+        }
+    }
+}
diff --git a/tests/tests/widget/src/android/widget/cts/ExpandableListViewBasicTest.java b/tests/tests/widget/src/android/widget/cts/ExpandableListViewBasicTest.java
index c6c0b35..fc39364 100644
--- a/tests/tests/widget/src/android/widget/cts/ExpandableListViewBasicTest.java
+++ b/tests/tests/widget/src/android/widget/cts/ExpandableListViewBasicTest.java
@@ -16,7 +16,10 @@
 
 package android.widget.cts;
 
-import java.util.List;
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
 
 import android.test.ActivityInstrumentationTestCase2;
 import android.test.suitebuilder.annotation.MediumTest;
@@ -27,21 +30,19 @@
 import android.widget.cts.util.ExpandableListScenario;
 import android.widget.cts.util.ListUtil;
 import android.widget.cts.util.ExpandableListScenario.MyGroup;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
+
+import java.util.List;
 
 @TestTargetClass(ExpandableListView.class)
 public class ExpandableListViewBasicTest extends
         ActivityInstrumentationTestCase2<ExpandableListSimple> {
     private ExpandableListScenario mActivity;
-    private ExpandableListView mListView;
+    private ExpandableListView mExpandableListView;
     private ExpandableListAdapter mAdapter;
     private ListUtil mListUtil;
 
     public ExpandableListViewBasicTest() {
-        super("com.android.cts.stub", ExpandableListSimple.class);
+        super(ExpandableListSimple.class);
     }
 
     @Override
@@ -49,27 +50,27 @@
         super.setUp();
 
         mActivity = getActivity();
-        mListView = mActivity.getExpandableListView();
-        mAdapter = mListView.getExpandableListAdapter();
-        mListUtil = new ListUtil(mListView, getInstrumentation());
+        mExpandableListView = mActivity.getExpandableListView();
+        mAdapter = mExpandableListView.getExpandableListAdapter();
+        mListUtil = new ListUtil(mExpandableListView, getInstrumentation());
     }
 
     @MediumTest
     public void testPreconditions() {
         assertNotNull(mActivity);
-        assertNotNull(mListView);
+        assertNotNull(mExpandableListView);
     }
 
     private int expandGroup(int numChildren, boolean atLeastOneChild) {
         final int groupPos = mActivity.findGroupWithNumChildren(numChildren, atLeastOneChild);
 
         assertTrue("Could not find group to expand", groupPos >= 0);
-        assertFalse("Group is already expanded", mListView.isGroupExpanded(groupPos));
+        assertFalse("Group is already expanded", mExpandableListView.isGroupExpanded(groupPos));
         mListUtil.arrowScrollToSelectedPosition(groupPos);
         getInstrumentation().waitForIdleSync();
         sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
         getInstrumentation().waitForIdleSync();
-        assertTrue("Group did not expand", mListView.isGroupExpanded(groupPos));
+        assertTrue("Group did not expand", mExpandableListView.isGroupExpanded(groupPos));
 
         return groupPos;
     }
@@ -97,7 +98,7 @@
 
         sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
         getInstrumentation().waitForIdleSync();
-        assertFalse("Group did not collapse", mListView.isGroupExpanded(groupPos));
+        assertFalse("Group did not collapse", mExpandableListView.isGroupExpanded(groupPos));
     }
 
     @TestTargets({
@@ -122,13 +123,13 @@
         getInstrumentation().waitForIdleSync();
 
         // Ensure it expanded
-        assertTrue("Group did not expand", mListView.isGroupExpanded(0));
+        assertTrue("Group did not expand", mExpandableListView.isGroupExpanded(0));
 
         // Wait until that's all good
         getInstrumentation().waitForIdleSync();
 
         // Make sure it expanded
-        assertTrue("Group did not expand", mListView.isGroupExpanded(0));
+        assertTrue("Group did not expand", mExpandableListView.isGroupExpanded(0));
 
         // Insert a collapsed group in front of the one just expanded
         List<MyGroup> groups = mActivity.getGroups();
@@ -149,8 +150,28 @@
 
         // Make sure the right group is expanded
         assertTrue("The expanded state didn't stay with the proper group",
-                mListView.isGroupExpanded(1));
+                mExpandableListView.isGroupExpanded(1));
         assertFalse("The expanded state was given to the inserted group",
-                mListView.isGroupExpanded(0));
+                mExpandableListView.isGroupExpanded(0));
+    }
+
+    @MediumTest
+    public void testContextMenus() {
+        ExpandableListTester tester = new ExpandableListTester(mExpandableListView, this);
+        tester.testContextMenus();
+    }
+
+    @MediumTest
+    public void testConvertionBetweenFlatAndPacked() {
+        ExpandableListTester tester = new ExpandableListTester(mExpandableListView, this);
+        tester.testConvertionBetweenFlatAndPackedOnGroups();
+        tester.testConvertionBetweenFlatAndPackedOnChildren();
+    }
+
+    @MediumTest
+    public void testSelectedPosition() {
+        ExpandableListTester tester = new ExpandableListTester(mExpandableListView, this);
+        tester.testSelectedPositionOnGroups();
+        tester.testSelectedPositionOnChildren();
     }
 }
diff --git a/tests/tests/widget/src/android/widget/cts/ExpandableListViewTest.java b/tests/tests/widget/src/android/widget/cts/ExpandableListViewTest.java
index af420b4..5ab7f4d 100644
--- a/tests/tests/widget/src/android/widget/cts/ExpandableListViewTest.java
+++ b/tests/tests/widget/src/android/widget/cts/ExpandableListViewTest.java
@@ -519,10 +519,10 @@
         args = {int.class, int.class}
     )
     public void testGetPackedPositionForChild() {
-        assertEquals((long) 0x8000000000000000L,
+        assertEquals(0x8000000000000000L,
                 ExpandableListView.getPackedPositionForChild(0, 0));
 
-        assertEquals((long) 0xffffffffffffffffL,
+        assertEquals(0xffffffffffffffffL,
                 ExpandableListView.getPackedPositionForChild(Integer.MAX_VALUE, 0xffffffff));
     }
 
diff --git a/tests/tests/widget/src/android/widget/cts/ExpandableListViewWithHeadersTest.java b/tests/tests/widget/src/android/widget/cts/ExpandableListViewWithHeadersTest.java
index 57776a0..fe65f98 100644
--- a/tests/tests/widget/src/android/widget/cts/ExpandableListViewWithHeadersTest.java
+++ b/tests/tests/widget/src/android/widget/cts/ExpandableListViewWithHeadersTest.java
@@ -16,16 +16,16 @@
 
 package android.widget.cts;
 
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+
 import android.test.ActivityInstrumentationTestCase2;
 import android.test.suitebuilder.annotation.LargeTest;
 import android.test.suitebuilder.annotation.MediumTest;
 import android.view.KeyEvent;
 import android.widget.ExpandableListView;
 import android.widget.cts.util.ListUtil;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
 
 @TestTargetClass(ExpandableListView.class)
 public class ExpandableListViewWithHeadersTest extends
@@ -34,7 +34,7 @@
     private ListUtil mListUtil;
 
     public ExpandableListViewWithHeadersTest() {
-        super("com.android.cts.stub", ExpandableListWithHeaders.class);
+        super(ExpandableListWithHeaders.class);
     }
 
     @Override
@@ -78,4 +78,24 @@
         getInstrumentation().waitForIdleSync();
         assertTrue(mExpandableListView.isGroupExpanded(0));
     }
+
+    @MediumTest
+    public void testContextMenus() {
+        ExpandableListTester tester = new ExpandableListTester(mExpandableListView, this);
+        tester.testContextMenus();
+    }
+
+    @MediumTest
+    public void testConvertionBetweenFlatAndPacked() {
+        ExpandableListTester tester = new ExpandableListTester(mExpandableListView, this);
+        tester.testConvertionBetweenFlatAndPackedOnGroups();
+        tester.testConvertionBetweenFlatAndPackedOnChildren();
+    }
+
+    @MediumTest
+    public void testSelectedPosition() {
+        ExpandableListTester tester = new ExpandableListTester(mExpandableListView, this);
+        tester.testSelectedPositionOnGroups();
+        tester.testSelectedPositionOnChildren();
+    }
 }
diff --git a/tests/tests/widget/src/android/widget/cts/GridViewTest.java b/tests/tests/widget/src/android/widget/cts/GridViewTest.java
index 57b5804..802aa96 100644
--- a/tests/tests/widget/src/android/widget/cts/GridViewTest.java
+++ b/tests/tests/widget/src/android/widget/cts/GridViewTest.java
@@ -16,6 +16,14 @@
 
 package android.widget.cts;
 
+import com.android.cts.stub.R;
+
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
+import dalvik.annotation.ToBeFixed;
+
 import org.xmlpull.v1.XmlPullParser;
 
 import android.app.Activity;
@@ -44,14 +52,6 @@
 import android.widget.ListAdapter;
 import android.widget.AdapterView.OnItemClickListener;
 
-import com.android.cts.stub.R;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.ToBeFixed;
-
 /**
  * Test {@link GridView}.
  */
@@ -72,7 +72,6 @@
     @Override
     protected void setUp() throws Exception {
         super.setUp();
-
         mGridView = null;
         mActivity = getActivity();
         mInstrumentation = getInstrumentation();
@@ -310,6 +309,7 @@
     )
     public void testSetHorizontalSpacing() {
         mGridView = findGridViewById(R.id.gridview);
+        mGridView.setStretchMode(GridView.NO_STRETCH);
         // Number of columns should be big enough, otherwise the
         // horizontal spacing cannot be correctly verified.
         mGridView.setNumColumns(20);
@@ -534,6 +534,48 @@
 
     @TestTargetNew(
         level = TestLevel.COMPLETE,
+        notes = "Test {@link GridView#getNumColumns()}",
+        method = "getNumColumns"
+    )
+    public void testGetNumColumns() {
+        mGridView = new GridView(mActivity);
+
+        assertEquals(mGridView.getNumColumns(), GridView.AUTO_FIT);
+
+        mGridView = findGridViewById(R.id.gridview);
+
+        mActivity.runOnUiThread(new Runnable() {
+            public void run() {
+                mGridView.setAdapter(new MockGridViewAdapter(10));
+                mGridView.setNumColumns(10);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+
+        assertEquals(mGridView.getNumColumns(), 10);
+
+        mActivity.runOnUiThread(new Runnable() {
+            public void run() {
+                mGridView.setNumColumns(1);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+
+        assertEquals(mGridView.getNumColumns(), 1);
+
+        mActivity.runOnUiThread(new Runnable() {
+            public void run() {
+                mGridView.setNumColumns(0);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+
+        //although setNumColumns(0) was called, the number of columns should be 1
+        assertEquals(mGridView.getNumColumns(), 1);
+    }
+
+    @TestTargetNew(
+        level = TestLevel.COMPLETE,
         method = "attachLayoutAnimationParameters",
         args = {android.view.View.class, android.view.ViewGroup.LayoutParams.class, int.class,
                 int.class}
diff --git a/tests/tests/widget/src/android/widget/cts/ListViewTest.java b/tests/tests/widget/src/android/widget/cts/ListViewTest.java
index e7b872a..ba597c1 100644
--- a/tests/tests/widget/src/android/widget/cts/ListViewTest.java
+++ b/tests/tests/widget/src/android/widget/cts/ListViewTest.java
@@ -16,9 +16,14 @@
 
 package android.widget.cts;
 
-import java.util.List;
+import com.android.cts.stub.R;
+import com.google.android.collect.Lists;
 
-import junit.framework.Assert;
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
+import dalvik.annotation.ToBeFixed;
 
 import org.xmlpull.v1.XmlPullParser;
 
@@ -44,14 +49,9 @@
 import android.widget.TextView;
 import android.widget.AdapterView.OnItemClickListener;
 
-import com.android.cts.stub.R;
-import com.google.android.collect.Lists;
+import java.util.List;
 
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.ToBeFixed;
+import junit.framework.Assert;
 
 @TestTargetClass(ListView.class)
 public class ListViewTest extends ActivityInstrumentationTestCase2<ListViewStubActivity> {
@@ -721,9 +721,11 @@
         mInstrumentation.runOnMainSync(new Runnable() {
             public void run() {
                 mListView.setAdapter(mAdapter_countries);
+                mListView.requestFocus();
             }
         });
         mInstrumentation.waitForIdleSync();
+        assertTrue(mListView.hasFocus());
 
         mInstrumentation.runOnMainSync(new Runnable() {
             public void run() {
diff --git a/tests/tests/widget/src/android/widget/cts/PositionTesterContextMenuListener.java b/tests/tests/widget/src/android/widget/cts/PositionTesterContextMenuListener.java
new file mode 100644
index 0000000..a1c9bc4
--- /dev/null
+++ b/tests/tests/widget/src/android/widget/cts/PositionTesterContextMenuListener.java
@@ -0,0 +1,111 @@
+/*
+ * 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.widget.cts;
+
+import android.view.ContextMenu;
+import android.view.View;
+import android.view.ContextMenu.ContextMenuInfo;
+import android.view.View.OnCreateContextMenuListener;
+import android.widget.ExpandableListView;
+import android.widget.AdapterView.AdapterContextMenuInfo;
+
+public class PositionTesterContextMenuListener implements OnCreateContextMenuListener {
+
+    private int groupPosition, childPosition;
+
+    // Fake constant to store in testType a test type specific to headers and footers
+    private static final int ADAPTER_TYPE = -1;
+    private int testType; // as returned by getPackedPositionType
+
+    // Will be set to null by each call to onCreateContextMenu, unless an error occurred. 
+    private String errorMessage;
+
+    public void expectGroupContextMenu(int groupPosition) {
+        this.groupPosition = groupPosition;
+        testType = ExpandableListView.PACKED_POSITION_TYPE_GROUP;
+    }
+
+    public void expectChildContextMenu(int groupPosition, int childPosition) {
+        this.groupPosition = groupPosition;
+        this.childPosition = childPosition;
+        testType = ExpandableListView.PACKED_POSITION_TYPE_CHILD;
+    }
+
+    public void expectAdapterContextMenu(int flatPosition) {
+        this.groupPosition = flatPosition;
+        testType = ADAPTER_TYPE;
+    }
+
+    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
+        errorMessage = null;
+        if (testType == ADAPTER_TYPE) {
+            if (!isTrue("MenuInfo is not an AdapterContextMenuInfo",
+                    menuInfo instanceof AdapterContextMenuInfo)) {
+                return;
+            }
+            AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
+            if (!areEqual("Wrong flat position", groupPosition, adapterContextMenuInfo.position)) {
+                return;
+            }
+        } else {
+            if (!isTrue("MenuInfo is not an ExpandableListContextMenuInfo",
+                    menuInfo instanceof ExpandableListView.ExpandableListContextMenuInfo)) {
+                return;
+            }
+            ExpandableListView.ExpandableListContextMenuInfo elvMenuInfo =
+                (ExpandableListView.ExpandableListContextMenuInfo) menuInfo;
+            long packedPosition = elvMenuInfo.packedPosition;
+
+            int packedPositionType = ExpandableListView.getPackedPositionType(packedPosition);
+            if (!areEqual("Wrong packed position type", testType, packedPositionType)) {
+                return;
+            }
+
+            int packedPositionGroup = ExpandableListView.getPackedPositionGroup(packedPosition);
+            if (!areEqual("Wrong group position", groupPosition, packedPositionGroup)) {
+                return;
+            }
+
+            if (testType == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
+                int packedPositionChild = ExpandableListView.getPackedPositionChild(packedPosition);
+                if (!areEqual("Wrong child position", childPosition, packedPositionChild)) {
+                    return;
+                }
+            }
+        }
+    }
+
+    private boolean areEqual(String message, int expected, int actual) {
+        if (expected != actual) {
+            errorMessage = String.format(message + " (%d vs %d", expected, actual);
+            return false;
+        }
+        return true;
+    }
+
+    private boolean isTrue(String message, boolean value) {
+        if (!value) {
+            errorMessage = message;
+            return false;
+        }
+        return true;
+    }
+
+    public String getErrorMessage() {
+        return errorMessage;
+    }
+}
diff --git a/tests/tests/widget/src/android/widget/cts/RemoteViewsTest.java b/tests/tests/widget/src/android/widget/cts/RemoteViewsTest.java
index 9331ff9..ddbe90d 100644
--- a/tests/tests/widget/src/android/widget/cts/RemoteViewsTest.java
+++ b/tests/tests/widget/src/android/widget/cts/RemoteViewsTest.java
@@ -40,6 +40,7 @@
 import android.view.View;
 import android.widget.AbsoluteLayout;
 import android.widget.Chronometer;
+import android.widget.EditText;
 import android.widget.FrameLayout;
 import android.widget.GridView;
 import android.widget.ImageView;
@@ -359,13 +360,6 @@
                 .getResources().getDrawable(R.drawable.testimage);
         WidgetTestUtils.assertEquals(d.getBitmap(),
                 ((BitmapDrawable) image.getDrawable()).getBitmap());
-
-        try {
-            mRemoteViews.reapply(mActivity, text);
-            fail("Should throw ActionException");
-        } catch (ActionException e) {
-            // expected
-        }
     }
 
     @TestTargetNew(
@@ -384,10 +378,11 @@
         assertTrue(mRemoteViews.onLoadClass(ImageView.class));
         assertTrue(mRemoteViews.onLoadClass(ProgressBar.class));
         assertTrue(mRemoteViews.onLoadClass(Chronometer.class));
+        assertTrue(mRemoteViews.onLoadClass(ListView.class));
+        assertTrue(mRemoteViews.onLoadClass(GridView.class));
 
         // those classes without annotation @RemoteView
-        assertFalse(mRemoteViews.onLoadClass(ListView.class));
-        assertFalse(mRemoteViews.onLoadClass(GridView.class));
+        assertFalse(mRemoteViews.onLoadClass(EditText.class));
     }
 
     @TestTargetNew(
diff --git a/tests/tests/widget/src/android/widget/cts/ScrollViewTest.java b/tests/tests/widget/src/android/widget/cts/ScrollViewTest.java
index b852e5b..de2b167 100644
--- a/tests/tests/widget/src/android/widget/cts/ScrollViewTest.java
+++ b/tests/tests/widget/src/android/widget/cts/ScrollViewTest.java
@@ -658,6 +658,7 @@
     @UiThreadTest
     public void testRequestChildRectangleOnScreen() {
         mScrollView.setSmoothScrollingEnabled(false);
+        mScrollView.setVerticalFadingEdgeEnabled(true);
         int edge = mScrollView.getVerticalFadingEdgeLength();
 
         View child = mScrollView.findViewById(R.id.first_child);
diff --git a/tests/tests/widget/src/android/widget/cts/TextViewTest.java b/tests/tests/widget/src/android/widget/cts/TextViewTest.java
index 9bd8cc4..dd8ea7f 100644
--- a/tests/tests/widget/src/android/widget/cts/TextViewTest.java
+++ b/tests/tests/widget/src/android/widget/cts/TextViewTest.java
@@ -44,6 +44,7 @@
 import android.graphics.drawable.Drawable;
 import android.net.Uri;
 import android.os.Bundle;
+import android.os.Debug;
 import android.test.ActivityInstrumentationTestCase2;
 import android.test.TouchUtils;
 import android.test.UiThreadTest;
@@ -111,7 +112,10 @@
     private Activity mActivity;
     private Instrumentation mInstrumentation;
     private static final String LONG_TEXT = "This is a really long string which exceeds "
-            + "the width of the view.";
+            + "the width of the view. New devices have a much larger screen which "
+            + "actually enables long strings to be displayed with no fading. "
+            + "I have made this string longer to fix this case. If you are correcting "
+            + "this text, I would love to see the kind of devices you guys now use!";
     private static final long TIMEOUT = 5000;
     private CharSequence mTransformedText;
 
@@ -1803,7 +1807,7 @@
         // a key event that will not change the TextView's text
         assertEquals("", mTextView.getText().toString());
         // The icon and error message will not be reset to null
-        assertNotNull(mTextView.getError());
+        assertNull(mTextView.getError());
 
         mInstrumentation.sendStringSync("1");
         // a key event cause changes to the TextView's text
diff --git a/tests/tests/widget/src/android/widget/cts/TimePickerTest.java b/tests/tests/widget/src/android/widget/cts/TimePickerTest.java
index 881693f..8287ae6 100644
--- a/tests/tests/widget/src/android/widget/cts/TimePickerTest.java
+++ b/tests/tests/widget/src/android/widget/cts/TimePickerTest.java
@@ -136,20 +136,19 @@
         int initialHour = 13;
         int initialMinute = 50;
         mTimePicker = new TimePicker(mContext);
-        mTimePicker.setCurrentHour(Integer.valueOf(initialHour));
-        mTimePicker.setCurrentMinute(Integer.valueOf(initialMinute));
+
         MockOnTimeChangeListener listener = new MockOnTimeChangeListener();
         mTimePicker.setOnTimeChangedListener(listener);
+        mTimePicker.setCurrentHour(Integer.valueOf(initialHour));
+        mTimePicker.setCurrentMinute(Integer.valueOf(initialMinute));
+        assertEquals(initialHour, listener.getNotifiedHourOfDay());
+        assertEquals(initialMinute, listener.getNotifiedMinute());
 
         // set the same hour as current
         listener.reset();
         mTimePicker.setCurrentHour(Integer.valueOf(initialHour));
-        assertTrue(listener.hasCalledOnTimeChanged());
-        assertEquals(initialHour, listener.getNotifiedHourOfDay());
-        assertEquals(initialMinute, listener.getNotifiedMinute());
-        assertSame(mTimePicker, listener.getNotifiedView());
+        assertFalse(listener.hasCalledOnTimeChanged());
 
-        listener.reset();
         mTimePicker.setCurrentHour(Integer.valueOf(initialHour + 1));
         assertTrue(listener.hasCalledOnTimeChanged());
         assertEquals(initialHour + 1, listener.getNotifiedHourOfDay());
@@ -159,10 +158,7 @@
         // set the same minute as current
         listener.reset();
         mTimePicker.setCurrentMinute(initialMinute);
-        assertTrue(listener.hasCalledOnTimeChanged());
-        assertEquals(initialHour + 1, listener.getNotifiedHourOfDay());
-        assertEquals(initialMinute, listener.getNotifiedMinute());
-        assertSame(mTimePicker, listener.getNotifiedView());
+        assertFalse(listener.hasCalledOnTimeChanged());
 
         listener.reset();
         mTimePicker.setCurrentMinute(initialMinute + 1);
@@ -174,10 +170,7 @@
         // change time picker mode
         listener.reset();
         mTimePicker.setIs24HourView( !mTimePicker.is24HourView() );
-        assertTrue(listener.hasCalledOnTimeChanged());
-        assertEquals(initialHour + 1, listener.getNotifiedHourOfDay());
-        assertEquals(initialMinute + 1, listener.getNotifiedMinute());
-        assertSame(mTimePicker, listener.getNotifiedView());
+        assertFalse(listener.hasCalledOnTimeChanged());
     }
 
     @TestTargets({
diff --git a/tools/device-setup/TestDeviceSetup/Android.mk b/tools/device-setup/TestDeviceSetup/Android.mk
index 3704be5..413f50b 100644
--- a/tools/device-setup/TestDeviceSetup/Android.mk
+++ b/tools/device-setup/TestDeviceSetup/Android.mk
@@ -30,3 +30,14 @@
 
 include $(BUILD_PACKAGE)
 
+# ======================================================
+# also build a static host library for the device info constants
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := src/android/tests/getinfo/DeviceInfoConstants.java
+
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_MODULE := ctsdeviceinfolib
+
+include $(BUILD_HOST_JAVA_LIBRARY)
diff --git a/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoActivity.java b/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoActivity.java
index e6c0e14..bcba1cb 100644
--- a/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoActivity.java
+++ b/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoActivity.java
@@ -64,7 +64,7 @@
             touchScreen = "finger";
         }
         if (touchScreen != null) {
-            DeviceInfoInstrument.addResult(DeviceInfoInstrument.TOUCH_SCREEN,
+            DeviceInfoInstrument.addResult(DeviceInfoConstants.TOUCH_SCREEN,
                     touchScreen);
         }
 
@@ -82,7 +82,7 @@
         }
 
         if (navigation != null) {
-            DeviceInfoInstrument.addResult(DeviceInfoInstrument.NAVIGATION,
+            DeviceInfoInstrument.addResult(DeviceInfoConstants.NAVIGATION,
                     navigation);
         }
 
@@ -97,7 +97,7 @@
             keypad = "12key";
         }
         if (keypad != null) {
-            DeviceInfoInstrument.addResult(DeviceInfoInstrument.KEYPAD, keypad);
+            DeviceInfoInstrument.addResult(DeviceInfoConstants.KEYPAD, keypad);
         }
 
         String[] locales = getAssets().getLocales();
@@ -110,7 +110,7 @@
             }
             localeList.append(";");
         }
-        DeviceInfoInstrument.addResult(DeviceInfoInstrument.LOCALES,
+        DeviceInfoInstrument.addResult(DeviceInfoConstants.LOCALES,
                 localeList.toString());
 
         synchronized (sync) {
diff --git a/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoConstants.java b/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoConstants.java
new file mode 100644
index 0000000..d181a9b
--- /dev/null
+++ b/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoConstants.java
@@ -0,0 +1,60 @@
+/*
+ * 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.tests.getinfo;
+
+/**
+ * Constants for device info attributes to be sent as instrumentation keys.
+ * <p/>
+ * These values should correspond to attributes defined in cts_result.xsd.
+ */
+public interface DeviceInfoConstants {
+
+    public static final String OPEN_GL_ES_VERSION = "openGlEsVersion";
+    public static final String PROCESSES = "processes";
+    public static final String FEATURES = "features";
+    public static final String PHONE_NUMBER = "phoneNumber";
+    public static final String LOCALES = "locales";
+    public static final String IMSI = "imsi";
+    public static final String IMEI = "imei";
+    public static final String NETWORK = "network";
+    public static final String KEYPAD = "keypad";
+    public static final String NAVIGATION = "navigation";
+    public static final String TOUCH_SCREEN = "touch";
+    public static final String SCREEN_Y_DENSITY = "Ydpi";
+    public static final String SCREEN_X_DENSITY = "Xdpi";
+    public static final String SCREEN_SIZE = "screen_size";
+    public static final String SCREEN_DENSITY_BUCKET = "screen_density_bucket";
+    public static final String SCREEN_DENSITY = "screen_density";
+    public static final String SCREEN_HEIGHT = "screen_height";
+    public static final String SCREEN_WIDTH = "screen_width";
+    public static final String VERSION_SDK = "androidPlatformVersion";
+    public static final String VERSION_RELEASE = "buildVersion";
+    public static final String BUILD_ABI = "build_abi";
+    public static final String BUILD_ABI2 = "build_abi2";
+    public static final String BUILD_FINGERPRINT = "build_fingerprint";
+    public static final String BUILD_TYPE = "build_type";
+    public static final String BUILD_MODEL = "build_model";
+    public static final String BUILD_BRAND = "build_brand";
+    public static final String BUILD_MANUFACTURER = "build_manufacturer";
+    public static final String BUILD_BOARD = "build_board";
+    public static final String BUILD_DEVICE = "build_device";
+    public static final String PRODUCT_NAME = "buildName";
+    public static final String BUILD_ID = "buildID";
+    public static final String BUILD_VERSION = "buildVersion";
+    public static final String BUILD_TAGS = "build_tags";
+    public static final String SERIAL_NUMBER = "serialNumber";
+}
diff --git a/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoInstrument.java b/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoInstrument.java
index 31168fd..1299aae 100644
--- a/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoInstrument.java
+++ b/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoInstrument.java
@@ -37,43 +37,10 @@
 import java.util.List;
 import java.util.Set;
 
-public class DeviceInfoInstrument extends Instrumentation {
+public class DeviceInfoInstrument extends Instrumentation implements DeviceInfoConstants {
 
     private static final String TAG = "DeviceInfoInstrument";
 
-    // constants for device info attributes to be sent as instrumentation keys
-    // these values should correspond to attributes defined in cts_result.xsd
-    private static final String OPEN_GL_ES_VERSION = "openGlEsVersion";
-    private static final String PROCESSES = "processes";
-    private static final String FEATURES = "features";
-    private static final String PHONE_NUMBER = "phoneNumber";
-    public static final String LOCALES = "locales";
-    private static final String IMSI = "imsi";
-    private static final String IMEI = "imei";
-    private static final String NETWORK = "network";
-    public static final String KEYPAD = "keypad";
-    public static final String NAVIGATION = "navigation";
-    public static final String TOUCH_SCREEN = "touch";
-    private static final String SCREEN_Y_DENSITY = "Ydpi";
-    private static final String SCREEN_X_DENSITY = "Xdpi";
-    private static final String SCREEN_SIZE = "screen_size";
-    private static final String SCREEN_DENSITY_BUCKET = "screen_density_bucket";
-    private static final String SCREEN_DENSITY = "screen_density";
-    private static final String SCREEN_HEIGHT = "screen_height";
-    private static final String SCREEN_WIDTH = "screen_width";
-    private static final String VERSION_SDK = "androidPlatformVersion";
-    private static final String VERSION_RELEASE = "buildVersion";
-    private static final String BUILD_ABI = "build_abi";
-    private static final String BUILD_ABI2 = "build_abi2";
-    private static final String BUILD_FINGERPRINT = "build_fingerprint";
-    private static final String BUILD_TYPE = "build_type";
-    private static final String BUILD_MODEL = "build_model";
-    private static final String BUILD_BRAND = "build_brand";
-    private static final String BUILD_MANUFACTURER = "build_manufacturer";
-    private static final String BUILD_BOARD = "build_board";
-    private static final String BUILD_DEVICE = "build_device";
-    private static final String PRODUCT_NAME = "buildName";
-    private static final String BUILD_ID = "buildID";
     private static Bundle mResults = new Bundle();
 
     public DeviceInfoInstrument() {
diff --git a/tools/host/src/Android.mk b/tools/host/src/Android.mk
index 5ad3998..d9195eb 100644
--- a/tools/host/src/Android.mk
+++ b/tools/host/src/Android.mk
@@ -23,6 +23,8 @@
 LOCAL_JAVA_LIBRARIES := \
     ddmlib-prebuilt junit hosttestlib CtsTestAnnotationsHostLib
 
+LOCAL_STATIC_JAVA_LIBRARIES := ctsdeviceinfolib
+
 LOCAL_MODULE := cts
 
 include $(BUILD_HOST_JAVA_LIBRARY)
diff --git a/tools/host/src/com/android/cts/TestDevice.java b/tools/host/src/com/android/cts/TestDevice.java
index 88bcd68..19f754a 100644
--- a/tools/host/src/com/android/cts/TestDevice.java
+++ b/tools/host/src/com/android/cts/TestDevice.java
@@ -32,6 +32,8 @@
 import com.android.ddmlib.log.LogReceiver;
 import com.android.ddmlib.log.LogReceiver.ILogListener;
 
+import android.tests.getinfo.DeviceInfoConstants;
+
 import java.io.BufferedReader;
 import java.io.FileNotFoundException;
 import java.io.IOException;
@@ -400,42 +402,7 @@
     /**
      * Store the build information of a device
      */
-    public static final class DeviceParameterCollector{
-        // the device info keys expected to be sent from device info instrumentation
-        // these constants should match exactly with those defined in DeviceInfoInstrument.jaa
-        public static final String PRODUCT_NAME = "buildName";
-        public static final String BUILD_VERSION = "buildVersion";
-        public static final String BUILD_ID = "buildID";
-        public static final String BUILD_FINGERPRINT = "build_fingerprint";
-        public static final String BUILD_TAGS = "build_tags";
-        public static final String BUILD_TYPE = "build_type";
-        public static final String BUILD_MANUFACTURER = "build_manufacturer";
-        public static final String BUILD_MODEL = "build_model";
-        public static final String BUILD_BRAND = "build_brand";
-        public static final String BUILD_BOARD = "build_board";
-        public static final String BUILD_DEVICE = "build_device";
-        public static final String BUILD_ABI = "build_abi";
-        public static final String BUILD_ABI2 = "build_abi2";
-        public static final String SCREEN_SIZE = "screen_size";
-        public static final String SCREEN_HEIGHT = "screen_height";
-        public static final String SCREEN_WIDTH = "screen_width";
-        public static final String SCREEN_DENSITY = "screen_density";
-        public static final String SCREEN_DENSITY_BUCKET = "screen_density_bucket";
-        public static final String SERIAL_NUMBER = "serialNumber";
-        public static final String VERSION_SDK = "androidPlatformVersion";
-        public static final String LOCALES = "locales";
-        public static final String SCREEN_Y_DENSITY = "Ydpi";
-        public static final String SCREEN_X_DENSITY = "Xdpi";
-        public static final String TOUCH_SCREEN = "touch";
-        public static final String NAVIGATION = "navigation";
-        public static final String KEYPAD = "keypad";
-        public static final String NETWORK = "network";
-        public static final String IMEI = "imei";
-        public static final String IMSI = "imsi";
-        public static final String PHONE_NUMBER = "phoneNumber";
-        public static final String FEATURES = "features";
-        public static final String PROCESSES = "processes";
-        public static final String OPEN_GL_ES_VERSION = "openGlEsVersion";
+    public static final class DeviceParameterCollector implements DeviceInfoConstants {
 
         private HashMap<String, String> mInfoMap;
 
diff --git a/tools/host/src/res/cts_result.xsd b/tools/host/src/res/cts_result.xsd
index 51bad35..d154bc4 100644
--- a/tools/host/src/res/cts_result.xsd
+++ b/tools/host/src/res/cts_result.xsd
@@ -148,11 +148,12 @@
 
 <xs:complexType name="testPackageType">
   <xs:sequence>
-    <xs:element name="TestSuite" type="testSuiteType"/>
+    <xs:element name="TestSuite" type="testSuiteType" minOccurs="0" maxOccurs="unbounded" />
   </xs:sequence>
   <xs:attribute name="appPackageName" type="xs:string"/>
   <xs:attribute name="digest" type="xs:hexBinary"/>
   <xs:attribute name="name" type="xs:string" use="required"/>
+  <xs:attribute name="signatureCheck" type="xs:boolean" />
 </xs:complexType>
 
 <xs:complexType name="testSuiteType">
diff --git a/tools/tradefed-host/Android.mk b/tools/tradefed-host/Android.mk
index c1e5c54..ceec5db 100644
--- a/tools/tradefed-host/Android.mk
+++ b/tools/tradefed-host/Android.mk
@@ -18,7 +18,7 @@
 
 # Only compile source java files in this lib.
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
-LOCAL_JAVA_RESOURCE_DIRS := res
+LOCAL_JAVA_RESOURCE_DIRS := res ../host/src/res
 
 LOCAL_MODULE := cts-tradefed
 LOCAL_MODULE_TAGS := optional
diff --git a/tools/tradefed-host/etc/Android.mk b/tools/tradefed-host/etc/Android.mk
new file mode 100644
index 0000000..f3bee3f
--- /dev/null
+++ b/tools/tradefed-host/etc/Android.mk
@@ -0,0 +1,22 @@
+# 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.
+
+LOCAL_PATH := $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_PREBUILT_EXECUTABLES := cts-tradefed
+include $(BUILD_HOST_PREBUILT)
+
diff --git a/tools/tradefed-host/etc/cts-tradefed b/tools/tradefed-host/etc/cts-tradefed
new file mode 100755
index 0000000..8bbce80
--- /dev/null
+++ b/tools/tradefed-host/etc/cts-tradefed
@@ -0,0 +1,76 @@
+#!/bin/bash
+
+# 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.
+
+# launcher script for cts-tradefed harness
+# can be used from an Android build environment, or a standalone cts zip
+
+checkFile() {
+    if [ ! -f "$1" ]; then
+        echo "Unable to locate $1"
+        exit
+    fi;
+}
+
+checkPath() {
+    if ! type -P $1 &> /dev/null; then
+        echo "Unable to find $1 in path."
+        exit
+    fi;
+}
+
+checkPath adb
+checkPath java
+
+# check java version
+JAVA_VERSION=$(java -version 2>&1 | head -n 1 | grep '[ "]1\.6[\. "$$]')
+if [ "${JAVA_VERSION}" == "" ]; then
+    echo "Wrong java version. 1.6 is required."
+    exit
+fi
+
+# check if in Android build env
+if [ ! -z ${ANDROID_BUILD_TOP} ]; then
+    HOST=`uname`
+    if [ "$HOST" == "Linux" ]; then
+        OS="linux-x86"
+    elif [ "$HOST" == "Darwin" ]; then
+        OS="darwin-x86"
+    else
+        echo "Unrecognized OS"
+        exit
+    fi;
+    CTS_ROOT=${ANDROID_BUILD_TOP}/out/host/${OS}/cts
+    if [ ! -d ${CTS_ROOT} ]; then
+        echo "Could not find $CTS_ROOT in Android build environment. Try 'make cts'"
+        exit
+    fi;
+fi;
+
+if [ -z ${CTS_ROOT} ]; then
+    # assume we're in an extracted cts install
+    CTS_ROOT="$(dirname $0)/../.."
+fi;
+
+JAR_DIR=${CTS_ROOT}/android-cts/tools
+JARS="ddmlib-prebuilt.jar tradefed-prebuilt.jar hosttestlib.jar cts-tradefed.jar"
+
+for JAR in $JARS; do
+    checkFile ${JAR_DIR}/${JAR}
+    JAR_PATH=${JAR_PATH}:${JAR_DIR}/${JAR}
+done
+
+java -cp ${JAR_PATH} com.android.tradefed.command.Command "$@" --cts-install-path ${CTS_ROOT} cts
+
diff --git a/tools/tradefed-host/res/config/cts.xml b/tools/tradefed-host/res/config/cts.xml
index d98c7fb..165ba96 100644
--- a/tools/tradefed-host/res/config/cts.xml
+++ b/tools/tradefed-host/res/config/cts.xml
@@ -19,7 +19,7 @@
     <build_provider class="com.android.cts.tradefed.targetsetup.CtsBuildProvider" />
     <device_recovery class="com.android.tradefed.device.WaitDeviceRecovery" />
     <target_preparer class="com.android.cts.tradefed.targetsetup.CtsSetup" />
-    <test class="com.android.cts.tradefed.testtype.PlanTest" />
+    <test class="com.android.cts.tradefed.testtype.CtsTest" />
     <logger class="com.android.tradefed.log.FileLogger" />
     <result_reporter class="com.android.cts.tradefed.result.CtsXmlResultReporter" />
 
diff --git a/tools/tradefed-host/res/result/cts_result.css b/tools/tradefed-host/res/result/cts_result.css
deleted file mode 100644
index d7ce510..0000000
--- a/tools/tradefed-host/res/result/cts_result.css
+++ /dev/null
@@ -1,234 +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.
-*/
-
-body {
-    font-family:arial,sans-serif;
-    color:#000;
-    font-size:13px;
-    color:#333;
-    padding:10;
-    margin:10;
-}
-
-table {
-    font-size:1em;
-    margin:0 0 1em;
-    padding:0;
-    border-collapse:collapse;
-    border-width:0;
-    empty-cells:show;
-    width: 95%;
-}
-
-/* Report logo and device name */
-#title table {
-    padding:5px;
-    border-width: 0px;
-    margin-left:auto;
-    margin-right:auto;
-    vertical-align:middle;
-}
-
-/* Device and test plan summary below the title */
-#summary table {
-    background-color: rgb(212, 233, 169);
-    -moz-border-radius:5px;
-    border-radius:5px;
-    padding:5px;
-    border-color: #A5C639 #A5C639 #A5C639 #A5C639;
-    border-width: 0px 0px 0px 0px;
-    margin-left:auto;
-    margin-right:auto;
-    width:80%;
-}
-
-#summary th {
-    background-color: #A5C639;
-    font-size:1.2em;
-    height: 2em;
-    width: 50%;
-}
-
-#summary td {
-    border-width: 0px 0px 0px 0px;
-    border-color: gray;
-    border-style: inset;
-    font-size:1em;
-    vertical-align: top;
-}
-
-#summaryinfo table {
-    background-color: rgb(212, 233, 169);
-    padding:5px;
-    border-width:0;
-    margin-left:auto;
-    margin-right:auto;
-}
-
-#summaryinfo td {
-    padding:1px;
-    border-width: 0px 0px 0px 0px;
-    vertical-align: top;
-}
-
-/* The test summary */
-#testsummary table {
-    background-color: rgb(212, 233, 169);
-    padding:5px;
-    border-width:1;
-    border-color: #A5C639;
-    margin-left:auto;
-    margin-right:auto;
-    width: 40%;
-}
-
-#testsummary th {
-    background-color: #A5C639;
-    border-width: 1px;
-    border-color: gray;
-    border-style: outset;
-    height: 2em;
-}
-
-#testsummary td {
-    border-width: 1px;
-    border-color: #A5C639;
-    border-style: outset;
-    text-align: center;
-}
-
-/* The test details */
-#testdetail table {
-    background-color: rgb(212, 233, 169);
-    padding:5px;
-    border-width:1;
-    border-color: #A5C639;
-    margin-left:auto;
-    margin-right:auto;
-    width: 95%;
-    table-layout:fixed;
-    vertical-align: top;
-}
-
-#testdetail th {
-    background-color: #A5C639;
-    border-width: 1px;
-    border-color: gray;
-    border-style: outset;
-    height: 2em;
-}
-
-#testdetail td {
-    border-width: 1px;
-    border-color: #A5C639;
-    border-style: outset;
-    text-align: left;
-    vertical-align: top;
-    padding:1;
-}
-
-/* The test package name */
-#none table {
-    border-width:0;
-    border-color: white;
-    background-color: white;
-    text-align:left;
-    border-collapse:collapse;
-}
-
-#none td {
-    border-width:0;
-    border-color: white;
-    background-color: white;
-    text-align:left;
-    border-collapse:collapse;
-    font-weight:bold;
-}
-
-/* Test cell details */
-td.failed {
-    background-color: #FA5858;
-    font-weight:bold;
-    vertical-align: top;
-    text-align: center;
-}
-
-td.failuredetails {
-    text-align: left;
-}
-
-td.pass {
-    text-align: center;
-    margin-left:auto;
-    margin-right:auto;
-}
-
-td.timeout, td.omitted, td.notExecuted {
-    background-color: #A5C639;
-    vertical-align: top;
-    text-align: center;
-}
-
-td.testname {
-    border-width: 1px;
-    border-color: #A5C639;
-    border-style: outset;
-    text-align: left;
-    vertical-align: top;
-    padding:1;
-    overflow:hidden;
-}
-
-td.testcase {
-    border-width: 1px;
-    border-color: #A5C639;
-    border-style: outset;
-    text-align: left;
-    vertical-align: top;
-    padding:1;
-    overflow:hidden;
-    font-weight:bold;
-}
-
-td.testcasespacer {
-    border-width: 1px;
-    border-color: #A5C639;
-    border-style: outset;
-    text-align: left;
-    vertical-align: top;
-    padding:1;
-    overflow:hidden;
-    font-weight:bold;
-}
-
-td.testsuite {
-    border-width: 1px;
-    border-color: #A5C639;
-    border-style: outset;
-    text-align: left;
-    vertical-align: top;
-    padding:1;
-    overflow:hidden;
-    font-weight:bold;
-}
-
-#details {
-    white-space: pre-wrap;       /* css-3 */
-    white-space: -moz-pre-wrap;  /* Mozilla, since 1999 */
-    white-space: -pre-wrap;      /* Opera 4-6 */
-    white-space: -o-pre-wrap;    /* Opera 7 */
-    word-wrap: break-word;       /* Internet Explorer 5.5+ */
-    overflow:auto;
-}
diff --git a/tools/tradefed-host/res/result/cts_result.xsd b/tools/tradefed-host/res/result/cts_result.xsd
deleted file mode 100644
index f2fc3a8..0000000
--- a/tools/tradefed-host/res/result/cts_result.xsd
+++ /dev/null
@@ -1,192 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- * 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.
- -->
-
-<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
-           targetNamespace="http://compatibility.android.com/cts_result/2.0"
-           xmlns="http://compatibility.android.com/cts_result/2.0"
-           elementFormDefault="qualified">
-
-<xs:element name="TestResult">
-  <xs:complexType>
-    <xs:sequence>
-      <xs:element name="DeviceInfo" type="deviceInfoType"/>
-      <xs:element name="HostInfo" type="hostInfoType"/>
-      <xs:element name="Summary" type="summaryType"/>
-      <xs:element name="TestPackage" type="testPackageType" maxOccurs="unbounded" minOccurs="1"/>
-    </xs:sequence>
-    <xs:attribute name="starttime" type="xs:string"/>
-    <xs:attribute name="endtime" type="xs:string"/>
-    <xs:attribute name="testPlan" type="xs:string"/>
-    <xs:attribute name="version" type="xs:string"/>
-    <xs:attribute name="profile" type="xs:string"/>
-  </xs:complexType>
-</xs:element>
-
-<xs:complexType name="deviceInfoType">
-  <xs:sequence>
-    <xs:element name="Screen">
-      <xs:complexType>
-        <xs:attribute name="resolution" type="xs:string"/>
-      </xs:complexType>
-    </xs:element>
-    <xs:element name="PhoneSubInfo">
-      <xs:complexType>
-        <xs:attribute name="subscriberId" type="xs:string"/>
-      </xs:complexType>
-    </xs:element>
-    <xs:element name="BuildInfo">
-      <xs:complexType>
-        <xs:attribute name="Xdpi" type="xs:decimal"/>
-        <xs:attribute name="Ydpi" type="xs:decimal"/>
-        <xs:attribute name="androidPlatformVersion" type="xs:integer"/>
-        <xs:attribute name="buildID" type="xs:string"/>
-        <xs:attribute name="buildName" type="xs:string"/>
-        <xs:attribute name="buildVersion" type="xs:string"/>
-        <xs:attribute name="build_board" type="xs:string"/>
-        <xs:attribute name="build_brand" type="xs:string"/>
-        <xs:attribute name="build_device" type="xs:string"/>
-        <xs:attribute name="build_fingerprint" type="xs:string"/>
-        <xs:attribute name="build_model" type="xs:string"/>
-        <xs:attribute name="build_type" type="xs:string"/>
-        <xs:attribute name="deviceID" type="xs:string"/>
-        <xs:attribute name="imei" type="xs:integer"/>
-        <xs:attribute name="imsi" type="xs:integer"/>
-        <xs:attribute name="keypad" type="xs:string"/>
-        <xs:attribute name="locales" type="xs:string"/>
-        <xs:attribute name="navigation" type="xs:string"/>
-        <xs:attribute name="network" type="xs:string"/>
-        <xs:attribute name="touch" type="xs:string"/>
-        <xs:attribute name="openGlEsVersion" type="xs:string"/>
-        <xs:attribute name="build_abi" type="xs:string"/>
-        <xs:attribute name="build_abi2" type="xs:string"/>
-      </xs:complexType>
-    </xs:element>
-    <xs:element name="FeatureInfo" type="featureInfoType"/>
-    <xs:element name="ProcessInfo" type="processInfoType"/>
-  </xs:sequence>
-</xs:complexType>
-
-<xs:complexType name="hostInfoType">
-  <xs:sequence>
-    <xs:element name="Os">
-      <xs:complexType>
-        <xs:attribute name="arch" type="xs:string"/>
-        <xs:attribute name="name" type="xs:string"/>
-        <xs:attribute name="version" type="xs:string"/>
-      </xs:complexType>
-    </xs:element>
-    <xs:element name="Java">
-      <xs:complexType>
-        <xs:attribute name="name" type="xs:string"/>
-        <xs:attribute name="version" type="xs:string"/>
-      </xs:complexType>
-    </xs:element>
-    <xs:element name="Cts">
-      <xs:complexType>
-        <xs:sequence>
-          <xs:element name="IntValue" minOccurs="0" maxOccurs="unbounded">
-            <xs:complexType>
-              <xs:attribute name="name" type="xs:string"/>
-              <xs:attribute name="value" type="xs:integer"/>
-            </xs:complexType>
-          </xs:element>
-        </xs:sequence>
-        <xs:attribute name="version" type="xs:string"/>
-      </xs:complexType>
-    </xs:element>
-  </xs:sequence>
-  <xs:attribute name="name" type="xs:string"/>
-</xs:complexType>
-
-<xs:complexType name="featureInfoType">
-    <xs:sequence>
-        <xs:element name="Feature" minOccurs="0" maxOccurs="unbounded">
-            <xs:complexType>
-                <xs:attribute name="name" type="xs:string" />
-                <xs:attribute name="type" type="xs:string" />
-                <xs:attribute name="available" type="xs:string" />
-            </xs:complexType>
-        </xs:element>
-    </xs:sequence>
-</xs:complexType>
-
-<xs:complexType name="processInfoType">
-    <xs:sequence>
-        <xs:element name="Process" minOccurs="0" maxOccurs="unbounded">
-            <xs:complexType>
-                <xs:attribute name="name" type="xs:string" />
-                <xs:attribute name="uid" type="xs:integer" />
-            </xs:complexType>
-        </xs:element>
-    </xs:sequence>
-</xs:complexType>
-
-<xs:complexType name="summaryType">
-  <xs:attribute name="failed" type="xs:integer"/>
-  <xs:attribute name="notExecuted" type="xs:integer"/>
-  <xs:attribute name="pass" type="xs:integer"/>
-  <xs:attribute name="timeout" type="xs:integer"/>
-  <xs:attribute name="omitted" type="xs:integer"/>
-  <xs:attribute name="total" type="xs:integer"/>
-</xs:complexType>
-
-<xs:complexType name="testPackageType">
-    <xs:complexContent>
-        <xs:extension base="summaryType">
-            <xs:sequence>
-                <xs:element name="TestCase" type="testCaseType" />
-            </xs:sequence>
-            <xs:attribute name="digest" type="xs:hexBinary" />
-            <xs:attribute name="name" type="xs:string" use="required" />
-            <xs:attribute name="runtime" type="xs:string" />
-        </xs:extension>
-    </xs:complexContent>
-</xs:complexType>
-
-<xs:complexType name="testCaseType">
-  <xs:sequence>
-    <xs:element name="Test" type="testType" minOccurs="0" maxOccurs="unbounded"/>
-  </xs:sequence>
-  <xs:attribute name="name" type="xs:string" use="required"/>
-</xs:complexType>
-
-<xs:complexType name="testType">
-  <xs:sequence>
-    <xs:element name="FailedScene" minOccurs="0" maxOccurs="1">
-      <xs:complexType>
-          <xs:simpleContent>
-              <xs:extension base="xs:string">
-                  <xs:attribute name="message" type="xs:string" />
-              </xs:extension>
-          </xs:simpleContent>
-      </xs:complexType>
-    </xs:element>
-  </xs:sequence>
-  <xs:attribute name="name" type="xs:string" use="required"/>
-  <xs:attribute name="result" type="resultType" use="required"/>
-</xs:complexType>
-
-<xs:simpleType name="resultType">
-  <xs:restriction base="xs:string">
-    <xs:enumeration value="pass"/>
-    <xs:enumeration value="fail"/>
-    <xs:enumeration value="timeout"/>
-    <xs:enumeration value="notExecuted"/>
-    <xs:enumeration value="omitted"/>
-  </xs:restriction>
-</xs:simpleType>
-</xs:schema>
diff --git a/tools/tradefed-host/res/result/cts_result.xsl b/tools/tradefed-host/res/result/cts_result.xsl
deleted file mode 100644
index cb220e1..0000000
--- a/tools/tradefed-host/res/result/cts_result.xsl
+++ /dev/null
@@ -1,513 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- 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.
--->
-
-<!DOCTYPE xsl:stylesheet [ <!ENTITY nbsp "&#160;"> ]>
-<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
-    <xsl:output method="html" version="1.0" encoding="UTF-8" indent="yes"/>
-
-    <xsl:template match="/">
-
-        <html>
-            <STYLE type="text/css">
-                @import "cts_result.css";
-            </STYLE>
-
-            <body>
-                <!-- Title of the Report -->
-                <DIV id="title">
-                    <TABLE>
-                        <TR>
-                            <TD width="40%" align="left"><img src="logo.gif"></img></TD>
-                            <TD width="60%" align="left">
-                                <h1>Test Report for <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@build_model"/> -
-                                <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@deviceID"/>
-                            </h1>
-                        </TD>
-                    </TR>
-                </TABLE>
-            </DIV>
-            <img src="newrule-green.png" align="left"></img>
-
-            <br></br>
-            <br></br>
-
-            <!-- Header with phone and plan information -->
-            <DIV id="summary">
-                <TABLE width="90%" frame="none">
-                    <TR>
-                        <TH>Device Information</TH>
-                        <TH>Test Summary</TH>
-                    </TR>
-
-                    <TR>
-                        <TD>
-                            <!-- Device information -->
-                            <div id="summaryinfo">
-                                <TABLE width="75%">
-                                    <TR>
-                                        <TD class="rowtitle">Build Model</TD>
-                                        <TD>
-                                            <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@build_model"/>
-                                        </TD>
-                                    </TR>
-                                    <TR>
-                                        <TD class="rowtitle">Build Name</TD>
-                                        <TD>
-                                            <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@buildName"/>
-                                        </TD>
-                                    </TR>
-                                    <TR>
-                                        <TD class="rowtitle">Device ID</TD>
-                                        <TD>
-                                            <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@deviceID"/>
-                                        </TD>
-                                    </TR>
-                                    <TR>
-                                        <TD class="rowtitle">Firmware Version</TD>
-                                        <TD>
-                                            <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@buildVersion"/>
-                                        </TD>
-                                    </TR>
-                                    <TR>
-                                        <TD class="rowtitle">Firmware Build Number</TD>
-                                        <TD>
-                                            <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@buildID"/>
-                                        </TD>
-                                    </TR>
-                                    <TR>
-                                        <TD class="rowtitle">Build Fingerprint</TD>
-                                        <TD>
-                                            <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@build_fingerprint"/>
-                                        </TD>
-                                    </TR>
-                                    <TR>
-                                        <TD class="rowtitle">Build ABI</TD>
-                                        <TD>
-                                            <xsl:value-of
-                                              select="TestResult/DeviceInfo/BuildInfo/@build_abi"/>
-                                        </TD>
-                                    </TR>
-                                    <TR>
-                                        <TD class="rowtitle">Build ABI2</TD>
-                                        <TD>
-                                            <xsl:value-of
-                                              select="TestResult/DeviceInfo/BuildInfo/@build_abi2"/>
-                                        </TD>
-                                    </TR>
-                                    <TR>
-                                        <TD class="rowtitle">Android Platform Version</TD>
-                                        <TD>
-                                            <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@androidPlatformVersion"/>
-                                        </TD>
-                                    </TR>
-                                    <TR>
-                                        <TD class="rowtitle">Supported Locales</TD>
-                                        <TD>
-                                            <xsl:call-template name="formatDelimitedString">
-                                                <xsl:with-param name="string" select="TestResult/DeviceInfo/BuildInfo/@locales"/>
-                                            </xsl:call-template>
-                                        </TD>
-                                    </TR>
-                                    <TR>
-                                        <TD class="rowtitle">Screen size</TD>
-                                        <TD>
-                                            <xsl:value-of select="TestResult/DeviceInfo/Screen/@resolution"/>
-                                        </TD>
-                                    </TR>
-                                    <TR>
-                                        <TD class="rowtitle">Phone number</TD>
-                                        <TD>
-                                            <xsl:value-of select="TestResult/DeviceInfo/PhoneSubInfo/@subscriberId"/>
-                                        </TD>
-                                    </TR>
-                                    <TR>
-                                        <TD class="rowtitle">x dpi</TD>
-                                        <TD>
-                                            <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@Xdpi"/>
-                                        </TD>
-                                    </TR>
-                                    <TR>
-                                        <TD class="rowtitle">y dpi</TD>
-                                        <TD>
-                                            <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@Ydpi"/>
-                                        </TD>
-                                    </TR>
-                                    <TR>
-                                        <TD class="rowtitle">Touch</TD>
-                                        <TD>
-                                            <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@touch"/>
-                                        </TD>
-                                    </TR>
-                                    <TR>
-                                        <TD class="rowtitle">Navigation</TD>
-                                        <TD>
-                                            <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@navigation"/>
-                                        </TD>
-                                    </TR>
-                                    <TR>
-                                        <TD class="rowtitle">Keypad</TD>
-                                        <TD>
-                                            <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@keypad"/>
-                                        </TD>
-                                    </TR>
-                                    <TR>
-                                        <TD class="rowtitle">Network</TD>
-                                        <TD>
-                                            <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@network"/>
-                                        </TD>
-                                    </TR>
-                                    <TR>
-                                        <TD class="rowtitle">IMEI</TD>
-                                        <TD>
-                                            <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@imei"/>
-                                        </TD>
-                                    </TR>
-                                    <TR>
-                                        <TD class="rowtitle">IMSI</TD>
-                                        <TD>
-                                            <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@imsi"/>
-                                        </TD>
-                                    </TR>
-                                    <TR>
-                                        <TD class="rowtitle">Open GL ES Version</TD>
-                                        <TD>
-                                            <xsl:value-of select="TestResult/DeviceInfo/BuildInfo/@openGlEsVersion"/>
-                                        </TD>
-                                    </TR>
-                                    <TR>
-                                        <TD class="rowtitle">Features</TD>
-                                        <TD>
-                                            <xsl:for-each select="TestResult/DeviceInfo/FeatureInfo/Feature[@type='sdk']">
-                                                <xsl:text>[</xsl:text>
-                                                <xsl:choose>
-                                                    <xsl:when test="@available = 'true'">
-                                                        <xsl:text>X</xsl:text>
-                                                    </xsl:when>
-                                                    <xsl:otherwise>
-                                                        <xsl:text>_</xsl:text>
-                                                    </xsl:otherwise>
-                                                </xsl:choose>
-                                                <xsl:text>] </xsl:text>
-
-                                                <xsl:value-of select="@name" />
-                                                <br />
-                                            </xsl:for-each>
-                                        </TD>
-                                    </TR>
-                                    <TR>
-                                        <TD class="rowtitle">Other Features</TD>
-                                        <TD>
-                                            <UL>
-                                                <xsl:for-each select="TestResult/DeviceInfo/FeatureInfo/Feature[@type='other']">
-                                                    <LI><xsl:value-of select="@name" /></LI>
-                                                </xsl:for-each>
-                                            </UL>
-                                        </TD>
-                                    </TR>
-                                    <TR>
-                                        <TD class="rowtitle">Root Processes</TD>
-                                        <TD>
-                                            <UL>
-                                                <xsl:for-each select="TestResult/DeviceInfo/ProcessInfo/Process[@uid='0']">
-                                                    <LI><xsl:value-of select="@name" /></LI>
-                                                </xsl:for-each>
-                                            </UL>
-                                        </TD>
-                                    </TR>
-                                </TABLE>
-                            </div>
-                        </TD>
-
-                        <!-- plan information -->
-                        <TD>
-                            <div id="summaryinfo">
-                                <TABLE width="75%">
-                                    <TR>
-                                        <TD class="rowtitle">CTS version</TD>
-                                        <TD>
-                                            <xsl:value-of select="TestResult/HostInfo/Cts/@version"/>
-                                        </TD>
-                                    </TR>
-                                    <TR>
-                                        <TD class="rowtitle">Test timeout</TD>
-                                        <TD>
-                                            <xsl:value-of select="TestResult/HostInfo/Cts/IntValue[@name='testStatusTimeoutMs']/@value" /> ms
-                                        </TD>
-                                    </TR>
-                                    <TR>
-                                        <TD class="rowtitle">Host Info</TD>
-                                        <TD>
-                                            <xsl:value-of select="TestResult/HostInfo/@name"/>
-                                            (<xsl:value-of select="TestResult/HostInfo/Os/@name"/> - 
-                                              <xsl:value-of select="TestResult/HostInfo/Os/@version"/>)
-                                        </TD>
-                                    </TR>
-                                    <TR><TD><BR></BR></TD><TD></TD></TR>
-                                    <TR>
-                                        <TD class="rowtitle">Plan name</TD>
-                                        <TD>
-                                            <xsl:value-of select="TestResult/@testPlan"/>
-                                        </TD>
-                                    </TR>
-                                    <TR>
-                                        <TD class="rowtitle">Profile</TD>
-                                        <TD>
-                                            <xsl:value-of select="TestResult/@profile"/>
-                                        </TD>
-                                    </TR>
-                                    <TR>
-                                        <TD class="rowtitle">Start time</TD>
-                                        <TD>
-                                            <xsl:value-of select="TestResult/@starttime"/>
-                                        </TD>
-                                    </TR>
-                                    <TR>
-                                        <TD class="rowtitle">End time</TD>
-                                        <TD>
-                                            <xsl:value-of select="TestResult/@endtime"/>
-                                        </TD>
-                                    </TR>
-
-                                    <!-- Test Summary -->
-                                    <TR><TD><BR></BR></TD><TD></TD></TR>
-                                    <TR>
-                                        <TD class="rowtitle">Tests Passed</TD>
-                                        <TD>
-                                            <xsl:value-of select="TestResult/Summary/@pass"/>
-                                        </TD>
-                                    </TR>
-                                    <TR>
-                                        <TD class="rowtitle">Tests Failed</TD>
-                                        <TD>
-                                            <xsl:value-of select="TestResult/Summary/@failed"/>
-                                        </TD>
-                                    </TR>
-                                    <TR>
-                                        <TD class="rowtitle">Tests Timed out</TD>
-                                        <TD>
-                                            <xsl:value-of select="TestResult/Summary/@timeout"/>
-                                        </TD>
-                                    </TR>
-                                    <TR>
-                                        <TD class="rowtitle">Tests Omitted</TD>
-                                        <TD>
-                                            <xsl:value-of select="TestResult/Summary/@omitted"/>
-                                        </TD>
-                                    </TR>
-                                    <TR>
-                                        <TD class="rowtitle">Tests Not Executed</TD>
-                                        <TD>
-                                            <xsl:value-of select="TestResult/Summary/@notExecuted"/>
-                                        </TD>
-                                    </TR>
-                                </TABLE>
-                            </div>
-                        </TD>
-                    </TR>
-                </TABLE>
-            </DIV>
-
-            <!-- High level summary of test execution -->
-            <h2 align="center">Test Summary by Package</h2>
-            <DIV id="testsummary">
-                <TABLE>
-                    <TR>
-                        <TH>Test Package</TH>
-                        <TH>Passed</TH>
-                        <TH>Failed</TH>
-                        <TH>Timed Out</TH>
-                        <TH>Total Tests</TH>
-                    </TR>
-                    <xsl:for-each select="TestResult/TestPackage">
-                        <TR>
-                            <TD>
-                                <xsl:variable name="href"><xsl:value-of select="@name"/></xsl:variable>
-                                <a href="#{$href}"><xsl:value-of select="@name"/></a>
-                            </TD>
-                            <TD>
-                                <xsl:value-of select="@pass"/>
-                            </TD>
-                            <TD>
-                                <xsl:value-of select="@failed"/>
-                            </TD>
-                            <TD>
-                                <xsl:value-of select="@timeout"/>
-                            </TD>
-                            <TD>
-                                <xsl:value-of select="@total"/>
-                            </TD>
-                        </TR>
-                    </xsl:for-each> <!-- end package -->
-                </TABLE>
-            </DIV>
-
-            <!-- Details of all the executed tests -->
-            <h2 align="center">Detailed Test Report</h2>
-
-            <!-- test package -->
-            <DIV id="testdetail">
-                <xsl:for-each select="TestResult/TestPackage">
-                    <DIV id="none">
-                        <TABLE>
-                            <TR>
-                                <TD class="none" align="left">
-                                    <xsl:variable name="href"><xsl:value-of select="@name"/></xsl:variable>
-                                    <a name="{$href}">Compatibility Test Package: <xsl:value-of select="@name"/></a>
-                                </TD>
-                            </TR>
-                        </TABLE>
-                    </DIV>
-
-                    <TABLE>
-                        <TR>
-                            <TH width="25%">Test</TH>
-                            <TH width="7%">Result</TH>
-                            <TH width="68%">Failure Details</TH>
-                        </TR>
-
-                        <!-- test case -->
-                        <xsl:for-each select="TestCase">
-
-                            <!-- emit a blank row before every test suite name -->
-                            <xsl:if test="position()!=1">
-                                <TR> <TD class="testcasespacer" colspan="3"></TD> </TR>
-                            </xsl:if>
-
-
-                            <TR>
-                                <TD class="testcase" colspan="3">
-                                    <xsl:value-of select="@name"/>
-                                </TD>
-                            </TR>
-                            
-                            <!-- test -->
-                            <xsl:for-each select="Test">
-                                <TR>
-                                    <TD class="testname"> -- <xsl:value-of select="@name"/></TD>
-
-                                    <!-- test results -->
-                                    <xsl:choose>
-                                        <xsl:when test="string(@KnownFailure)">
-                                            <!-- "pass" indicates the that test actually passed (results have been inverted already) -->
-                                            <xsl:if test="@result='pass'">
-                                                <TD class="pass">
-                                                    <div style="text-align: center; margin-left:auto; margin-right:auto;">
-                                                        known problem
-                                                    </div>
-                                                </TD>
-                                                <TD class="failuredetails"></TD>
-                                            </xsl:if>
-
-                                            <!-- "fail" indicates that a known failure actually passed (results have been inverted already) -->
-                                            <xsl:if test="@result='fail'">
-                                                <TD class="failed">
-                                                    <div style="text-align: center; margin-left:auto; margin-right:auto;">
-                                                        <xsl:value-of select="@result"/>
-                                                    </div>
-                                                </TD>
-                                               <TD class="failuredetails">
-                                                    <div id="details">
-                                                        A test that was a known failure actually passed. Please check.
-                                                    </div>
-                                               </TD>
-                                            </xsl:if>
-                                        </xsl:when>
-
-                                        <xsl:otherwise>
-                                            <xsl:if test="@result='pass'">
-                                                <TD class="pass">
-                                                    <div style="text-align: center; margin-left:auto; margin-right:auto;">
-                                                        <xsl:value-of select="@result"/>
-                                                    </div>
-                                                </TD>
-                                                <TD class="failuredetails"></TD>
-                                            </xsl:if>
-
-                                            <xsl:if test="@result='fail'">
-                                                <TD class="failed">
-                                                    <div style="text-align: center; margin-left:auto; margin-right:auto;">
-                                                        <xsl:value-of select="@result"/>
-                                                    </div>
-                                                </TD>
-                                                <TD class="failuredetails">
-                                                    <div id="details">
-                                                        <xsl:value-of select="FailedScene/@message"/>
-                                                    </div>
-                                                </TD>
-                                            </xsl:if>
-
-                                            <xsl:if test="@result='timeout'">
-                                                <TD class="timeout">
-                                                    <div style="text-align: center; margin-left:auto; margin-right:auto;">
-                                                        <xsl:value-of select="@result"/>
-                                                    </div>
-                                                <TD class="failuredetails"></TD>
-                                                </TD>
-                                            </xsl:if>
-
-                                            <xsl:if test="@result='omitted'">
-                                                <TD class="omitted">
-                                                    <div style="text-align: center; margin-left:auto; margin-right:auto;">
-                                                        <xsl:value-of select="@result"/>
-                                                    </div>
-                                                </TD>
-                                                <TD class="failuredetails"></TD>
-                                            </xsl:if>
-
-                                            <xsl:if test="@result='notExecuted'">
-                                                <TD class="notExecuted">
-                                                    <div style="text-align: center; margin-left:auto; margin-right:auto;">
-                                                        <xsl:value-of select="@result"/>
-                                                    </div>
-                                                </TD>
-                                                <TD class="failuredetails"></TD>
-                                            </xsl:if>
-                                        </xsl:otherwise>
-                                    </xsl:choose>
-                                </TR> <!-- finished with a row -->
-                            </xsl:for-each> <!-- end test -->
-                        </xsl:for-each> <!-- end test case -->
-                    </TABLE>
-                </xsl:for-each> <!-- end test package -->
-            </DIV>
-            </body>
-        </html>
-    </xsl:template>
-
-    <!-- Take a delimited string and insert line breaks after a some number of elements. --> 
-    <xsl:template name="formatDelimitedString">
-        <xsl:param name="string" />
-        <xsl:param name="numTokensPerRow" select="10" />
-        <xsl:param name="tokenIndex" select="1" />
-        <xsl:if test="$string">
-            <!-- Requires the last element to also have a delimiter after it. -->
-            <xsl:variable name="token" select="substring-before($string, ';')" />
-            <xsl:value-of select="$token" />
-            <xsl:text>&#160;</xsl:text>
-          
-            <xsl:if test="$tokenIndex mod $numTokensPerRow = 0">
-                <br />
-            </xsl:if>
-
-            <xsl:call-template name="formatDelimitedString">
-                <xsl:with-param name="string" select="substring-after($string, ';')" />
-                <xsl:with-param name="numTokensPerRow" select="$numTokensPerRow" />
-                <xsl:with-param name="tokenIndex" select="$tokenIndex + 1" />
-            </xsl:call-template>
-        </xsl:if>
-    </xsl:template>
-
-</xsl:stylesheet>
diff --git a/tools/tradefed-host/res/result/logo.gif b/tools/tradefed-host/res/result/logo.gif
deleted file mode 100644
index 61970b3..0000000
--- a/tools/tradefed-host/res/result/logo.gif
+++ /dev/null
Binary files differ
diff --git a/tools/tradefed-host/res/result/newrule-green.png b/tools/tradefed-host/res/result/newrule-green.png
deleted file mode 100644
index 10a4194..0000000
--- a/tools/tradefed-host/res/result/newrule-green.png
+++ /dev/null
Binary files differ
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/result/CtsXmlResultReporter.java b/tools/tradefed-host/src/com/android/cts/tradefed/result/CtsXmlResultReporter.java
index 4c29b01..fcbb5ee 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/result/CtsXmlResultReporter.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/result/CtsXmlResultReporter.java
@@ -26,7 +26,6 @@
 import com.android.tradefed.result.LogDataType;
 import com.android.tradefed.result.TestResult;
 import com.android.tradefed.result.TestRunResult;
-import com.android.tradefed.result.TestResult.TestStatus;
 import com.android.tradefed.targetsetup.IBuildInfo;
 import com.android.tradefed.targetsetup.IFolderBuildInfo;
 import com.android.tradefed.util.FileUtil;
@@ -44,7 +43,6 @@
 import java.text.SimpleDateFormat;
 import java.util.Date;
 import java.util.HashMap;
-import java.util.LinkedHashMap;
 import java.util.Map;
 import java.util.concurrent.TimeUnit;
 
@@ -60,15 +58,14 @@
     private static final String LOG_TAG = "CtsXmlResultReporter";
 
     private static final String TEST_RESULT_FILE_NAME = "testResult.xml";
-    private static final String CTS_RESULT_FILE_VERSION = "2.0";
+    private static final String CTS_RESULT_FILE_VERSION = "1.10";
     private static final String CTS_VERSION = "99";
 
-
     private static final String[] CTS_RESULT_RESOURCES = {"cts_result.xsl", "cts_result.css",
         "logo.gif", "newrule-green.png"};
 
     /** the XML namespace */
-    private static final String ns = null;
+    static final String ns = null;
 
     private static final String REPORT_DIR_NAME = "output-file-path";
     @Option(name=REPORT_DIR_NAME, description="root file system path to directory to store xml " +
@@ -80,6 +77,8 @@
 
     private String mStartTime;
 
+    private String mReportPath = "";
+
     public void setReportDir(File reportDir) {
         mReportDir = reportDir;
     }
@@ -115,7 +114,17 @@
      */
     @Override
     public void testLog(String dataName, LogDataType dataType, InputStream dataStream) {
-        // TODO: implement this
+        // save as zip file in report dir
+        // TODO: ensure uniqueness of file name
+        // TODO: use dataType.getFileExt() when its made public
+        String fileName = String.format("%s.%s", dataName, dataType.name().toLowerCase());
+        // TODO: consider compressing large files
+        File logFile = new File(mReportDir, fileName);
+        try {
+            FileUtil.writeToFile(dataStream, logFile);
+        } catch (IOException e) {
+            Log.e(LOG_TAG, String.format("Failed to write log %s", logFile.getAbsolutePath()));
+        }
     }
 
     /**
@@ -171,7 +180,7 @@
             serializer.endDocument();
             // TODO: output not executed timeout omitted counts
             String msg = String.format("XML test result file generated at %s. Total tests %d, " +
-                    "Failed %d, Error %d", reportDir.getAbsolutePath(), getNumTotalTests(),
+                    "Failed %d, Error %d", getReportPath(), getNumTotalTests(),
                     getNumFailedTests(), getNumErrorTests());
             Log.logAndDisplay(LogLevel.INFO, LOG_TAG, msg);
             Log.logAndDisplay(LogLevel.INFO, LOG_TAG, String.format("Time: %s",
@@ -188,6 +197,10 @@
         }
     }
 
+    private String getReportPath() {
+        return mReportPath;
+    }
+
     /**
      * Output the results XML.
      *
@@ -201,7 +214,6 @@
         serializer.startTag(ns, "TestResult");
         // TODO: output test plan and profile values
         serializer.attribute(ns, "testPlan", "unknown");
-        serializer.attribute(ns, "profile", "unknown");
         serializer.attribute(ns, "starttime", startTime);
         serializer.attribute(ns, "endtime", endTime);
         serializer.attribute(ns, "version", CTS_RESULT_FILE_VERSION);
@@ -387,12 +399,10 @@
         serializer.startTag(ns, "Summary");
         serializer.attribute(ns, "failed", Integer.toString(getNumErrorTests() +
                 getNumFailedTests()));
-        // TODO: output notExecuted, timeout, and omitted count
+        // TODO: output notExecuted, timeout count
         serializer.attribute(ns, "notExecuted", "0");
         serializer.attribute(ns, "timeout", "0");
-        serializer.attribute(ns, "omitted", "0");
         serializer.attribute(ns, "pass", Integer.toString(getNumPassedTests()));
-        serializer.attribute(ns, "total", Integer.toString(getNumTotalTests()));
         serializer.endTag(ns, "Summary");
     }
 
@@ -423,130 +433,34 @@
         }
         serializer.startTag(ns, "TestPackage");
         serializer.attribute(ns, "name", runResult.getName());
-        serializer.attribute(ns, "runTime", formatElapsedTime(runResult.getElapsedTime()));
-        // TODO: generate digest
-        serializer.attribute(ns, "digest", "");
-        serializer.attribute(ns, "failed", Integer.toString(runResult.getNumErrorTests() +
-                runResult.getNumFailedTests()));
-        // TODO: output notExecuted, timeout, and omitted count
-        serializer.attribute(ns, "notExecuted", "0");
-        serializer.attribute(ns, "timeout", "0");
-        serializer.attribute(ns, "omitted", "0");
-        serializer.attribute(ns, "pass", Integer.toString(runResult.getNumPassedTests()));
-        serializer.attribute(ns, "total", Integer.toString(runResult.getNumTests()));
+        serializer.attribute(ns, "appPackageName", runResult.getName());
+        serializer.attribute(ns, "digest", getMetric(runResult, "digest"));
 
-        // the results XML needs to organize test's by class. Build a nested data structure that
-        // group's the results by class name
-        Map<String, Map<TestIdentifier, TestResult>> classResultsMap = buildClassNameMap(
-                runResult.getTestResults());
+        // Dump the results.
 
-        for (Map.Entry<String, Map<TestIdentifier, TestResult>> resultsEntry :
-                classResultsMap.entrySet()) {
-            serializer.startTag(ns, "TestCase");
-            serializer.attribute(ns, "name", resultsEntry.getKey());
-            serializeTests(serializer, resultsEntry.getValue());
-            serializer.endTag(ns, "TestCase");
+        // organize the tests into data structures that mirror the expected xml output.
+        TestSuiteRoot suiteRoot = new TestSuiteRoot();
+        for (Map.Entry<TestIdentifier, TestResult> testEntry : runResult.getTestResults()
+                .entrySet()) {
+            suiteRoot.insertTest(testEntry.getKey(), testEntry.getValue());
         }
+        suiteRoot.serialize(serializer);
         serializer.endTag(ns, "TestPackage");
     }
 
     /**
-     * Organizes the test run results into a format organized by class name.
-     */
-    private Map<String, Map<TestIdentifier, TestResult>> buildClassNameMap(
-            Map<TestIdentifier, TestResult> results) {
-        // use a linked hashmap to have predictable iteration order
-        Map<String, Map<TestIdentifier, TestResult>> classResultMap =
-            new LinkedHashMap<String, Map<TestIdentifier, TestResult>>();
-        for (Map.Entry<TestIdentifier, TestResult> resultEntry : results.entrySet()) {
-            String className = resultEntry.getKey().getClassName();
-            Map<TestIdentifier, TestResult> resultsForClass = classResultMap.get(className);
-            if (resultsForClass == null) {
-                resultsForClass = new LinkedHashMap<TestIdentifier, TestResult>();
-                classResultMap.put(className, resultsForClass);
-            }
-            resultsForClass.put(resultEntry.getKey(), resultEntry.getValue());
-        }
-        return classResultMap;
-    }
-
-    /**
-     * Output XML for given map of tests their results
+     * Helper method to retrieve the metric value with given name, or blank if not found
      *
-     * @param serializer
-     * @param results
-     * @throws IOException
-     */
-    private void serializeTests(KXmlSerializer serializer, Map<TestIdentifier, TestResult> results)
-            throws IOException {
-        for (Map.Entry<TestIdentifier, TestResult> resultEntry : results.entrySet()) {
-            serializeTest(serializer, resultEntry.getKey(), resultEntry.getValue());
-        }
-    }
-
-    /**
-     * Output the XML for given test and result.
-     *
-     * @param serializer
-     * @param testId
-     * @param result
-     * @throws IOException
-     */
-    private void serializeTest(KXmlSerializer serializer, TestIdentifier testId, TestResult result)
-            throws IOException {
-        serializer.startTag(ns, "Test");
-        serializer.attribute(ns, "name", testId.getTestName());
-        serializer.attribute(ns, "result", convertStatus(result.getStatus()));
-
-        if (result.getStackTrace() != null) {
-            String sanitizedStack = sanitizeStackTrace(result.getStackTrace());
-            serializer.startTag(ns, "FailedScene");
-            serializer.attribute(ns, "message", getFailureMessageFromStackTrace(sanitizedStack));
-            serializer.text(sanitizedStack);
-            serializer.endTag(ns, "FailedScene");
-        }
-        serializer.endTag(ns, "Test");
-    }
-
-    /**
-     * Convert a {@link TestStatus} to the result text to output in XML
-     *
-     * @param status the {@link TestStatus}
+     * @param runResult
+     * @param string
      * @return
      */
-    private String convertStatus(TestStatus status) {
-        switch (status) {
-            case ERROR:
-                return "fail";
-            case FAILURE:
-                return "fail";
-            case PASSED:
-                return "pass";
-            // TODO add notExecuted, omitted timeout
+    private String getMetric(TestRunResult runResult, String keyName) {
+        String value = runResult.getRunMetrics().get(keyName);
+        if (value == null) {
+            return "";
         }
-        return "omitted";
-    }
-
-    /**
-     * Strip out any invalid XML characters that might cause the report to be unviewable.
-     * http://www.w3.org/TR/REC-xml/#dt-character
-     */
-    private static String sanitizeStackTrace(String trace) {
-        if (trace != null) {
-            return trace.replaceAll("[^\\u0009\\u000A\\u000D\\u0020-\\uD7FF\\uE000-\\uFFFD]", "");
-        } else {
-            return null;
-        }
-    }
-
-    private static String getFailureMessageFromStackTrace(String stack) {
-        // This is probably too simplistic to work in all cases, but for now, just return first
-        // line of stack as failure message
-        int firstNewLine = stack.indexOf('\n');
-        if (firstNewLine != -1) {
-            return stack.substring(0, firstNewLine);
-        }
-        return stack;
+        return value;
     }
 
     /**
@@ -594,11 +508,14 @@
 
     /**
      * Creates the output stream to use for test results. Exposed for mocking.
+     * @param mReportPath
      */
     OutputStream createOutputResultStream(File reportDir) throws IOException {
         File reportFile = new File(reportDir, TEST_RESULT_FILE_NAME);
         Log.i(LOG_TAG, String.format("Created xml report file at %s",
                 reportFile.getAbsolutePath()));
+        // TODO: convert to path relative to cts root
+        mReportPath = reportFile.getAbsolutePath();
         return new FileOutputStream(reportFile);
     }
 
@@ -610,7 +527,7 @@
     private void copyFormattingFiles(File resultsDir) {
         for (String resultFileName : CTS_RESULT_RESOURCES) {
             InputStream configStream = getClass().getResourceAsStream(
-                    String.format("/result/%s", resultFileName));
+                    String.format("%s", resultFileName));
             if (configStream != null) {
                 File resultFile = new File(resultsDir, resultFileName);
                 try {
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/result/TestCase.java b/tools/tradefed-host/src/com/android/cts/tradefed/result/TestCase.java
new file mode 100644
index 0000000..3fce8c4
--- /dev/null
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/result/TestCase.java
@@ -0,0 +1,130 @@
+/*
+ * 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 com.android.cts.tradefed.result;
+
+import com.android.tradefed.result.TestResult;
+import com.android.tradefed.result.TestResult.TestStatus;
+
+import org.kxml2.io.KXmlSerializer;
+
+import java.io.IOException;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * Data structure that represents a "TestCase" XML element and its children.
+ */
+class TestCase {
+
+    private final String mName;
+
+    Map<String, TestResult> mChildTestMap = new LinkedHashMap<String, TestResult>();
+
+    /**
+     * Create a {@link TestCase}
+     * @param testCaseName
+     */
+    public TestCase(String testCaseName) {
+        mName = testCaseName;
+    }
+
+    /**
+     * Inserts given test result
+     *
+     * @param testName
+     * @param testResult
+     */
+    public void insertTest(String testName, TestResult testResult) {
+        mChildTestMap.put(testName, testResult);
+    }
+
+    /**
+     * Serialize this object and all its contents to XML.
+     *
+     * @param serializer
+     * @throws IOException
+     */
+    public void serialize(KXmlSerializer serializer) throws IOException {
+        serializer.startTag(CtsXmlResultReporter.ns, "TestCase");
+        serializer.attribute(CtsXmlResultReporter.ns, "name", mName);
+        // unused
+        serializer.attribute(CtsXmlResultReporter.ns, "priority", "");
+        for (Map.Entry<String, TestResult> resultEntry: mChildTestMap.entrySet()) {
+            serializeTestResult(serializer, resultEntry.getKey(), resultEntry.getValue());
+        }
+       serializer.endTag(CtsXmlResultReporter.ns, "TestCase");
+    }
+
+    private void serializeTestResult(KXmlSerializer serializer, String name, TestResult result)
+            throws IOException {
+        serializer.startTag(CtsXmlResultReporter.ns, "Test");
+        serializer.attribute(CtsXmlResultReporter.ns, "name", name);
+        serializer.attribute(CtsXmlResultReporter.ns, "result", convertStatus(result.getStatus()));
+
+        if (result.getStackTrace() != null) {
+            String sanitizedStack = sanitizeStackTrace(result.getStackTrace());
+            serializer.startTag(CtsXmlResultReporter.ns, "FailedScene");
+            serializer.attribute(CtsXmlResultReporter.ns, "message",
+                    getFailureMessageFromStackTrace(sanitizedStack));
+            serializer.text(sanitizedStack);
+            serializer.endTag(CtsXmlResultReporter.ns, "FailedScene");
+        }
+
+        serializer.endTag(CtsXmlResultReporter.ns, "Test");
+
+    }
+
+    /**
+     * Convert a {@link TestStatus} to the result text to output in XML
+     *
+     * @param status the {@link TestStatus}
+     * @return
+     */
+    private String convertStatus(TestStatus status) {
+        switch (status) {
+            case ERROR:
+                return "fail";
+            case FAILURE:
+                return "fail";
+            case PASSED:
+                return "pass";
+            // TODO add notExecuted
+        }
+        return "omitted";
+    }
+
+    /**
+     * Strip out any invalid XML characters that might cause the report to be unviewable.
+     * http://www.w3.org/TR/REC-xml/#dt-character
+     */
+    private static String sanitizeStackTrace(String trace) {
+        if (trace != null) {
+            return trace.replaceAll("[^\\u0009\\u000A\\u000D\\u0020-\\uD7FF\\uE000-\\uFFFD]", "");
+        } else {
+            return null;
+        }
+    }
+
+    private static String getFailureMessageFromStackTrace(String stack) {
+        // This is probably too simplistic to work in all cases, but for now, just return first
+        // line of stack as failure message
+        int firstNewLine = stack.indexOf('\n');
+        if (firstNewLine != -1) {
+            return stack.substring(0, firstNewLine);
+        }
+        return stack;
+    }
+}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/result/TestSuite.java b/tools/tradefed-host/src/com/android/cts/tradefed/result/TestSuite.java
new file mode 100644
index 0000000..7711740
--- /dev/null
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/result/TestSuite.java
@@ -0,0 +1,116 @@
+/*
+ * 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 com.android.cts.tradefed.result;
+
+import com.android.tradefed.result.TestResult;
+
+import org.kxml2.io.KXmlSerializer;
+
+import java.io.IOException;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Data structure that represents a "TestSuite" XML element and its children.
+ */
+class TestSuite {
+
+    private final String mName;
+
+    // use linked hash map for predictable iteration order
+    Map<String, TestSuite> mChildSuiteMap = new LinkedHashMap<String, TestSuite>();
+    Map<String, TestCase> mChildTestCaseMap = new LinkedHashMap<String, TestCase>();
+
+    /**
+     * @param testSuite
+     */
+    public TestSuite(String suiteName) {
+        mName = suiteName;
+    }
+
+    /**
+     * Insert the given test result into this suite.
+     *
+     * @param suiteNames list of remaining suite names for this test
+     * @param testClassName the test class name
+     * @param testName the test method name
+     * @param testResult the {@link TestResult}
+     */
+    public void insertTest(List<String> suiteNames, String testClassName, String testName,
+            TestResult testResult) {
+        if (suiteNames.size() <= 0) {
+            // no more package segments
+            TestCase testCase = getTestCase(testClassName);
+            testCase.insertTest(testName, testResult);
+        } else {
+            String rootName = suiteNames.remove(0);
+            TestSuite suite = getTestSuite(rootName);
+            suite.insertTest(suiteNames, testClassName, testName, testResult);
+        }
+    }
+
+    /**
+     * Get the child {@link TestSuite} with given name, creating if necessary.
+     *
+     * @param suiteName
+     * @return the {@link TestSuite}
+     */
+    private TestSuite getTestSuite(String suiteName) {
+        TestSuite testSuite = mChildSuiteMap.get(suiteName);
+        if (testSuite == null) {
+            testSuite = new TestSuite(suiteName);
+            mChildSuiteMap.put(suiteName, testSuite);
+        }
+        return testSuite;
+    }
+
+    /**
+     * Get the child {@link TestCase} with given name, creating if necessary.
+     * @param testCaseName
+     * @return
+     */
+    private TestCase getTestCase(String testCaseName) {
+        TestCase testCase = mChildTestCaseMap.get(testCaseName);
+        if (testCase == null) {
+            testCase = new TestCase(testCaseName);
+            mChildTestCaseMap.put(testCaseName, testCase);
+        }
+        return testCase;
+    }
+
+    /**
+     * Serialize this object and all its contents to XML.
+     *
+     * @param serializer
+     * @throws IOException
+     */
+    public void serialize(KXmlSerializer serializer) throws IOException {
+        if (mName != null) {
+            serializer.startTag(CtsXmlResultReporter.ns, "TestSuite");
+            serializer.attribute(CtsXmlResultReporter.ns, "name", mName);
+        }
+        for (TestSuite childSuite : mChildSuiteMap.values()) {
+            childSuite.serialize(serializer);
+        }
+        for (TestCase childCase : mChildTestCaseMap.values()) {
+            childCase.serialize(serializer);
+        }
+        if (mName != null) {
+            serializer.endTag(CtsXmlResultReporter.ns, "TestSuite");
+        }
+    }
+}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/result/TestSuiteRoot.java b/tools/tradefed-host/src/com/android/cts/tradefed/result/TestSuiteRoot.java
new file mode 100644
index 0000000..bb0b0fb
--- /dev/null
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/result/TestSuiteRoot.java
@@ -0,0 +1,63 @@
+/*
+ * 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 com.android.cts.tradefed.result;
+
+import com.android.ddmlib.Log;
+import com.android.ddmlib.testrunner.TestIdentifier;
+import com.android.tradefed.result.TestResult;
+
+import java.util.Arrays;
+import java.util.LinkedList;
+import java.util.List;
+
+/**
+ * Helper class for converting test results into the CTS XML serialization format.
+ * <p/>
+ * A TestIdentifier with name "com.example.ExampleTest#testExample will get serialized as the
+ * following XML
+ * <pre>
+ * TestSuite name="com"
+ *    TestSuite name ="example"
+ *        TestCase name = "ExampleTest"
+ *            Test name="testExample"
+ * </pre>
+ */
+class TestSuiteRoot extends TestSuite {
+
+    private static final String LOG_TAG = "TestSuiteRoot";
+
+    public TestSuiteRoot() {
+        super(null);
+    }
+
+    /**
+     * Insert the given test result.
+     *
+     * @param testId
+     * @param testResult
+     */
+    public void insertTest(TestIdentifier testId, TestResult testResult) {
+        List<String> classNameSegments = new LinkedList<String>();
+        classNameSegments.addAll(Arrays.asList(testId.getClassName().split("\\.")));
+        if (classNameSegments.size() <= 0) {
+            Log.e(LOG_TAG, String.format("Unrecognized package name format for test class '%s'",
+                    testId.getClassName()));
+        } else {
+            String testCaseName = classNameSegments.remove(classNameSegments.size()-1);
+            insertTest(classNameSegments, testCaseName, testId.getTestName(), testResult);
+        }
+    }
+}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/targetsetup/CtsBuildProvider.java b/tools/tradefed-host/src/com/android/cts/tradefed/targetsetup/CtsBuildProvider.java
index 90fb8ba..131c605 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/targetsetup/CtsBuildProvider.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/targetsetup/CtsBuildProvider.java
@@ -50,4 +50,11 @@
     public void buildNotTested(IBuildInfo info) {
         // ignore
     }
+
+    /**
+     * {@inheritDoc}
+     */
+    public void cleanUp(IBuildInfo info) {
+        // ignore
+    }
 }
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/targetsetup/CtsSetup.java b/tools/tradefed-host/src/com/android/cts/tradefed/targetsetup/CtsSetup.java
index 77b4656..2ae939c 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/targetsetup/CtsSetup.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/targetsetup/CtsSetup.java
@@ -15,7 +15,7 @@
  */
 package com.android.cts.tradefed.targetsetup;
 
-import com.android.cts.tradefed.testtype.PlanTest;
+import com.android.cts.tradefed.testtype.CtsTest;
 import com.android.tradefed.config.ConfigurationException;
 import com.android.tradefed.config.IConfiguration;
 import com.android.tradefed.config.IConfigurationReceiver;
@@ -74,9 +74,9 @@
         try {
             CtsBuildHelper buildHelper = createBuildHelper(ctsBuildInfo.getRootDir());
             // pass necessary build information to the other config objects
-            mConfiguration.injectOptionValue(PlanTest.TEST_CASES_DIR_OPTION,
+            mConfiguration.injectOptionValue(CtsTest.TEST_CASES_DIR_OPTION,
                     buildHelper.getTestCasesDir().getAbsolutePath());
-            mConfiguration.injectOptionValue(PlanTest.TEST_PLANS_DIR_OPTION,
+            mConfiguration.injectOptionValue(CtsTest.TEST_PLANS_DIR_OPTION,
                     buildHelper.getTestPlansDir().getAbsolutePath());
             installCtsPrereqs(device, buildHelper);
         } catch (FileNotFoundException e) {
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/CtsTest.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/CtsTest.java
new file mode 100644
index 0000000..702956a
--- /dev/null
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/CtsTest.java
@@ -0,0 +1,345 @@
+/*
+ * 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 com.android.cts.tradefed.testtype;
+
+import com.android.cts.tradefed.device.DeviceInfoCollector;
+import com.android.ddmlib.Log;
+import com.android.ddmlib.Log.LogLevel;
+import com.android.tradefed.config.Option;
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.result.ITestInvocationListener;
+import com.android.tradefed.testtype.AbstractRemoteTest;
+import com.android.tradefed.testtype.IDeviceTest;
+import com.android.tradefed.testtype.IRemoteTest;
+import com.android.tradefed.util.xml.AbstractXmlParser.ParseException;
+
+import java.io.BufferedInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import junit.framework.Test;
+
+/**
+ * A {@link Test} for running CTS tests.
+ * <p/>
+ * Supports running all the tests contained in a CTS plan, or individual test packages.
+ */
+public class CtsTest extends AbstractRemoteTest implements IDeviceTest, IRemoteTest {
+
+    private static final String LOG_TAG = "PlanTest";
+
+    public static final String TEST_CASES_DIR_OPTION = "test-cases-path";
+    public static final String TEST_PLANS_DIR_OPTION = "test-plans-path";
+    private static final String PLAN_OPTION = "plan";
+    private static final String PACKAGE_OPTION = "package";
+    private static final String CLASS_OPTION = "class";
+    private static final String METHOD_OPTION = "method";
+
+    private ITestDevice mDevice;
+
+    @Option(name = PLAN_OPTION, description = "the test plan to run")
+    private String mPlanName = null;
+
+    @Option(name = PACKAGE_OPTION, description = "the test packages(s) to run")
+    private Collection<String> mPackageNames = new ArrayList<String>();
+
+    @Option(name = "exclude-package", description = "the test packages(s) to exclude from the run")
+    private Collection<String> mExcludedPackageNames = new ArrayList<String>();
+
+    @Option(name = CLASS_OPTION, shortName = 'c', description = "run a specific test class")
+    private String mClassName = null;
+
+    @Option(name = METHOD_OPTION, shortName = 'm',
+            description = "run a specific test method, from given --class")
+    private String mMethodName = null;
+
+    @Option(name = TEST_CASES_DIR_OPTION, description =
+        "file path to directory containing CTS test cases")
+    private File mTestCaseDir = null;
+
+    @Option(name = TEST_PLANS_DIR_OPTION, description =
+        "file path to directory containing CTS test plans")
+    private File mTestPlanDir = null;
+
+    @Option(name = "collect-device-info", description =
+        "flag to control whether to collect info from device. Default true")
+    private boolean mCollectDeviceInfo = true;
+
+    /**
+     * {@inheritDoc}
+     */
+    public ITestDevice getDevice() {
+        return mDevice;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public void setDevice(ITestDevice device) {
+        mDevice = device;
+    }
+
+    /**
+     * Set the test plan directory.
+     * <p/>
+     * Exposed for unit testing
+     */
+    void setTestPlanDir(File planDir) {
+        mTestPlanDir = planDir;
+    }
+
+    /**
+     * Set the test case directory.
+     * <p/>
+     * Exposed for unit testing
+     */
+    void setTestCaseDir(File testCaseDir) {
+        mTestCaseDir = testCaseDir;
+    }
+
+    /**
+     * Set the plan name to run.
+     * <p/>
+     * Exposed for unit testing
+     */
+    void setPlanName(String planName) {
+        mPlanName = planName;
+    }
+
+    /**
+     * Set the collect device info flag.
+     * <p/>
+     * Exposed for unit testing
+     */
+    void setCollectDeviceInfo(boolean collectDeviceInfo) {
+        mCollectDeviceInfo = collectDeviceInfo;
+    }
+
+    /**
+     * Adds a package name to the list of test packages to run.
+     * <p/>
+     * Exposed for unit testing
+     */
+    void addPackageName(String packageName) {
+        mPackageNames.add(packageName);
+    }
+
+    /**
+     * Adds a package name to the list of test packages to exclude.
+     * <p/>
+     * Exposed for unit testing
+     */
+    void addExcludedPackageName(String packageName) {
+        mExcludedPackageNames.add(packageName);
+    }
+
+    /**
+     * Set the test class name to run.
+     * <p/>
+     * Exposed for unit testing
+     */
+    void setClassName(String className) {
+        mClassName = className;
+    }
+
+    /**
+     * Set the test method name to run.
+     * <p/>
+     * Exposed for unit testing
+     */
+    void setMethodName(String methodName) {
+        mMethodName = methodName;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public void run(List<ITestInvocationListener> listeners) throws DeviceNotAvailableException {
+        checkFields();
+
+        Log.i(LOG_TAG, String.format("Executing CTS test plan %s", mPlanName));
+
+        try {
+            ITestCaseRepo testRepo = createTestCaseRepo();
+            Collection<String> testUris = getTestsToRun(testRepo);
+            collectDeviceInfo(getDevice(), mTestCaseDir, listeners);
+            for (String testUri : testUris) {
+                ITestPackageDef testPackage = testRepo.getTestPackage(testUri);
+                if (testPackage != null) {
+                    runTest(listeners, testPackage);
+                } else {
+                    Log.e(LOG_TAG, String.format("Could not find test package uri %s", testUri));
+                }
+            }
+        } catch (FileNotFoundException e) {
+            throw new IllegalArgumentException("failed to find CTS plan file", e);
+        } catch (ParseException e) {
+            throw new IllegalArgumentException("failed to parse CTS plan file", e);
+        }
+    }
+
+    /**
+     * Return the list of test uris to run
+     *
+     * @return the list of test uris to run
+     * @throws ParseException
+     * @throws FileNotFoundException
+     */
+    private Collection<String> getTestsToRun(ITestCaseRepo testRepo) throws ParseException,
+            FileNotFoundException {
+        Set<String> testUris = new HashSet<String>();
+        if (mPlanName != null) {
+            String ctsPlanRelativePath = String.format("%s.xml", mPlanName);
+            File ctsPlanFile = new File(mTestPlanDir, ctsPlanRelativePath);
+            IPlanXmlParser parser = createXmlParser();
+            parser.parse(createXmlStream(ctsPlanFile));
+            testUris.addAll(parser.getTestUris());
+        } else if (mPackageNames.size() > 0){
+            testUris.addAll(mPackageNames);
+        } else if (mClassName != null) {
+            // try to find package to run from class name
+            String packageUri = testRepo.findPackageForTest(mClassName);
+            if (packageUri != null) {
+                testUris.add(packageUri);
+            } else {
+                Log.logAndDisplay(LogLevel.WARN, LOG_TAG, String.format(
+                        "Could not find package for test class %s", mClassName));
+            }
+        } else {
+            // should never get here - was checkFields() not called?
+            throw new IllegalStateException("nothing to run?");
+        }
+        testUris.removeAll(mExcludedPackageNames);
+        return testUris;
+    }
+
+    private void checkFields() {
+        // for simplicity of command line usage, make --plan, --package, and --class mutually
+        // exclusive
+        boolean mutualExclusiveArgs = xor(mPlanName != null, mPackageNames.size() > 0,
+                mClassName != null);
+
+        if (!mutualExclusiveArgs) {
+            throw new IllegalArgumentException(String.format(
+                    "Ambiguous or missing arguments. " +
+                    "One and only of --%s --%s(s) or --%s to run can be specified",
+                    PLAN_OPTION, PACKAGE_OPTION, CLASS_OPTION));
+        }
+        if (mMethodName != null && mClassName == null) {
+            throw new IllegalArgumentException(String.format(
+                    "Must specify --%s when --%s is used", CLASS_OPTION, METHOD_OPTION));
+        }
+        if (getDevice() == null) {
+            throw new IllegalArgumentException("missing device");
+        }
+        if (mTestCaseDir == null) {
+            throw new IllegalArgumentException(String.format("missing %s option",
+                    TEST_CASES_DIR_OPTION));
+        }
+        if (mTestPlanDir == null) {
+            throw new IllegalArgumentException(String.format("missing %s", TEST_PLANS_DIR_OPTION));
+        }
+    }
+
+    /**
+     * Helper method to perform exclusive or on list of boolean arguments
+     *
+     * @param args set of booleans on which to perform exclusive or
+     * @return <code>true</code> if one and only one of <var>args</code> is <code>true</code>.
+     *         Otherwise return <code>false</code>.
+     */
+    private boolean xor(boolean... args) {
+        boolean currentVal = args[0];
+        for (int i=1; i < args.length; i++) {
+            if (currentVal && args[i]) {
+                return false;
+            }
+            currentVal |= args[i];
+        }
+        return currentVal;
+    }
+
+    /**
+     * Runs the test.
+     *
+     * @param listeners
+     * @param testPackage
+     * @throws DeviceNotAvailableException
+     */
+    private void runTest(List<ITestInvocationListener> listeners, ITestPackageDef testPackage)
+            throws DeviceNotAvailableException {
+        IRemoteTest test = testPackage.createTest(mTestCaseDir, mClassName, mMethodName);
+        if (test != null) {
+            if (test instanceof IDeviceTest) {
+                ((IDeviceTest)test).setDevice(getDevice());
+            }
+            ResultFilter filter = new ResultFilter(listeners, testPackage);
+            test.run(filter);
+        }
+    }
+
+    /**
+     * Runs the device info collector instrumentation on device, and forwards it to test listeners
+     * as run metrics.
+     * <p/>
+     * Exposed so unit tests can mock.
+     *
+     * @param listeners
+     * @throws DeviceNotAvailableException
+     */
+    void collectDeviceInfo(ITestDevice device, File testApkDir,
+            List<ITestInvocationListener> listeners) throws DeviceNotAvailableException {
+        if (mCollectDeviceInfo) {
+            DeviceInfoCollector.collectDeviceInfo(device, testApkDir, listeners);
+        }
+    }
+
+    /**
+     * Factory method for creating a {@link ITestCaseRepo}.
+     * <p/>
+     * Exposed for unit testing
+     */
+    ITestCaseRepo createTestCaseRepo() {
+        return new TestCaseRepo(mTestCaseDir);
+    }
+
+    /**
+     * Factory method for creating a {@link PlanXmlParser}.
+     * <p/>
+     * Exposed for unit testing
+     */
+    IPlanXmlParser createXmlParser() {
+        return new PlanXmlParser();
+    }
+
+    /**
+     * Factory method for creating a {@link InputStream} from a plan xml file.
+     * <p/>
+     * Exposed for unit testing
+     */
+    InputStream createXmlStream(File xmlFile) throws FileNotFoundException {
+        return new BufferedInputStream(new FileInputStream(xmlFile));
+    }
+}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ITestCaseRepo.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ITestCaseRepo.java
index 18ea7cf..ffcde46 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ITestCaseRepo.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ITestCaseRepo.java
@@ -16,9 +16,6 @@
 
 package com.android.cts.tradefed.testtype;
 
-import com.android.tradefed.testtype.IRemoteTest;
-
-import java.util.Collection;
 
 /**
  * Interface for accessing tests from the CTS repository.
@@ -26,11 +23,19 @@
 interface ITestCaseRepo {
 
     /**
-     * Gets a list of tests identified by given list of uris
+     * Get a {@link TestPackageDef} given a uri
      *
-     * @param testUris the string uris
-     * @return a {@link Collection} of {@link IRemoteTest}
+     * @param testUri the string uris
+     * @return a {@link TestPackageDef} or <code>null</code> if the uri cannot be found in repo
      */
-    public Collection<IRemoteTest> getTests(Collection<String> testUris);
+    public ITestPackageDef getTestPackage(String testUri);
+
+    /**
+     * Attempt to find the package uri for a given test class name
+     *
+     * @param testClassName the test class name
+     * @return the package uri or <code>null</code> if the package cannot be found
+     */
+    public String findPackageForTest(String testClassName);
 
 }
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ITestPackageDef.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ITestPackageDef.java
new file mode 100644
index 0000000..057e803
--- /dev/null
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ITestPackageDef.java
@@ -0,0 +1,66 @@
+/*
+ * 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 com.android.cts.tradefed.testtype;
+
+import com.android.ddmlib.testrunner.TestIdentifier;
+import com.android.tradefed.testtype.IRemoteTest;
+
+import java.io.File;
+
+/**
+ * Container for CTS test info.
+ * <p/>
+ * Knows how to translate this info into a runnable {@link IRemoteTest}.
+ */
+interface ITestPackageDef {
+
+    /**
+     * Get the unique URI of the test package.
+     * @return the {@link String} uri
+     */
+    public String getUri();
+
+    /**
+     * Creates a runnable {@link IRemoteTest} from info stored in this definition.
+     *
+     * @param testCaseDir {@link File} representing directory of test case data
+     * @param className the test class to restrict this run to or <code>null</code> to run all tests
+     *            in package
+     * @param methodName the optional test method to restrict this run to, or <code>null</code> to
+     *            run all tests in class/package
+     * @return a {@link IRemoteTest} with all necessary data populated to run the test or
+     *         <code>null</code> if test could not be created
+     */
+    public IRemoteTest createTest(File testCaseDir, String className, String methodName);
+
+    /**
+     * Determine if given test is defined in this package.
+     *
+     * @param testDef the {@link TestIdentifier}
+     * @return <code>true</code> if test is defined
+     */
+    public boolean isKnownTest(TestIdentifier testDef);
+
+    /**
+     * Determine if given test class is defined in this package.
+     *
+     * @param testClassName the fully qualified test class name
+     * @return <code>true</code> if test class is defined
+     */
+    public boolean isKnownTestClass(String testClassName);
+
+}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/InstrumentationAppTest.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/InstrumentationAppTest.java
new file mode 100644
index 0000000..41f9b79
--- /dev/null
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/InstrumentationAppTest.java
@@ -0,0 +1,73 @@
+/*
+ * 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 com.android.cts.tradefed.testtype;
+
+import com.android.ddmlib.Log;
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.result.ITestInvocationListener;
+import com.android.tradefed.testtype.InstrumentationTest;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * A {@link InstrumentationTest] that will install other dependent apks before test execution,
+ * and uninstall apps on execution completion.
+ */
+public class InstrumentationAppTest extends InstrumentationTest {
+
+    private static final String LOG_TAG = "InstrumentationAppTest";
+
+    // TODO: consider moving this class to tradefed proper
+
+    private Collection<File> mInstallFiles = new ArrayList<File>();
+    private Collection<String> mInstallPackages = new ArrayList<String>();
+
+    /**
+     * Add a dependent apk to install.
+     *
+     * @param apkFile the apk file
+     * @param packageName the apk's Android package name
+     */
+    public void addInstallApp(File apkFile, String packageName) {
+        mInstallFiles.add(apkFile);
+        mInstallPackages.add(packageName);
+    }
+
+    @Override
+    public void run(final List<ITestInvocationListener> listeners)
+            throws DeviceNotAvailableException {
+        if (getDevice() == null) {
+            throw new IllegalStateException("missing device");
+        }
+        try {
+            for (File apkFile : mInstallFiles) {
+                Log.d(LOG_TAG, String.format("Installing %s on %s", apkFile.getName(),
+                        getDevice().getSerialNumber()));
+                getDevice().installPackage(apkFile, true);
+            }
+            super.run(listeners);
+        } finally {
+            for (String packageName : mInstallPackages) {
+                Log.d(LOG_TAG, String.format("Uninstalling %s on %s", packageName,
+                        getDevice().getSerialNumber()));
+                getDevice().uninstallPackage(packageName);
+            }
+        }
+    }
+}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/PlanTest.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/PlanTest.java
deleted file mode 100644
index 212eb66..0000000
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/PlanTest.java
+++ /dev/null
@@ -1,184 +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 com.android.cts.tradefed.testtype;
-
-import com.android.cts.tradefed.device.DeviceInfoCollector;
-import com.android.ddmlib.Log;
-import com.android.tradefed.config.Option;
-import com.android.tradefed.device.DeviceNotAvailableException;
-import com.android.tradefed.device.ITestDevice;
-import com.android.tradefed.result.ITestInvocationListener;
-import com.android.tradefed.testtype.AbstractRemoteTest;
-import com.android.tradefed.testtype.IDeviceTest;
-import com.android.tradefed.testtype.IRemoteTest;
-import com.android.tradefed.util.xml.AbstractXmlParser.ParseException;
-
-import java.io.BufferedInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.InputStream;
-import java.util.Collection;
-import java.util.List;
-
-import junit.framework.Test;
-
-/**
- * A {@link Test} that runs all the tests in the CTS test plan with given name
- */
-public class PlanTest extends AbstractRemoteTest implements IDeviceTest, IRemoteTest {
-
-    private static final String LOG_TAG = "PlanTest";
-
-    public static final String TEST_CASES_DIR_OPTION = "test-cases-path";
-    public static final String TEST_PLANS_DIR_OPTION = "test-plans-path";
-
-    private ITestDevice mDevice;
-
-    @Option(name = "plan", description = "the test plan to run")
-    private String mPlanName = null;
-
-    @Option(name = TEST_CASES_DIR_OPTION, description =
-        "file path to directory containing CTS test cases")
-    private File mTestCaseDir = null;
-
-    @Option(name = TEST_PLANS_DIR_OPTION, description =
-        "file path to directory containing CTS test plans")
-    private File mTestPlanDir = null;
-
-    /**
-     * {@inheritDoc}
-     */
-    public ITestDevice getDevice() {
-        return mDevice;
-    }
-
-    /**
-     * {@inheritDoc}
-     */
-    public void setDevice(ITestDevice device) {
-        mDevice = device;
-    }
-
-    /**
-     * Set the test plan directory.
-     * <p/>
-     * Exposed for unit testing
-     */
-    void setTestPlanDir(File planDir) {
-        mTestPlanDir = planDir;
-    }
-
-    /**
-     * Set the test case directory.
-     * <p/>
-     * Exposed for unit testing
-     */
-    void setTestCaseDir(File testCaseDir) {
-        mTestCaseDir = testCaseDir;
-    }
-
-    /**
-     * Set the plan name to run.
-     * <p/>
-     * Exposed for unit testing
-     */
-    void setPlanName(String planName) {
-        mPlanName = planName;
-    }
-
-    /**
-     * {@inheritDoc}
-     */
-    public void run(List<ITestInvocationListener> listeners) throws DeviceNotAvailableException {
-        if (mPlanName == null) {
-            throw new IllegalArgumentException("missing --plan option");
-        }
-        if (getDevice() == null) {
-            throw new IllegalArgumentException("missing device");
-        }
-        if (mTestCaseDir == null) {
-            throw new IllegalArgumentException(String.format("missing %s option",
-                    TEST_CASES_DIR_OPTION));
-        }
-        if (mTestPlanDir == null) {
-            throw new IllegalArgumentException(String.format("missing %s", TEST_PLANS_DIR_OPTION));
-        }
-
-        Log.i(LOG_TAG, String.format("Executing CTS test plan %s", mPlanName));
-
-        try {
-            String ctsPlanRelativePath = String.format("%s.xml", mPlanName);
-            File ctsPlanFile = new File(mTestPlanDir, ctsPlanRelativePath);
-            IPlanXmlParser parser = createXmlParser();
-            parser.parse(createXmlStream(ctsPlanFile));
-            Collection<String> testUris = parser.getTestUris();
-            ITestCaseRepo testRepo = createTestCaseRepo();
-            Collection<IRemoteTest> tests = testRepo.getTests(testUris);
-            collectDeviceInfo(getDevice(), mTestCaseDir, listeners);
-            for (IRemoteTest test : tests) {
-                if (test instanceof IDeviceTest) {
-                    ((IDeviceTest)test).setDevice(getDevice());
-                }
-                test.run(listeners);
-            }
-        } catch (FileNotFoundException e) {
-            throw new IllegalArgumentException("failed to find CTS plan file", e);
-        } catch (ParseException e) {
-            throw new IllegalArgumentException("failed to parse CTS plan file", e);
-        }
-    }
-
-    /**
-     * Runs the device info collector instrumentation on device, and forwards it to test listeners
-     * as run metrics.
-     *
-     * @param listeners
-     * @throws DeviceNotAvailableException
-     */
-    private void collectDeviceInfo(ITestDevice device, File testApkDir,
-            List<ITestInvocationListener> listeners) throws DeviceNotAvailableException {
-        DeviceInfoCollector.collectDeviceInfo(device, testApkDir, listeners);
-    }
-
-    /**
-     * Factory method for creating a {@link ITestCaseRepo}.
-     * <p/>
-     * Exposed for unit testing
-     */
-    ITestCaseRepo createTestCaseRepo() {
-        return new TestCaseRepo(mTestCaseDir);
-    }
-
-    /**
-     * Factory method for creating a {@link PlanXmlParser}.
-     * <p/>
-     * Exposed for unit testing
-     */
-    IPlanXmlParser createXmlParser() {
-        return new PlanXmlParser();
-    }
-
-    /**
-     * Factory method for creating a {@link InputStream} from a plan xml file.
-     * <p/>
-     * Exposed for unit testing
-     */
-    InputStream createXmlStream(File xmlFile) throws FileNotFoundException {
-        return new BufferedInputStream(new FileInputStream(xmlFile));
-    }
-}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ResultFilter.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ResultFilter.java
new file mode 100644
index 0000000..d11ab03
--- /dev/null
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ResultFilter.java
@@ -0,0 +1,186 @@
+/*
+ * 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 com.android.cts.tradefed.testtype;
+
+import com.android.ddmlib.Log;
+import com.android.ddmlib.testrunner.TestIdentifier;
+import com.android.tradefed.result.ITestInvocationListener;
+import com.android.tradefed.result.LogDataType;
+import com.android.tradefed.result.TestSummary;
+import com.android.tradefed.targetsetup.IBuildInfo;
+
+import java.io.InputStream;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * A {@link ITestInvocationListener} that filters test results based on the set of expected tests
+ * in CTS test package xml files.
+ */
+class ResultFilter implements ITestInvocationListener {
+
+    private final List<ITestInvocationListener> mListeners;
+    private final ITestPackageDef mTestPackage;
+
+    /**
+     * Create a {@link ResultFilter}.
+     *
+     * @param listeners the real {@link ITestInvocationListener} to forward results to
+     * @param testPackage the {@link ITestPackageDef} that defines the expected tests
+     */
+    ResultFilter(List<ITestInvocationListener> listeners, ITestPackageDef testPackage) {
+        mListeners = listeners;
+        mTestPackage = testPackage;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void invocationStarted(IBuildInfo buildInfo) {
+        for (ITestInvocationListener listener : mListeners) {
+            listener.invocationStarted(buildInfo);
+        }
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void invocationFailed(Throwable cause) {
+        for (ITestInvocationListener listener : mListeners) {
+            listener.invocationFailed(cause);
+        }
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void invocationEnded(long elapsedTime) {
+        for (ITestInvocationListener listener : mListeners) {
+            listener.invocationEnded(elapsedTime);
+        }
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public TestSummary getSummary() {
+        // should never be called
+        return null;
+    }
+
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void testLog(String dataName, LogDataType dataType, InputStream dataStream) {
+        for (ITestInvocationListener listener : mListeners) {
+            listener.testLog(dataName, dataType, dataStream);
+        }
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void testRunStarted(String runName, int testCount) {
+        for (ITestInvocationListener listener : mListeners) {
+            listener.testRunStarted(runName, testCount);
+        }
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void testRunFailed(String errorMessage) {
+        for (ITestInvocationListener listener : mListeners) {
+            listener.testRunFailed(errorMessage);
+        }
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void testRunStopped(long elapsedTime) {
+        for (ITestInvocationListener listener : mListeners) {
+            listener.testRunStopped(elapsedTime);
+        }
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void testRunEnded(long elapsedTime, Map<String, String> runMetrics) {
+        for (ITestInvocationListener listener : mListeners) {
+            listener.testRunEnded(elapsedTime, runMetrics);
+        }
+        // TODO: consider reporting all remaining tests in mTestPackage as failed tests with
+        // notExecuted result
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void testStarted(TestIdentifier test) {
+        if (isKnownTest(test)) {
+            for (ITestInvocationListener listener : mListeners) {
+                listener.testStarted(test);
+            }
+        } else {
+            Log.d("ResultFilter", String.format("Skipping reporting unknown test %s", test));
+        }
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void testFailed(TestFailure status, TestIdentifier test, String trace) {
+        if (isKnownTest(test)) {
+            for (ITestInvocationListener listener : mListeners) {
+                listener.testFailed(status, test, trace);
+            }
+        }
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void testEnded(TestIdentifier test, Map<String, String> testMetrics) {
+        if (isKnownTest(test)) {
+            for (ITestInvocationListener listener : mListeners) {
+                listener.testEnded(test, testMetrics);
+            }
+        }
+    }
+
+    /**
+     * @param test
+     * @return
+     */
+    private boolean isKnownTest(TestIdentifier test) {
+        return mTestPackage.isKnownTest(test);
+    }
+}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestCaseRepo.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestCaseRepo.java
index 8392762..404da4d 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestCaseRepo.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestCaseRepo.java
@@ -16,7 +16,6 @@
 package com.android.cts.tradefed.testtype;
 
 import com.android.ddmlib.Log;
-import com.android.tradefed.testtype.IRemoteTest;
 import com.android.tradefed.util.xml.AbstractXmlParser.ParseException;
 
 import java.io.BufferedInputStream;
@@ -25,8 +24,6 @@
 import java.io.FileNotFoundException;
 import java.io.FilenameFilter;
 import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.Collection;
 import java.util.Hashtable;
 import java.util.Map;
 
@@ -115,21 +112,21 @@
     /**
      * {@inheritDoc}
      */
-    public Collection<IRemoteTest> getTests(Collection<String> testUris) {
-        Collection<IRemoteTest> tests = new ArrayList<IRemoteTest>(testUris.size());
-        for (String uri : testUris) {
-            TestPackageDef def = mTestMap.get(uri);
-            if (def != null) {
-                IRemoteTest test = def.createTest(mTestCaseDir);
-                if (test != null) {
-                    tests.add(test);
-                } else {
-                    Log.w(LOG_TAG, String.format("Failed to create test from package uri %s", uri));
-                }
-            } else {
-                Log.w(LOG_TAG, String.format("Could not find test with uri %s", uri));
+    @Override
+    public ITestPackageDef getTestPackage(String testUri) {
+        return mTestMap.get(testUri);
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public String findPackageForTest(String testClassName) {
+        for (Map.Entry<String, TestPackageDef> entry : mTestMap.entrySet()) {
+            if (entry.getValue().isKnownTestClass(testClassName)) {
+                return entry.getKey();
             }
         }
-        return tests;
+        return null;
     }
 }
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageDef.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageDef.java
index a75295e..3b89926 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageDef.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageDef.java
@@ -23,15 +23,18 @@
 import java.io.File;
 import java.util.ArrayList;
 import java.util.Collection;
+import java.util.LinkedHashSet;
 
 /**
  * Container for CTS test info.
  * <p/>
  * Knows how to translate this info into a runnable {@link IRemoteTest}.
  */
-public class TestPackageDef {
+class TestPackageDef implements ITestPackageDef {
 
     private static final String LOG_TAG = "TestPackageDef";
+    private static final String SIGNATURE_TEST_METHOD = "testSignature";
+    private static final String SIGNATURE_TEST_CLASS = "android.tests.sigtest.SimpleSignatureTest";
 
     private String mUri = null;
     private String mAppNameSpace = null;
@@ -41,16 +44,20 @@
     private String mJarPath = null;
     private boolean mIsSignatureTest = false;
     private boolean mIsReferenceAppTest = false;
+    private String mPackageToTest = null;
+    private String mApkToTestName = null;
 
-    private Collection<TestIdentifier> mTests = new ArrayList<TestIdentifier>();
+    // use a LinkedHashSet for predictable iteration insertion-order, and fast lookups
+    private Collection<TestIdentifier> mTests = new LinkedHashSet<TestIdentifier>();
+    // also maintain an index of known test classes
+    private Collection<String> mTestClasses = new LinkedHashSet<String>();
 
     void setUri(String uri) {
         mUri = uri;
     }
 
     /**
-     * Get the unique URI of the test package.
-     * @return the {@link String} uri
+     * {@inheritDoc}
      */
     public String getUri() {
         return mUri;
@@ -113,37 +120,38 @@
         return mIsReferenceAppTest;
     }
 
+    void setPackageToTest(String packageName) {
+        mPackageToTest = packageName;
+    }
+
+    void setApkToTest(String apkName) {
+        mApkToTestName = apkName;
+    }
+
     /**
-     * Creates a runnable {@link IRemoteTest} from info stored in this definition.
-     *
-     * @param testCaseDir {@link File} representing directory of test case data
-     * @return a {@link IRemoteTest} with all necessary data populated to run the test or
-     *         <code>null</code> if test could not be created
+     * {@inheritDoc}
      */
-    public IRemoteTest createTest(File testCaseDir) {
+    public IRemoteTest createTest(File testCaseDir, String className, String methodName) {
         if (mIsHostSideTest) {
             Log.d(LOG_TAG, String.format("Creating host test for %s", mName));
             JarHostTest hostTest = new JarHostTest();
             hostTest.setRunName(mName);
             hostTest.setJarFile(new File(testCaseDir, mJarPath));
             hostTest.setTestAppPath(testCaseDir.getAbsolutePath());
-            hostTest.setTests(mTests);
+            hostTest.setTests(filterTests(mTests, className, methodName));
             return hostTest;
         } else if (mIsSignatureTest) {
-            // TODO: implement this
-            Log.w(LOG_TAG, String.format("Skipping currently unsupported signature test %s",
-                    mName));
-            return null;
-        } else if (mIsReferenceAppTest) {
-            // TODO: implement this
-            Log.w(LOG_TAG, String.format("Skipping currently unsupported reference app test %s",
-                    mName));
-            return null;
-        } else {
-            Log.d(LOG_TAG, String.format("Creating instrumentation test for %s", mName));
+            // TODO: hardcode the runner/class/method for now, since current package xml
+            // points to specialized instrumentation. Eventually this special case for signatureTest
+            // can be removed, and it can be treated just like a normal InstrumentationTest
+            Log.d(LOG_TAG, String.format("Creating signature test %s", mName));
             InstrumentationTest instrTest = new InstrumentationTest();
             instrTest.setPackageName(mAppNameSpace);
-            instrTest.setRunnerName(mRunner);
+            instrTest.setRunnerName("android.test.InstrumentationTestRunner");
+            instrTest.setClassName(SIGNATURE_TEST_CLASS);
+            instrTest.setMethodName(SIGNATURE_TEST_METHOD);
+            // add signature test to list of known tests
+            addTest(new TestIdentifier(SIGNATURE_TEST_CLASS, SIGNATURE_TEST_METHOD));
             // mName means 'apk file name' for instrumentation tests
             File apkFile = new File(testCaseDir, String.format("%s.apk", mName));
             if (!apkFile.exists()) {
@@ -153,16 +161,93 @@
             }
             instrTest.setInstallFile(apkFile);
             return instrTest;
+        } else if (mIsReferenceAppTest) {
+            // a reference app test is just a InstrumentationTest with one extra apk to install
+            InstrumentationAppTest instrTest = new InstrumentationAppTest();
+            File apkFile = new File(testCaseDir, String.format("%s.apk", mApkToTestName));
+            if (!apkFile.exists()) {
+                Log.w(LOG_TAG, String.format("Could not find apk file %s",
+                        apkFile.getAbsolutePath()));
+                return null;
+            }
+            instrTest.addInstallApp(apkFile, mPackageToTest);
+            return setInstrumentationTest(testCaseDir, className, methodName, instrTest);
+        } else {
+            Log.d(LOG_TAG, String.format("Creating instrumentation test for %s", mName));
+            InstrumentationTest instrTest = new InstrumentationTest();
+            return setInstrumentationTest(testCaseDir, className, methodName, instrTest);
         }
     }
 
     /**
+     * Populates given {@link InstrumentationTest} with data from the package xml
+     *
+     * @param testCaseDir
+     * @param className
+     * @param methodName
+     * @param instrTest
+     * @return the populated {@link InstrumentationTest} or <code>null</code>
+     */
+    private InstrumentationTest setInstrumentationTest(File testCaseDir, String className,
+            String methodName, InstrumentationTest instrTest) {
+        instrTest.setPackageName(mAppNameSpace);
+        instrTest.setRunnerName(mRunner);
+        instrTest.setClassName(className);
+        instrTest.setMethodName(methodName);
+        // mName means 'apk file name' for instrumentation tests
+        File apkFile = new File(testCaseDir, String.format("%s.apk", mName));
+        if (!apkFile.exists()) {
+            Log.w(LOG_TAG, String.format("Could not find apk file %s",
+                    apkFile.getAbsolutePath()));
+            return null;
+        }
+        instrTest.setInstallFile(apkFile);
+        return instrTest;
+    }
+
+    /**
+     * Filter the tests to run based on class and method name
+     *
+     * @param tests the full set of tests in package
+     * @param className the test class name filter. <code>null</code> to run all test classes
+     * @param methodName the test method name. <code>null</code> to run all test methods
+     * @return the filtered collection of tests
+     */
+    private Collection<TestIdentifier> filterTests(Collection<TestIdentifier> tests,
+            String className, String methodName) {
+        Collection<TestIdentifier> filteredTests = new ArrayList<TestIdentifier>(tests.size());
+        for (TestIdentifier test : tests) {
+            if (className == null || test.getClassName().equals(className)) {
+                if (methodName == null || test.getTestName().equals(methodName)) {
+                    filteredTests.add(test);
+                }
+            }
+        }
+        return filteredTests;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public boolean isKnownTest(TestIdentifier testDef) {
+        return mTests.contains(testDef);
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public boolean isKnownTestClass(String className) {
+        return mTestClasses.contains(className);
+    }
+
+    /**
      * Add a {@link TestDef} to the list of tests in this package.
      *
      * @param testdef
      */
     void addTest(TestIdentifier testDef) {
         mTests.add(testDef);
+        mTestClasses.add(testDef.getClassName());
     }
 
     /**
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageXmlParser.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageXmlParser.java
index 9bf6968..d12fb9d 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageXmlParser.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageXmlParser.java
@@ -70,6 +70,8 @@
                 final String jarPath = attributes.getValue("jarPath");
                 final String signatureCheck = attributes.getValue("signatureCheck");
                 final String referenceApp = attributes.getValue("referenceAppTest");
+                final String apkToTest = attributes.getValue("apkToTestName");
+                final String packageToTest = attributes.getValue("packageToTest");
 
                 mPackageDef = new TestPackageDef();
                 mPackageDef.setUri(entryUriValue);
@@ -80,6 +82,8 @@
                 mPackageDef.setJarPath(jarPath);
                 mPackageDef.setIsSignatureCheck(parseBoolean(signatureCheck));
                 mPackageDef.setIsReferenceApp(parseBoolean(referenceApp));
+                mPackageDef.setApkToTest(apkToTest);
+                mPackageDef.setPackageToTest(packageToTest);
 
                 // reset the class name
                 mClassNameStack = new Stack<String>();
diff --git a/tools/tradefed-host/tests/src/com/android/cts/tradefed/UnitTests.java b/tools/tradefed-host/tests/src/com/android/cts/tradefed/UnitTests.java
new file mode 100644
index 0000000..3da40dd
--- /dev/null
+++ b/tools/tradefed-host/tests/src/com/android/cts/tradefed/UnitTests.java
@@ -0,0 +1,49 @@
+/*
+ * 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 com.android.cts.tradefed;
+
+import com.android.cts.tradefed.result.CtsXmlResultReporterTest;
+import com.android.cts.tradefed.targetsetup.CtsSetupTest;
+import com.android.cts.tradefed.testtype.JarHostTestTest;
+import com.android.cts.tradefed.testtype.CtsTestTest;
+import com.android.cts.tradefed.testtype.PlanXmlParserTest;
+import com.android.cts.tradefed.testtype.TestPackageXmlParserTest;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+/**
+ * A test suite for all cts-tradefed unit tests.
+ * <p/>
+ * All tests listed here should be self-contained, and do not require any external dependencies
+ * (such as a full CTS build with XML etc).
+ */
+public class UnitTests extends TestSuite {
+
+    public UnitTests() {
+        super();
+        addTestSuite(CtsXmlResultReporterTest.class);
+        addTestSuite(CtsSetupTest.class);
+        addTestSuite(JarHostTestTest.class);
+        addTestSuite(CtsTestTest.class);
+        addTestSuite(PlanXmlParserTest.class);
+        addTestSuite(TestPackageXmlParserTest.class);
+    }
+
+    public static Test suite() {
+        return new UnitTests();
+    }
+}
diff --git a/tools/tradefed-host/tests/src/com/android/cts/tradefed/result/CtsXmlResultReporterTest.java b/tools/tradefed-host/tests/src/com/android/cts/tradefed/result/CtsXmlResultReporterTest.java
index 113496c..88bb5d1 100644
--- a/tools/tradefed-host/tests/src/com/android/cts/tradefed/result/CtsXmlResultReporterTest.java
+++ b/tools/tradefed-host/tests/src/com/android/cts/tradefed/result/CtsXmlResultReporterTest.java
@@ -75,14 +75,23 @@
      * A simple test to ensure expected output is generated for test run with no tests.
      */
     public void testEmptyGeneration() {
-        final String expectedOutput = "<?xml version='1.0' encoding='UTF-8' standalone='no' ?>" +
-            "<?xml-stylesheet type=\"text/xsl\" href=\"cts_result.xsl\"?>" +
-            "<TestResult testPlan=\"unknown\" profile=\"unknown\" starttime=\"ignore\" endtime=\"ignore\" version=\"2.0\"> " +
-            "<Summary failed=\"0\" notExecuted=\"0\" timeout=\"0\" omitted=\"0\" pass=\"0\" total=\"0\" />" +
-            "</TestResult>";
+        final String expectedHeaderOutput = "<?xml version='1.0' encoding='UTF-8' standalone='no' ?>" +
+            "<?xml-stylesheet type=\"text/xsl\" href=\"cts_result.xsl\"?>";
+        final String expectedTestOutput =
+            "<TestResult testPlan=\"unknown\" starttime=\"ignore\" endtime=\"ignore\" version=\"1.10\"> ";
+        final String expectedSummaryOutput =
+            "<Summary failed=\"0\" notExecuted=\"0\" timeout=\"0\" omitted=\"0\" pass=\"0\" total=\"0\" />";
+        final String expectedEndTag = "</TestResult>";
         mResultReporter.invocationStarted(new BuildInfo(1, "test", "test"));
         mResultReporter.invocationEnded(1);
-        assertEquals(expectedOutput, getOutput());
+        String actualOutput = getOutput();
+        assertTrue(actualOutput.startsWith(expectedHeaderOutput));
+        assertTrue(String.format("test output did not contain expected test result. Got %s",
+                actualOutput), actualOutput.contains(expectedTestOutput));
+        assertTrue(String.format("test output did not contain expected test summary. Got %s",
+                actualOutput), actualOutput.contains(expectedSummaryOutput));
+        assertTrue(String.format("test output did not contain expected TestResult end tag. Got %s",
+                actualOutput), actualOutput.endsWith(expectedEndTag));
     }
 
     /**
@@ -101,8 +110,8 @@
         // TODO: consider doing xml based compare
         assertTrue(output.contains(
                 "<Summary failed=\"0\" notExecuted=\"0\" timeout=\"0\" omitted=\"0\" pass=\"1\" total=\"1\" />"));
-        assertTrue(output.contains("<TestPackage name=\"run\" runTime=\"3s\" digest=\"\" " +
-                "failed=\"0\" notExecuted=\"0\" timeout=\"0\" omitted=\"0\" pass=\"1\" total=\"1\">"));
+        assertTrue(output.contains("<TestPackage name=\"run\" digest=\"\" " +
+                "failed=\"0\" notExecuted=\"0\" timeout=\"0\" pass=\"1\" >"));
         assertTrue(output.contains(String.format("<TestCase name=\"%s\">", testId.getClassName())));
 
         final String testCaseTag = String.format(
diff --git a/tools/tradefed-host/tests/src/com/android/cts/tradefed/targetsetup/CtsSetupTest.java b/tools/tradefed-host/tests/src/com/android/cts/tradefed/targetsetup/CtsSetupTest.java
index 932f3dc..1304a63 100644
--- a/tools/tradefed-host/tests/src/com/android/cts/tradefed/targetsetup/CtsSetupTest.java
+++ b/tools/tradefed-host/tests/src/com/android/cts/tradefed/targetsetup/CtsSetupTest.java
@@ -16,6 +16,7 @@
 package com.android.cts.tradefed.targetsetup;
 
 import com.android.ddmlib.Log;
+import com.android.tradefed.config.IConfiguration;
 import com.android.tradefed.device.DeviceNotAvailableException;
 import com.android.tradefed.device.ITestDevice;
 import com.android.tradefed.targetsetup.BuildError;
@@ -76,6 +77,20 @@
     }
 
     /**
+     * Test {@link CtsSetup#setUp(ITestDevice, IBuildInfo)} when a {@link IConfiguration} has not
+     * been provided.
+     */
+    public void testSetUp_missingConfig() throws TargetSetupError, BuildError,
+            DeviceNotAvailableException {
+        try {
+            mSetup.setUp(mMockDevice,  EasyMock.createMock(IFolderBuildInfo.class));
+            fail("IllegalStateException not thrown");
+        } catch (IllegalStateException e) {
+            // expected
+        }
+    }
+
+    /**
      * Test normal case for {@link CtsSetup#setUp(ITestDevice, IBuildInfo)}
      */
     public void testSetUp() throws TargetSetupError, BuildError, DeviceNotAvailableException {
@@ -87,6 +102,7 @@
                 mMockDevice.installPackage((File)EasyMock.anyObject(), EasyMock.anyBoolean()))
                 .andReturn(null)
                 .anyTimes();
+        mSetup.setConfiguration(EasyMock.createMock(IConfiguration.class));
         EasyMock.replay(ctsBuild, mMockDevice);
         mSetup.setUp(mMockDevice, ctsBuild);
     }
diff --git a/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/CtsTestTest.java b/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/CtsTestTest.java
new file mode 100644
index 0000000..e884365
--- /dev/null
+++ b/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/CtsTestTest.java
@@ -0,0 +1,257 @@
+/*
+ * 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 com.android.cts.tradefed.testtype;
+
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.result.ITestInvocationListener;
+import com.android.tradefed.testtype.IRemoteTest;
+import com.android.tradefed.util.xml.AbstractXmlParser.ParseException;
+
+import org.easymock.EasyMock;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Collection;
+
+import junit.framework.TestCase;
+
+/**
+ * Unit tests for {@link CtsTest}.
+ */
+public class CtsTestTest extends TestCase {
+
+    private static final String PACKAGE_NAME = "test-uri";
+    /** the test fixture under test, with all external dependencies mocked out */
+    private CtsTest mCtsTest;
+    private ITestCaseRepo mMockRepo;
+    private IPlanXmlParser mMockPlanParser;
+    private ITestDevice mMockDevice;
+    private ITestInvocationListener mMockListener;
+
+    private static final String PLAN_NAME = "CTS";
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        mMockRepo = EasyMock.createMock(ITestCaseRepo.class);
+        mMockPlanParser = EasyMock.createMock(IPlanXmlParser.class);
+        mMockDevice = EasyMock.createMock(ITestDevice.class);
+        mMockListener = EasyMock.createNiceMock(ITestInvocationListener.class);
+
+        mCtsTest = new CtsTest() {
+            @Override
+            ITestCaseRepo createTestCaseRepo() {
+                return mMockRepo;
+            }
+
+            @Override
+            IPlanXmlParser createXmlParser() {
+                return mMockPlanParser;
+            }
+
+            @Override
+            InputStream createXmlStream(File xmlFile) throws FileNotFoundException {
+                // return empty stream, not used
+                return new ByteArrayInputStream(new byte[0]);
+            }
+        };
+        mCtsTest.setDevice(mMockDevice);
+        // not used, but needs to be non-null
+        mCtsTest.setTestCaseDir(new File("tmp"));
+        mCtsTest.setTestPlanDir(new File("tmp"));
+        // turn off device collection for simplicity
+        mCtsTest.setCollectDeviceInfo(false);
+    }
+
+    /**
+     * Test normal case {@link CtsTest#run(java.util.List)} when running a plan.
+     */
+    @SuppressWarnings("unchecked")
+    public void testRun_plan() throws DeviceNotAvailableException, ParseException {
+        setParsePlanExceptations();
+
+        ITestPackageDef mockPackageDef = EasyMock.createMock(ITestPackageDef.class);
+        IRemoteTest mockTest = EasyMock.createMock(IRemoteTest.class);
+        EasyMock.expect(mMockRepo.getTestPackage(PACKAGE_NAME)).andReturn(mockPackageDef);
+        EasyMock.expect(mockPackageDef.createTest((File)EasyMock.anyObject(),
+                (String)EasyMock.anyObject(), (String)EasyMock.anyObject())).andReturn(mockTest);
+        mockTest.run((ITestInvocationListener)EasyMock.anyObject());
+
+        replayMocks(mockTest, mockPackageDef);
+        mCtsTest.run(mMockListener);
+        verifyMocks(mockTest, mockPackageDef);
+    }
+
+
+
+    /**
+     * Test normal case {@link CtsTest#run(java.util.List)} when running a package.
+     */
+    @SuppressWarnings("unchecked")
+    public void testRun_package() throws DeviceNotAvailableException {
+        mCtsTest.addPackageName(PACKAGE_NAME);
+        ITestPackageDef mockPackageDef = EasyMock.createMock(ITestPackageDef.class);
+        IRemoteTest mockTest = EasyMock.createMock(IRemoteTest.class);
+        EasyMock.expect(mMockRepo.getTestPackage(PACKAGE_NAME)).andReturn(mockPackageDef);
+        EasyMock.expect(mockPackageDef.createTest((File)EasyMock.anyObject(),
+                (String)EasyMock.anyObject(), (String)EasyMock.anyObject())).andReturn(mockTest);
+        mockTest.run((ITestInvocationListener)EasyMock.anyObject());
+
+        replayMocks(mockTest, mockPackageDef);
+        mCtsTest.run(mMockListener);
+        verifyMocks(mockTest, mockPackageDef);
+    }
+
+    /**
+     * Test normal case {@link CtsTest#run(java.util.List)} when running a class.
+     */
+    @SuppressWarnings("unchecked")
+    public void testRun_class() throws DeviceNotAvailableException {
+        final String className = "className";
+        final String methodName = "methodName";
+        mCtsTest.setClassName(className);
+        mCtsTest.setMethodName(methodName);
+
+
+        EasyMock.expect(mMockRepo.findPackageForTest(className)).andReturn(PACKAGE_NAME);
+        ITestPackageDef mockPackageDef = EasyMock.createMock(ITestPackageDef.class);
+        EasyMock.expect(mMockRepo.getTestPackage(PACKAGE_NAME)).andReturn(mockPackageDef);
+        IRemoteTest mockTest = EasyMock.createMock(IRemoteTest.class);
+        EasyMock.expect(mockPackageDef.createTest((File)EasyMock.anyObject(),
+                EasyMock.eq(className), EasyMock.eq(methodName))).andReturn(mockTest);
+        mockTest.run((ITestInvocationListener)EasyMock.anyObject());
+
+        replayMocks(mockTest, mockPackageDef);
+        mCtsTest.run(mMockListener);
+        verifyMocks(mockTest, mockPackageDef);
+    }
+
+    /**
+     * Test {@link CtsTest#run(java.util.List)} when --excluded-package is specified
+     */
+    public void testRun_excludedPackage() throws DeviceNotAvailableException, ParseException {
+        setParsePlanExceptations();
+
+        mCtsTest.addExcludedPackageName(PACKAGE_NAME);
+
+        // PACKAGE_NAME would normally be run, but it has been excluded. Expect nothing to happen
+        replayMocks();
+        mCtsTest.run(mMockListener);
+        verifyMocks();
+    }
+
+    /**
+     * Set EasyMock expectations for parsing {@link #PLAN_NAME}
+     */
+    private void setParsePlanExceptations() throws ParseException {
+        mCtsTest.setPlanName(PLAN_NAME);
+        mMockPlanParser.parse((InputStream)EasyMock.anyObject());
+        Collection<String> uris = new ArrayList<String>(1);
+        uris.add(PACKAGE_NAME);
+        EasyMock.expect(mMockPlanParser.getTestUris()).andReturn(uris);
+    }
+
+    /**
+     * Test {@link CtsTest#run(java.util.List)} when --plan and --package options have not been
+     * specified
+     */
+    public void testRun_nothingToRun() throws DeviceNotAvailableException {
+        try {
+            mCtsTest.run(mMockListener);
+            fail("IllegalArgumentException not thrown");
+        } catch (IllegalArgumentException e) {
+            // expected
+        }
+    }
+
+    /**
+     * Test {@link CtsTest#run(java.util.List)} when --plan and --package options have been
+     * specified
+     */
+    public void testRun_packagePlan() throws DeviceNotAvailableException {
+        mCtsTest.setPlanName(PLAN_NAME);
+        mCtsTest.addPackageName(PACKAGE_NAME);
+        try {
+            mCtsTest.run(mMockListener);
+            fail("IllegalArgumentException not thrown");
+        } catch (IllegalArgumentException e) {
+            // expected
+        }
+    }
+
+    /**
+     * Test {@link CtsTest#run(java.util.List)} when --plan and --class options have been
+     * specified
+     */
+    public void testRun_planClass() throws DeviceNotAvailableException {
+        mCtsTest.setPlanName(PLAN_NAME);
+        mCtsTest.setClassName("class");
+        try {
+            mCtsTest.run(mMockListener);
+            fail("IllegalArgumentException not thrown");
+        } catch (IllegalArgumentException e) {
+            // expected
+        }
+    }
+
+    /**
+     * Test {@link CtsTest#run(java.util.List)} when --package and --class options have been
+     * specified
+     */
+    public void testRun_packageClass() throws DeviceNotAvailableException {
+        mCtsTest.addPackageName(PACKAGE_NAME);
+        mCtsTest.setClassName("class");
+        try {
+            mCtsTest.run(mMockListener);
+            fail("IllegalArgumentException not thrown");
+        } catch (IllegalArgumentException e) {
+            // expected
+        }
+    }
+
+    /**
+     * Test {@link CtsTest#run(java.util.List)} when --plan, --package and --class options have been
+     * specified
+     */
+    public void testRun_planPackageClass() throws DeviceNotAvailableException {
+        mCtsTest.setPlanName(PLAN_NAME);
+        mCtsTest.addPackageName(PACKAGE_NAME);
+        mCtsTest.setClassName("class");
+        try {
+            mCtsTest.run(mMockListener);
+            fail("IllegalArgumentException not thrown");
+        } catch (IllegalArgumentException e) {
+            // expected
+        }
+    }
+
+    private void replayMocks(Object... mocks) {
+        EasyMock.replay(mMockRepo, mMockPlanParser, mMockDevice, mMockListener);
+        EasyMock.replay(mocks);
+    }
+
+    private void verifyMocks(Object... mocks) {
+        EasyMock.verify(mMockRepo, mMockPlanParser, mMockDevice, mMockListener);
+        EasyMock.verify(mocks);
+    }
+}
diff --git a/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/JarHostTestTest.java b/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/JarHostTestTest.java
index fcd9563..20292d3 100644
--- a/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/JarHostTestTest.java
+++ b/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/JarHostTestTest.java
@@ -17,11 +17,15 @@
 
 import com.android.ddmlib.testrunner.TestIdentifier;
 import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.device.ITestDevice;
 import com.android.tradefed.result.ITestInvocationListener;
 
 import org.easymock.EasyMock;
 
+import java.io.File;
 import java.net.URL;
+import java.util.ArrayList;
+import java.util.Collection;
 import java.util.Collections;
 
 import junit.framework.TestCase;
@@ -51,6 +55,10 @@
             super(name);
         }
 
+        public MockTest() {
+            super();
+        }
+
         public void testFoo() {
         }
     }
@@ -64,15 +72,20 @@
         ITestInvocationListener listener = EasyMock.createMock(ITestInvocationListener.class);
         TestIdentifier expectedTest = new TestIdentifier(MockTest.class.getName(), "testFoo");
 
+        Collection<TestIdentifier> tests = new ArrayList<TestIdentifier>(1);
+        tests.add(expectedTest);
         listener.testRunStarted(RUN_NAME, 1);
         listener.testStarted(expectedTest);
         listener.testEnded(expectedTest, Collections.EMPTY_MAP);
         listener.testRunEnded(EasyMock.anyLong(), EasyMock.eq(Collections.EMPTY_MAP));
+        mJarTest.setTests(tests);
+        mJarTest.setDevice(EasyMock.createMock(ITestDevice.class));
+        mJarTest.setJarFile(new File("fakefile"));
+        mJarTest.setRunName(RUN_NAME);
 
         EasyMock.replay(listener);
-
-        mJarTest.setRunName(RUN_NAME);
         mJarTest.run(listener);
+        EasyMock.verify(listener);
     }
 
 }
diff --git a/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/PlanTestTest.java b/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/PlanTestTest.java
deleted file mode 100644
index 1c2b4b6..0000000
--- a/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/PlanTestTest.java
+++ /dev/null
@@ -1,120 +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 com.android.cts.tradefed.testtype;
-
-import com.android.tradefed.device.DeviceNotAvailableException;
-import com.android.tradefed.device.ITestDevice;
-import com.android.tradefed.result.ITestInvocationListener;
-import com.android.tradefed.testtype.IRemoteTest;
-import com.android.tradefed.util.xml.AbstractXmlParser.ParseException;
-
-import org.easymock.EasyMock;
-
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-/**
- * Unit tests for {@link PlanTest}.
- */
-public class PlanTestTest extends TestCase {
-
-    /** the test fixture under test, with all external dependencies mocked out */
-    private PlanTest mPlanTest;
-    private ITestCaseRepo mMockRepo;
-    private IPlanXmlParser mMockPlanParser;
-    private ITestDevice mMockDevice;
-    private ITestInvocationListener mMockListener;
-
-    private static final String PLAN_NAME = "CTS";
-
-    /**
-     * {@inheritDoc}
-     */
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
-        mMockRepo = EasyMock.createMock(ITestCaseRepo.class);
-        mMockPlanParser = EasyMock.createMock(IPlanXmlParser.class);
-        mMockDevice = EasyMock.createMock(ITestDevice.class);
-        mMockListener = EasyMock.createNiceMock(ITestInvocationListener.class);
-
-        mPlanTest = new PlanTest() {
-            @Override
-            ITestCaseRepo createTestCaseRepo() {
-                return mMockRepo;
-            }
-
-            @Override
-            IPlanXmlParser createXmlParser() {
-                return mMockPlanParser;
-            }
-
-            @Override
-            InputStream createXmlStream(File xmlFile) throws FileNotFoundException {
-                // return empty stream, not used
-                return new ByteArrayInputStream(new byte[0]);
-            }
-        };
-        mPlanTest.setDevice(mMockDevice);
-        // not used, but needs to be non-null
-        mPlanTest.setTestCaseDir(new File("tmp"));
-        mPlanTest.setTestPlanDir(new File("tmp"));
-        mPlanTest.setPlanName(PLAN_NAME);
-    }
-
-    /**
-     * Test normal case {@link PlanTest#run(java.util.List)}.
-     * <p/>
-     * Not that interesting of a test in its current form, but sets the stage for testing more
-     * complicated scenarios.
-     */
-    @SuppressWarnings("unchecked")
-    public void testRun() throws DeviceNotAvailableException, ParseException {
-        // expect
-        mMockPlanParser.parse((InputStream)EasyMock.anyObject());
-        Collection<String> uris = new ArrayList<String>(1);
-        uris.add("test-uri");
-        EasyMock.expect(mMockPlanParser.getTestUris()).andReturn(uris);
-
-        IRemoteTest mockTest = EasyMock.createMock(IRemoteTest.class);
-        Collection<IRemoteTest> tests = new ArrayList<IRemoteTest>(1);
-        tests.add(mockTest);
-        EasyMock.expect(mMockRepo.getTests(uris)).andReturn(tests);
-
-        // expect
-        mockTest.run((List<ITestInvocationListener>)EasyMock.anyObject());
-
-        replayMocks();
-        EasyMock.replay(mockTest);
-        mPlanTest.run(mMockListener);
-        verifyMocks();
-    }
-
-    private void replayMocks() {
-        EasyMock.replay(mMockRepo, mMockPlanParser, mMockDevice, mMockListener);
-    }
-
-    private void verifyMocks() {
-        EasyMock.verify(mMockRepo, mMockPlanParser, mMockDevice, mMockListener);
-    }
-}
diff --git a/tools/utils/Android.mk b/tools/utils/Android.mk
index ddb06c8..0782116 100644
--- a/tools/utils/Android.mk
+++ b/tools/utils/Android.mk
@@ -20,7 +20,7 @@
 
 LOCAL_MODULE := descGen
 
-LOCAL_SRC_FILES := CollectAllTests.java DescriptionGenerator.java VogarUtils.java
+LOCAL_SRC_FILES := CollectAllTests.java DescriptionGenerator.java
 
 LOCAL_CLASSPATH := $(HOST_JDK_TOOLS_JAR) $(LOCAL_PATH)/lib/junit.jar
 
diff --git a/tools/utils/CollectAllTests.java b/tools/utils/CollectAllTests.java
index c443db2..cb109e8 100644
--- a/tools/utils/CollectAllTests.java
+++ b/tools/utils/CollectAllTests.java
@@ -14,15 +14,6 @@
  * limitations under the License.
  */
 
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import vogar.Expectation;
-import vogar.ExpectationStore;
-import vogar.ModeId;
-
 import java.io.BufferedReader;
 import java.io.File;
 import java.io.FileInputStream;
@@ -49,6 +40,15 @@
 import junit.textui.ResultPrinter;
 import junit.textui.TestRunner;
 
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+import vogar.ExpectationStore;
+import vogar.Expectation;
+import vogar.ModeId;
+
 public class CollectAllTests extends DescriptionGenerator {
 
     static final String ATTRIBUTE_RUNNER = "runner";
@@ -103,13 +103,12 @@
     private static String MANIFESTFILE = "";
     private static String TESTSUITECLASS = "";
     private static String ANDROID_MAKE_FILE = "";
-    private static String LIBCORE_EXPECTATION_DIR = null;
+    private static String EXPECTATION_DIR = null;
 
     private static Test TESTSUITE;
 
     static XMLGenerator xmlGenerator;
-    private static ExpectationStore libcoreVogarExpectationStore;
-    private static ExpectationStore ctsVogarExpectationStore;
+    private static ExpectationStore vogarExpectationStore;
 
     public static void main(String[] args) {
         if (args.length > 2) {
@@ -117,7 +116,7 @@
             MANIFESTFILE = args [1];
             TESTSUITECLASS = args[2];
             if (args.length > 3) {
-                LIBCORE_EXPECTATION_DIR = args[3];
+                EXPECTATION_DIR = args[3];
             }
             if (args.length > 4) {
                 ANDROID_MAKE_FILE = args[4];
@@ -196,8 +195,7 @@
         }
 
         try {
-            libcoreVogarExpectationStore = VogarUtils.provideExpectationStore(LIBCORE_EXPECTATION_DIR);
-            ctsVogarExpectationStore = VogarUtils.provideExpectationStore(CTS_EXPECTATION_DIR);
+            vogarExpectationStore = provideExpectationStore(EXPECTATION_DIR);
         } catch (IOException e) {
             System.err.println("Can't initialize vogar expectation store");
             e.printStackTrace(System.err);
@@ -328,6 +326,15 @@
         return getAnnotation(testClass, testName, SIDE_EFFECT) != null;
     }
 
+    private boolean isVogarKnownFailure(final Class<? extends TestCase> testClass,
+            final String testName) {
+        if (vogarExpectationStore == null) {
+            return false;
+        }
+        String fullTestName = String.format("%s#%s", testClass.getName(), testName);
+        return vogarExpectationStore.get(fullTestName) != Expectation.SUCCESS;
+    }
+
     private String getAnnotation(final Class<? extends TestCase> testClass,
             final String testName, final String annotationName) {
         try {
@@ -378,11 +385,8 @@
         } else if (hasSideEffects(test.getClass(), testName)) {
             System.out.println("ignoring test with side effects: " + test);
             return;
-        } else if (VogarUtils.isVogarKnownFailure(libcoreVogarExpectationStore, test.getClass().getName(), testName)) {
-            System.out.println("ignoring libcore expectation known failure: " + test);
-            return;
-        } else if (VogarUtils.isVogarKnownFailure(ctsVogarExpectationStore, test.getClass().getName(), testName)) {
-            System.out.println("ignoring cts expectation known failure: " + test);
+        } else if (isVogarKnownFailure(test.getClass(), testName)) {
+            System.out.println("ignoring vogar known failure: " + test);
             return;
         }
 
@@ -412,4 +416,26 @@
             failed.add(test.getClass().getName());
         }
     }
+
+    public static ExpectationStore provideExpectationStore(String dir) throws IOException {
+        if (dir == null) {
+            return null;
+        }
+        ExpectationStore result = ExpectationStore.parse(getExpectationFiles(dir), ModeId.DEVICE);
+        return result;
+    }
+
+    private static Set<File> getExpectationFiles(String dir) {
+        Set<File> expectSet = new HashSet<File>();
+        File[] files = new File(dir).listFiles(new FilenameFilter() {
+            // ignore obviously temporary files
+            public boolean accept(File dir, String name) {
+                return !name.endsWith("~") && !name.startsWith(".");
+            }
+        });
+        if (files != null) {
+            expectSet.addAll(Arrays.asList(files));
+        }
+        return expectSet;
+    }
 }
diff --git a/tools/utils/DescriptionGenerator.java b/tools/utils/DescriptionGenerator.java
index 0731b49..2d58543 100644
--- a/tools/utils/DescriptionGenerator.java
+++ b/tools/utils/DescriptionGenerator.java
@@ -37,8 +37,6 @@
 import org.w3c.dom.Node;
 import org.w3c.dom.NodeList;
 
-import vogar.ExpectationStore;
-
 import com.sun.javadoc.AnnotationDesc;
 import com.sun.javadoc.AnnotationTypeDoc;
 import com.sun.javadoc.AnnotationValue;
@@ -69,7 +67,6 @@
     static final String BROKEN_TEST = "dalvik.annotation.BrokenTest";
     static final String SIDE_EFFECT = "dalvik.annotation.SideEffect";
     static final String SUPPRESSED_TEST = "android.test.suitebuilder.annotation.Suppress";
-    static final String CTS_EXPECTATION_DIR = "cts/tests/expectations";
 
     static final String JUNIT_TEST_CASE_CLASS_NAME = "junit.framework.testcase";
     static final String TAG_PACKAGE = "TestPackage";
@@ -120,17 +117,9 @@
             return true;
         }
 
-        ExpectationStore ctsExpectationStore = null;
-        try {
-            ctsExpectationStore = VogarUtils.provideExpectationStore("./" + CTS_EXPECTATION_DIR);
-        } catch (IOException e) {
-            Log.e("Couldn't load expectation store.", e);
-            return false;
-        }
-
         for (ClassDoc clazz : classes) {
             if ((!clazz.isAbstract()) && (isValidJUnitTestCase(clazz))) {
-                xmlGenerator.addTestClass(new TestClass(clazz, ctsExpectationStore));
+                xmlGenerator.addTestClass(new TestClass(clazz));
             }
         }
 
@@ -511,9 +500,9 @@
          *
          * @param clazz The specified ClassDoc.
          */
-        TestClass(ClassDoc clazz, ExpectationStore expectationStore) {
+        TestClass(ClassDoc clazz) {
             mName = clazz.toString();
-            mCases = getTestMethods(expectationStore, clazz);
+            mCases = getTestMethods(clazz);
         }
 
         /**
@@ -522,7 +511,7 @@
          * @param clazz The specified ClassDoc.
          * @return A collection of TestMethod.
          */
-        Collection<TestMethod> getTestMethods(ExpectationStore expectationStore, ClassDoc clazz) {
+        Collection<TestMethod> getTestMethods(ClassDoc clazz) {
             Collection<MethodDoc> methods = getAllMethods(clazz);
 
             ArrayList<TestMethod> cases = new ArrayList<TestMethod>();
@@ -552,10 +541,6 @@
                     }
                 }
 
-                if (VogarUtils.isVogarKnownFailure(expectationStore, clazz.toString(), name)) {
-                    isBroken = true;
-                }
-
                 if (name.startsWith("test")) {
                     cases.add(new TestMethod(name, method.commentText(), controller, knownFailure,
                             isBroken, isSuppressed));
diff --git a/tools/utils/VogarUtils.java b/tools/utils/VogarUtils.java
deleted file mode 100644
index 06b48c6..0000000
--- a/tools/utils/VogarUtils.java
+++ /dev/null
@@ -1,59 +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.
- */
-
-import vogar.Expectation;
-import vogar.ExpectationStore;
-import vogar.ModeId;
-
-import java.io.File;
-import java.io.FilenameFilter;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Set;
-
-public class VogarUtils {
-
-    public static boolean isVogarKnownFailure(ExpectationStore expectationStore,
-            final String testClassName,
-            final String testMethodName) {
-        String fullTestName = String.format("%s#%s", testClassName, testMethodName);
-        return expectationStore != null
-                && expectationStore.get(fullTestName) != Expectation.SUCCESS;
-    }
-
-    public static ExpectationStore provideExpectationStore(String dir) throws IOException {
-        if (dir == null) {
-            return null;
-        }
-        ExpectationStore result = ExpectationStore.parse(getExpectationFiles(dir), ModeId.DEVICE);
-        return result;
-    }
-
-    private static Set<File> getExpectationFiles(String dir) {
-        Set<File> expectSet = new HashSet<File>();
-        File[] files = new File(dir).listFiles(new FilenameFilter() {
-            // ignore obviously temporary files
-            public boolean accept(File dir, String name) {
-                return !name.endsWith("~") && !name.startsWith(".");
-            }
-        });
-        if (files != null) {
-            expectSet.addAll(Arrays.asList(files));
-        }
-        return expectSet;
-    }
-}