Merge "media: use small frame size for resource manager test." into mnc-dev
diff --git a/CtsTestCaseList.mk b/CtsTestCaseList.mk
index 8e0d83d..7a37542 100644
--- a/CtsTestCaseList.mk
+++ b/CtsTestCaseList.mk
@@ -211,6 +211,7 @@
     CtsHostUi \
     CtsMonkeyTestCases \
     CtsThemeHostTestCases \
+    CtsUsageHostTestCases \
     CtsSecurityHostTestCases \
     CtsUsbTests
 
diff --git a/apps/CtsVerifier/AndroidManifest.xml b/apps/CtsVerifier/AndroidManifest.xml
index cb39f3e..39302c1 100644
--- a/apps/CtsVerifier/AndroidManifest.xml
+++ b/apps/CtsVerifier/AndroidManifest.xml
@@ -56,6 +56,7 @@
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
     <uses-permission android:name="com.android.providers.tv.permission.READ_EPG_DATA" />
     <uses-permission android:name="com.android.providers.tv.permission.WRITE_EPG_DATA" />
+    <uses-permission android:name="android.permission.USE_FINGERPRINT"/>
 
     <!-- Needed by the Audio Quality Verifier to store the sound samples that will be mailed. -->
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
@@ -352,6 +353,28 @@
             <meta-data android:name="test_category" android:value="@string/test_category_security" />
         </activity>
 
+        <activity android:name=".security.FingerprintBoundKeysTest"
+                android:label="@string/sec_fingerprint_bound_key_test"
+                android:configChanges="keyboardHidden|orientation|screenSize" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.cts.intent.category.MANUAL_TEST" />
+            </intent-filter>
+            <meta-data android:name="test_category" android:value="@string/test_category_security" />
+            <meta-data android:name="test_excluded_features"
+                       android:value="android.hardware.type.television:android.software.leanback:android.hardware.type.watch" />
+        </activity>
+        <activity android:name=".security.ScreenLockBoundKeysTest"
+                android:label="@string/sec_lock_bound_key_test"
+                android:configChanges="keyboardHidden|orientation|screenSize" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.cts.intent.category.MANUAL_TEST" />
+            </intent-filter>
+            <meta-data android:name="test_category" android:value="@string/test_category_security" />
+            <meta-data android:name="test_excluded_features"
+                       android:value="android.hardware.type.television:android.software.leanback:android.hardware.type.watch" />
+        </activity>
         <activity android:name=".security.LockConfirmBypassTest"
                 android:label="@string/lock_confirm_test_title"
                 android:configChanges="keyboardHidden|orientation|screenSize" >
diff --git a/apps/CtsVerifier/res/layout/sec_screen_lock_keys_main.xml b/apps/CtsVerifier/res/layout/sec_screen_lock_keys_main.xml
new file mode 100644
index 0000000..af53335
--- /dev/null
+++ b/apps/CtsVerifier/res/layout/sec_screen_lock_keys_main.xml
@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- 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.
+-->
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+        android:layout_width="match_parent"
+        android:layout_height="match_parent"
+        android:padding="10dip"
+        >
+
+    <Button android:id="@+id/sec_start_test_button"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_centerInParent="true"
+            android:text="@string/sec_start_test"
+            />
+
+    <include android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:layout_alignParentBottom="true"
+            layout="@layout/pass_fail_buttons"
+            />
+
+</RelativeLayout>
+
diff --git a/apps/CtsVerifier/res/values/strings.xml b/apps/CtsVerifier/res/values/strings.xml
index 0f2b013..d8637ca 100644
--- a/apps/CtsVerifier/res/values/strings.xml
+++ b/apps/CtsVerifier/res/values/strings.xml
@@ -124,6 +124,24 @@
     <string name="da_lock_success">It appears the screen was locked successfully!</string>
     <string name="da_lock_error">It does not look like the screen was locked...</string>
 
+    <!-- Strings for lock bound keys test -->
+    <string name="sec_lock_bound_key_test">Lock Bound Keys Test</string>
+    <string name="sec_lock_bound_key_test_info">
+        This test ensures that Keystore cryptographic keys that are bound to lock screen authentication
+        are unusable without a recent enough authentication. You need to set up a screen lock in order to
+        complete this test. If available, this test should be run by using fingerprint authentication
+        as well as PIN/pattern/password authentication.
+    </string>
+    <string name="sec_fingerprint_bound_key_test">Fingerprint Bound Keys Test</string>
+    <string name="sec_fingerprint_bound_key_test_info">
+        This test ensures that Keystore cryptographic keys that are bound to fingerprint authentication
+        are unusable without an authentication. You need to set up a fingerprint order to
+        complete this test.
+    </string>
+    <string name="sec_fp_dialog_message">Authenticate now with fingerprint</string>
+    <string name="sec_fp_auth_failed">Authentication failed</string>
+    <string name="sec_start_test">Start Test</string>
+
     <!-- Strings for BluetoothActivity -->
     <string name="bluetooth_test">Bluetooth Test</string>
     <string name="bluetooth_test_info">The Bluetooth Control tests check whether or not the device
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/security/FingerprintBoundKeysTest.java b/apps/CtsVerifier/src/com/android/cts/verifier/security/FingerprintBoundKeysTest.java
new file mode 100644
index 0000000..70899c6
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/security/FingerprintBoundKeysTest.java
@@ -0,0 +1,247 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.verifier.security;
+
+import com.android.cts.verifier.PassFailButtons;
+import com.android.cts.verifier.R;
+
+import android.Manifest;
+import android.app.AlertDialog;
+import android.app.Dialog;
+import android.app.DialogFragment;
+import android.app.KeyguardManager;
+import android.content.Context;
+import android.content.DialogInterface;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.hardware.fingerprint.FingerprintManager;
+import android.os.Bundle;
+import android.os.CancellationSignal;
+import android.util.Log;
+import android.security.keystore.KeyGenParameterSpec;
+import android.security.keystore.KeyPermanentlyInvalidatedException;
+import android.security.keystore.KeyProperties;
+import android.security.keystore.UserNotAuthenticatedException;
+import android.view.View;
+import android.view.View.OnClickListener;
+import android.widget.Button;
+import android.widget.Toast;
+
+import java.io.IOException;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidKeyException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.UnrecoverableKeyException;
+import java.security.cert.CertificateException;
+
+import javax.crypto.BadPaddingException;
+import javax.crypto.Cipher;
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.KeyGenerator;
+import javax.crypto.NoSuchPaddingException;
+import javax.crypto.SecretKey;
+
+public class FingerprintBoundKeysTest extends PassFailButtons.Activity {
+    private static final String TAG = "FingerprintBoundKeysTest";
+
+    /** Alias for our key in the Android Key Store. */
+    private static final String KEY_NAME = "my_key";
+    private static final byte[] SECRET_BYTE_ARRAY = new byte[] {1, 2, 3, 4, 5, 6};
+    private static final int AUTHENTICATION_DURATION_SECONDS = 5;
+    private static final int CONFIRM_CREDENTIALS_REQUEST_CODE = 1;
+    private static final int FINGERPRINT_PERMISSION_REQUEST_CODE = 0;
+
+    private FingerprintManager mFingerprintManager;
+    private KeyguardManager mKeyguardManager;
+    private FingerprintAuthDialogFragment mFingerprintDialog;
+    private Cipher mCipher;
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.sec_screen_lock_keys_main);
+        setPassFailButtonClickListeners();
+        setInfoResources(R.string.sec_fingerprint_bound_key_test, R.string.sec_fingerprint_bound_key_test_info, -1);
+        getPassButton().setEnabled(false);
+        requestPermissions(new String[]{Manifest.permission.USE_FINGERPRINT},
+                FINGERPRINT_PERMISSION_REQUEST_CODE);
+    }
+
+    @Override
+    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] state) {
+        if (requestCode == FINGERPRINT_PERMISSION_REQUEST_CODE && state[0] == PackageManager.PERMISSION_GRANTED) {
+            mFingerprintManager = (FingerprintManager) getSystemService(Context.FINGERPRINT_SERVICE);
+            mKeyguardManager = (KeyguardManager) getSystemService(KeyguardManager.class);
+
+            try {
+                KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
+                keyStore.load(null);
+                SecretKey secretKey = (SecretKey) keyStore.getKey(KEY_NAME, null);
+                mCipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/"
+                            + KeyProperties.BLOCK_MODE_CBC + "/"
+                            + KeyProperties.ENCRYPTION_PADDING_PKCS7);
+
+                mCipher.init(Cipher.ENCRYPT_MODE, secretKey);
+            } catch (KeyPermanentlyInvalidatedException e) {
+                createKey();
+                showToast("The key has been invalidated, please try again.\n");
+            } catch (NoSuchPaddingException | KeyStoreException | CertificateException | UnrecoverableKeyException | IOException
+                    | NoSuchAlgorithmException | InvalidKeyException e) {
+                throw new RuntimeException("Failed to init Cipher", e);
+            }
+
+            Button startTestButton = (Button) findViewById(R.id.sec_start_test_button);
+            startTestButton.setOnClickListener(new OnClickListener() {
+                @Override
+                public void onClick(View v) {
+                    if (tryEncrypt()) {
+                        showToast("Test failed. Key accessible without auth.");
+                    } else {
+                        showAuthenticationScreen();
+                    }
+                }
+
+            });
+
+            if (!mKeyguardManager.isKeyguardSecure()) {
+                // Show a message that the user hasn't set up a lock screen.
+                showToast( "Secure lock screen hasn't been set up.\n"
+                                + "Go to 'Settings -> Security -> Screen lock' to set up a lock screen");
+                startTestButton.setEnabled(false);
+            } else if (!mFingerprintManager.hasEnrolledFingerprints()) {
+                showToast("No fingerprints enrolled.\n"
+                                + "Go to 'Settings -> Security -> Fingerprint' to set up a fingerprint");
+                startTestButton.setEnabled(false);
+            } else {
+                createKey();
+            }
+        }
+    }
+
+    /**
+     * Creates a symmetric key in the Android Key Store which can only be used after the user has
+     * authenticated with device credentials within the last X seconds.
+     */
+    private void createKey() {
+        // Generate a key to decrypt payment credentials, tokens, etc.
+        // This will most likely be a registration step for the user when they are setting up your app.
+        try {
+            KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
+            keyStore.load(null);
+            KeyGenerator keyGenerator = KeyGenerator.getInstance(
+                    KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
+
+            // Set the alias of the entry in Android KeyStore where the key will appear
+            // and the constrains (purposes) in the constructor of the Builder
+            keyGenerator.init(new KeyGenParameterSpec.Builder(KEY_NAME,
+                    KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
+                    .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
+                    .setUserAuthenticationRequired(true)
+                    .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
+                    .build());
+            keyGenerator.generateKey();
+        } catch (NoSuchAlgorithmException | NoSuchProviderException
+                | InvalidAlgorithmParameterException | KeyStoreException
+                | CertificateException | IOException e) {
+            throw new RuntimeException("Failed to create a symmetric key", e);
+        }
+    }
+
+    /**
+     * Tries to encrypt some data with the generated key in {@link #createKey} which is
+     * only works if the user has just authenticated via device credentials.
+     */
+    private boolean tryEncrypt() {
+        try {
+            mCipher.doFinal(SECRET_BYTE_ARRAY);
+            return true;
+        } catch (BadPaddingException | IllegalBlockSizeException e) {
+            return false;
+        }
+    }
+
+    private void showAuthenticationScreen() {
+        mFingerprintDialog = new FingerprintAuthDialogFragment();
+        mFingerprintDialog.show(getFragmentManager(), "fingerprint_dialog");
+    }
+
+    private void showToast(String message) {
+        Toast.makeText(this, message, Toast.LENGTH_LONG)
+            .show();
+    }
+
+    public class FingerprintAuthDialogFragment extends DialogFragment {
+
+        private CancellationSignal mCancellationSignal;
+        private FingerprintManagerCallback mFingerprintManagerCallback;
+        private boolean mSelfCancelled;
+
+        class FingerprintManagerCallback extends FingerprintManager.AuthenticationCallback {
+            @Override
+            public void onAuthenticationError(int errMsgId, CharSequence errString) {
+                if (!mSelfCancelled) {
+                    showToast(errString.toString());
+                }
+            }
+
+            @Override
+            public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) {
+                showToast(helpString.toString());
+            }
+
+            @Override
+            public void onAuthenticationFailed() {
+                showToast(getString(R.string.sec_fp_auth_failed));
+            }
+
+            @Override
+            public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
+                if (tryEncrypt()) {
+                    showToast("Test passed.");
+                    getPassButton().setEnabled(true);
+                    FingerprintAuthDialogFragment.this.dismiss();
+                } else {
+                    showToast("Test failed. Key not accessible after auth");
+                }
+            }
+        }
+
+        @Override
+        public void onDismiss(DialogInterface dialog) {
+            mCancellationSignal.cancel();
+            mSelfCancelled = true;
+        }
+
+        @Override
+        public Dialog onCreateDialog(Bundle savedInstanceState) {
+            mCancellationSignal = new CancellationSignal();
+            mSelfCancelled = false;
+            mFingerprintManagerCallback = new FingerprintManagerCallback();
+            mFingerprintManager.authenticate(new FingerprintManager.CryptoObject(mCipher),
+                    mCancellationSignal, 0, mFingerprintManagerCallback, null);
+            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
+            builder.setMessage(R.string.sec_fp_dialog_message);
+            return builder.create();
+        }
+
+    }
+}
+
+
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/security/ScreenLockBoundKeysTest.java b/apps/CtsVerifier/src/com/android/cts/verifier/security/ScreenLockBoundKeysTest.java
new file mode 100644
index 0000000..618b99a
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/security/ScreenLockBoundKeysTest.java
@@ -0,0 +1,204 @@
+/*
+ * 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.verifier.security;
+
+import com.android.cts.verifier.PassFailButtons;
+import com.android.cts.verifier.R;
+
+import android.app.AlertDialog;
+import android.app.KeyguardManager;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Bundle;
+import android.security.keystore.KeyGenParameterSpec;
+import android.security.keystore.KeyPermanentlyInvalidatedException;
+import android.security.keystore.KeyProperties;
+import android.security.keystore.UserNotAuthenticatedException;
+import android.view.View;
+import android.view.View.OnClickListener;
+import android.widget.Button;
+import android.widget.Toast;
+
+import java.io.IOException;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidKeyException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.UnrecoverableKeyException;
+import java.security.cert.CertificateException;
+
+import javax.crypto.BadPaddingException;
+import javax.crypto.Cipher;
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.KeyGenerator;
+import javax.crypto.NoSuchPaddingException;
+import javax.crypto.SecretKey;
+
+public class ScreenLockBoundKeysTest extends PassFailButtons.Activity {
+
+    /** Alias for our key in the Android Key Store. */
+    private static final String KEY_NAME = "my_key";
+    private static final byte[] SECRET_BYTE_ARRAY = new byte[] {1, 2, 3, 4, 5, 6};
+    private static final int AUTHENTICATION_DURATION_SECONDS = 5;
+    private static final int CONFIRM_CREDENTIALS_REQUEST_CODE = 1;
+
+    private KeyguardManager mKeyguardManager;
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.sec_screen_lock_keys_main);
+        setPassFailButtonClickListeners();
+        setInfoResources(R.string.sec_lock_bound_key_test, R.string.sec_lock_bound_key_test_info, -1);
+
+        mKeyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
+
+        getPassButton().setEnabled(false);
+
+        Button startTestButton = (Button) findViewById(R.id.sec_start_test_button);
+        startTestButton.setOnClickListener(new OnClickListener() {
+            @Override
+            public void onClick(View v) {
+                showToast("Test running...");
+                v.postDelayed(new Runnable() {
+                    @Override
+                    public void run() {
+                        if (tryEncrypt()) {
+                            showToast("Test failed. Key accessible without auth.");
+                        } else {
+                            showAuthenticationScreen();
+                        }
+                    }
+                },
+                AUTHENTICATION_DURATION_SECONDS * 1000);
+            }
+
+        });
+
+        if (!mKeyguardManager.isKeyguardSecure()) {
+            // Show a message that the user hasn't set up a lock screen.
+            Toast.makeText(this,
+                    "Secure lock screen hasn't set up.\n"
+                            + "Go to 'Settings -> Security -> Screenlock' to set up a lock screen",
+                    Toast.LENGTH_LONG).show();
+            startTestButton.setEnabled(false);
+            return;
+        }
+
+        createKey();
+    }
+
+    /**
+     * Creates a symmetric key in the Android Key Store which can only be used after the user has
+     * authenticated with device credentials within the last X seconds.
+     */
+    private void createKey() {
+        // Generate a key to decrypt payment credentials, tokens, etc.
+        // This will most likely be a registration step for the user when they are setting up your app.
+        try {
+            KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
+            keyStore.load(null);
+            KeyGenerator keyGenerator = KeyGenerator.getInstance(
+                    KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
+
+            // Set the alias of the entry in Android KeyStore where the key will appear
+            // and the constrains (purposes) in the constructor of the Builder
+            keyGenerator.init(new KeyGenParameterSpec.Builder(KEY_NAME,
+                    KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
+                    .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
+                    .setUserAuthenticationRequired(true)
+                            // Require that the user has unlocked in the last 30 seconds
+                    .setUserAuthenticationValidityDurationSeconds(AUTHENTICATION_DURATION_SECONDS)
+                    .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
+                    .build());
+            keyGenerator.generateKey();
+        } catch (NoSuchAlgorithmException | NoSuchProviderException
+                | InvalidAlgorithmParameterException | KeyStoreException
+                | CertificateException | IOException e) {
+            throw new RuntimeException("Failed to create a symmetric key", e);
+        }
+    }
+
+    /**
+     * Tries to encrypt some data with the generated key in {@link #createKey} which is
+     * only works if the user has just authenticated via device credentials.
+     */
+    private boolean tryEncrypt() {
+        try {
+            KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
+            keyStore.load(null);
+            SecretKey secretKey = (SecretKey) keyStore.getKey(KEY_NAME, null);
+            Cipher cipher = Cipher.getInstance(
+                    KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/"
+                            + KeyProperties.ENCRYPTION_PADDING_PKCS7);
+
+            // Try encrypting something, it will only work if the user authenticated within
+            // the last AUTHENTICATION_DURATION_SECONDS seconds.
+            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
+            cipher.doFinal(SECRET_BYTE_ARRAY);
+            return true;
+        } catch (UserNotAuthenticatedException e) {
+            // User is not authenticated, let's authenticate with device credentials.
+            return false;
+        } catch (KeyPermanentlyInvalidatedException e) {
+            // This happens if the lock screen has been disabled or reset after the key was
+            // generated after the key was generated.
+            createKey();
+            Toast.makeText(this, "Set up lockscreen after test ran. Retry the test.\n"
+                            + e.getMessage(),
+                    Toast.LENGTH_LONG).show();
+            return false;
+        } catch (BadPaddingException | IllegalBlockSizeException | KeyStoreException |
+                CertificateException | UnrecoverableKeyException | IOException
+                | NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    private void showAuthenticationScreen() {
+        // Create the Confirm Credentials screen. You can customize the title and description. Or
+        // we will provide a generic one for you if you leave it null
+        Intent intent = mKeyguardManager.createConfirmDeviceCredentialIntent(null, null);
+        if (intent != null) {
+            startActivityForResult(intent, CONFIRM_CREDENTIALS_REQUEST_CODE);
+        }
+    }
+
+    private void showToast(String message) {
+        Toast.makeText(this, message, Toast.LENGTH_LONG)
+            .show();
+    }
+
+    @Override
+    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+        super.onActivityResult(requestCode, resultCode, data);
+        switch (requestCode) {
+            case CONFIRM_CREDENTIALS_REQUEST_CODE:
+                if (resultCode == RESULT_OK) {
+                    if (tryEncrypt()) {
+                        showToast("Test passed.");
+                        getPassButton().setEnabled(true);
+                    } else {
+                        showToast("Test failed. Key not accessible after auth");
+                    }
+                }
+        }
+    }
+}
+
diff --git a/hostsidetests/appsecurity/src/com/android/cts/appsecurity/AdoptionHostTest.java b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/AdoptionHostTest.java
new file mode 100644
index 0000000..147e1da
--- /dev/null
+++ b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/AdoptionHostTest.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.appsecurity;
+
+import com.android.cts.tradefed.build.CtsBuildHelper;
+import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.testtype.DeviceTestCase;
+import com.android.tradefed.testtype.IAbi;
+import com.android.tradefed.testtype.IAbiReceiver;
+import com.android.tradefed.testtype.IBuildReceiver;
+
+/**
+ * Set of tests that verify behavior of adopted storage media, if supported.
+ */
+public class AdoptionHostTest extends DeviceTestCase implements IAbiReceiver, IBuildReceiver {
+    private IAbi mAbi;
+    private CtsBuildHelper mCtsBuild;
+
+    @Override
+    public void setAbi(IAbi abi) {
+        mAbi = abi;
+    }
+
+    @Override
+    public void setBuild(IBuildInfo buildInfo) {
+        mCtsBuild = CtsBuildHelper.createBuildHelper(buildInfo);
+    }
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+
+        assertNotNull(mAbi);
+        assertNotNull(mCtsBuild);
+    }
+
+    @Override
+    protected void tearDown() throws Exception {
+        super.tearDown();
+    }
+
+    public void testAdoptionApps() throws Exception {
+    }
+
+    public void testAdoptionStorage() throws Exception {
+    }
+}
diff --git a/hostsidetests/appsecurity/src/com/android/cts/appsecurity/AppSecurityTests.java b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/AppSecurityTests.java
index 206bdbe..bf9e81c 100644
--- a/hostsidetests/appsecurity/src/com/android/cts/appsecurity/AppSecurityTests.java
+++ b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/AppSecurityTests.java
@@ -19,15 +19,8 @@
 import com.android.cts.tradefed.build.CtsBuildHelper;
 import com.android.cts.util.AbiUtils;
 import com.android.ddmlib.Log;
-import com.android.ddmlib.testrunner.InstrumentationResultParser;
-import com.android.ddmlib.testrunner.TestIdentifier;
-import com.android.ddmlib.testrunner.TestResult;
-import com.android.ddmlib.testrunner.TestResult.TestStatus;
-import com.android.ddmlib.testrunner.TestRunResult;
 import com.android.tradefed.build.IBuildInfo;
 import com.android.tradefed.device.DeviceNotAvailableException;
-import com.android.tradefed.device.ITestDevice;
-import com.android.tradefed.result.CollectingTestListener;
 import com.android.tradefed.testtype.DeviceTestCase;
 import com.android.tradefed.testtype.IAbi;
 import com.android.tradefed.testtype.IAbiReceiver;
@@ -35,15 +28,13 @@
 
 import java.io.File;
 import java.io.FileNotFoundException;
-import java.util.Map;
 
 /**
- * Set of tests that verify various security checks involving multiple apps are properly enforced.
+ * Set of tests that verify various security checks involving multiple apps are
+ * properly enforced.
  */
 public class AppSecurityTests extends DeviceTestCase implements IAbiReceiver, IBuildReceiver {
 
-    private static final String RUNNER = "android.support.test.runner.AndroidJUnitRunner";
-
     // testSharedUidDifferentCerts constants
     private static final String SHARED_UI_APK = "CtsSharedUidInstall.apk";
     private static final String SHARED_UI_PKG = "com.android.cts.shareuidinstall";
@@ -68,18 +59,6 @@
     private static final String APP_ACCESS_DATA_APK = "CtsAppAccessData.apk";
     private static final String APP_ACCESS_DATA_PKG = "com.android.cts.appaccessdata";
 
-    // External storage constants
-    private static final String COMMON_EXTERNAL_STORAGE_APP_CLASS = "com.android.cts.externalstorageapp.CommonExternalStorageTest";
-    private static final String EXTERNAL_STORAGE_APP_APK = "CtsExternalStorageApp.apk";
-    private static final String EXTERNAL_STORAGE_APP_PKG = "com.android.cts.externalstorageapp";
-    private static final String EXTERNAL_STORAGE_APP_CLASS = EXTERNAL_STORAGE_APP_PKG + ".ExternalStorageTest";
-    private static final String READ_EXTERNAL_STORAGE_APP_APK = "CtsReadExternalStorageApp.apk";
-    private static final String READ_EXTERNAL_STORAGE_APP_PKG = "com.android.cts.readexternalstorageapp";
-    private static final String READ_EXTERNAL_STORAGE_APP_CLASS = READ_EXTERNAL_STORAGE_APP_PKG + ".ReadExternalStorageTest";
-    private static final String WRITE_EXTERNAL_STORAGE_APP_APK = "CtsWriteExternalStorageApp.apk";
-    private static final String WRITE_EXTERNAL_STORAGE_APP_PKG = "com.android.cts.writeexternalstorageapp";
-    private static final String WRITE_EXTERNAL_STORAGE_APP_CLASS = WRITE_EXTERNAL_STORAGE_APP_PKG + ".WriteExternalStorageTest";
-
     // testInstrumentationDiffCert constants
     private static final String TARGET_INSTRUMENT_APK = "CtsTargetInstrumentationApp.apk";
     private static final String TARGET_INSTRUMENT_PKG = "com.android.cts.targetinstrumentationapp";
@@ -97,17 +76,8 @@
     private static final String PERMISSION_DIFF_CERT_PKG =
         "com.android.cts.usespermissiondiffcertapp";
 
-    private static final String READ_EXTERNAL_STORAGE = "android.permission.READ_EXTERNAL_STORAGE";
-
-    private static final String MULTIUSER_STORAGE_APK = "CtsMultiUserStorageApp.apk";
-    private static final String MULTIUSER_STORAGE_PKG = "com.android.cts.multiuserstorageapp";
-    private static final String MULTIUSER_STORAGE_CLASS = MULTIUSER_STORAGE_PKG
-            + ".MultiUserStorageTest";
-
     private static final String LOG_TAG = "AppSecurityTests";
 
-    private static final int USER_OWNER = 0;
-
     private IAbi mAbi;
     private CtsBuildHelper mCtsBuild;
 
@@ -156,8 +126,7 @@
             assertNotNull("shared uid app with different cert than existing app installed " +
                     "successfully", installResult);
             assertEquals("INSTALL_FAILED_SHARED_USER_INCOMPATIBLE", installResult);
-        }
-        finally {
+        } finally {
             getDevice().uninstallPackage(SHARED_UI_PKG);
             getDevice().uninstallPackage(SHARED_UI_DIFF_CERT_PKG);
         }
@@ -183,8 +152,7 @@
             assertNotNull("app upgrade with different cert than existing app installed " +
                     "successfully", installResult);
             assertEquals("INSTALL_FAILED_UPDATE_INCOMPATIBLE", installResult);
-        }
-        finally {
+        } finally {
             getDevice().uninstallPackage(SIMPLE_APP_PKG);
         }
     }
@@ -205,132 +173,21 @@
             assertNull(String.format("failed to install app with data. Reason: %s", installResult),
                     installResult);
             // run appwithdata's tests to create private data
-            assertTrue("failed to create app's private data", runDeviceTests(APP_WITH_DATA_PKG,
-                    APP_WITH_DATA_CLASS, APP_WITH_DATA_CREATE_METHOD));
+            runDeviceTests(APP_WITH_DATA_PKG, APP_WITH_DATA_CLASS, APP_WITH_DATA_CREATE_METHOD);
 
             installResult = getDevice().installPackage(getTestAppFile(APP_ACCESS_DATA_APK),
                     false, options);
             assertNull(String.format("failed to install app access data. Reason: %s",
                     installResult), installResult);
             // run appaccessdata's tests which attempt to access appwithdata's private data
-            assertTrue("could access app's private data", runDeviceTests(APP_ACCESS_DATA_PKG));
-        }
-        finally {
+            runDeviceTests(APP_ACCESS_DATA_PKG);
+        } finally {
             getDevice().uninstallPackage(APP_WITH_DATA_PKG);
             getDevice().uninstallPackage(APP_ACCESS_DATA_PKG);
         }
     }
 
     /**
-     * Verify that app with no external storage permissions works correctly.
-     */
-    public void testExternalStorageNone() throws Exception {
-        final int[] users = createUsersForTest();
-        try {
-            wipePrimaryExternalStorage(getDevice());
-
-            getDevice().uninstallPackage(EXTERNAL_STORAGE_APP_PKG);
-            String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
-            assertNull(getDevice()
-                    .installPackage(getTestAppFile(EXTERNAL_STORAGE_APP_APK), false, options));
-
-            for (int user : users) {
-                assertTrue("Failed external storage with no permissions",
-                        runDeviceTests(EXTERNAL_STORAGE_APP_PKG, user));
-            }
-        } finally {
-            getDevice().uninstallPackage(EXTERNAL_STORAGE_APP_PKG);
-            removeUsersForTest(users);
-        }
-    }
-
-    /**
-     * Verify that app with
-     * {@link android.Manifest.permission#READ_EXTERNAL_STORAGE} works
-     * correctly.
-     */
-    public void testExternalStorageRead() throws Exception {
-        final int[] users = createUsersForTest();
-        try {
-            wipePrimaryExternalStorage(getDevice());
-
-            getDevice().uninstallPackage(READ_EXTERNAL_STORAGE_APP_PKG);
-            String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
-            assertNull(getDevice()
-                    .installPackage(getTestAppFile(READ_EXTERNAL_STORAGE_APP_APK), false, options));
-
-            for (int user : users) {
-                assertTrue("Failed external storage with read permissions",
-                        runDeviceTests(READ_EXTERNAL_STORAGE_APP_PKG, user));
-            }
-        } finally {
-            getDevice().uninstallPackage(READ_EXTERNAL_STORAGE_APP_PKG);
-            removeUsersForTest(users);
-        }
-    }
-
-    /**
-     * Verify that app with
-     * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} works
-     * correctly.
-     */
-    public void testExternalStorageWrite() throws Exception {
-        final int[] users = createUsersForTest();
-        try {
-            wipePrimaryExternalStorage(getDevice());
-
-            getDevice().uninstallPackage(WRITE_EXTERNAL_STORAGE_APP_PKG);
-            String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
-            assertNull(getDevice()
-                    .installPackage(getTestAppFile(WRITE_EXTERNAL_STORAGE_APP_APK), false, options));
-
-            for (int user : users) {
-                assertTrue("Failed external storage with write permissions",
-                        runDeviceTests(WRITE_EXTERNAL_STORAGE_APP_PKG, user));
-            }
-        } finally {
-            getDevice().uninstallPackage(WRITE_EXTERNAL_STORAGE_APP_PKG);
-            removeUsersForTest(users);
-        }
-    }
-
-    /**
-     * Verify that app with WRITE_EXTERNAL can leave gifts in external storage
-     * directories belonging to other apps, and those apps can read.
-     */
-    public void testExternalStorageGifts() throws Exception {
-        final int[] users = createUsersForTest();
-        try {
-            wipePrimaryExternalStorage(getDevice());
-
-            getDevice().uninstallPackage(EXTERNAL_STORAGE_APP_PKG);
-            getDevice().uninstallPackage(READ_EXTERNAL_STORAGE_APP_PKG);
-            getDevice().uninstallPackage(WRITE_EXTERNAL_STORAGE_APP_PKG);
-            String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
-            assertNull(getDevice()
-                    .installPackage(getTestAppFile(EXTERNAL_STORAGE_APP_APK), false, options));
-            assertNull(getDevice()
-                    .installPackage(getTestAppFile(READ_EXTERNAL_STORAGE_APP_APK), false, options));
-            assertNull(getDevice()
-                    .installPackage(getTestAppFile(WRITE_EXTERNAL_STORAGE_APP_APK), false, options));
-
-            for (int user : users) {
-                assertTrue("Failed to write gifts", runDeviceTests(WRITE_EXTERNAL_STORAGE_APP_PKG,
-                        WRITE_EXTERNAL_STORAGE_APP_CLASS, "doWriteGifts", user));
-                assertTrue("Read failed to verify gifts", runDeviceTests(READ_EXTERNAL_STORAGE_APP_PKG,
-                        READ_EXTERNAL_STORAGE_APP_CLASS, "doVerifyGifts", user));
-                assertTrue("None failed to verify gifts", runDeviceTests(EXTERNAL_STORAGE_APP_PKG,
-                        EXTERNAL_STORAGE_APP_CLASS, "doVerifyGifts", user));
-            }
-        } finally {
-            getDevice().uninstallPackage(EXTERNAL_STORAGE_APP_PKG);
-            getDevice().uninstallPackage(READ_EXTERNAL_STORAGE_APP_PKG);
-            getDevice().uninstallPackage(WRITE_EXTERNAL_STORAGE_APP_PKG);
-            removeUsersForTest(users);
-        }
-    }
-
-    /**
      * Test that uninstall of an app removes its private data.
      */
     public void testUninstallRemovesData() throws Exception {
@@ -345,8 +202,7 @@
             assertNull(String.format("failed to install app with data. Reason: %s", installResult),
                     installResult);
             // run appwithdata's tests to create private data
-            assertTrue("failed to create app's private data", runDeviceTests(APP_WITH_DATA_PKG,
-                    APP_WITH_DATA_CLASS, APP_WITH_DATA_CREATE_METHOD));
+            runDeviceTests(APP_WITH_DATA_PKG, APP_WITH_DATA_CLASS, APP_WITH_DATA_CREATE_METHOD);
 
             getDevice().uninstallPackage(APP_WITH_DATA_PKG);
 
@@ -355,11 +211,9 @@
             assertNull(String.format("failed to install app with data second time. Reason: %s",
                     installResult), installResult);
             // run appwithdata's 'check if file exists' test
-            assertTrue("app's private data still exists after install", runDeviceTests(
-                    APP_WITH_DATA_PKG, APP_WITH_DATA_CLASS, APP_WITH_DATA_CHECK_NOEXIST_METHOD));
-
-        }
-        finally {
+            runDeviceTests(APP_WITH_DATA_PKG, APP_WITH_DATA_CLASS,
+                    APP_WITH_DATA_CHECK_NOEXIST_METHOD);
+        } finally {
             getDevice().uninstallPackage(APP_WITH_DATA_PKG);
         }
     }
@@ -389,10 +243,8 @@
             // run INSTRUMENT_DIFF_CERT_PKG tests
             // this test will attempt to call startInstrumentation directly and verify
             // SecurityException is thrown
-            assertTrue("running instrumentation with diff cert unexpectedly succeeded",
-                    runDeviceTests(INSTRUMENT_DIFF_CERT_PKG));
-        }
-        finally {
+            runDeviceTests(INSTRUMENT_DIFF_CERT_PKG);
+        } finally {
             getDevice().uninstallPackage(TARGET_INSTRUMENT_PKG);
             getDevice().uninstallPackage(INSTRUMENT_DIFF_CERT_PKG);
         }
@@ -427,209 +279,20 @@
             assertNull(String.format("failed to install permission app with diff cert. Reason: %s",
                     installResult), installResult);
             // run PERMISSION_DIFF_CERT_PKG tests which try to access the permission
-            TestRunResult result = doRunTests(PERMISSION_DIFF_CERT_PKG, null, null, USER_OWNER);
-            assertDeviceTestsPass(result);
-        }
-        finally {
+            runDeviceTests(PERMISSION_DIFF_CERT_PKG);
+        } finally {
             getDevice().uninstallPackage(DECLARE_PERMISSION_PKG);
             getDevice().uninstallPackage(DECLARE_PERMISSION_COMPAT_PKG);
             getDevice().uninstallPackage(PERMISSION_DIFF_CERT_PKG);
         }
     }
 
-    /**
-     * Test multi-user emulated storage environment, ensuring that each user has
-     * isolated storage.
-     */
-    public void testMultiUserStorageIsolated() throws Exception {
-        final String PACKAGE = MULTIUSER_STORAGE_PKG;
-        final String CLAZZ = MULTIUSER_STORAGE_CLASS;
-
-        final int[] users = createUsersForTest();
-        try {
-            if (users.length == 1) {
-                Log.d(LOG_TAG, "Single user device; skipping isolated storage tests");
-                return;
-            }
-
-            final int owner = users[0];
-            final int secondary = users[1];
-
-            // Install our test app
-            getDevice().uninstallPackage(MULTIUSER_STORAGE_PKG);
-            String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
-            final String installResult = getDevice()
-                    .installPackage(getTestAppFile(MULTIUSER_STORAGE_APK), false, options);
-            assertNull("Failed to install: " + installResult, installResult);
-
-            // Clear data from previous tests
-            assertDeviceTestsPass(
-                    doRunTests(PACKAGE, CLAZZ, "cleanIsolatedStorage", owner));
-            assertDeviceTestsPass(
-                    doRunTests(PACKAGE, CLAZZ, "cleanIsolatedStorage", secondary));
-
-            // Have both users try writing into isolated storage
-            assertDeviceTestsPass(
-                    doRunTests(PACKAGE, CLAZZ, "writeIsolatedStorage", owner));
-            assertDeviceTestsPass(
-                    doRunTests(PACKAGE, CLAZZ, "writeIsolatedStorage", secondary));
-
-            // Verify they both have isolated view of storage
-            assertDeviceTestsPass(
-                    doRunTests(PACKAGE, CLAZZ, "readIsolatedStorage", owner));
-            assertDeviceTestsPass(
-                    doRunTests(PACKAGE, CLAZZ, "readIsolatedStorage", secondary));
-        } finally {
-            getDevice().uninstallPackage(MULTIUSER_STORAGE_PKG);
-            removeUsersForTest(users);
-        }
+    private void runDeviceTests(String packageName) throws DeviceNotAvailableException {
+        Utils.runDeviceTests(getDevice(), packageName);
     }
 
-    /**
-     * Helper method that checks that all tests in given result passed, and attempts to generate
-     * a meaningful error message if they failed.
-     *
-     * @param result
-     */
-    private void assertDeviceTestsPass(TestRunResult result) {
-        // TODO: consider rerunning if this occurred
-        assertFalse(String.format("Failed to successfully run device tests for %s. Reason: %s",
-                result.getName(), result.getRunFailureMessage()), result.isRunFailure());
-
-        if (result.hasFailedTests()) {
-            // build a meaningful error message
-            StringBuilder errorBuilder = new StringBuilder("on-device tests failed:\n");
-            for (Map.Entry<TestIdentifier, TestResult> resultEntry :
-                result.getTestResults().entrySet()) {
-                if (!resultEntry.getValue().getStatus().equals(TestStatus.PASSED)) {
-                    errorBuilder.append(resultEntry.getKey().toString());
-                    errorBuilder.append(":\n");
-                    errorBuilder.append(resultEntry.getValue().getStackTrace());
-                }
-            }
-            fail(errorBuilder.toString());
-        }
-    }
-
-    /**
-     * Helper method that will the specified packages tests on device.
-     *
-     * @param pkgName Android application package for tests
-     * @return <code>true</code> if all tests passed.
-     * @throws DeviceNotAvailableException if connection to device was lost.
-     */
-    private boolean runDeviceTests(String pkgName) throws DeviceNotAvailableException {
-        return runDeviceTests(pkgName, null, null, USER_OWNER);
-    }
-
-    private boolean runDeviceTests(String pkgName, int userId) throws DeviceNotAvailableException {
-        return runDeviceTests(pkgName, null, null, userId);
-    }
-
-    /**
-     * Helper method that will the specified packages tests on device.
-     *
-     * @param pkgName Android application package for tests
-     * @return <code>true</code> if all tests passed.
-     * @throws DeviceNotAvailableException if connection to device was lost.
-     */
-    private boolean runDeviceTests(String pkgName, String testClassName, String testMethodName)
+    private void runDeviceTests(String packageName, String testClassName, String testMethodName)
             throws DeviceNotAvailableException {
-        return runDeviceTests(pkgName, testClassName, testMethodName, USER_OWNER);
-    }
-
-    private boolean runDeviceTests(String pkgName, String testClassName, String testMethodName,
-            int userId) throws DeviceNotAvailableException {
-        TestRunResult runResult = doRunTests(pkgName, testClassName, testMethodName,
-                userId);
-        return !runResult.hasFailedTests();
-    }
-
-    private static boolean isMultiUserSupportedOnDevice(ITestDevice device)
-            throws DeviceNotAvailableException {
-        // TODO: move this to ITestDevice once it supports users
-        final String output = device.executeShellCommand("pm get-max-users");
-        try {
-            return Integer.parseInt(output.substring(output.lastIndexOf(" ")).trim()) > 1;
-        } catch (NumberFormatException e) {
-            fail("Failed to parse result: " + output);
-        }
-        return false;
-    }
-
-    /**
-     * Return set of users that test should be run for, creating a secondary
-     * user if the device supports it. Always call
-     * {@link #removeUsersForTest(int[])} when finished.
-     */
-    private int[] createUsersForTest() throws DeviceNotAvailableException {
-        if (isMultiUserSupportedOnDevice(getDevice())) {
-            return new int[] { USER_OWNER, createUserOnDevice(getDevice()) };
-        } else {
-            Log.d(LOG_TAG, "Single user device; skipping isolated storage tests");
-            return new int[] { USER_OWNER };
-        }
-    }
-
-    private void removeUsersForTest(int[] users) throws DeviceNotAvailableException {
-        for (int user : users) {
-            if (user != USER_OWNER) {
-                removeUserOnDevice(getDevice(), user);
-            }
-        }
-   }
-
-    private static int createUserOnDevice(ITestDevice device) throws DeviceNotAvailableException {
-        // TODO: move this to ITestDevice once it supports users
-        final String name = "CTS_" + System.currentTimeMillis();
-        final String output = device.executeShellCommand("pm create-user " + name);
-        if (output.startsWith("Success")) {
-            try {
-                final int userId = Integer.parseInt(
-                        output.substring(output.lastIndexOf(" ")).trim());
-                device.executeShellCommand("am start-user " + userId);
-                return userId;
-            } catch (NumberFormatException e) {
-                fail("Failed to parse result: " + output);
-            }
-        } else {
-            fail("Failed to create user: " + output);
-        }
-        throw new IllegalStateException();
-    }
-
-    private static void removeUserOnDevice(ITestDevice device, int userId)
-            throws DeviceNotAvailableException {
-        // TODO: move this to ITestDevice once it supports users
-        final String output = device.executeShellCommand("pm remove-user " + userId);
-        if (output.startsWith("Error")) {
-            fail("Failed to remove user: " + output);
-        }
-    }
-
-    private TestRunResult doRunTests(String pkgName, String testClassName, String testMethodName,
-            int userId) throws DeviceNotAvailableException {
-        // TODO: move this to RemoteAndroidTestRunner once it supports users
-        final StringBuilder cmd = new StringBuilder("am instrument --user " + userId + " -w -r");
-        if (testClassName != null) {
-            cmd.append(" -e class " + testClassName);
-            if (testMethodName != null) {
-                cmd.append("#" + testMethodName);
-            }
-        }
-        cmd.append(" " + pkgName + "/" + RUNNER);
-
-        Log.i(LOG_TAG, "Running " + cmd + " on " + getDevice().getSerialNumber());
-
-        CollectingTestListener listener = new CollectingTestListener();
-        InstrumentationResultParser parser = new InstrumentationResultParser(pkgName, listener);
-
-        getDevice().executeShellCommand(cmd.toString(), parser);
-        return listener.getCurrentRunResults();
-    }
-
-    private static void wipePrimaryExternalStorage(ITestDevice device)
-            throws DeviceNotAvailableException {
-        device.executeShellCommand("rm -rf /sdcard/*");
+        Utils.runDeviceTests(getDevice(), packageName, testClassName, testMethodName);
     }
 }
diff --git a/hostsidetests/appsecurity/src/com/android/cts/appsecurity/DocumentsTest.java b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/DocumentsTest.java
index fbde558..a4ec65a 100644
--- a/hostsidetests/appsecurity/src/com/android/cts/appsecurity/DocumentsTest.java
+++ b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/DocumentsTest.java
@@ -24,6 +24,10 @@
 import com.android.tradefed.testtype.IAbiReceiver;
 import com.android.tradefed.testtype.IBuildReceiver;
 
+/**
+ * Set of tests that verify behavior of
+ * {@link android.provider.DocumentsContract} and related intents.
+ */
 public class DocumentsTest extends DeviceTestCase implements IAbiReceiver, IBuildReceiver {
     private static final String PROVIDER_PKG = "com.android.cts.documentprovider";
     private static final String PROVIDER_APK = "CtsDocumentProvider.apk";
diff --git a/hostsidetests/appsecurity/src/com/android/cts/appsecurity/ExternalStorageHostTest.java b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/ExternalStorageHostTest.java
new file mode 100644
index 0000000..d74ec52
--- /dev/null
+++ b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/ExternalStorageHostTest.java
@@ -0,0 +1,245 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.appsecurity;
+
+import com.android.cts.tradefed.build.CtsBuildHelper;
+import com.android.cts.util.AbiUtils;
+import com.android.ddmlib.Log;
+import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.testtype.DeviceTestCase;
+import com.android.tradefed.testtype.IAbi;
+import com.android.tradefed.testtype.IAbiReceiver;
+import com.android.tradefed.testtype.IBuildReceiver;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+
+/**
+ * Set of tests that verify behavior of external storage devices.
+ */
+public class ExternalStorageHostTest extends DeviceTestCase
+        implements IAbiReceiver, IBuildReceiver {
+    private static final String TAG = "ExternalStorageHostTest";
+
+    private static final String COMMON_CLASS =
+            "com.android.cts.externalstorageapp.CommonExternalStorageTest";
+
+    private static final String NONE_APK = "CtsExternalStorageApp.apk";
+    private static final String NONE_PKG = "com.android.cts.externalstorageapp";
+    private static final String NONE_CLASS = ".ExternalStorageTest";
+    private static final String READ_APK = "CtsReadExternalStorageApp.apk";
+    private static final String READ_PKG = "com.android.cts.readexternalstorageapp";
+    private static final String READ_CLASS = ".ReadExternalStorageTest";
+    private static final String WRITE_APK = "CtsWriteExternalStorageApp.apk";
+    private static final String WRITE_PKG = "com.android.cts.writeexternalstorageapp";
+    private static final String WRITE_CLASS = ".WriteExternalStorageTest";
+    private static final String MULTIUSER_APK = "CtsMultiUserStorageApp.apk";
+    private static final String MULTIUSER_PKG = "com.android.cts.multiuserstorageapp";
+    private static final String MULTIUSER_CLASS = ".MultiUserStorageTest";
+
+    private IAbi mAbi;
+    private CtsBuildHelper mCtsBuild;
+
+    @Override
+    public void setAbi(IAbi abi) {
+        mAbi = abi;
+    }
+
+    @Override
+    public void setBuild(IBuildInfo buildInfo) {
+        mCtsBuild = CtsBuildHelper.createBuildHelper(buildInfo);
+    }
+
+    private File getTestAppFile(String fileName) throws FileNotFoundException {
+        return mCtsBuild.getTestApp(fileName);
+    }
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+
+        assertNotNull(mAbi);
+        assertNotNull(mCtsBuild);
+    }
+
+    @Override
+    protected void tearDown() throws Exception {
+        super.tearDown();
+    }
+
+    /**
+     * Verify that app with no external storage permissions works correctly.
+     */
+    public void testExternalStorageNone() throws Exception {
+        final int[] users = createUsersForTest();
+        try {
+            wipePrimaryExternalStorage();
+
+            getDevice().uninstallPackage(NONE_PKG);
+            String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
+            assertNull(getDevice().installPackage(getTestAppFile(NONE_APK), false, options));
+
+            for (int user : users) {
+                runDeviceTests(NONE_PKG, COMMON_CLASS, user);
+                runDeviceTests(NONE_PKG, NONE_CLASS, user);
+            }
+        } finally {
+            getDevice().uninstallPackage(NONE_PKG);
+            removeUsersForTest(users);
+        }
+    }
+
+    /**
+     * Verify that app with
+     * {@link android.Manifest.permission#READ_EXTERNAL_STORAGE} works
+     * correctly.
+     */
+    public void testExternalStorageRead() throws Exception {
+        final int[] users = createUsersForTest();
+        try {
+            wipePrimaryExternalStorage();
+
+            getDevice().uninstallPackage(READ_PKG);
+            String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
+            assertNull(getDevice().installPackage(getTestAppFile(READ_APK), false, options));
+
+            for (int user : users) {
+                runDeviceTests(READ_PKG, COMMON_CLASS, user);
+                runDeviceTests(READ_PKG, READ_CLASS, user);
+            }
+        } finally {
+            getDevice().uninstallPackage(READ_PKG);
+            removeUsersForTest(users);
+        }
+    }
+
+    /**
+     * Verify that app with
+     * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} works
+     * correctly.
+     */
+    public void testExternalStorageWrite() throws Exception {
+        final int[] users = createUsersForTest();
+        try {
+            wipePrimaryExternalStorage();
+
+            getDevice().uninstallPackage(WRITE_PKG);
+            String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
+            assertNull(getDevice().installPackage(getTestAppFile(WRITE_APK), false, options));
+
+            for (int user : users) {
+                runDeviceTests(WRITE_PKG, COMMON_CLASS, user);
+                runDeviceTests(WRITE_PKG, WRITE_CLASS, user);
+            }
+        } finally {
+            getDevice().uninstallPackage(WRITE_PKG);
+            removeUsersForTest(users);
+        }
+    }
+
+    /**
+     * Verify that app with WRITE_EXTERNAL can leave gifts in external storage
+     * directories belonging to other apps, and those apps can read.
+     */
+    public void testExternalStorageGifts() throws Exception {
+        final int[] users = createUsersForTest();
+        try {
+            wipePrimaryExternalStorage();
+
+            getDevice().uninstallPackage(NONE_PKG);
+            getDevice().uninstallPackage(READ_PKG);
+            getDevice().uninstallPackage(WRITE_PKG);
+            String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
+            assertNull(getDevice().installPackage(getTestAppFile(NONE_APK), false, options));
+            assertNull(getDevice().installPackage(getTestAppFile(READ_APK), false, options));
+            assertNull(getDevice().installPackage(getTestAppFile(WRITE_APK), false, options));
+
+            for (int user : users) {
+                runDeviceTests(WRITE_PKG, "WriteGiftTest", user);
+                runDeviceTests(READ_PKG, "ReadGiftTest", user);
+                runDeviceTests(NONE_PKG, "GiftTest", user);
+            }
+        } finally {
+            getDevice().uninstallPackage(NONE_PKG);
+            getDevice().uninstallPackage(READ_PKG);
+            getDevice().uninstallPackage(WRITE_PKG);
+            removeUsersForTest(users);
+        }
+    }
+
+    /**
+     * Test multi-user emulated storage environment, ensuring that each user has
+     * isolated storage.
+     */
+    public void testMultiUserStorageIsolated() throws Exception {
+        final int[] users = createUsersForTest();
+        try {
+            if (users.length == 1) {
+                Log.d(TAG, "Single user device; skipping isolated storage tests");
+                return;
+            }
+
+            final int owner = users[0];
+            final int secondary = users[1];
+
+            // Install our test app
+            getDevice().uninstallPackage(MULTIUSER_PKG);
+            String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
+            final String installResult = getDevice()
+                    .installPackage(getTestAppFile(MULTIUSER_APK), false, options);
+            assertNull("Failed to install: " + installResult, installResult);
+
+            // Clear data from previous tests
+            runDeviceTests(MULTIUSER_PKG, MULTIUSER_CLASS, "testCleanIsolatedStorage", owner);
+            runDeviceTests(MULTIUSER_PKG, MULTIUSER_CLASS, "testCleanIsolatedStorage", secondary);
+
+            // Have both users try writing into isolated storage
+            runDeviceTests(MULTIUSER_PKG, MULTIUSER_CLASS, "testWriteIsolatedStorage", owner);
+            runDeviceTests(MULTIUSER_PKG, MULTIUSER_CLASS, "testWriteIsolatedStorage", secondary);
+
+            // Verify they both have isolated view of storage
+            runDeviceTests(MULTIUSER_PKG, MULTIUSER_CLASS, "testReadIsolatedStorage", owner);
+            runDeviceTests(MULTIUSER_PKG, MULTIUSER_CLASS, "testReadIsolatedStorage", secondary);
+        } finally {
+            getDevice().uninstallPackage(MULTIUSER_PKG);
+            removeUsersForTest(users);
+        }
+    }
+
+    private void wipePrimaryExternalStorage() throws DeviceNotAvailableException {
+        getDevice().executeShellCommand("rm -rf /sdcard/*");
+    }
+
+    private int[] createUsersForTest() throws DeviceNotAvailableException {
+        return Utils.createUsersForTest(getDevice());
+    }
+
+    private void removeUsersForTest(int[] users) throws DeviceNotAvailableException {
+        Utils.removeUsersForTest(getDevice(), users);
+    }
+
+    private void runDeviceTests(String packageName, String testClassName, int userId)
+            throws DeviceNotAvailableException {
+        Utils.runDeviceTests(getDevice(), packageName, testClassName, userId);
+    }
+
+    private void runDeviceTests(String packageName, String testClassName, String testMethodName,
+            int userId) throws DeviceNotAvailableException {
+        Utils.runDeviceTests(getDevice(), packageName, testClassName, testMethodName, userId);
+    }
+}
diff --git a/hostsidetests/appsecurity/src/com/android/cts/appsecurity/PermissionsHostTest.java b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/PermissionsHostTest.java
index 2eafcfc..4b5259d 100644
--- a/hostsidetests/appsecurity/src/com/android/cts/appsecurity/PermissionsHostTest.java
+++ b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/PermissionsHostTest.java
@@ -24,6 +24,10 @@
 import com.android.tradefed.testtype.IAbiReceiver;
 import com.android.tradefed.testtype.IBuildReceiver;
 
+/**
+ * Set of tests that verify behavior of runtime permissions, including both
+ * dynamic granting and behavior of legacy apps.
+ */
 public class PermissionsHostTest extends DeviceTestCase implements IAbiReceiver, IBuildReceiver {
     private static final String PKG = "com.android.cts.usepermission";
 
diff --git a/hostsidetests/appsecurity/src/com/android/cts/appsecurity/Utils.java b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/Utils.java
index c58d6bf..fdf84d3 100644
--- a/hostsidetests/appsecurity/src/com/android/cts/appsecurity/Utils.java
+++ b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/Utils.java
@@ -16,6 +16,7 @@
 
 package com.android.cts.appsecurity;
 
+import com.android.ddmlib.Log;
 import com.android.ddmlib.testrunner.RemoteAndroidTestRunner;
 import com.android.ddmlib.testrunner.TestIdentifier;
 import com.android.ddmlib.testrunner.TestResult;
@@ -28,13 +29,37 @@
 import java.util.Map;
 
 public class Utils {
+    private static final String TAG = "AppSecurity";
+
+    public static final int USER_OWNER = 0;
+
     public static void runDeviceTests(ITestDevice device, String packageName)
             throws DeviceNotAvailableException {
-        runDeviceTests(device, packageName, null, null);
+        runDeviceTests(device, packageName, null, null, USER_OWNER);
+    }
+
+    public static void runDeviceTests(ITestDevice device, String packageName, int userId)
+            throws DeviceNotAvailableException {
+        runDeviceTests(device, packageName, null, null, userId);
+    }
+
+    public static void runDeviceTests(ITestDevice device, String packageName, String testClassName)
+            throws DeviceNotAvailableException {
+        runDeviceTests(device, packageName, testClassName, null, USER_OWNER);
+    }
+
+    public static void runDeviceTests(ITestDevice device, String packageName, String testClassName,
+            int userId) throws DeviceNotAvailableException {
+        runDeviceTests(device, packageName, testClassName, null, userId);
     }
 
     public static void runDeviceTests(ITestDevice device, String packageName, String testClassName,
             String testMethodName) throws DeviceNotAvailableException {
+        runDeviceTests(device, packageName, testClassName, testMethodName, USER_OWNER);
+    }
+
+    public static void runDeviceTests(ITestDevice device, String packageName, String testClassName,
+            String testMethodName, int userId) throws DeviceNotAvailableException {
         if (testClassName != null && testClassName.startsWith(".")) {
             testClassName = packageName + testClassName;
         }
@@ -43,6 +68,13 @@
                 "android.support.test.runner.AndroidJUnitRunner", device.getIDevice());
         if (testClassName != null && testMethodName != null) {
             testRunner.setMethodName(testClassName, testMethodName);
+        } else if (testClassName != null) {
+            testRunner.setClassName(testClassName);
+        }
+
+        if (userId != USER_OWNER) {
+            // TODO: move this to RemoteAndroidTestRunner once it supports users
+            testRunner.addInstrumentationArg("hack_key", "hack_value --user " + userId);
         }
 
         final CollectingTestListener listener = new CollectingTestListener();
@@ -68,4 +100,66 @@
             throw new AssertionError(errorBuilder.toString());
         }
     }
+
+    private static boolean isMultiUserSupportedOnDevice(ITestDevice device)
+            throws DeviceNotAvailableException {
+        // TODO: move this to ITestDevice once it supports users
+        final String output = device.executeShellCommand("pm get-max-users");
+        try {
+            return Integer.parseInt(output.substring(output.lastIndexOf(" ")).trim()) > 1;
+        } catch (NumberFormatException e) {
+            throw new AssertionError("Failed to parse result: " + output);
+        }
+    }
+
+    /**
+     * Return set of users that test should be run for, creating a secondary
+     * user if the device supports it. Always call
+     * {@link #removeUsersForTest(ITestDevice, int[])} when finished.
+     */
+    public static int[] createUsersForTest(ITestDevice device) throws DeviceNotAvailableException {
+        if (isMultiUserSupportedOnDevice(device)) {
+            return new int[] { USER_OWNER, createUserOnDevice(device) };
+        } else {
+            Log.d(TAG, "Single user device; skipping isolated storage tests");
+            return new int[] { USER_OWNER };
+        }
+    }
+
+    public static void removeUsersForTest(ITestDevice device, int[] users)
+            throws DeviceNotAvailableException {
+        for (int user : users) {
+            if (user != USER_OWNER) {
+                removeUserOnDevice(device, user);
+            }
+        }
+    }
+
+    private static int createUserOnDevice(ITestDevice device) throws DeviceNotAvailableException {
+        // TODO: move this to ITestDevice once it supports users
+        final String name = "CTS_" + System.currentTimeMillis();
+        final String output = device.executeShellCommand("pm create-user " + name);
+        if (output.startsWith("Success")) {
+            try {
+                final int userId = Integer.parseInt(
+                        output.substring(output.lastIndexOf(" ")).trim());
+                device.executeShellCommand("am start-user " + userId);
+                return userId;
+            } catch (NumberFormatException e) {
+                throw new AssertionError("Failed to parse result: " + output);
+            }
+        } else {
+            throw new AssertionError("Failed to create user: " + output);
+        }
+    }
+
+    private static void removeUserOnDevice(ITestDevice device, int userId)
+            throws DeviceNotAvailableException {
+        // TODO: move this to ITestDevice once it supports users
+        final String output = device.executeShellCommand("pm remove-user " + userId);
+        if (output.startsWith("Error")) {
+            throw new AssertionError("Failed to remove user: " + output);
+        }
+    }
+
 }
diff --git a/hostsidetests/appsecurity/test-apps/ExternalStorageApp/src/com/android/cts/externalstorageapp/CommonExternalStorageTest.java b/hostsidetests/appsecurity/test-apps/ExternalStorageApp/src/com/android/cts/externalstorageapp/CommonExternalStorageTest.java
index 379de5f..c935c91 100644
--- a/hostsidetests/appsecurity/test-apps/ExternalStorageApp/src/com/android/cts/externalstorageapp/CommonExternalStorageTest.java
+++ b/hostsidetests/appsecurity/test-apps/ExternalStorageApp/src/com/android/cts/externalstorageapp/CommonExternalStorageTest.java
@@ -100,7 +100,7 @@
         for (File path : paths) {
             assertNotNull("Valid media must be inserted during CTS", path);
             assertEquals("Valid media must be inserted during CTS", Environment.MEDIA_MOUNTED,
-                    Environment.getStorageState(path));
+                    Environment.getExternalStorageState(path));
 
             assertDirReadWriteAccess(path);
 
diff --git a/hostsidetests/appsecurity/test-apps/ExternalStorageApp/src/com/android/cts/externalstorageapp/ExternalStorageTest.java b/hostsidetests/appsecurity/test-apps/ExternalStorageApp/src/com/android/cts/externalstorageapp/ExternalStorageTest.java
index 5d492b2..7dc462a 100644
--- a/hostsidetests/appsecurity/test-apps/ExternalStorageApp/src/com/android/cts/externalstorageapp/ExternalStorageTest.java
+++ b/hostsidetests/appsecurity/test-apps/ExternalStorageApp/src/com/android/cts/externalstorageapp/ExternalStorageTest.java
@@ -16,16 +16,9 @@
 
 package com.android.cts.externalstorageapp;
 
-import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_NONE;
-import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_READ;
-import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_WRITE;
 import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertDirNoAccess;
 import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertDirReadWriteAccess;
-import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertFileNoAccess;
-import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertFileReadWriteAccess;
-import static com.android.cts.externalstorageapp.CommonExternalStorageTest.buildGiftForPackage;
 import static com.android.cts.externalstorageapp.CommonExternalStorageTest.getAllPackageSpecificPaths;
-import static com.android.cts.externalstorageapp.CommonExternalStorageTest.readInt;
 
 import android.app.DownloadManager;
 import android.app.DownloadManager.Query;
@@ -75,7 +68,7 @@
             }
 
             // Keep walking up until we leave device
-            while (Environment.MEDIA_MOUNTED.equals(Environment.getStorageState(path))) {
+            while (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState(path))) {
                 assertDirNoAccess(path);
                 path = path.getParentFile();
             }
@@ -120,21 +113,6 @@
     }
 
     /**
-     * Verify we can read only our gifts.
-     */
-    public void doVerifyGifts() throws Exception {
-        final File none = buildGiftForPackage(getContext(), PACKAGE_NONE);
-        assertFileReadWriteAccess(none);
-        assertEquals(100, readInt(none));
-
-        final File read = buildGiftForPackage(getContext(), PACKAGE_READ);
-        assertFileNoAccess(read);
-
-        final File write = buildGiftForPackage(getContext(), PACKAGE_WRITE);
-        assertFileNoAccess(write);
-    }
-
-    /**
      * Shamelessly borrowed from DownloadManagerTest.java
      */
     private static class DownloadCompleteReceiver extends BroadcastReceiver {
diff --git a/hostsidetests/appsecurity/test-apps/ExternalStorageApp/src/com/android/cts/externalstorageapp/GiftTest.java b/hostsidetests/appsecurity/test-apps/ExternalStorageApp/src/com/android/cts/externalstorageapp/GiftTest.java
new file mode 100644
index 0000000..e482b2f
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/ExternalStorageApp/src/com/android/cts/externalstorageapp/GiftTest.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.externalstorageapp;
+
+import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_NONE;
+import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_READ;
+import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_WRITE;
+import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertFileNoAccess;
+import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertFileReadWriteAccess;
+import static com.android.cts.externalstorageapp.CommonExternalStorageTest.buildGiftForPackage;
+import static com.android.cts.externalstorageapp.CommonExternalStorageTest.readInt;
+
+import android.test.AndroidTestCase;
+
+import java.io.File;
+
+public class GiftTest extends AndroidTestCase {
+    /**
+     * Verify we can read only our gifts.
+     */
+    public void testGifts() throws Exception {
+        final File none = buildGiftForPackage(getContext(), PACKAGE_NONE);
+        assertFileReadWriteAccess(none);
+        assertEquals(100, readInt(none));
+
+        final File read = buildGiftForPackage(getContext(), PACKAGE_READ);
+        assertFileNoAccess(read);
+
+        final File write = buildGiftForPackage(getContext(), PACKAGE_WRITE);
+        assertFileNoAccess(write);
+    }
+}
diff --git a/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/src/com/android/cts/multiuserstorageapp/MultiUserStorageTest.java b/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/src/com/android/cts/multiuserstorageapp/MultiUserStorageTest.java
index 2a80c75..ed84a66 100644
--- a/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/src/com/android/cts/multiuserstorageapp/MultiUserStorageTest.java
+++ b/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/src/com/android/cts/multiuserstorageapp/MultiUserStorageTest.java
@@ -45,7 +45,9 @@
 
     private void wipeTestFiles(File dir) {
         dir.mkdirs();
-        for (File file : dir.listFiles()) {
+        final File[] files = dir.listFiles();
+        if (files == null) return;
+        for (File file : files) {
             if (file.getName().startsWith(FILE_PREFIX)) {
                 Log.d(TAG, "Wiping " + file);
                 file.delete();
@@ -53,11 +55,11 @@
         }
     }
 
-    public void cleanIsolatedStorage() throws Exception {
+    public void testCleanIsolatedStorage() throws Exception {
         wipeTestFiles(Environment.getExternalStorageDirectory());
     }
 
-    public void writeIsolatedStorage() throws Exception {
+    public void testWriteIsolatedStorage() throws Exception {
         final int uid = android.os.Process.myUid();
 
         writeInt(buildApiPath(FILE_SINGLETON), uid);
@@ -67,13 +69,13 @@
         for (File path : getAllPackageSpecificPathsExceptObb(getContext())) {
             assertNotNull("Valid media must be inserted during CTS", path);
             assertEquals("Valid media must be inserted during CTS", Environment.MEDIA_MOUNTED,
-                    Environment.getStorageState(path));
+                    Environment.getExternalStorageState(path));
 
             writeInt(new File(path, FILE_SINGLETON), uid);
         }
     }
 
-    public void readIsolatedStorage() throws Exception {
+    public void testReadIsolatedStorage() throws Exception {
         final int uid = android.os.Process.myUid();
 
         // Expect that the value we wrote earlier is still valid and wasn't
@@ -91,23 +93,23 @@
         for (File path : getAllPackageSpecificPathsExceptObb(getContext())) {
             assertNotNull("Valid media must be inserted during CTS", path);
             assertEquals("Valid media must be inserted during CTS", Environment.MEDIA_MOUNTED,
-                    Environment.getStorageState(path));
+                    Environment.getExternalStorageState(path));
 
             assertEquals("Unexpected value in singleton file at " + path, uid,
                     readInt(new File(path, FILE_SINGLETON)));
         }
     }
 
-    public void cleanObbStorage() throws Exception {
+    public void testCleanObbStorage() throws Exception {
         wipeTestFiles(getContext().getObbDir());
     }
 
-    public void writeObbStorage() throws Exception {
+    public void testWriteObbStorage() throws Exception {
         writeInt(buildApiObbPath(FILE_OBB_API_SINGLETON), OBB_API_VALUE);
         writeInt(buildEnvObbPath(FILE_OBB_SINGLETON), OBB_VALUE);
     }
 
-    public void readObbStorage() throws Exception {
+    public void testReadObbStorage() throws Exception {
         assertEquals("Failed to read OBB file from API path", OBB_API_VALUE,
                 readInt(buildApiObbPath(FILE_OBB_API_SINGLETON)));
 
diff --git a/hostsidetests/appsecurity/test-apps/ReadExternalStorageApp/src/com/android/cts/readexternalstorageapp/ReadExternalStorageTest.java b/hostsidetests/appsecurity/test-apps/ReadExternalStorageApp/src/com/android/cts/readexternalstorageapp/ReadExternalStorageTest.java
index bbd1e7a..71faab2 100644
--- a/hostsidetests/appsecurity/test-apps/ReadExternalStorageApp/src/com/android/cts/readexternalstorageapp/ReadExternalStorageTest.java
+++ b/hostsidetests/appsecurity/test-apps/ReadExternalStorageApp/src/com/android/cts/readexternalstorageapp/ReadExternalStorageTest.java
@@ -16,16 +16,9 @@
 
 package com.android.cts.readexternalstorageapp;
 
-import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_NONE;
-import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_READ;
-import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_WRITE;
 import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertDirReadOnlyAccess;
 import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertDirReadWriteAccess;
-import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertFileReadOnlyAccess;
-import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertFileReadWriteAccess;
-import static com.android.cts.externalstorageapp.CommonExternalStorageTest.buildGiftForPackage;
 import static com.android.cts.externalstorageapp.CommonExternalStorageTest.getAllPackageSpecificPaths;
-import static com.android.cts.externalstorageapp.CommonExternalStorageTest.readInt;
 
 import android.os.Environment;
 import android.test.AndroidTestCase;
@@ -54,7 +47,7 @@
         for (File path : paths) {
             assertNotNull("Valid media must be inserted during CTS", path);
             assertEquals("Valid media must be inserted during CTS", Environment.MEDIA_MOUNTED,
-                    Environment.getStorageState(path));
+                    Environment.getExternalStorageState(path));
 
             assertTrue(path.getAbsolutePath().contains(packageName));
 
@@ -65,27 +58,10 @@
             }
 
             // Keep walking up until we leave device
-            while (Environment.MEDIA_MOUNTED.equals(Environment.getStorageState(path))) {
+            while (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState(path))) {
                 assertDirReadOnlyAccess(path);
                 path = path.getParentFile();
             }
         }
     }
-
-    /**
-     * Verify we can read all gifts.
-     */
-    public void doVerifyGifts() throws Exception {
-        final File none = buildGiftForPackage(getContext(), PACKAGE_NONE);
-        assertFileReadOnlyAccess(none);
-        assertEquals(100, readInt(none));
-
-        final File read = buildGiftForPackage(getContext(), PACKAGE_READ);
-        assertFileReadWriteAccess(read);
-        assertEquals(101, readInt(read));
-
-        final File write = buildGiftForPackage(getContext(), PACKAGE_WRITE);
-        assertFileReadOnlyAccess(write);
-        assertEquals(102, readInt(write));
-    }
 }
diff --git a/hostsidetests/appsecurity/test-apps/ReadExternalStorageApp/src/com/android/cts/readexternalstorageapp/ReadGiftTest.java b/hostsidetests/appsecurity/test-apps/ReadExternalStorageApp/src/com/android/cts/readexternalstorageapp/ReadGiftTest.java
new file mode 100644
index 0000000..e72be77
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/ReadExternalStorageApp/src/com/android/cts/readexternalstorageapp/ReadGiftTest.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.readexternalstorageapp;
+
+import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_NONE;
+import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_READ;
+import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_WRITE;
+import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertFileReadOnlyAccess;
+import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertFileReadWriteAccess;
+import static com.android.cts.externalstorageapp.CommonExternalStorageTest.buildGiftForPackage;
+import static com.android.cts.externalstorageapp.CommonExternalStorageTest.readInt;
+
+import android.test.AndroidTestCase;
+
+import java.io.File;
+
+public class ReadGiftTest extends AndroidTestCase {
+    /**
+     * Verify we can read all gifts.
+     */
+    public void testGifts() throws Exception {
+        final File none = buildGiftForPackage(getContext(), PACKAGE_NONE);
+        assertFileReadOnlyAccess(none);
+        assertEquals(100, readInt(none));
+
+        final File read = buildGiftForPackage(getContext(), PACKAGE_READ);
+        assertFileReadWriteAccess(read);
+        assertEquals(101, readInt(read));
+
+        final File write = buildGiftForPackage(getContext(), PACKAGE_WRITE);
+        assertFileReadOnlyAccess(write);
+        assertEquals(102, readInt(write));
+    }
+}
diff --git a/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/src/com/android/cts/writeexternalstorageapp/WriteExternalStorageTest.java b/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/src/com/android/cts/writeexternalstorageapp/WriteExternalStorageTest.java
index afee8541..badc852 100644
--- a/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/src/com/android/cts/writeexternalstorageapp/WriteExternalStorageTest.java
+++ b/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/src/com/android/cts/writeexternalstorageapp/WriteExternalStorageTest.java
@@ -17,14 +17,10 @@
 package com.android.cts.writeexternalstorageapp;
 
 import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_NONE;
-import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_READ;
-import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_WRITE;
 import static com.android.cts.externalstorageapp.CommonExternalStorageTest.TAG;
 import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertDirNoWriteAccess;
 import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertDirReadOnlyAccess;
 import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertDirReadWriteAccess;
-import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertFileReadWriteAccess;
-import static com.android.cts.externalstorageapp.CommonExternalStorageTest.buildGiftForPackage;
 import static com.android.cts.externalstorageapp.CommonExternalStorageTest.buildProbeFile;
 import static com.android.cts.externalstorageapp.CommonExternalStorageTest.deleteContents;
 import static com.android.cts.externalstorageapp.CommonExternalStorageTest.getAllPackageSpecificPaths;
@@ -142,12 +138,12 @@
         for (File path : paths) {
             assertNotNull("Valid media must be inserted during CTS", path);
             assertEquals("Valid media must be inserted during CTS", Environment.MEDIA_MOUNTED,
-                    Environment.getStorageState(path));
+                    Environment.getExternalStorageState(path));
 
             assertTrue(path.getAbsolutePath().contains(packageName));
 
             // Walk until we leave device, writing the whole way
-            while (Environment.MEDIA_MOUNTED.equals(Environment.getStorageState(path))) {
+            while (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState(path))) {
                 assertDirReadWriteAccess(path);
                 path = path.getParentFile();
             }
@@ -179,7 +175,7 @@
         int depth = 0;
         while (depth++ < 32) {
             assertDirReadWriteAccess(path);
-            assertEquals(Environment.MEDIA_MOUNTED, Environment.getStorageState(path));
+            assertEquals(Environment.MEDIA_MOUNTED, Environment.getExternalStorageState(path));
 
             if (path.getAbsolutePath().equals(top.getAbsolutePath())) {
                 break;
@@ -194,7 +190,7 @@
         // And going one step further should be outside our reach
         path = path.getParentFile();
         assertDirNoWriteAccess(path);
-        assertEquals(Environment.MEDIA_UNKNOWN, Environment.getStorageState(path));
+        assertEquals(Environment.MEDIA_UNKNOWN, Environment.getExternalStorageState(path));
     }
 
     /**
@@ -202,11 +198,11 @@
      */
     public void testMountStatus() {
         assertEquals(Environment.MEDIA_UNKNOWN,
-                Environment.getStorageState(new File("/meow-should-never-exist")));
+                Environment.getExternalStorageState(new File("/meow-should-never-exist")));
 
         // Internal data isn't a mount point
         assertEquals(Environment.MEDIA_UNKNOWN,
-                Environment.getStorageState(getContext().getCacheDir()));
+                Environment.getExternalStorageState(getContext().getCacheDir()));
     }
 
     /**
@@ -220,7 +216,7 @@
         for (File path : paths) {
             assertNotNull("Valid media must be inserted during CTS", path);
             assertEquals("Valid media must be inserted during CTS", Environment.MEDIA_MOUNTED,
-                    Environment.getStorageState(path));
+                    Environment.getExternalStorageState(path));
 
             assertTrue(path.getAbsolutePath().contains(packageName));
 
@@ -231,7 +227,7 @@
             }
 
             // Keep walking up until we leave device
-            while (Environment.MEDIA_MOUNTED.equals(Environment.getStorageState(path))) {
+            while (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState(path))) {
                 assertDirReadOnlyAccess(path);
                 path = path.getParentFile();
             }
@@ -250,12 +246,12 @@
         for (File path : paths) {
             assertNotNull("Valid media must be inserted during CTS", path);
             assertEquals("Valid media must be inserted during CTS", Environment.MEDIA_MOUNTED,
-                    Environment.getStorageState(path));
+                    Environment.getExternalStorageState(path));
 
             final File start = path;
 
             boolean found = false;
-            while (Environment.MEDIA_MOUNTED.equals(Environment.getStorageState(path))) {
+            while (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState(path))) {
                 final File test = new File(path, ".nomedia");
                 if (test.exists()) {
                     found = true;
@@ -301,33 +297,4 @@
            probe.delete();
        }
     }
-
-    /**
-     * Leave gifts for other packages in their primary external cache dirs.
-     */
-    public void doWriteGifts() throws Exception {
-        final File none = buildGiftForPackage(getContext(), PACKAGE_NONE);
-        none.getParentFile().mkdirs();
-        none.createNewFile();
-        assertFileReadWriteAccess(none);
-
-        writeInt(none, 100);
-        assertEquals(100, readInt(none));
-
-        final File read = buildGiftForPackage(getContext(), PACKAGE_READ);
-        read.getParentFile().mkdirs();
-        read.createNewFile();
-        assertFileReadWriteAccess(read);
-
-        writeInt(read, 101);
-        assertEquals(101, readInt(read));
-
-        final File write = buildGiftForPackage(getContext(), PACKAGE_WRITE);
-        write.getParentFile().mkdirs();
-        write.createNewFile();
-        assertFileReadWriteAccess(write);
-
-        writeInt(write, 102);
-        assertEquals(102, readInt(write));
-    }
 }
diff --git a/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/src/com/android/cts/writeexternalstorageapp/WriteGiftTest.java b/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/src/com/android/cts/writeexternalstorageapp/WriteGiftTest.java
new file mode 100644
index 0000000..5da42da
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/src/com/android/cts/writeexternalstorageapp/WriteGiftTest.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.writeexternalstorageapp;
+
+import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_NONE;
+import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_READ;
+import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_WRITE;
+import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertFileReadWriteAccess;
+import static com.android.cts.externalstorageapp.CommonExternalStorageTest.buildGiftForPackage;
+import static com.android.cts.externalstorageapp.CommonExternalStorageTest.readInt;
+import static com.android.cts.externalstorageapp.CommonExternalStorageTest.writeInt;
+
+import android.test.AndroidTestCase;
+
+import java.io.File;
+
+public class WriteGiftTest extends AndroidTestCase {
+    /**
+     * Leave gifts for other packages in their primary external cache dirs.
+     */
+    public void testGifts() throws Exception {
+        final File none = buildGiftForPackage(getContext(), PACKAGE_NONE);
+        none.getParentFile().mkdirs();
+        none.createNewFile();
+        assertFileReadWriteAccess(none);
+
+        writeInt(none, 100);
+        assertEquals(100, readInt(none));
+
+        final File read = buildGiftForPackage(getContext(), PACKAGE_READ);
+        read.getParentFile().mkdirs();
+        read.createNewFile();
+        assertFileReadWriteAccess(read);
+
+        writeInt(read, 101);
+        assertEquals(101, readInt(read));
+
+        final File write = buildGiftForPackage(getContext(), PACKAGE_WRITE);
+        write.getParentFile().mkdirs();
+        write.createNewFile();
+        assertFileReadWriteAccess(write);
+
+        writeInt(write, 102);
+        assertEquals(102, readInt(write));
+    }
+}
diff --git a/hostsidetests/devicepolicy/app/IntentReceiver/AndroidManifest.xml b/hostsidetests/devicepolicy/app/IntentReceiver/AndroidManifest.xml
index 36ac7a7..2a24f4d 100644
--- a/hostsidetests/devicepolicy/app/IntentReceiver/AndroidManifest.xml
+++ b/hostsidetests/devicepolicy/app/IntentReceiver/AndroidManifest.xml
@@ -32,6 +32,29 @@
                 <category android:name="android.intent.category.DEFAULT" />
             </intent-filter>
         </activity>
+
+        <activity android:name=".SimpleIntentReceiverActivity" android:exported="true"/>
+
+        <activity-alias android:name=".BrowserActivity"
+            android:targetActivity=".SimpleIntentReceiverActivity">
+            <intent-filter>
+                <action android:name="android.intent.action.VIEW"/>
+                <category android:name="android.intent.category.DEFAULT"/>
+                <category android:name="android.intent.category.BROWSABLE"/>
+                <data android:scheme="http"/>
+            </intent-filter>
+        </activity-alias>
+
+        <activity-alias android:name=".AppLinkActivity"
+            android:targetActivity=".SimpleIntentReceiverActivity">
+            <intent-filter>
+                <action android:name="android.intent.action.VIEW"/>
+                <category android:name="android.intent.category.DEFAULT"/>
+                <category android:name="android.intent.category.BROWSABLE"/>
+                <data android:scheme="http" android:host="com.android.cts.intent.receiver"/>
+            </intent-filter>
+        </activity-alias>
+
     </application>
 
 </manifest>
diff --git a/hostsidetests/devicepolicy/app/IntentReceiver/src/com/android/cts/intent/receiver/SimpleIntentReceiverActivity.java b/hostsidetests/devicepolicy/app/IntentReceiver/src/com/android/cts/intent/receiver/SimpleIntentReceiverActivity.java
new file mode 100644
index 0000000..23755df
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/IntentReceiver/src/com/android/cts/intent/receiver/SimpleIntentReceiverActivity.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.intent.receiver;
+
+import android.app.admin.DevicePolicyManager;
+import android.app.Activity;
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+import android.os.Bundle;
+
+/**
+ * An activity that receives an intent and returns immediately, indicating its own name and if it is
+ * running in a managed profile.
+ */
+public class SimpleIntentReceiverActivity extends Activity {
+    private static final String TAG = "SimpleIntentReceiverActivity";
+
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        String className = getIntent().getComponent().getClassName();
+
+        // We try to check if we are in a managed profile or not.
+        // To do this, check if com.android.cts.managedprofile is the profile owner.
+        DevicePolicyManager dpm =
+                (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
+        boolean inManagedProfile = dpm.isProfileOwnerApp("com.android.cts.managedprofile");
+
+        Log.i(TAG, "activity " + className + " started, is in managed profile: "
+                + inManagedProfile);
+        Intent result = new Intent();
+        result.putExtra("extra_receiver_class", className);
+        result.putExtra("extra_in_managed_profile", inManagedProfile);
+        setResult(Activity.RESULT_OK, result);
+        finish();
+    }
+}
diff --git a/hostsidetests/devicepolicy/app/IntentSender/src/com/android/cts/intent/sender/AppLinkTest.java b/hostsidetests/devicepolicy/app/IntentSender/src/com/android/cts/intent/sender/AppLinkTest.java
new file mode 100644
index 0000000..51ff362
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/IntentSender/src/com/android/cts/intent/sender/AppLinkTest.java
@@ -0,0 +1,99 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.intent.sender;
+
+import android.app.Activity;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.net.Uri;
+import android.test.InstrumentationTestCase;
+import android.util.Log;
+
+public class AppLinkTest extends InstrumentationTestCase {
+
+    private static final String TAG = "AppLinkTest";
+
+    private Context mContext;
+    private IntentSenderActivity mActivity;
+
+    private static final String EXTRA_IN_MANAGED_PROFILE = "extra_in_managed_profile";
+    private static final String EXTRA_RECEIVER_CLASS = "extra_receiver_class";
+    private static final String APP_LINK_ACTIVITY
+            = "com.android.cts.intent.receiver.AppLinkActivity";
+    private static final String BROWSER_ACTIVITY
+            = "com.android.cts.intent.receiver.BrowserActivity";
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        mContext = getInstrumentation().getTargetContext();
+        mActivity = launchActivity(mContext.getPackageName(), IntentSenderActivity.class, null);
+    }
+
+    @Override
+    public void tearDown() throws Exception {
+        mActivity.finish();
+        super.tearDown();
+    }
+
+    public void testReceivedByAppLinkActivityInPrimary() throws Exception {
+        checkHttpIntentResult(APP_LINK_ACTIVITY, false);
+    }
+
+    public void testReceivedByAppLinkActivityInManaged() throws Exception {
+        checkHttpIntentResult(APP_LINK_ACTIVITY, true);
+    }
+
+    public void testReceivedByBrowserActivityInManaged() throws Exception {
+        checkHttpIntentResult(BROWSER_ACTIVITY, true);
+    }
+
+    public void testTwoReceivers() {
+        assertNumberOfReceivers(2);
+    }
+
+    public void testThreeReceivers() {
+        assertNumberOfReceivers(3);
+    }
+
+    // Should not be called if there are several possible receivers to the intent
+    // (see getHttpIntent)
+    private void checkHttpIntentResult(String receiverClassName, boolean inManagedProfile)
+            throws Exception {
+        PackageManager pm = mContext.getPackageManager();
+
+        Intent result = mActivity.getResult(getHttpIntent());
+        // If it is received in the other profile, we cannot check the class from the ResolveInfo
+        // returned by queryIntentActivities. So we rely on the receiver telling us its class.
+        assertEquals(receiverClassName, result.getStringExtra(EXTRA_RECEIVER_CLASS));
+        assertTrue(result.hasExtra(EXTRA_IN_MANAGED_PROFILE));
+        assertEquals(inManagedProfile, result.getBooleanExtra(EXTRA_IN_MANAGED_PROFILE, false));
+    }
+
+    private void assertNumberOfReceivers(int n) {
+        PackageManager pm = mContext.getPackageManager();
+        assertEquals(n, pm.queryIntentActivities(getHttpIntent(), /* flags = */ 0).size());
+    }
+
+    private Intent getHttpIntent() {
+        Intent i = new Intent(Intent.ACTION_VIEW);
+        i.addCategory(Intent.CATEGORY_BROWSABLE);
+        i.setData(Uri.parse("http://com.android.cts.intent.receiver"));
+        return i;
+    }
+}
diff --git a/hostsidetests/devicepolicy/app/IntentSender/src/com/android/cts/intent/sender/IntentSenderActivity.java b/hostsidetests/devicepolicy/app/IntentSender/src/com/android/cts/intent/sender/IntentSenderActivity.java
index fd421ac..eb64d47 100644
--- a/hostsidetests/devicepolicy/app/IntentSender/src/com/android/cts/intent/sender/IntentSenderActivity.java
+++ b/hostsidetests/devicepolicy/app/IntentSender/src/com/android/cts/intent/sender/IntentSenderActivity.java
@@ -66,8 +66,12 @@
     }
 
     public Intent getResult(Intent intent) throws Exception {
+        Log.d(TAG, "Sending intent " + intent);
         startActivityForResult(intent, 42);
         final Result result = mResult.poll(30, TimeUnit.SECONDS);
+        if (result != null) {
+            Log.d(TAG, "Result intent: " + result.data);
+        }
         return (result != null) ? result.data : null;
     }
 
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/Android.mk b/hostsidetests/devicepolicy/app/ManagedProfile/Android.mk
index 7b3fba3..b31e74b 100644
--- a/hostsidetests/devicepolicy/app/ManagedProfile/Android.mk
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/Android.mk
@@ -26,7 +26,8 @@
 
 LOCAL_JAVA_LIBRARIES := android.test.runner cts-junit
 
-LOCAL_STATIC_JAVA_LIBRARIES = android-support-v4 ctstestrunner compatibility-device-util_v2
+LOCAL_STATIC_JAVA_LIBRARIES = android-support-v4 ctstestrunner compatibility-device-util_v2 \
+	ub-uiautomator
 
 LOCAL_SDK_VERSION := current
 
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/AndroidManifest.xml b/hostsidetests/devicepolicy/app/ManagedProfile/AndroidManifest.xml
index 9bf7046..e03ebdc 100644
--- a/hostsidetests/devicepolicy/app/ManagedProfile/AndroidManifest.xml
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/AndroidManifest.xml
@@ -52,12 +52,7 @@
                 <category android:name="android.intent.category.LAUNCHER" />
             </intent-filter>
         </activity>
-        <activity android:name=".ComponentDisablingActivity" >
-            <intent-filter>
-                <action android:name="android.intent.action.MAIN" />
-                <category android:name="android.intent.category.DEFAULT"/>
-                <category android:name="android.intent.category.LAUNCHER" />
-            </intent-filter>
+        <activity android:name=".ComponentDisablingActivity" android:exported="true">
         </activity>
         <activity android:name=".ManagedProfileActivity">
             <intent-filter>
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/BaseManagedProfileTest.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/BaseManagedProfileTest.java
index 2a54d97..49754d0 100644
--- a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/BaseManagedProfileTest.java
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/BaseManagedProfileTest.java
@@ -19,7 +19,8 @@
 import android.app.admin.DevicePolicyManager;
 import android.content.ComponentName;
 import android.content.Context;
-import android.test.AndroidTestCase;
+import android.support.test.uiautomator.UiDevice;
+import android.test.InstrumentationTestCase;
 
 /**
  * Base class for profile-owner based tests.
@@ -27,7 +28,7 @@
  * This class handles making sure that the test is the profile owner and that it has an active admin
  * registered, so that all tests may assume these are done.
  */
-public class BaseManagedProfileTest extends AndroidTestCase {
+public class BaseManagedProfileTest extends InstrumentationTestCase {
 
     public static class BasicAdminReceiver extends DeviceAdminReceiver {
     }
@@ -36,21 +37,23 @@
             BasicAdminReceiver.class.getPackage().getName(), BasicAdminReceiver.class.getName());
 
     protected DevicePolicyManager mDevicePolicyManager;
+    protected Context mContext;
 
     @Override
     protected void setUp() throws Exception {
         super.setUp();
+        mContext = getInstrumentation().getContext();
 
-       mDevicePolicyManager = (DevicePolicyManager)
-               mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
-       assertNotNull(mDevicePolicyManager);
+        mDevicePolicyManager = (DevicePolicyManager)
+                mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
+        assertNotNull(mDevicePolicyManager);
 
-       // TODO: Only check the below if we are running as the profile user. If running under the
-       // user owner, can we check that there is a profile and that the below holds for it? If we
-       // don't want to do these checks every time we could get rid of this class altogether and
-       // just have a single test case running under the profile user that do them.
-       assertTrue(mDevicePolicyManager.isAdminActive(ADMIN_RECEIVER_COMPONENT));
-       assertTrue(mDevicePolicyManager.isProfileOwnerApp(
-               ADMIN_RECEIVER_COMPONENT.getPackageName()));
+        // TODO: Only check the below if we are running as the profile user. If running under the
+        // user owner, can we check that there is a profile and that the below holds for it? If we
+        // don't want to do these checks every time we could get rid of this class altogether and
+        // just have a single test case running under the profile user that do them.
+        assertTrue(mDevicePolicyManager.isAdminActive(ADMIN_RECEIVER_COMPONENT));
+        assertTrue(mDevicePolicyManager.isProfileOwnerApp(
+                ADMIN_RECEIVER_COMPONENT.getPackageName()));
     }
 }
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/CrossProfileUtils.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/CrossProfileUtils.java
index 21b2d36..6a63cea 100644
--- a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/CrossProfileUtils.java
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/CrossProfileUtils.java
@@ -20,9 +20,16 @@
 
 import android.app.admin.DevicePolicyManager;
 import android.content.Context;
+import android.content.Intent;
 import android.content.IntentFilter;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.net.Uri;
 import android.os.UserManager;
 import android.test.AndroidTestCase;
+import android.util.Log;
+
+import java.util.List;
 
 /**
  * The methods in this class are not really tests.
@@ -31,6 +38,8 @@
  * device-side methods from the host.
  */
 public class CrossProfileUtils extends AndroidTestCase {
+    private static final String TAG = "CrossProfileUtils";
+
     private static final String ACTION_READ_FROM_URI = "com.android.cts.action.READ_FROM_URI";
 
     private static final String ACTION_WRITE_TO_URI = "com.android.cts.action.WRITE_TO_URI";
@@ -86,4 +95,18 @@
         dpm.clearUserRestriction(ADMIN_RECEIVER_COMPONENT,
                 UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
     }
+
+    // Disables all browsers in current user
+    public void testDisableAllBrowsers() {
+        PackageManager pm = (PackageManager) getContext().getPackageManager();
+        DevicePolicyManager dpm = (DevicePolicyManager)
+               getContext().getSystemService(Context.DEVICE_POLICY_SERVICE);
+        Intent webIntent = new Intent(Intent.ACTION_VIEW);
+        webIntent.setData(Uri.parse("http://com.android.cts.intent.receiver"));
+        List<ResolveInfo> ris = pm.queryIntentActivities(webIntent, 0 /* no flags*/);
+        for (ResolveInfo ri : ris) {
+            Log.d(TAG, "Hiding " + ri.activityInfo.packageName);
+            dpm.setApplicationHidden(ADMIN_RECEIVER_COMPONENT, ri.activityInfo.packageName, true);
+        }
+    }
 }
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/PermissionsTest.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/PermissionsTest.java
index 727b47f..7ddf77f 100644
--- a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/PermissionsTest.java
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/PermissionsTest.java
@@ -23,6 +23,12 @@
 import android.content.IntentFilter;
 import android.content.pm.PackageManager;
 import android.os.UserManager;
+import android.support.test.uiautomator.By;
+import android.support.test.uiautomator.BySelector;
+import android.support.test.uiautomator.UiDevice;
+import android.support.test.uiautomator.UiObject2;
+import android.support.test.uiautomator.UiWatcher;
+import android.support.test.uiautomator.Until;
 import android.util.Log;
 
 import java.util.concurrent.ArrayBlockingQueue;
@@ -54,9 +60,18 @@
     private static final String EXTRA_GRANT_STATE
             = "com.android.cts.permission.extra.GRANT_STATE";
     private static final int PERMISSION_ERROR = -2;
+    private static final BySelector CRASH_POPUP_BUTTON_SELECTOR = By
+            .clazz(android.widget.Button.class.getName())
+            .text("OK")
+            .pkg("android");
+    private static final BySelector CRASH_POPUP_TEXT_SELECTOR = By
+            .clazz(android.widget.TextView.class.getName())
+            .pkg("android");
+    private static final String CRASH_WATCHER_ID = "CRASH";
 
     private PermissionBroadcastReceiver mReceiver;
     private PackageManager mPackageManager;
+    private UiDevice mDevice;
 
     @Override
     protected void setUp() throws Exception {
@@ -69,11 +84,13 @@
         mReceiver = new PermissionBroadcastReceiver();
         mContext.registerReceiver(mReceiver, new IntentFilter(ACTION_PERMISSION_RESULT));
         mPackageManager = mContext.getPackageManager();
+        mDevice = UiDevice.getInstance(getInstrumentation());
     }
 
     @Override
     protected void tearDown() throws Exception {
         mContext.unregisterReceiver(mReceiver);
+        mDevice.removeWatcher(CRASH_WATCHER_ID);
         super.tearDown();
     }
 
@@ -144,6 +161,28 @@
         assertPermissionRequest(PackageManager.PERMISSION_GRANTED);
     }
 
+    public void testPermissionPrompts() throws Exception {
+        // register a crash watcher
+        mDevice.registerWatcher(CRASH_WATCHER_ID, new UiWatcher() {
+            @Override
+            public boolean checkForCondition() {
+                UiObject2 button = mDevice.findObject(CRASH_POPUP_BUTTON_SELECTOR);
+                if (button != null) {
+                    UiObject2 text = mDevice.findObject(CRASH_POPUP_TEXT_SELECTOR);
+                    Log.d(TAG, "Removing an error dialog: " + text != null ? text.getText() : null);
+                    button.click();
+                    return true;
+                }
+                return false;
+            }
+        });
+        mDevice.runWatchers();
+
+        assertSetPermissionPolicy(DevicePolicyManager.PERMISSION_POLICY_PROMPT);
+        assertPermissionRequest(PackageManager.PERMISSION_DENIED, "permission_deny_button");
+        assertPermissionRequest(PackageManager.PERMISSION_GRANTED, "permission_allow_button");
+    }
+
     public void testPermissionUpdate_setDeniedState() throws Exception {
         assertEquals(mDevicePolicyManager.getPermissionGrantState(ADMIN_RECEIVER_COMPONENT,
                 PERMISSION_APP_PACKAGE_NAME, PERMISSION_NAME),
@@ -192,13 +231,18 @@
     }
 
     private void assertPermissionRequest(int expected) throws Exception {
+        assertPermissionRequest(expected, null);
+    }
+
+    private void assertPermissionRequest(int expected, String buttonResource) throws Exception {
         Intent launchIntent = new Intent();
         launchIntent.setComponent(new ComponentName(PERMISSION_APP_PACKAGE_NAME,
                 PERMISSIONS_ACTIVITY_NAME));
         launchIntent.putExtra(EXTRA_PERMISSION, PERMISSION_NAME);
         launchIntent.setAction(ACTION_REQUEST_PERMISSION);
-        launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+        launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
         mContext.startActivity(launchIntent);
+        pressPermissionPromptButton(buttonResource);
         assertEquals(expected, mReceiver.waitForBroadcast());
         assertEquals(expected, mPackageManager.checkPermission(PERMISSION_NAME,
                 PERMISSION_APP_PACKAGE_NAME));
@@ -212,7 +256,7 @@
                 PERMISSIONS_ACTIVITY_NAME));
         launchIntent.putExtra(EXTRA_PERMISSION, PERMISSION_NAME);
         launchIntent.setAction(ACTION_CHECK_HAS_PERMISSION);
-        launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+        launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
         mContext.startActivity(launchIntent);
         assertEquals(expected, mReceiver.waitForBroadcast());
     }
@@ -246,6 +290,20 @@
                 PackageManager.PERMISSION_GRANTED);
     }
 
+    private void pressPermissionPromptButton(String resName) throws Exception {
+        if (resName == null) {
+            return;
+        }
+
+        BySelector selector = By
+                .clazz(android.widget.Button.class.getName())
+                .res("com.android.packageinstaller", resName);
+        mDevice.wait(Until.hasObject(selector), 5000);
+        UiObject2 button = mDevice.findObject(selector);
+        assertNotNull("Couldn't find button with resource id: " + resName, button);
+        button.click();
+    }
+
     private class PermissionBroadcastReceiver extends BroadcastReceiver {
         private BlockingQueue<Integer> mQueue = new ArrayBlockingQueue<Integer> (1);
 
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/WipeDataTest.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/WipeDataTest.java
index 76a9e44..9646e61 100644
--- a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/WipeDataTest.java
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/WipeDataTest.java
@@ -64,11 +64,4 @@
         // Verify the profile is deleted
         assertFalse(mUserManager.getUserProfiles().contains(currentUser));
     }
-
-    // Override this test inherited from base class, as it will trigger another round of setUp()
-    // which would fail because the managed profile has been removed by this test.
-    @Override
-    @Ignore
-    public void testAndroidTestCaseSetupProperly() {
-    }
 }
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseDevicePolicyTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseDevicePolicyTest.java
index 374f2f9..de7c16b 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseDevicePolicyTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseDevicePolicyTest.java
@@ -103,8 +103,6 @@
         CLog.logAndDisplay(LogLevel.INFO, "Output for command " + command + ": " + commandOutput);
         assertTrue(commandOutput + " expected to start with \"Success:\"",
                 commandOutput.startsWith("Success:"));
-        // Wait 60 seconds for intents generated to be handled.
-        Thread.sleep(60 * 1000);
     }
 
     protected int getMaxNumberOfUsersSupported() throws DeviceNotAvailableException {
@@ -144,12 +142,14 @@
     }
 
     protected void removeUser(int userId) throws Exception  {
+        String stopUserCommand = "am stop-user -w " + userId;
+        CLog.logAndDisplay(LogLevel.INFO, "starting command \"" + stopUserCommand + "\" and waiting.");
+        CLog.logAndDisplay(LogLevel.INFO, "Output for command " + stopUserCommand + ": "
+                + getDevice().executeShellCommand(stopUserCommand));
         String removeUserCommand = "pm remove-user " + userId;
         CLog.logAndDisplay(LogLevel.INFO, "starting command " + removeUserCommand);
         CLog.logAndDisplay(LogLevel.INFO, "Output for command " + removeUserCommand + ": "
                 + getDevice().executeShellCommand(removeUserCommand));
-        // Wait 60 seconds for user to finish being removed.
-        Thread.sleep(60 * 1000);
     }
 
     protected void removeTestUsers() throws Exception {
@@ -288,8 +288,6 @@
         String[] tokens = commandOutput.split("\\s+");
         assertTrue(tokens.length > 0);
         assertEquals("Success:", tokens[0]);
-        // Wait 60 seconds for intents generated to be handled.
-        Thread.sleep(60 * 1000);
         return Integer.parseInt(tokens[tokens.length-1]);
     }
 
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java
index 50987ef..52e1e75 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java
@@ -55,6 +55,8 @@
     private static final String FEATURE_CAMERA = "android.hardware.camera";
     private static final String FEATURE_WIFI = "android.hardware.wifi";
 
+    private static final String ADD_RESTRICTION_COMMAND = "add-restriction";
+
     private static final int USER_OWNER = 0;
 
     // ID of the profile we'll create. This will always be a profile of USER_OWNER.
@@ -179,6 +181,49 @@
         // TODO: Test with startActivity
     }
 
+    public void testAppLinks() throws Exception {
+        if (!mHasFeature) {
+            return;
+        }
+        // Disable all pre-existing browsers in the managed profile so they don't interfere with
+        // intents resolution.
+        assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileUtils",
+                "testDisableAllBrowsers", mUserId));
+        installApp(INTENT_RECEIVER_APK);
+        installApp(INTENT_SENDER_APK);
+
+        changeVerificationStatus(USER_OWNER, INTENT_RECEIVER_PKG, "ask");
+        changeVerificationStatus(mUserId, INTENT_RECEIVER_PKG, "ask");
+        // We should have two receivers: IntentReceiverActivity and BrowserActivity in the
+        // managed profile
+        assertAppLinkResult("testTwoReceivers");
+
+        changeUserRestrictionForUser("allow_parent_profile_app_linking", ADD_RESTRICTION_COMMAND,
+                mUserId);
+        // Now we should also have one receiver in the primary user, so three receivers in total.
+        assertAppLinkResult("testThreeReceivers");
+
+        changeVerificationStatus(USER_OWNER, INTENT_RECEIVER_PKG, "never");
+        // The primary user one has been set to never: we should only have the managed profile ones.
+        assertAppLinkResult("testTwoReceivers");
+
+        changeVerificationStatus(mUserId, INTENT_RECEIVER_PKG, "never");
+        // Now there's only the browser in the managed profile left
+        assertAppLinkResult("testReceivedByBrowserActivityInManaged");
+
+        changeVerificationStatus(USER_OWNER, INTENT_RECEIVER_PKG, "always");
+        changeVerificationStatus(mUserId, INTENT_RECEIVER_PKG, "ask");
+        // We've set the receiver in the primary user to always: only this one should receive the
+        // intent.
+        assertAppLinkResult("testReceivedByAppLinkActivityInPrimary");
+
+        changeVerificationStatus(mUserId, INTENT_RECEIVER_PKG, "always");
+        // We have one always in the primary user and one always in the managed profile: the managed
+        // profile one should have precedence.
+        assertAppLinkResult("testReceivedByAppLinkActivityInManaged");
+    }
+
+
     public void testSettingsIntents() throws Exception {
         if (!mHasFeature) {
             return;
@@ -269,17 +314,16 @@
             return;
         }
         String restriction = "no_debugging_features";  // UserManager.DISALLOW_DEBUGGING_FEATURES
-        String command = "add-restriction";
 
         String addRestrictionCommandOutput =
-                changeUserRestrictionForUser(restriction, command, mUserId);
+                changeUserRestrictionForUser(restriction, ADD_RESTRICTION_COMMAND, mUserId);
         assertTrue("Command was expected to succeed " + addRestrictionCommandOutput,
                 addRestrictionCommandOutput.contains("Status: ok"));
 
         // This should now fail, as the shell is not available to start activities under a different
         // user once the restriction is in place.
         addRestrictionCommandOutput =
-                changeUserRestrictionForUser(restriction, command, mUserId);
+                changeUserRestrictionForUser(restriction, ADD_RESTRICTION_COMMAND, mUserId);
         assertTrue(
                 "Expected SecurityException when starting the activity "
                         + addRestrictionCommandOutput,
@@ -532,6 +576,22 @@
                 "testPermissionMixedPolicies", mUserId));
     }
 
+    public void testPermissionPrompts() throws Exception {
+        if (!mHasFeature) {
+            return;
+        }
+        try {
+            // unlock device and ensure that the screen stays on
+            getDevice().executeShellCommand("input keyevent 82");
+            getDevice().executeShellCommand("settings put global stay_on_while_plugged_in 2");
+            installAppAsUser(PERMISSIONS_APP_APK, mUserId);
+            assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PermissionsTest",
+                    "testPermissionPrompts", mUserId));
+        } finally {
+            getDevice().executeShellCommand("settings put global stay_on_while_plugged_in 0");
+        }
+    }
+
     public void testPermissionAppUpdate() throws Exception {
         if (!mHasFeature) {
             return;
@@ -607,4 +667,16 @@
                 "Output for command " + adbCommand + ": " + commandOutput);
         return commandOutput;
     }
+
+    // status should be one of never, undefined, ask, always
+    private void changeVerificationStatus(int userId, String packageName, String status)
+            throws DeviceNotAvailableException {
+        String command = "pm set-app-link --user " + userId + " " + packageName + " " + status;
+        CLog.logAndDisplay(LogLevel.INFO, "Output for command " + command + ": "
+                + getDevice().executeShellCommand(command));
+    }
+
+    private void assertAppLinkResult(String methodName) throws DeviceNotAvailableException {
+        assertTrue(runDeviceTestsAsUser(INTENT_SENDER_PKG, ".AppLinkTest", methodName, mUserId));
+    }
 }
diff --git a/hostsidetests/monkey/src/com/android/cts/monkey/SeedTest.java b/hostsidetests/monkey/src/com/android/cts/monkey/SeedTest.java
index d070972..a0016e2 100644
--- a/hostsidetests/monkey/src/com/android/cts/monkey/SeedTest.java
+++ b/hostsidetests/monkey/src/com/android/cts/monkey/SeedTest.java
@@ -16,8 +16,6 @@
 
 package com.android.cts.monkey;
 
-import com.android.tradefed.log.LogUtil.CLog;
-
 import java.util.Scanner;
 
 public class SeedTest extends AbstractMonkeyTest {
@@ -26,15 +24,11 @@
         String cmd1 = MONKEY_CMD + " -s 1337 -v -p " + PKGS[0] + " 500";
         String out1 = mDevice.executeShellCommand(cmd1);
         String out2 = mDevice.executeShellCommand(cmd1);
-        CLog.d("monkey output1: %s", out1);
-        CLog.d("monkey output2: %s", out2);
         assertOutputs(out1, out2);
 
         String cmd2 = MONKEY_CMD + " -s 3007 -v -p " + PKGS[0] + " 125";
         String out3 = mDevice.executeShellCommand(cmd2);
         String out4 = mDevice.executeShellCommand(cmd2);
-        CLog.d("monkey output3: %s", out3);
-        CLog.d("monkey output4: %s", out4);
         assertOutputs(out3, out4);
     }
 
diff --git a/hostsidetests/usage/Android.mk b/hostsidetests/usage/Android.mk
new file mode 100644
index 0000000..917528b
--- /dev/null
+++ b/hostsidetests/usage/Android.mk
@@ -0,0 +1,32 @@
+# Copyright (C) 2015 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+
+LOCAL_MODULE_TAGS := optional
+
+# Must match the package name in CtsTestCaseList.mk
+LOCAL_MODULE := CtsUsageHostTestCases
+
+LOCAL_JAVA_LIBRARIES := cts-tradefed tradefed-prebuilt
+
+LOCAL_CTS_TEST_PACKAGE := android.host.app.usage
+
+include $(BUILD_CTS_HOST_JAVA_LIBRARY)
+
+include $(call all-subdir-makefiles)
diff --git a/hostsidetests/usage/app/Android.mk b/hostsidetests/usage/app/Android.mk
new file mode 100644
index 0000000..b23efbc
--- /dev/null
+++ b/hostsidetests/usage/app/Android.mk
@@ -0,0 +1,28 @@
+# Copyright (C) 2015 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+# Don't include this package in any target.
+LOCAL_MODULE_TAGS := tests
+
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+
+LOCAL_SDK_VERSION := current
+
+LOCAL_PACKAGE_NAME := CtsDeviceAppUsageTestApp
+
+include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/usage/app/AndroidManifest.xml b/hostsidetests/usage/app/AndroidManifest.xml
new file mode 100755
index 0000000..bad453f
--- /dev/null
+++ b/hostsidetests/usage/app/AndroidManifest.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.android.cts.app.usage.test">
+
+    <application>
+        <activity android:name=".TestActivity">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.DEFAULT" />
+            </intent-filter>
+        </activity>
+    </application>
+</manifest>
+
diff --git a/tests/tests/hardware/src/android/hardware/input/cts/InputCallback.java b/hostsidetests/usage/app/src/com/android/cts/app/usage/test/TestActivity.java
similarity index 67%
rename from tests/tests/hardware/src/android/hardware/input/cts/InputCallback.java
rename to hostsidetests/usage/app/src/com/android/cts/app/usage/test/TestActivity.java
index accdcaf..9432477 100644
--- a/tests/tests/hardware/src/android/hardware/input/cts/InputCallback.java
+++ b/hostsidetests/usage/app/src/com/android/cts/app/usage/test/TestActivity.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2015 The Android Open Source Project
+ * Copyright (C) 2015 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -14,12 +14,9 @@
  * limitations under the License.
  */
 
-package android.hardware.input.cts;
+package com.android.cts.app.usage.test;
 
-import android.view.KeyEvent;
-import android.view.MotionEvent;
+import android.app.Activity;
 
-public interface InputCallback {
-    public void onKeyEvent(KeyEvent ev);
-    public void onMotionEvent(MotionEvent ev);
-}
+public class TestActivity extends Activity {
+}
\ No newline at end of file
diff --git a/hostsidetests/usage/src/com/android/cts/app/usage/AppIdleHostTest.java b/hostsidetests/usage/src/com/android/cts/app/usage/AppIdleHostTest.java
new file mode 100644
index 0000000..f24be0e
--- /dev/null
+++ b/hostsidetests/usage/src/com/android/cts/app/usage/AppIdleHostTest.java
@@ -0,0 +1,154 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.app.usage;
+
+import com.android.cts.tradefed.build.CtsBuildHelper;
+import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.testtype.DeviceTestCase;
+import com.android.tradefed.testtype.IBuildReceiver;
+
+public class AppIdleHostTest extends DeviceTestCase implements IBuildReceiver {
+    private static final String SETTINGS_APP_IDLE_CONSTANTS = "app_idle_constants";
+
+    private static final String TEST_APP_PACKAGE = "com.android.cts.app.usage.test";
+    private static final String TEST_APP_APK = "CtsDeviceAppUsageTestApp.apk";
+    private static final String TEST_APP_CLASS = "TestActivity";
+
+    private static final long ACTIVITY_LAUNCH_WAIT_MILLIS = 500;
+
+    /**
+     * A reference to the build.
+     */
+    private CtsBuildHelper mBuild;
+
+    /**
+     * A reference to the device under test.
+     */
+    private ITestDevice mDevice;
+
+    @Override
+    public void setBuild(IBuildInfo buildInfo) {
+        // Get the build, this is used to access the APK.
+        mBuild = CtsBuildHelper.createBuildHelper(buildInfo);
+    }
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        // Get the device, this gives a handle to run commands and install APKs.
+        mDevice = getDevice();
+
+        // Remove any previously installed versions of this APK.
+        mDevice.uninstallPackage(TEST_APP_PACKAGE);
+
+        // Install the APK on the device.
+        mDevice.installPackage(mBuild.getTestApp(TEST_APP_APK), false);
+    }
+
+    @Override
+    protected void tearDown() throws Exception {
+        // Remove the package once complete.
+        mDevice.uninstallPackage(TEST_APP_PACKAGE);
+        super.tearDown();
+    }
+
+    /**
+     * Checks whether an package is idle.
+     * @param appPackage The package to check for idleness.
+     * @return true if the package is idle
+     * @throws DeviceNotAvailableException
+     */
+    private boolean isAppIdle(String appPackage) throws DeviceNotAvailableException {
+        String result = mDevice.executeShellCommand(String.format("am get-inactive %s", appPackage));
+        return result.contains("Idle=true");
+    }
+
+    /**
+     * Set the app idle settings.
+     * @param settingsStr The settings string, a comma separated key=value list.
+     * @throws DeviceNotAvailableException
+     */
+    private void setAppIdleSettings(String settingsStr) throws DeviceNotAvailableException {
+        mDevice.executeShellCommand(String.format("settings put global %s \"%s\"",
+                SETTINGS_APP_IDLE_CONSTANTS, settingsStr));
+    }
+
+    /**
+     * Get the current app idle settings.
+     * @throws DeviceNotAvailableException
+     */
+    private String getAppIdleSettings() throws DeviceNotAvailableException {
+        String result = mDevice.executeShellCommand(String.format("settings get global %s",
+                SETTINGS_APP_IDLE_CONSTANTS));
+        return result.trim();
+    }
+
+    /**
+     * Launch the test app for a few hundred milliseconds then launch home.
+     * @throws DeviceNotAvailableException
+     */
+    private void startAndStopTestApp() throws DeviceNotAvailableException {
+        // Launch the app.
+        mDevice.executeShellCommand(
+                String.format("am start -W -a android.intent.action.MAIN -n %s/%s.%s",
+                        TEST_APP_PACKAGE, TEST_APP_PACKAGE, TEST_APP_CLASS));
+
+        // Wait for some time.
+        sleepUninterrupted(ACTIVITY_LAUNCH_WAIT_MILLIS);
+
+        // Launch home.
+        mDevice.executeShellCommand(
+                "am start -W -a android.intent.action.MAIN -c android.intent.category.HOME");
+    }
+
+    /**
+     * Tests that the app is idle when the idle threshold is passed, and that the app is not-idle
+     * before the threshold is passed.
+     *
+     * @throws Exception
+     */
+    public void testAppIsIdle() throws Exception {
+        final String previousState = getAppIdleSettings();
+        try {
+            // Set the app idle time to be super low.
+            setAppIdleSettings("idle_duration=5,wallclock_threshold=5");
+            startAndStopTestApp();
+            assertTrue(isAppIdle(TEST_APP_PACKAGE));
+
+            // Set the app idle time to something larger.
+            setAppIdleSettings("idle_duration=10000,wallclock_threshold=10000");
+            startAndStopTestApp();
+            assertFalse(isAppIdle(TEST_APP_PACKAGE));
+        } finally {
+            setAppIdleSettings(previousState);
+        }
+    }
+
+    private static void sleepUninterrupted(long timeMillis) {
+        boolean interrupted;
+        do {
+            try {
+                Thread.sleep(timeMillis);
+                interrupted = false;
+            } catch (InterruptedException e) {
+                interrupted = true;
+            }
+        } while (interrupted);
+    }
+}
diff --git a/suite/cts/deviceTests/videoperf/src/com/android/cts/videoperf/VideoEncoderDecoderTest.java b/suite/cts/deviceTests/videoperf/src/com/android/cts/videoperf/VideoEncoderDecoderTest.java
index a2fd20d9..2553d60 100644
--- a/suite/cts/deviceTests/videoperf/src/com/android/cts/videoperf/VideoEncoderDecoderTest.java
+++ b/suite/cts/deviceTests/videoperf/src/com/android/cts/videoperf/VideoEncoderDecoderTest.java
@@ -362,7 +362,6 @@
 
     private void doTestGoog(String mimeType, int w, int h) throws Exception {
         mTestConfig.mTestPixels = false;
-        mTestConfig.mReportFrameTime = true;
         mTestConfig.mTotalFrames = 3000;
         mTestConfig.mNumberOfRepeat = 2;
         doTest(true /* isGoog */, mimeType, w, h);
@@ -371,7 +370,6 @@
     private void doTestOther(String mimeType, int w, int h) throws Exception {
         mTestConfig.mTestPixels = false;
         mTestConfig.mTestResult = true;
-        mTestConfig.mReportFrameTime = true;
         mTestConfig.mTotalFrames = 3000;
         mTestConfig.mNumberOfRepeat = 2;
         doTest(false /* isGoog */, mimeType, w, h);
diff --git a/tests/tests/content/src/android/content/res/cts/PrivateAttributeTest.java b/tests/tests/content/src/android/content/res/cts/PrivateAttributeTest.java
index 35466be..3024896 100644
--- a/tests/tests/content/src/android/content/res/cts/PrivateAttributeTest.java
+++ b/tests/tests/content/src/android/content/res/cts/PrivateAttributeTest.java
@@ -26,7 +26,7 @@
  */
 public class PrivateAttributeTest extends AndroidTestCase {
 
-    private static final int sLastPublicAttr = 0x010104d5;
+    private static final int sLastPublicAttr = 0x010104f1;
 
     public void testNoAttributesAfterLastPublicAttribute() throws Exception {
         final Resources res = getContext().getResources();
diff --git a/tests/tests/hardware/AndroidManifest.xml b/tests/tests/hardware/AndroidManifest.xml
index 1d1e3a8..031b19e 100644
--- a/tests/tests/hardware/AndroidManifest.xml
+++ b/tests/tests/hardware/AndroidManifest.xml
@@ -26,6 +26,7 @@
     <uses-permission android:name="android.permission.BODY_SENSORS" />
     <uses-permission android:name="android.permission.TRANSMIT_IR" />
     <uses-permission android:name="android.permission.REORDER_TASKS" />
+    <uses-permission android:name="android.permission.USE_FINGERPRINT" />
 
     <application>
         <uses-library android:name="android.test.runner" />
@@ -71,8 +72,10 @@
             android:process=":camera2ActivityProcess">
         </activity>
 
-        <activity android:name="android.hardware.input.cts.InputCtsActivity"
-            android:label="InputCtsActivity" />
+        <activity android:name="android.hardware.cts.FingerprintTestActivity"
+            android:label="FingerprintTestActivity">
+        </activity>
+
     </application>
 
     <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
diff --git a/tests/tests/hardware/res/raw/gamepad_press_a.json b/tests/tests/hardware/res/raw/gamepad_press_a.json
deleted file mode 100644
index ff3ca4f..0000000
--- a/tests/tests/hardware/res/raw/gamepad_press_a.json
+++ /dev/null
@@ -1,39 +0,0 @@
-{
-    "id": 1,
-    "command": "register",
-    "name": "Odie (Test)",
-    "vid": 0x18d1,
-    "pid": 0x2c40,
-    "descriptor": [0x05, 0x01, 0x09, 0x05, 0xa1, 0x01, 0x85, 0x01, 0x05, 0x09, 0x0a, 0x01, 0x00,
-        0x0a, 0x02, 0x00, 0x0a, 0x04, 0x00, 0x0a, 0x05, 0x00, 0x0a, 0x07, 0x00, 0x0a, 0x08, 0x00,
-        0x0a, 0x0e, 0x00, 0x0a, 0x0f, 0x00, 0x0a, 0x0d, 0x00, 0x05, 0x0c, 0x0a, 0x24, 0x02, 0x0a,
-        0x23, 0x02, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x0b, 0x81, 0x02, 0x75, 0x01, 0x95,
-        0x01, 0x81, 0x03, 0x05, 0x01, 0x75, 0x04, 0x95, 0x01, 0x25, 0x07, 0x46, 0x3b, 0x01, 0x66,
-        0x14, 0x00, 0x09, 0x39, 0x81, 0x42, 0x66, 0x00, 0x00, 0x09, 0x01, 0xa1, 0x00, 0x09, 0x30,
-        0x09, 0x31, 0x09, 0x32, 0x09, 0x35, 0x05, 0x02, 0x09, 0xc5, 0x09, 0xc4, 0x15, 0x00, 0x26,
-        0xff, 0x00, 0x35, 0x00, 0x46, 0xff, 0x00, 0x75, 0x08, 0x95, 0x06, 0x81, 0x02, 0xc0, 0x85,
-        0x02, 0x05, 0x08, 0x0a, 0x01, 0x00, 0x0a, 0x02, 0x00, 0x0a, 0x03, 0x00, 0x0a, 0x04, 0x00,
-        0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x04, 0x91, 0x02, 0x75, 0x04, 0x95, 0x01, 0x91,
-        0x03, 0xc0, 0x05, 0x0c, 0x09, 0x01, 0xa1, 0x01, 0x85, 0x03, 0x05, 0x01, 0x09, 0x06, 0xa1,
-        0x02, 0x05, 0x06, 0x09, 0x20, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x01, 0x81,
-        0x02, 0x06, 0xbc, 0xff, 0x0a, 0xad, 0xbd, 0x75, 0x08, 0x95, 0x06, 0x81, 0x02, 0xc0, 0xc0],
-    "report": [0x01, 0x00, 0x80, 0x90, 0x80, 0x7f, 0x73, 0x00, 0x00]
-}
-
-{
-    "id": 1,
-    "command": "report",
-    "report": [0x01, 0x01, 0x80, 0x90, 0x80, 0x7f, 0x73, 0x00, 0x00]
-}
-
-{
-    "id": 1,
-    "command": "delay",
-    "duration": 10
-}
-
-{
-    "id": 1,
-    "command": "report",
-    "report": [0x01, 0x00, 0x80, 0x90, 0x80, 0x7f, 0x73, 0x00, 0x00]
-}
diff --git a/tests/tests/hardware/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java b/tests/tests/hardware/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java
index da083a6..f8ee615 100644
--- a/tests/tests/hardware/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java
@@ -64,7 +64,11 @@
     private String[] mIds;
     private CameraErrorCollector mCollector;
 
+    private static final Size FULLHD = new Size(1920, 1080);
+    private static final Size FULLHD_ALT = new Size(1920, 1088);
+    private static final Size HD = new Size(1280, 720);
     private static final Size VGA = new Size(640, 480);
+    private static final Size QVGA = new Size(320, 240);
 
     /*
      * HW Levels short hand
@@ -149,14 +153,102 @@
             assertArrayContains(String.format("No JPEG image format for: ID %s",
                     mIds[counter]), outputFormats, ImageFormat.JPEG);
 
-            Size[] sizes = config.getOutputSizes(ImageFormat.YUV_420_888);
-            CameraTestUtils.assertArrayNotEmpty(sizes,
+            Size[] yuvSizes = config.getOutputSizes(ImageFormat.YUV_420_888);
+            Size[] jpegSizes = config.getOutputSizes(ImageFormat.JPEG);
+            Size[] privateSizes = config.getOutputSizes(ImageFormat.PRIVATE);
+
+            CameraTestUtils.assertArrayNotEmpty(yuvSizes,
                     String.format("No sizes for preview format %x for: ID %s",
                             ImageFormat.YUV_420_888, mIds[counter]));
 
-            assertArrayContains(String.format(
-                            "Required VGA size not found for format %x for: ID %s",
-                            ImageFormat.YUV_420_888, mIds[counter]), sizes, VGA);
+            Rect activeRect = CameraTestUtils.getValueNotNull(
+                    c, CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE);
+            Size activeArraySize = new Size(activeRect.width(), activeRect.height());
+            Integer hwLevel = c.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL);
+
+            if (activeArraySize.getWidth() >= FULLHD.getWidth() &&
+                    activeArraySize.getHeight() >= FULLHD.getHeight()) {
+                assertArrayContains(String.format(
+                        "Required FULLHD size not found for format %x for: ID %s",
+                        ImageFormat.JPEG, mIds[counter]), jpegSizes, FULLHD);
+            }
+
+            if (activeArraySize.getWidth() >= HD.getWidth() &&
+                    activeArraySize.getHeight() >= HD.getHeight()) {
+                assertArrayContains(String.format(
+                        "Required HD size not found for format %x for: ID %s",
+                        ImageFormat.JPEG, mIds[counter]), jpegSizes, HD);
+            }
+
+            if (activeArraySize.getWidth() >= VGA.getWidth() &&
+                    activeArraySize.getHeight() >= VGA.getHeight()) {
+                assertArrayContains(String.format(
+                        "Required VGA size not found for format %x for: ID %s",
+                        ImageFormat.JPEG, mIds[counter]), jpegSizes, VGA);
+            }
+
+            if (activeArraySize.getWidth() >= QVGA.getWidth() &&
+                    activeArraySize.getHeight() >= QVGA.getHeight()) {
+                assertArrayContains(String.format(
+                        "Required QVGA size not found for format %x for: ID %s",
+                        ImageFormat.JPEG, mIds[counter]), jpegSizes, QVGA);
+            }
+
+            ArrayList<Size> jpegSizesList = new ArrayList<>(Arrays.asList(jpegSizes));
+            ArrayList<Size> yuvSizesList = new ArrayList<>(Arrays.asList(yuvSizes));
+            ArrayList<Size> privateSizesList = new ArrayList<>(Arrays.asList(privateSizes));
+
+            CamcorderProfile maxVideoProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
+            Size maxVideoSize = new Size(
+                    maxVideoProfile.videoFrameWidth, maxVideoProfile.videoFrameHeight);
+
+            // Handle FullHD special case first
+            if (jpegSizesList.contains(FULLHD)) {
+                if (hwLevel == FULL || (hwLevel == LIMITED &&
+                        maxVideoSize.getWidth() >= FULLHD.getWidth() &&
+                        maxVideoSize.getHeight() >= FULLHD.getHeight())) {
+                    boolean yuvSupportFullHD = yuvSizesList.contains(FULLHD) ||
+                            yuvSizesList.contains(FULLHD_ALT);
+                    boolean privateSupportFullHD = privateSizesList.contains(FULLHD) ||
+                            privateSizesList.contains(FULLHD_ALT);
+                    assertTrue("Full device FullHD YUV size not found", yuvSupportFullHD);
+                    assertTrue("Full device FullHD PRIVATE size not found", privateSupportFullHD);
+                }
+                // remove all FullHD or FullHD_Alt sizes for the remaining of the test
+                jpegSizesList.remove(FULLHD);
+                jpegSizesList.remove(FULLHD_ALT);
+            }
+
+            // Check all sizes other than FullHD
+            if (hwLevel == LIMITED) {
+                // Remove all jpeg sizes larger than max video size
+                ArrayList<Size> toBeRemoved = new ArrayList<>();
+                for (Size size : jpegSizesList) {
+                    if (size.getWidth() >= maxVideoSize.getWidth() &&
+                            size.getHeight() >= maxVideoSize.getHeight()) {
+                        toBeRemoved.add(size);
+                    }
+                }
+                jpegSizesList.removeAll(toBeRemoved);
+            }
+
+            if (hwLevel == FULL || hwLevel == LIMITED) {
+                if (!yuvSizesList.containsAll(jpegSizesList)) {
+                    for (Size s : jpegSizesList) {
+                        if (!yuvSizesList.contains(s)) {
+                            fail("Size " + s + " not found in YUV format");
+                        }
+                    }
+                }
+            }
+
+            if (!privateSizesList.containsAll(yuvSizesList)) {
+                for (Size s : yuvSizesList) {
+                    if (!privateSizesList.contains(s)) {
+                        fail("Size " + s + " not found in PRIVATE format");
+                    }
+                }
+            }
 
             counter++;
         }
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/EventOrderingVerificationTest.java b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/EventOrderingVerificationTest.java
index b9848fa..f1dc229c8 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/EventOrderingVerificationTest.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/EventOrderingVerificationTest.java
@@ -41,16 +41,6 @@
     }
 
     /**
-     * Test that the verification passes when the timestamps are the same.
-     */
-    public void testSameTimestamp() {
-        SensorStats stats = new SensorStats();
-        EventOrderingVerification verification = getVerification(0, 0, 0, 0, 0);
-        verification.verify(stats);
-        verifyStats(stats, true, 0);
-    }
-
-    /**
      * Test that the verification passes when the timestamps are increasing.
      */
     public void testSequentialTimestamp() {
diff --git a/tests/tests/hardware/src/android/hardware/fingerprint/cts/FingerprintManagerTest.java b/tests/tests/hardware/src/android/hardware/fingerprint/cts/FingerprintManagerTest.java
new file mode 100644
index 0000000..dc03b38
--- /dev/null
+++ b/tests/tests/hardware/src/android/hardware/fingerprint/cts/FingerprintManagerTest.java
@@ -0,0 +1,118 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.hardware.fingerprint.cts;
+
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.hardware.fingerprint.FingerprintManager;
+import android.hardware.fingerprint.FingerprintManager.AuthenticationCallback;
+import android.os.CancellationSignal;
+import android.test.AndroidTestCase;
+
+/**
+ * Basic test cases for FingerprintManager
+ */
+public class FingerprintManagerTest extends AndroidTestCase {
+    private enum AuthState {
+        AUTH_UNKNOWN, AUTH_ERROR, AUTH_FAILED, AUTH_SUCCEEDED
+    }
+    private AuthState mAuthState = AuthState.AUTH_UNKNOWN;
+    private FingerprintManager mFingerprintManager;
+
+    boolean mHasFingerprintManager;
+    private AuthenticationCallback mAuthCallback = new AuthenticationCallback() {
+
+        @Override
+        public void onAuthenticationError(int errorCode, CharSequence errString) {
+        }
+
+        @Override
+        public void onAuthenticationFailed() {
+            mAuthState = AuthState.AUTH_SUCCEEDED;
+        }
+
+        @Override
+        public void onAuthenticationSucceeded(
+                android.hardware.fingerprint.FingerprintManager.AuthenticationResult result) {
+            mAuthState = AuthState.AUTH_SUCCEEDED;
+        }
+    };
+
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
+        // TODO: pm.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT);
+        // PackageManager pm = getContext().getPackageManager();
+        mHasFingerprintManager = true;
+        mAuthState = AuthState.AUTH_UNKNOWN;
+
+        if (mHasFingerprintManager) {
+            mFingerprintManager = (FingerprintManager)
+                    getContext().getSystemService(Context.FINGERPRINT_SERVICE);
+        }
+    }
+
+    public void test_hasFingerprintHardware() {
+        if (!mHasFingerprintManager) {
+            return; // skip test if no fingerprint feature
+        }
+        assertTrue(mFingerprintManager.isHardwareDetected());
+    }
+
+    public void test_hasEnrolledFingerprints() {
+        if (!mHasFingerprintManager) {
+            return; // skip test if no fingerprint feature
+        }
+        boolean hasEnrolledFingerprints = mFingerprintManager.hasEnrolledFingerprints();
+        assertTrue(!hasEnrolledFingerprints);
+    }
+
+    public void test_authenticateNullCallback() {
+        if (!mHasFingerprintManager) {
+            return; // skip test if no fingerprint feature
+        }
+        boolean exceptionTaken = false;
+        CancellationSignal cancelAuth = new CancellationSignal();
+        try {
+            mFingerprintManager.authenticate(null, cancelAuth, 0, null, null);
+        } catch (IllegalArgumentException e) {
+            exceptionTaken = true;
+        } finally {
+            assertTrue(mAuthState == AuthState.AUTH_UNKNOWN);
+            assertTrue(exceptionTaken);
+            cancelAuth.cancel();
+        }
+    }
+
+    public void test_authenticate() {
+        if (!mHasFingerprintManager) {
+            return; // skip test if no fingerprint feature
+        }
+        boolean exceptionTaken = false;
+        CancellationSignal cancelAuth = new CancellationSignal();
+        try {
+            mFingerprintManager.authenticate(null, cancelAuth, 0, mAuthCallback, null);
+        } catch (IllegalArgumentException e) {
+            exceptionTaken = true;
+        } finally {
+            assertFalse(exceptionTaken);
+            // We should never get out of this state without user interaction
+            assertTrue(mAuthState == AuthState.AUTH_UNKNOWN);
+            cancelAuth.cancel();
+        }
+    }
+}
diff --git a/tests/tests/hardware/src/android/hardware/input/cts/InputCtsActivity.java b/tests/tests/hardware/src/android/hardware/input/cts/InputCtsActivity.java
deleted file mode 100644
index b16cadb..0000000
--- a/tests/tests/hardware/src/android/hardware/input/cts/InputCtsActivity.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.hardware.input.cts;
-
-import android.app.Activity;
-import android.view.KeyEvent;
-import android.view.MotionEvent;
-
-import java.util.ArrayList;
-import java.util.List;
-
-public class InputCtsActivity extends Activity {
-    private InputCallback mInputCallback;
-
-    @Override
-    public boolean dispatchGenericMotionEvent(MotionEvent ev) {
-        if (mInputCallback != null) {
-            mInputCallback.onMotionEvent(ev);
-        }
-        return true;
-    }
-
-    @Override
-    public boolean dispatchTouchEvent(MotionEvent ev) {
-        if (mInputCallback != null) {
-            mInputCallback.onMotionEvent(ev);
-        }
-        return true;
-    }
-
-    @Override
-    public boolean dispatchTrackballEvent(MotionEvent ev) {
-        if (mInputCallback != null) {
-            mInputCallback.onMotionEvent(ev);
-        }
-        return true;
-    }
-
-    @Override
-    public boolean dispatchKeyEvent(KeyEvent ev) {
-        if (mInputCallback != null) {
-            mInputCallback.onKeyEvent(ev);
-        }
-        return true;
-    }
-
-    public void setInputCallback(InputCallback callback) {
-        mInputCallback = callback;
-    }
-}
diff --git a/tests/tests/hardware/src/android/hardware/input/cts/tests/GamepadTestCase.java b/tests/tests/hardware/src/android/hardware/input/cts/tests/GamepadTestCase.java
deleted file mode 100644
index 92fba12..0000000
--- a/tests/tests/hardware/src/android/hardware/input/cts/tests/GamepadTestCase.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.hardware.input.cts.tests;
-
-import android.util.Log;
-import android.view.KeyEvent;
-
-import java.io.Writer;
-import java.util.List;
-
-import com.android.cts.hardware.R;
-
-public class GamepadTestCase extends InputTestCase {
-    private static final String TAG = "GamepadTests";
-
-    public void testButtonA() throws Exception {
-        sendHidCommands(R.raw.gamepad_press_a);
-        assertReceivedKeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BUTTON_A);
-        assertReceivedKeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BUTTON_A);
-        assertNoMoreEvents();
-    }
-}
diff --git a/tests/tests/hardware/src/android/hardware/input/cts/tests/InputTestCase.java b/tests/tests/hardware/src/android/hardware/input/cts/tests/InputTestCase.java
deleted file mode 100644
index fba5f51..0000000
--- a/tests/tests/hardware/src/android/hardware/input/cts/tests/InputTestCase.java
+++ /dev/null
@@ -1,221 +0,0 @@
-/*
- * Copyright 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.hardware.input.cts.tests;
-
-import android.app.UiAutomation;
-import android.hardware.input.cts.InputCtsActivity;
-import android.hardware.input.cts.InputCallback;
-import android.system.ErrnoException;
-import android.system.Os;
-import android.test.ActivityInstrumentationTestCase2;
-import android.util.Log;
-import android.view.KeyEvent;
-import android.view.MotionEvent;
-
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileWriter;
-import java.io.InputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.Writer;
-import java.util.ArrayList;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.LinkedBlockingQueue;
-import java.util.concurrent.TimeUnit;
-import java.util.List;
-import java.util.UUID;
-
-public class InputTestCase extends ActivityInstrumentationTestCase2<InputCtsActivity> {
-    private static final String TAG = "InputTestCase";
-    private static final String HID_EXECUTABLE = "hid";
-    private static final int SHELL_UID = 2000;
-    private static final String[] KEY_ACTIONS = {"DOWN", "UP", "MULTIPLE"};
-
-    private File mFifo;
-    private Writer mWriter;
-
-    private BlockingQueue<KeyEvent> mKeys;
-    private BlockingQueue<MotionEvent> mMotions;
-    private InputListener mInputListener;
-
-    public InputTestCase() {
-        super(InputCtsActivity.class);
-        mKeys = new LinkedBlockingQueue<KeyEvent>();
-        mMotions = new LinkedBlockingQueue<MotionEvent>();
-        mInputListener = new InputListener();
-    }
-
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
-        mFifo = setupFifo();
-        clearKeys();
-        clearMotions();
-        getActivity().setInputCallback(mInputListener);
-    }
-
-    @Override
-    protected void tearDown() throws Exception {
-        if (mFifo != null) {
-            mFifo.delete();
-            mFifo = null;
-        }
-        closeQuietly(mWriter);
-        mWriter = null;
-        super.tearDown();
-    }
-
-    /**
-     * Sends the HID commands designated by the given resource id.
-     * The commands must be in the format expected by the `hid` shell command.
-     *
-     * @param id The resource id from which to load the HID commands. This must be a "raw"
-     * resource.
-     */
-    public void sendHidCommands(int id) {
-        try {
-            Writer w = getWriter();
-            w.write(getEvents(id));
-            w.flush();
-        } catch (IOException e) {
-            throw new RuntimeException(e);
-        }
-    }
-
-    /**
-     * Asserts that the application received a {@link android.view.KeyEvent} with the given action
-     * and keycode.
-     *
-     * If other KeyEvents are received by the application prior to the expected KeyEvent, or no
-     * KeyEvents are received within a reasonable amount of time, then this will throw an
-     * AssertionFailedError.
-     *
-     * @param action The action to expect on the next KeyEvent
-     * (e.g. {@link android.view.KeyEvent#ACTION_DOWN}).
-     * @param keyCode The expected key code of the next KeyEvent.
-     */
-    public void assertReceivedKeyEvent(int action, int keyCode) {
-        KeyEvent k = waitForKey();
-        if (k == null) {
-            fail("Timed out waiting for " + KeyEvent.keyCodeToString(keyCode)
-                    + " with action " + KEY_ACTIONS[action]);
-            return;
-        }
-        assertEquals(action, k.getAction());
-        assertEquals(keyCode, k.getKeyCode());
-    }
-
-    /**
-     * Asserts that no more events have been received by the application.
-     *
-     * If any more events have been received by the application, this throws an
-     * AssertionFailedError.
-     */
-    public void assertNoMoreEvents() {
-        KeyEvent key;
-        MotionEvent motion;
-        if ((key = mKeys.poll()) != null) {
-            fail("Extraneous key events generated: " + key);
-        }
-        if ((motion = mMotions.poll()) != null) {
-            fail("Extraneous motion events generated: " + motion);
-        }
-    }
-
-    private KeyEvent waitForKey() {
-        try {
-            return mKeys.poll(1, TimeUnit.SECONDS);
-        } catch (InterruptedException e) {
-            return null;
-        }
-    }
-
-    private void clearKeys() {
-        mKeys.clear();
-    }
-
-    private void clearMotions() {
-        mMotions.clear();
-    }
-
-    private File setupFifo() throws ErrnoException {
-        File dir = getActivity().getCacheDir();
-        String filename = dir.getAbsolutePath() + File.separator +  UUID.randomUUID().toString();
-        Os.mkfifo(filename, 0666);
-        File f = new File(filename);
-        return f;
-    }
-
-    private Writer getWriter() throws IOException {
-        if (mWriter == null) {
-            UiAutomation ui = getInstrumentation().getUiAutomation();
-            ui.executeShellCommand("hid " + mFifo.getAbsolutePath());
-            mWriter = new FileWriter(mFifo);
-        }
-        return mWriter;
-    }
-
-    private String getEvents(int id) throws IOException {
-        InputStream is =
-            getInstrumentation().getTargetContext().getResources().openRawResource(id);
-        return readFully(is);
-    }
-
-
-    private static void closeQuietly(AutoCloseable closeable) {
-        if (closeable != null) {
-            try {
-                closeable.close();
-            } catch (RuntimeException rethrown) {
-                throw rethrown;
-            } catch (Exception ignored) { }
-        }
-    }
-
-    private static String readFully(InputStream is) throws IOException {
-        ByteArrayOutputStream baos = new ByteArrayOutputStream();
-        int read = 0;
-        byte[] buffer = new byte[1024];
-        while ((read = is.read(buffer)) >= 0) {
-            baos.write(buffer, 0, read);
-        }
-        return baos.toString();
-    }
-
-    private class InputListener implements InputCallback {
-        public void onKeyEvent(KeyEvent ev) {
-            boolean done = false;
-            do {
-                try {
-                    mKeys.put(new KeyEvent(ev));
-                    done = true;
-                } catch (InterruptedException ignore) { }
-            } while (!done);
-        }
-
-        public void onMotionEvent(MotionEvent ev) {
-            boolean done = false;
-            do {
-                try {
-                    mMotions.put(MotionEvent.obtain(ev));
-                    done = true;
-                } catch (InterruptedException ignore) { }
-            } while (!done);
-        }
-    }
-}
diff --git a/tests/tests/keystore/src/android/keystore/cts/RSACipherTest.java b/tests/tests/keystore/src/android/keystore/cts/RSACipherTest.java
new file mode 100644
index 0000000..3403df3
--- /dev/null
+++ b/tests/tests/keystore/src/android/keystore/cts/RSACipherTest.java
@@ -0,0 +1,251 @@
+/*
+ * Copyright 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.keystore.cts;
+
+import java.math.BigInteger;
+import java.security.PrivateKey;
+import java.security.Provider;
+import java.security.PublicKey;
+import java.security.Security;
+import java.security.interfaces.RSAKey;
+
+import javax.crypto.BadPaddingException;
+import javax.crypto.Cipher;
+import javax.crypto.IllegalBlockSizeException;
+
+import android.security.keystore.KeyProperties;
+import android.test.AndroidTestCase;
+import android.test.MoreAsserts;
+
+public class RSACipherTest extends AndroidTestCase {
+
+    private static final String EXPECTED_PROVIDER_NAME = TestUtils.EXPECTED_CRYPTO_OP_PROVIDER_NAME;
+
+    public void testNoPaddingEncryptionAndDecryptionSucceedsWithInputShorterThanModulus()
+            throws Exception {
+        Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
+        assertNotNull(provider);
+
+        for (ImportedKey key : RSASignatureTest.importKatKeyPairs(getContext(),
+                TestUtils.getMinimalWorkingImportParametersForCipheringWith(
+                        "RSA/ECB/NoPadding",
+                        KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT,
+                        false))) {
+            try {
+                PublicKey publicKey = key.getKeystoreBackedKeyPair().getPublic();
+                PrivateKey privateKey = key.getKeystoreBackedKeyPair().getPrivate();
+                BigInteger modulus = ((RSAKey) publicKey).getModulus();
+                int modulusSizeBytes = (modulus.bitLength() + 7) / 8;
+
+                // 1-byte long input for which we know the output
+                byte[] input = new byte[] {1};
+                // Because of how RSA works, the output is 1 (left-padded with zero bytes).
+                byte[] expectedOutput = TestUtils.leftPadWithZeroBytes(input, modulusSizeBytes);
+
+                Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding", provider);
+                cipher.init(Cipher.ENCRYPT_MODE, publicKey);
+                MoreAsserts.assertEquals(expectedOutput, cipher.doFinal(input));
+
+                cipher.init(Cipher.DECRYPT_MODE, privateKey);
+                MoreAsserts.assertEquals(expectedOutput, cipher.doFinal(input));
+            } catch (Throwable e) {
+                throw new RuntimeException("Failed for key " + key.getAlias(), e);
+            }
+        }
+    }
+
+    public void testNoPaddingEncryptionSucceedsWithPlaintextOneSmallerThanModulus()
+            throws Exception {
+        Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
+        assertNotNull(provider);
+
+        for (ImportedKey key : RSASignatureTest.importKatKeyPairs(getContext(),
+                TestUtils.getMinimalWorkingImportParametersForCipheringWith(
+                        "RSA/ECB/NoPadding",
+                        KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT,
+                        false))) {
+            try {
+                PublicKey publicKey = key.getKeystoreBackedKeyPair().getPublic();
+                PrivateKey privateKey = key.getKeystoreBackedKeyPair().getPrivate();
+                BigInteger modulus = ((RSAKey) publicKey).getModulus();
+
+                // Plaintext is one smaller than the modulus
+                byte[] plaintext =
+                        TestUtils.getBigIntegerMagnitudeBytes(modulus.subtract(BigInteger.ONE));
+                Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding", provider);
+                cipher.init(Cipher.ENCRYPT_MODE, publicKey);
+                byte[] ciphertext = cipher.doFinal(plaintext);
+                cipher.init(Cipher.DECRYPT_MODE, privateKey);
+                MoreAsserts.assertEquals(plaintext, cipher.doFinal(ciphertext));
+            } catch (Throwable e) {
+                throw new RuntimeException("Failed for key " + key.getAlias(), e);
+            }
+        }
+    }
+
+    public void testNoPaddingEncryptionFailsWithPlaintextEqualToModulus() throws Exception {
+        Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
+        assertNotNull(provider);
+
+        for (ImportedKey key : RSASignatureTest.importKatKeyPairs(getContext(),
+                TestUtils.getMinimalWorkingImportParametersForCipheringWith(
+                        "RSA/ECB/NoPadding",
+                        KeyProperties.PURPOSE_ENCRYPT ,
+                        false))) {
+            try {
+                PublicKey publicKey = key.getKeystoreBackedKeyPair().getPublic();
+                BigInteger modulus = ((RSAKey) publicKey).getModulus();
+
+                // Plaintext is exactly the modulus
+                byte[] plaintext = TestUtils.getBigIntegerMagnitudeBytes(modulus);
+                Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding", provider);
+                cipher.init(Cipher.ENCRYPT_MODE, publicKey);
+                try {
+                    byte[] ciphertext = cipher.doFinal(plaintext);
+                    fail("Unexpectedly produced ciphertext (" + ciphertext.length + " bytes): "
+                            + HexEncoding.encode(ciphertext));
+                } catch (BadPaddingException expected) {}
+            } catch (Throwable e) {
+                throw new RuntimeException("Failed for key " + key.getAlias(), e);
+            }
+        }
+    }
+
+    public void testNoPaddingEncryptionFailsWithPlaintextOneLargerThanModulus() throws Exception {
+        Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
+        assertNotNull(provider);
+
+        for (ImportedKey key : RSASignatureTest.importKatKeyPairs(getContext(),
+                TestUtils.getMinimalWorkingImportParametersForCipheringWith(
+                        "RSA/ECB/NoPadding",
+                        KeyProperties.PURPOSE_ENCRYPT,
+                        false))) {
+            try {
+                PublicKey publicKey = key.getKeystoreBackedKeyPair().getPublic();
+                BigInteger modulus = ((RSAKey) publicKey).getModulus();
+
+                // Plaintext is one larger than the modulus
+                byte[] plaintext =
+                        TestUtils.getBigIntegerMagnitudeBytes(modulus.add(BigInteger.ONE));
+                Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding", provider);
+                cipher.init(Cipher.ENCRYPT_MODE, publicKey);
+                try {
+                    byte[] ciphertext = cipher.doFinal(plaintext);
+                    fail("Unexpectedly produced ciphertext (" + ciphertext.length + " bytes): "
+                            + HexEncoding.encode(ciphertext));
+                } catch (BadPaddingException expected) {}
+            } catch (Throwable e) {
+                throw new RuntimeException("Failed for key " + key.getAlias(), e);
+            }
+        }
+    }
+
+    public void testNoPaddingEncryptionFailsWithPlaintextOneByteLongerThanModulus()
+            throws Exception {
+        Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
+        assertNotNull(provider);
+
+        for (ImportedKey key : RSASignatureTest.importKatKeyPairs(getContext(),
+                TestUtils.getMinimalWorkingImportParametersForCipheringWith(
+                        "RSA/ECB/NoPadding",
+                        KeyProperties.PURPOSE_ENCRYPT,
+                        false))) {
+            try {
+                PublicKey publicKey = key.getKeystoreBackedKeyPair().getPublic();
+                BigInteger modulus = ((RSAKey) publicKey).getModulus();
+
+                // Plaintext is one byte longer than the modulus. The message is filled with zeros
+                // (thus being 0 if treated as a BigInteger). This is on purpose, to check that the
+                // Cipher implementation rejects such long message without comparing it to the value
+                // of the modulus.
+                byte[] plaintext = new byte[((modulus.bitLength() + 7) / 8) + 1];
+                Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding", provider);
+                cipher.init(Cipher.ENCRYPT_MODE, publicKey);
+                try {
+                    byte[] ciphertext = cipher.doFinal(plaintext);
+                    fail("Unexpectedly produced ciphertext (" + ciphertext.length + " bytes): "
+                            + HexEncoding.encode(ciphertext));
+                } catch (IllegalBlockSizeException expected) {}
+            } catch (Throwable e) {
+                throw new RuntimeException("Failed for key " + key.getAlias(), e);
+            }
+        }
+    }
+
+    public void testNoPaddingDecryptionFailsWithCiphertextOneByteLongerThanModulus()
+            throws Exception {
+        Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
+        assertNotNull(provider);
+
+        for (ImportedKey key : RSASignatureTest.importKatKeyPairs(getContext(),
+                TestUtils.getMinimalWorkingImportParametersForCipheringWith(
+                        "RSA/ECB/NoPadding",
+                        KeyProperties.PURPOSE_DECRYPT,
+                        false))) {
+            try {
+                PrivateKey privateKey = key.getKeystoreBackedKeyPair().getPrivate();
+                BigInteger modulus = ((RSAKey) privateKey).getModulus();
+
+                // Ciphertext is one byte longer than the modulus. The message is filled with zeros
+                // (thus being 0 if treated as a BigInteger). This is on purpose, to check that the
+                // Cipher implementation rejects such long message without comparing it to the value
+                // of the modulus.
+                byte[] ciphertext = new byte[((modulus.bitLength() + 7) / 8) + 1];
+                Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding", EXPECTED_PROVIDER_NAME);
+                cipher.init(Cipher.DECRYPT_MODE, privateKey);
+                try {
+                    byte[] plaintext = cipher.doFinal(ciphertext);
+                    fail("Unexpectedly produced plaintext (" + ciphertext.length + " bytes): "
+                            + HexEncoding.encode(plaintext));
+                } catch (IllegalBlockSizeException expected) {}
+            } catch (Throwable e) {
+                throw new RuntimeException("Failed for key " + key.getAlias(), e);
+            }
+        }
+    }
+
+    public void testNoPaddingWithZeroMessage() throws Exception {
+        Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
+        assertNotNull(provider);
+
+        for (ImportedKey key : RSASignatureTest.importKatKeyPairs(getContext(),
+                TestUtils.getMinimalWorkingImportParametersForCipheringWith(
+                        "RSA/ECB/NoPadding",
+                        KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT,
+                        false))) {
+            try {
+                PublicKey publicKey = key.getKeystoreBackedKeyPair().getPublic();
+                PrivateKey privateKey = key.getKeystoreBackedKeyPair().getPrivate();
+
+                byte[] plaintext = EmptyArray.BYTE;
+                Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding", EXPECTED_PROVIDER_NAME);
+                cipher.init(Cipher.ENCRYPT_MODE, publicKey);
+                byte[] ciphertext = cipher.doFinal(plaintext);
+                // Ciphertext should be all zero bytes
+                byte[] expectedCiphertext = new byte[(TestUtils.getKeySizeBits(publicKey) + 7) / 8];
+                MoreAsserts.assertEquals(expectedCiphertext, ciphertext);
+
+                cipher.init(Cipher.DECRYPT_MODE, privateKey);
+                // Decrypted plaintext should also be all zero bytes
+                byte[] expectedPlaintext = new byte[expectedCiphertext.length];
+                MoreAsserts.assertEquals(expectedPlaintext, cipher.doFinal(ciphertext));
+            } catch (Throwable e) {
+                throw new RuntimeException("Failed for key " + key.getAlias(), e);
+            }
+        }
+    }
+}
diff --git a/tests/tests/keystore/src/android/keystore/cts/TestUtils.java b/tests/tests/keystore/src/android/keystore/cts/TestUtils.java
index 1c4f6ad..b1ba453 100644
--- a/tests/tests/keystore/src/android/keystore/cts/TestUtils.java
+++ b/tests/tests/keystore/src/android/keystore/cts/TestUtils.java
@@ -27,6 +27,7 @@
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
+import java.math.BigInteger;
 import java.security.Key;
 import java.security.KeyFactory;
 import java.security.KeyPair;
@@ -890,4 +891,15 @@
             throw new IllegalArgumentException("Unsupported key algorithm: " + keyAlgorithm);
         }
     }
+
+    static byte[] getBigIntegerMagnitudeBytes(BigInteger value) {
+        return removeLeadingZeroByteIfPresent(value.toByteArray());
+    }
+
+    private static byte[] removeLeadingZeroByteIfPresent(byte[] value) {
+        if ((value.length < 1) || (value[0] != 0)) {
+            return value;
+        }
+        return TestUtils.subarray(value, 1, value.length - 1);
+    }
 }
diff --git a/tests/tests/media/Android.mk b/tests/tests/media/Android.mk
index 43e3e89..13daca6 100644
--- a/tests/tests/media/Android.mk
+++ b/tests/tests/media/Android.mk
@@ -41,7 +41,7 @@
 LOCAL_STATIC_JAVA_LIBRARIES := \
     ctsmediautil ctsdeviceutil ctstestserver ctstestrunner
 
-LOCAL_JNI_SHARED_LIBRARIES := libctsmediacodec_jni
+LOCAL_JNI_SHARED_LIBRARIES := libctsmediacodec_jni libaudio_jni
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
diff --git a/tests/tests/media/libaudiojni/Android.mk b/tests/tests/media/libaudiojni/Android.mk
new file mode 100644
index 0000000..a6c1bfc
--- /dev/null
+++ b/tests/tests/media/libaudiojni/Android.mk
@@ -0,0 +1,39 @@
+# Copyright (C) 2015 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE    := libaudio_jni
+
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_SRC_FILES := \
+	appendix-b-1-1-buffer-queue.cpp \
+	appendix-b-1-2-recording.cpp \
+	audio-record-native.cpp \
+	audio-track-native.cpp \
+	sl-utils.cpp
+
+LOCAL_C_INCLUDES := \
+	$(JNI_H_INCLUDE) \
+	system/core/include
+
+LOCAL_C_INCLUDES += $(call include-path-for, libaudiojni) \
+	$(call include-path-for, wilhelm)
+
+LOCAL_SHARED_LIBRARIES := libandroid liblog libnativehelper libOpenSLES libutils
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/tests/tests/media/libaudiojni/Blob.h b/tests/tests/media/libaudiojni/Blob.h
new file mode 100644
index 0000000..134232c
--- /dev/null
+++ b/tests/tests/media/libaudiojni/Blob.h
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_BLOB_H
+#define ANDROID_BLOB_H
+
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+namespace android {
+
+// read only byte buffer like object
+
+class BlobReadOnly {
+public:
+    BlobReadOnly(const void *data, size_t size, bool byReference) :
+        mMem(byReference ? NULL : malloc(size)),
+        mData(byReference ? data : mMem),
+        mSize(size) {
+        if (!byReference) {
+            memcpy(mMem, data, size);
+        }
+    }
+    ~BlobReadOnly() {
+        free(mMem);
+    }
+
+private:
+          void * const mMem;
+
+public:
+    const void * const mData;
+          const size_t mSize;
+};
+
+// read/write byte buffer like object
+
+class Blob {
+public:
+    Blob(size_t size) :
+        mData(malloc(size)),
+        mOffset(0),
+        mSize(size),
+        mMem(mData) { }
+
+    // by reference
+    Blob(void *data, size_t size) :
+        mData(data),
+        mOffset(0),
+        mSize(size),
+        mMem(NULL) { }
+
+    ~Blob() {
+        free(mMem);
+    }
+
+    void * const mData;
+          size_t mOffset;
+    const size_t mSize;
+
+private:
+    void * const mMem;
+};
+
+} // namespace android
+
+#endif // ANDROID_BLOB_H
diff --git a/tests/tests/media/libaudiojni/Gate.h b/tests/tests/media/libaudiojni/Gate.h
new file mode 100644
index 0000000..dfc15b7
--- /dev/null
+++ b/tests/tests/media/libaudiojni/Gate.h
@@ -0,0 +1,137 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_GATE_H
+#define ANDROID_GATE_H
+
+#include <stdint.h>
+#include <mutex>
+
+namespace android {
+
+// Gate is a synchronization object.
+//
+// Threads will pass if it is open.
+// Threads will block (wait) if it is closed.
+//
+// When a gate is opened, all waiting threads will pass through.
+//
+// Since gate holds no external locks, consistency with external
+// state needs to be handled elsewhere.
+//
+// We use mWaitCount to indicate the number of threads that have
+// arrived at the gate via wait().  Each thread entering
+// wait obtains a unique waitId (which is the current mWaitCount).
+// This can be viewed as a sequence number.
+//
+// We use mPassCount to indicate the number of threads that have
+// passed the gate.  If the waitId is less than or equal to the mPassCount
+// then that thread has passed the gate.  An open gate sets mPassedCount
+// to the current mWaitCount, allowing all prior threads to pass.
+//
+// See sync_timeline, sync_pt, etc. for graphics.
+
+class Gate {
+public:
+    Gate(bool open = false) :
+        mOpen(open),
+        mExit(false),
+        mWaitCount(0),
+        mPassCount(0)
+    { }
+
+    // waits for the gate to open, returns immediately if gate is already open.
+    //
+    // Do not hold a monitor lock while calling this.
+    //
+    // returns true if we passed the gate normally
+    //         false if gate is terminated and we didn't pass the gate.
+    bool wait() {
+        std::unique_lock<std::mutex> l(mLock);
+        size_t waitId = ++mWaitCount;
+        if (mOpen) {
+            mPassCount = waitId; // let me through
+        }
+        while (!passedGate_l(waitId) && !mExit) {
+            mCondition.wait(l);
+        }
+        return passedGate_l(waitId);
+    }
+
+    // close the gate.
+    void closeGate() {
+        std::lock_guard<std::mutex> l(mLock);
+        mOpen = false;
+        mExit = false;
+    }
+
+    // open the gate.
+    // signal to all waiters it is okay to go.
+    void openGate() {
+        std::lock_guard<std::mutex> l(mLock);
+        mOpen = true;
+        mExit = false;
+        if (waiters_l() > 0) {
+            mPassCount = mWaitCount;  // allow waiting threads to go through
+            // unoptimized pthreads will wake thread to find we still hold lock.
+            mCondition.notify_all();
+        }
+    }
+
+    // terminate (term has expired).
+    // all threads allowed to pass regardless of whether the gate is open or closed.
+    void terminate() {
+        std::lock_guard<std::mutex> l(mLock);
+        mExit = true;
+        if (waiters_l() > 0) {
+            // unoptimized pthreads will wake thread to find we still hold lock.
+            mCondition.notify_all();
+        }
+    }
+
+    bool isOpen() {
+        std::lock_guard<std::mutex> l(mLock);
+        return mOpen;
+    }
+
+    // return how many waiters are at the gate.
+    size_t waiters() {
+        std::lock_guard<std::mutex> l(mLock);
+        return waiters_l();
+    }
+
+private:
+    bool                    mOpen;
+    bool                    mExit;
+    size_t                  mWaitCount;  // total number of threads that have called wait()
+    size_t                  mPassCount;  // total number of threads passed the gate.
+    std::condition_variable mCondition;
+    std::mutex              mLock;
+
+    // return how many waiters are at the gate.
+    inline size_t waiters_l() {
+        return mWaitCount - mPassCount;
+    }
+
+    // return whether the waitId (from mWaitCount) has passed through the gate
+    inline bool passedGate_l(size_t waitId) {
+        return (ssize_t)(waitId - mPassCount) <= 0;
+    }
+};
+
+} // namespace android
+
+#endif // ANDROID_GATE_H
diff --git a/tests/tests/media/libaudiojni/appendix-b-1-1-buffer-queue.cpp b/tests/tests/media/libaudiojni/appendix-b-1-1-buffer-queue.cpp
new file mode 100644
index 0000000..5bb88a7
--- /dev/null
+++ b/tests/tests/media/libaudiojni/appendix-b-1-1-buffer-queue.cpp
@@ -0,0 +1,250 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+//#define LOG_NDEBUG 0
+#define LOG_TAG "OpenSL-ES-Test-B-1-1-Buffer-Queue"
+
+#include "sl-utils.h"
+
+/*
+ * See https://www.khronos.org/registry/sles/specs/OpenSL_ES_Specification_1.0.1.pdf
+ * Appendix B.1.1 sample code.
+ *
+ * Minor edits made to conform to Android coding style.
+ *
+ * Correction to code: SL_IID_VOLUME is now made optional for the mixer.
+ * It isn't supported on the standard Android mixer, but it is supported on the player.
+ */
+
+#define MAX_NUMBER_INTERFACES 3
+
+/* Local storage for Audio data in 16 bit words */
+#define AUDIO_DATA_STORAGE_SIZE 4096
+
+#define AUDIO_DATA_SEGMENTS 8
+
+/* Audio data buffer size in 16 bit words. 8 data segments are used in
+   this simple example */
+#define AUDIO_DATA_BUFFER_SIZE (AUDIO_DATA_STORAGE_SIZE / AUDIO_DATA_SEGMENTS)
+
+/* Structure for passing information to callback function */
+typedef struct  {
+    SLPlayItf playItf;
+    SLint16  *pDataBase; // Base address of local audio data storage
+    SLint16  *pData;     // Current address of local audio data storage
+    SLuint32  size;
+} CallbackCntxt;
+
+/* Local storage for Audio data */
+static SLint16 pcmData[AUDIO_DATA_STORAGE_SIZE];
+
+/* Callback for Buffer Queue events */
+static void BufferQueueCallback(
+        SLBufferQueueItf queueItf,
+        void *pContext)
+{
+    SLresult res;
+    CallbackCntxt *pCntxt = (CallbackCntxt*)pContext;
+    if (pCntxt->pData < (pCntxt->pDataBase + pCntxt->size)) {
+        res = (*queueItf)->Enqueue(queueItf, (void *)pCntxt->pData,
+                sizeof(SLint16) * AUDIO_DATA_BUFFER_SIZE); /* Size given in bytes. */
+        ALOGE_IF(res != SL_RESULT_SUCCESS, "error: %s", android::getSLErrStr(res));
+        /* Increase data pointer by buffer size */
+        pCntxt->pData += AUDIO_DATA_BUFFER_SIZE;
+    }
+}
+
+/* Play some music from a buffer queue */
+static void TestPlayMusicBufferQueue(SLObjectItf sl)
+{
+    SLEngineItf EngineItf;
+
+    SLresult res;
+
+    SLDataSource audioSource;
+    SLDataLocator_BufferQueue bufferQueue;
+    SLDataFormat_PCM pcm;
+
+    SLDataSink audioSink;
+    SLDataLocator_OutputMix locator_outputmix;
+
+    SLObjectItf player;
+    SLPlayItf playItf;
+    SLBufferQueueItf bufferQueueItf;
+    SLBufferQueueState state;
+
+    SLObjectItf OutputMix;
+    SLVolumeItf volumeItf;
+
+    int i;
+
+    SLboolean required[MAX_NUMBER_INTERFACES];
+    SLInterfaceID iidArray[MAX_NUMBER_INTERFACES];
+
+    /* Callback context for the buffer queue callback function */
+    CallbackCntxt cntxt;
+
+    /* Get the SL Engine Interface which is implicit */
+    res = (*sl)->GetInterface(sl, SL_IID_ENGINE, (void *)&EngineItf);
+    CheckErr(res);
+
+    /* Initialize arrays required[] and iidArray[] */
+    for (i = 0; i < MAX_NUMBER_INTERFACES; i++) {
+        required[i] = SL_BOOLEAN_FALSE;
+        iidArray[i] = SL_IID_NULL;
+    }
+
+    // Set arrays required[] and iidArray[] for VOLUME interface
+    required[0] = SL_BOOLEAN_FALSE; // ANDROID: we don't require this interface
+    iidArray[0] = SL_IID_VOLUME;
+
+#if 0
+    const unsigned interfaces = 1;
+#else
+
+    /* FIXME: Android doesn't properly support optional interfaces (required == false).
+    [3.1.6] When an application requests explicit interfaces during object creation,
+    it can flag any interface as required. If an implementation is unable to satisfy
+    the request for an interface that is not flagged as required (i.e. it is not required),
+    this will not cause the object to fail creation. On the other hand, if the interface
+    is flagged as required and the implementation is unable to satisfy the request
+    for the interface, the object will not be created.
+    */
+    const unsigned interfaces = 0;
+#endif
+    // Create Output Mix object to be used by player
+    res = (*EngineItf)->CreateOutputMix(EngineItf, &OutputMix, interfaces,
+            iidArray, required);
+    CheckErr(res);
+
+    // Realizing the Output Mix object in synchronous mode.
+    res = (*OutputMix)->Realize(OutputMix, SL_BOOLEAN_FALSE);
+    CheckErr(res);
+
+    volumeItf = NULL; // ANDROID: Volume interface on mix object may not be supported
+    res = (*OutputMix)->GetInterface(OutputMix, SL_IID_VOLUME,
+            (void *)&volumeItf);
+
+    /* Setup the data source structure for the buffer queue */
+    bufferQueue.locatorType = SL_DATALOCATOR_BUFFERQUEUE;
+    bufferQueue.numBuffers = 4; /* Four buffers in our buffer queue */
+
+    /* Setup the format of the content in the buffer queue */
+    pcm.formatType = SL_DATAFORMAT_PCM;
+    pcm.numChannels = 2;
+    pcm.samplesPerSec = SL_SAMPLINGRATE_44_1;
+    pcm.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16;
+    pcm.containerSize = 16;
+    pcm.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT;
+    pcm.endianness = SL_BYTEORDER_LITTLEENDIAN;
+    audioSource.pFormat = (void *)&pcm;
+    audioSource.pLocator = (void *)&bufferQueue;
+
+    /* Setup the data sink structure */
+    locator_outputmix.locatorType = SL_DATALOCATOR_OUTPUTMIX;
+    locator_outputmix.outputMix = OutputMix;
+    audioSink.pLocator = (void *)&locator_outputmix;
+    audioSink.pFormat = NULL;
+
+    /* Initialize the context for Buffer queue callbacks */
+    cntxt.pDataBase = pcmData;
+    cntxt.pData = cntxt.pDataBase;
+    cntxt.size = sizeof(pcmData) / sizeof(pcmData[0]); // ANDROID: Bug
+
+    /* Set arrays required[] and iidArray[] for SEEK interface
+       (PlayItf is implicit) */
+    required[0] = SL_BOOLEAN_TRUE;
+    iidArray[0] = SL_IID_BUFFERQUEUE;
+
+    /* Create the music player */
+
+    res = (*EngineItf)->CreateAudioPlayer(EngineItf, &player,
+            &audioSource, &audioSink, 1, iidArray, required);
+    CheckErr(res);
+
+    /* Realizing the player in synchronous mode. */
+    res = (*player)->Realize(player, SL_BOOLEAN_FALSE);
+    CheckErr(res);
+
+    /* Get seek and play interfaces */
+    res = (*player)->GetInterface(player, SL_IID_PLAY, (void *)&playItf);
+    CheckErr(res);
+    res = (*player)->GetInterface(player, SL_IID_BUFFERQUEUE,
+            (void *)&bufferQueueItf);
+    CheckErr(res);
+
+    /* Setup to receive buffer queue event callbacks */
+    res = (*bufferQueueItf)->RegisterCallback(bufferQueueItf,
+            BufferQueueCallback, &cntxt /* BUG, was NULL */);
+    CheckErr(res);
+
+    /* Before we start set volume to -3dB (-300mB) */
+    if (volumeItf != NULL) { // ANDROID: Volume interface may not be supported.
+        res = (*volumeItf)->SetVolumeLevel(volumeItf, -300);
+        CheckErr(res);
+    }
+
+    /* Enqueue a few buffers to get the ball rolling */
+    res = (*bufferQueueItf)->Enqueue(bufferQueueItf, cntxt.pData,
+            sizeof(SLint16) * AUDIO_DATA_BUFFER_SIZE); /* Size given in bytes. */
+    CheckErr(res);
+    cntxt.pData += AUDIO_DATA_BUFFER_SIZE;
+    res = (*bufferQueueItf)->Enqueue(bufferQueueItf, cntxt.pData,
+            sizeof(SLint16) * AUDIO_DATA_BUFFER_SIZE); /* Size given in bytes. */
+    CheckErr(res);
+    cntxt.pData += AUDIO_DATA_BUFFER_SIZE;
+    res = (*bufferQueueItf)->Enqueue(bufferQueueItf, cntxt.pData,
+            sizeof(SLint16) * AUDIO_DATA_BUFFER_SIZE); /* Size given in bytes. */
+    CheckErr(res);
+    cntxt.pData += AUDIO_DATA_BUFFER_SIZE;
+
+    /* Play the PCM samples using a buffer queue */
+    res = (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_PLAYING);
+    CheckErr(res);
+
+    /* Wait until the PCM data is done playing, the buffer queue callback
+       will continue to queue buffers until the entire PCM data has been
+       played. This is indicated by waiting for the count member of the
+       SLBufferQueueState to go to zero.
+     */
+    res = (*bufferQueueItf)->GetState(bufferQueueItf, &state);
+    CheckErr(res);
+
+    while (state.count) {
+        usleep(5 * 1000 /* usec */); // ANDROID: avoid busy waiting
+        (*bufferQueueItf)->GetState(bufferQueueItf, &state);
+    }
+
+    /* Make sure player is stopped */
+    res = (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_STOPPED);
+    CheckErr(res);
+
+    /* Destroy the player */
+    (*player)->Destroy(player);
+
+    /* Destroy Output Mix object */
+    (*OutputMix)->Destroy(OutputMix);
+}
+
+extern "C" void Java_android_media_cts_AudioNativeTest_nativeAppendixBBufferQueue(
+        JNIEnv * /* env */, jclass /* clazz */)
+{
+    SLObjectItf engineObject = android::OpenSLEngine();
+    LOG_ALWAYS_FATAL_IF(engineObject == NULL, "cannot open OpenSL ES engine");
+
+    TestPlayMusicBufferQueue(engineObject);
+    android::CloseSLEngine(engineObject);
+}
diff --git a/tests/tests/media/libaudiojni/appendix-b-1-2-recording.cpp b/tests/tests/media/libaudiojni/appendix-b-1-2-recording.cpp
new file mode 100644
index 0000000..5f6f3aa
--- /dev/null
+++ b/tests/tests/media/libaudiojni/appendix-b-1-2-recording.cpp
@@ -0,0 +1,221 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+//#define LOG_NDEBUG 0
+#define LOG_TAG "OpenSL-ES-Test-B-1-2-Recording"
+
+#include "sl-utils.h"
+
+/*
+ * See https://www.khronos.org/registry/sles/specs/OpenSL_ES_Specification_1.0.1.pdf
+ * Appendix B.1.2 sample code.
+ *
+ * Minor edits made to conform to Android coding style.
+ *
+ * Correction to code: SL_IID_AUDIOIODEVICECAPABILITIES is not supported.
+ * Detection of microphone should be made in Java layer.
+ */
+
+#define MAX_NUMBER_INTERFACES 5
+#define MAX_NUMBER_INPUT_DEVICES 3
+#define POSITION_UPDATE_PERIOD 1000 /* 1 sec */
+
+static void RecordEventCallback(SLRecordItf caller __unused,
+        void *pContext __unused,
+        SLuint32 recordevent __unused)
+{
+    /* Callback code goes here */
+}
+
+/*
+ * Test recording of audio from a microphone into a specified file
+ */
+static void TestAudioRecording(SLObjectItf sl)
+{
+    SLObjectItf recorder;
+    SLRecordItf recordItf;
+    SLEngineItf EngineItf;
+    SLAudioIODeviceCapabilitiesItf AudioIODeviceCapabilitiesItf;
+    SLAudioInputDescriptor AudioInputDescriptor;
+    SLresult res;
+
+    SLDataSource audioSource;
+    SLDataLocator_IODevice locator_mic;
+    SLDeviceVolumeItf devicevolumeItf;
+    SLDataSink audioSink;
+    SLDataLocator_URI uri;
+    SLDataFormat_MIME mime;
+
+    int i;
+    SLboolean required[MAX_NUMBER_INTERFACES];
+    SLInterfaceID iidArray[MAX_NUMBER_INTERFACES];
+
+    SLuint32 InputDeviceIDs[MAX_NUMBER_INPUT_DEVICES];
+    SLint32 numInputs = 0;
+    SLboolean mic_available = SL_BOOLEAN_FALSE;
+    SLuint32 mic_deviceID = 0;
+
+    /* Get the SL Engine Interface which is implicit */
+    res = (*sl)->GetInterface(sl, SL_IID_ENGINE, (void *)&EngineItf);
+    CheckErr(res);
+
+    AudioIODeviceCapabilitiesItf = NULL;
+    /* Get the Audio IO DEVICE CAPABILITIES interface, which is also
+       implicit */
+    res = (*sl)->GetInterface(sl, SL_IID_AUDIOIODEVICECAPABILITIES,
+            (void *)&AudioIODeviceCapabilitiesItf);
+    // ANDROID: obtaining SL_IID_AUDIOIODEVICECAPABILITIES may fail
+    if (AudioIODeviceCapabilitiesItf != NULL ) {
+        numInputs = MAX_NUMBER_INPUT_DEVICES;
+        res = (*AudioIODeviceCapabilitiesItf)->GetAvailableAudioInputs(
+                AudioIODeviceCapabilitiesItf, &numInputs, InputDeviceIDs);
+        CheckErr(res);
+        /* Search for either earpiece microphone or headset microphone input
+           device - with a preference for the latter */
+        for (i = 0; i < numInputs; i++) {
+            res = (*AudioIODeviceCapabilitiesItf)->QueryAudioInputCapabilities(
+                    AudioIODeviceCapabilitiesItf, InputDeviceIDs[i], &AudioInputDescriptor);
+            CheckErr(res);
+            if ((AudioInputDescriptor.deviceConnection == SL_DEVCONNECTION_ATTACHED_WIRED)
+                    && (AudioInputDescriptor.deviceScope == SL_DEVSCOPE_USER)
+                    && (AudioInputDescriptor.deviceLocation == SL_DEVLOCATION_HEADSET)) {
+                mic_deviceID = InputDeviceIDs[i];
+                mic_available = SL_BOOLEAN_TRUE;
+                break;
+            }
+            else if ((AudioInputDescriptor.deviceConnection == SL_DEVCONNECTION_INTEGRATED)
+                    && (AudioInputDescriptor.deviceScope == SL_DEVSCOPE_USER)
+                    && (AudioInputDescriptor.deviceLocation == SL_DEVLOCATION_HANDSET)) {
+                mic_deviceID = InputDeviceIDs[i];
+                mic_available = SL_BOOLEAN_TRUE;
+                break;
+            }
+        }
+    } else {
+        mic_deviceID = SL_DEFAULTDEVICEID_AUDIOINPUT;
+        mic_available = true;
+    }
+
+    /* If neither of the preferred input audio devices is available, no
+       point in continuing */
+    if (!mic_available) {
+        /* Appropriate error message here */
+        ALOGW("No microphone available");
+        return;
+    }
+
+    /* Initialize arrays required[] and iidArray[] */
+    for (i = 0; i < MAX_NUMBER_INTERFACES; i++) {
+        required[i] = SL_BOOLEAN_FALSE;
+        iidArray[i] = SL_IID_NULL;
+    }
+
+    // ANDROID: the following may fail for volume
+    devicevolumeItf = NULL;
+    /* Get the optional DEVICE VOLUME interface from the engine */
+    res = (*sl)->GetInterface(sl, SL_IID_DEVICEVOLUME,
+            (void *)&devicevolumeItf);
+
+    /* Set recording volume of the microphone to -3 dB */
+    if (devicevolumeItf != NULL) { // ANDROID: Volume may not be supported
+        res = (*devicevolumeItf)->SetVolume(devicevolumeItf, mic_deviceID, -300);
+        CheckErr(res);
+    }
+
+    /* Setup the data source structure */
+    locator_mic.locatorType = SL_DATALOCATOR_IODEVICE;
+    locator_mic.deviceType = SL_IODEVICE_AUDIOINPUT;
+    locator_mic.deviceID = mic_deviceID;
+    locator_mic.device= NULL;
+
+    audioSource.pLocator = (void *)&locator_mic;
+    audioSource.pFormat = NULL;
+
+#if 0
+    /* Setup the data sink structure */
+    uri.locatorType = SL_DATALOCATOR_URI;
+    uri.URI = (SLchar *) "file:///recordsample.wav";
+    mime.formatType = SL_DATAFORMAT_MIME;
+    mime.mimeType = (SLchar *) "audio/x-wav";
+    mime.containerType = SL_CONTAINERTYPE_WAV;
+    audioSink.pLocator = (void *)&uri;
+    audioSink.pFormat = (void *)&mime;
+#else
+    // FIXME: Android requires SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE
+    // because the recorder makes the distinction from SL_DATALOCATOR_BUFFERQUEUE
+    // which the player does not.
+    SLDataLocator_AndroidSimpleBufferQueue loc_bq = {
+            SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, 2
+    };
+    SLDataFormat_PCM format_pcm = {
+            SL_DATAFORMAT_PCM, 1, SL_SAMPLINGRATE_16,
+            SL_PCMSAMPLEFORMAT_FIXED_16, SL_PCMSAMPLEFORMAT_FIXED_16,
+            SL_SPEAKER_FRONT_LEFT, SL_BYTEORDER_LITTLEENDIAN
+    };
+    audioSink = { &loc_bq, &format_pcm };
+#endif
+
+    /* Create audio recorder */
+    res = (*EngineItf)->CreateAudioRecorder(EngineItf, &recorder,
+            &audioSource, &audioSink, 0, iidArray, required);
+    CheckErr(res);
+
+    /* Realizing the recorder in synchronous mode. */
+    res = (*recorder)->Realize(recorder, SL_BOOLEAN_FALSE);
+    CheckErr(res);
+
+    /* Get the RECORD interface - it is an implicit interface */
+    res = (*recorder)->GetInterface(recorder, SL_IID_RECORD, (void *)&recordItf);
+    CheckErr(res);
+
+    // ANDROID: Should register SL_IID_ANDROIDSIMPLEBUFFERQUEUE interface for callback.
+    // but does original SL_DATALOCATOR_BUFFERQUEUE variant work just as well ?
+
+    /* Setup to receive position event callbacks */
+    res = (*recordItf)->RegisterCallback(recordItf, RecordEventCallback, NULL);
+    CheckErr(res);
+
+    /* Set notifications to occur after every second - may be useful in
+       updating a recording progress bar */
+    res = (*recordItf)->SetPositionUpdatePeriod(recordItf, POSITION_UPDATE_PERIOD);
+    CheckErr(res);
+    res = (*recordItf)->SetCallbackEventsMask(recordItf, SL_RECORDEVENT_HEADATNEWPOS);
+    CheckErr(res);
+
+    /* Set the duration of the recording - 30 seconds (30,000
+       milliseconds) */
+    res = (*recordItf)->SetDurationLimit(recordItf, 30000);
+    CheckErr(res);
+
+    /* Record the audio */
+    res = (*recordItf)->SetRecordState(recordItf, SL_RECORDSTATE_RECORDING);
+    CheckErr(res);
+
+    // ANDROID: BUG - we don't wait for anything to record!
+
+    /* Destroy the recorder object */
+    (*recorder)->Destroy(recorder);
+}
+
+extern "C" void Java_android_media_cts_AudioNativeTest_nativeAppendixBRecording(
+        JNIEnv * /* env */, jclass /* clazz */)
+{
+    SLObjectItf engineObject = android::OpenSLEngine();
+    LOG_ALWAYS_FATAL_IF(engineObject == NULL, "cannot open OpenSL ES engine");
+
+    TestAudioRecording(engineObject);
+    android::CloseSLEngine(engineObject);
+}
diff --git a/tests/tests/media/libaudiojni/audio-record-native.cpp b/tests/tests/media/libaudiojni/audio-record-native.cpp
new file mode 100644
index 0000000..9103cdc
--- /dev/null
+++ b/tests/tests/media/libaudiojni/audio-record-native.cpp
@@ -0,0 +1,631 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+//#define LOG_NDEBUG 0
+#define LOG_TAG "audio-record-native"
+
+#include "Blob.h"
+#include "Gate.h"
+#include "sl-utils.h"
+
+#include <deque>
+#include <utils/Errors.h>
+
+// Select whether to use STL shared pointer or to use Android strong pointer.
+// We really don't promote any sharing of this object for its lifetime, but nevertheless could
+// change the shared pointer value on the fly if desired.
+#define USE_SHARED_POINTER
+
+#ifdef USE_SHARED_POINTER
+#include <memory>
+template <typename T> using shared_pointer = std::shared_ptr<T>;
+#else
+#include <utils/RefBase.h>
+template <typename T> using shared_pointer = android::sp<T>;
+#endif
+
+using namespace android;
+
+// Must be kept in sync with Java android.media.cts.AudioRecordNative.ReadFlags
+enum {
+    READ_FLAG_BLOCKING = (1 << 0),
+};
+
+// buffer queue buffers on the OpenSL ES side.
+// The choice can be >= 1.  There is also internal buffering by AudioRecord.
+
+static const size_t BUFFER_SIZE_MSEC = 20;
+
+// TODO: Add a single buffer blocking read mode which does not require additional memory.
+// TODO: Add internal buffer memory (e.g. use circular buffer, right now mallocs on heap).
+
+class AudioRecordNative
+#ifndef USE_SHARED_POINTER
+        : public RefBase // android strong pointers require RefBase
+#endif
+{
+public:
+    AudioRecordNative() :
+        mEngineObj(NULL),
+        mEngine(NULL),
+        mRecordObj(NULL),
+        mRecord(NULL),
+        mBufferQueue(NULL),
+        mRecordState(SL_RECORDSTATE_STOPPED),
+        mBufferSize(0),
+        mNumBuffers(0)
+    { }
+
+    ~AudioRecordNative() {
+        close();
+    }
+
+    typedef std::lock_guard<std::recursive_mutex> auto_lock;
+
+    status_t open(uint32_t numChannels, uint32_t sampleRate, bool useFloat, uint32_t numBuffers) {
+        close();
+        auto_lock l(mLock);
+        mEngineObj = OpenSLEngine();
+        if (mEngineObj == NULL) {
+            ALOGW("cannot create OpenSL ES engine");
+            return INVALID_OPERATION;
+        }
+
+        SLresult res;
+        for (;;) {
+            /* Get the SL Engine Interface which is implicit */
+            res = (*mEngineObj)->GetInterface(mEngineObj, SL_IID_ENGINE, (void *)&mEngine);
+            if (res != SL_RESULT_SUCCESS) break;
+
+            SLDataLocator_IODevice locator_mic;
+            /* Setup the data source structure */
+            locator_mic.locatorType = SL_DATALOCATOR_IODEVICE;
+            locator_mic.deviceType = SL_IODEVICE_AUDIOINPUT;
+            locator_mic.deviceID = SL_DEFAULTDEVICEID_AUDIOINPUT;
+            locator_mic.device= NULL;
+            SLDataSource audioSource;
+            audioSource.pLocator = (void *)&locator_mic;
+            audioSource.pFormat = NULL;
+
+            // FIXME: Android requires SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE
+            // because the recorder makes the distinction from SL_DATALOCATOR_BUFFERQUEUE
+            // which the player does not.
+            SLDataLocator_AndroidSimpleBufferQueue loc_bq = {
+                    SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, numBuffers
+            };
+#if 0
+            SLDataFormat_PCM pcm = {
+                    SL_DATAFORMAT_PCM, 1, SL_SAMPLINGRATE_16,
+                    SL_PCMSAMPLEFORMAT_FIXED_16, SL_PCMSAMPLEFORMAT_FIXED_16,
+                    SL_SPEAKER_FRONT_LEFT, SL_BYTEORDER_LITTLEENDIAN
+            };
+#else
+            SLAndroidDataFormat_PCM_EX pcm;
+            pcm.formatType = useFloat ? SL_ANDROID_DATAFORMAT_PCM_EX : SL_DATAFORMAT_PCM;
+            pcm.numChannels = numChannels;
+            pcm.sampleRate = sampleRate * 1000;
+            pcm.bitsPerSample = useFloat ?
+                    SL_PCMSAMPLEFORMAT_FIXED_32 : SL_PCMSAMPLEFORMAT_FIXED_16;
+            pcm.containerSize = pcm.bitsPerSample;
+            pcm.channelMask = channelCountToMask(numChannels);
+            pcm.endianness = SL_BYTEORDER_LITTLEENDIAN;
+            // additional
+            pcm.representation = useFloat ? SL_ANDROID_PCM_REPRESENTATION_FLOAT
+                                    : SL_ANDROID_PCM_REPRESENTATION_SIGNED_INT;
+#endif
+            SLDataSink audioSink;
+            audioSink = { &loc_bq, &pcm };
+
+            SLboolean required[2];
+            SLInterfaceID iidArray[2];
+            /* Request the AndroidSimpleBufferQueue and AndroidConfiguration interfaces */
+            required[0] = SL_BOOLEAN_TRUE;
+            iidArray[0] = SL_IID_ANDROIDSIMPLEBUFFERQUEUE;
+            required[1] = SL_BOOLEAN_TRUE;
+            iidArray[1] = SL_IID_ANDROIDCONFIGURATION;
+
+            ALOGV("creating recorder");
+            /* Create audio recorder */
+            res = (*mEngine)->CreateAudioRecorder(mEngine, &mRecordObj,
+                    &audioSource, &audioSink, 2, iidArray, required);
+            if (res != SL_RESULT_SUCCESS) break;
+
+            ALOGV("realizing recorder");
+            /* Realizing the recorder in synchronous mode. */
+            res = (*mRecordObj)->Realize(mRecordObj, SL_BOOLEAN_FALSE /* async */);
+            if (res != SL_RESULT_SUCCESS) break;
+
+            ALOGV("geting record interface");
+            /* Get the RECORD interface - it is an implicit interface */
+            res = (*mRecordObj)->GetInterface(mRecordObj, SL_IID_RECORD, (void *)&mRecord);
+            if (res != SL_RESULT_SUCCESS) break;
+
+            ALOGV("geting buffer queue interface");
+            /* Get the buffer queue interface which was explicitly requested */
+            res = (*mRecordObj)->GetInterface(mRecordObj, SL_IID_ANDROIDSIMPLEBUFFERQUEUE,
+                    (void *)&mBufferQueue);
+            if (res != SL_RESULT_SUCCESS) break;
+
+            ALOGV("registering buffer queue interface");
+            /* Setup to receive buffer queue event callbacks */
+            res = (*mBufferQueue)->RegisterCallback(mBufferQueue, BufferQueueCallback, this);
+            if (res != SL_RESULT_SUCCESS) break;
+
+            mBufferSize = (BUFFER_SIZE_MSEC * sampleRate / 1000)
+                    * numChannels * (useFloat ? sizeof(float) : sizeof(int16_t));
+            mNumBuffers = numBuffers;
+            // success
+            break;
+        }
+        if (res != SL_RESULT_SUCCESS) {
+            close(); // should be safe to close even with lock held
+            ALOGW("open error %s", android::getSLErrStr(res));
+            return INVALID_OPERATION;
+        }
+        return OK;
+    }
+
+    void close() {
+        SLObjectItf engineObj;
+        SLObjectItf recordObj;
+        {
+            auto_lock l(mLock);
+            (void)stop();
+            // once stopped, we can unregister the callback
+            if (mBufferQueue != NULL) {
+                (void)(*mBufferQueue)->RegisterCallback(
+                        mBufferQueue, NULL /* callback */, NULL /* *pContext */);
+            }
+            (void)flush();
+            engineObj = mEngineObj;
+            recordObj = mRecordObj;
+            // clear out interfaces and objects
+            mRecord = NULL;
+            mBufferQueue = NULL;
+            mEngine = NULL;
+            mRecordObj = NULL;
+            mEngineObj = NULL;
+            mRecordState = SL_RECORDSTATE_STOPPED;
+            mBufferSize = 0;
+            mNumBuffers = 0;
+        }
+        // destroy without lock
+        if (recordObj != NULL) {
+            (*recordObj)->Destroy(recordObj);
+        }
+        if (engineObj) {
+            CloseSLEngine(engineObj);
+        }
+    }
+
+    status_t setRecordState(SLuint32 recordState) {
+        auto_lock l(mLock);
+        if (mRecord == NULL) {
+            return INVALID_OPERATION;
+        }
+        if (recordState == SL_RECORDSTATE_RECORDING) {
+            queueBuffers();
+        }
+        SLresult res = (*mRecord)->SetRecordState(mRecord, recordState);
+        if (res != SL_RESULT_SUCCESS) {
+            ALOGW("setRecordState %d error %s", recordState, android::getSLErrStr(res));
+            return INVALID_OPERATION;
+        }
+        mRecordState = recordState;
+        return OK;
+    }
+
+    SLuint32 getRecordState() {
+        auto_lock l(mLock);
+        if (mRecord == NULL) {
+            return SL_RECORDSTATE_STOPPED;
+        }
+        SLuint32 recordState;
+        SLresult res = (*mRecord)->GetRecordState(mRecord, &recordState);
+        if (res != SL_RESULT_SUCCESS) {
+            ALOGW("getRecordState error %s", android::getSLErrStr(res));
+            return SL_RECORDSTATE_STOPPED;
+        }
+        return recordState;
+    }
+
+    status_t getPositionInMsec(int64_t *position) {
+        auto_lock l(mLock);
+        if (mRecord == NULL) {
+            return INVALID_OPERATION;
+        }
+        if (position == NULL) {
+            return BAD_VALUE;
+        }
+        SLuint32 pos;
+        SLresult res = (*mRecord)->GetPosition(mRecord, &pos);
+        if (res != SL_RESULT_SUCCESS) {
+            ALOGW("getPosition error %s", android::getSLErrStr(res));
+            return INVALID_OPERATION;
+        }
+        // only lower 32 bits valid
+        *position = pos;
+        return OK;
+    }
+
+    status_t start() {
+        return setRecordState(SL_RECORDSTATE_RECORDING);
+    }
+
+    status_t pause() {
+        return setRecordState(SL_RECORDSTATE_PAUSED);
+    }
+
+    status_t stop() {
+        return setRecordState(SL_RECORDSTATE_STOPPED);
+    }
+
+    status_t flush() {
+        auto_lock l(mLock);
+        status_t result = OK;
+        if (mBufferQueue != NULL) {
+            SLresult res = (*mBufferQueue)->Clear(mBufferQueue);
+            if (res != SL_RESULT_SUCCESS) {
+                return INVALID_OPERATION;
+            }
+        }
+        mReadyQueue.clear();
+        // possible race if the engine is in the callback
+        // safety is only achieved if the recorder is paused or stopped.
+        mDeliveredQueue.clear();
+        mReadBlob = NULL;
+        mReadReady.terminate();
+        return result;
+    }
+
+    ssize_t read(void *buffer, size_t size, bool blocking = false) {
+        std::lock_guard<std::mutex> rl(mReadLock);
+        // not needed if we assume that a single thread is doing the reading
+        // or we always operate in non-blocking mode.
+
+        ALOGV("reading:%p  %zu", buffer, size);
+        size_t copied;
+        std::shared_ptr<Blob> blob;
+        {
+            auto_lock l(mLock);
+            if (mEngine == NULL) {
+                return INVALID_OPERATION;
+            }
+            size_t osize = size;
+            while (!mReadyQueue.empty() && size > 0) {
+                auto b = mReadyQueue.front();
+                size_t tocopy = min(size, b->mSize - b->mOffset);
+                // ALOGD("buffer:%p  size:%zu  b->mSize:%zu  b->mOffset:%zu tocopy:%zu ",
+                //        buffer, size, b->mSize, b->mOffset, tocopy);
+                memcpy(buffer, (char *)b->mData + b->mOffset, tocopy);
+                buffer = (char *)buffer + tocopy;
+                size -= tocopy;
+                b->mOffset += tocopy;
+                if (b->mOffset == b->mSize) {
+                    mReadyQueue.pop_front();
+                }
+            }
+            copied = osize - size;
+            if (!blocking || size == 0 || mReadBlob.get() != NULL) {
+                return copied;
+            }
+            blob = std::make_shared<Blob>(buffer, size);
+            mReadBlob = blob;
+            mReadReady.closeGate(); // the callback will open gate when read is completed.
+        }
+        if (mReadReady.wait()) {
+            // success then the blob is ours with valid data otherwise a flush has occurred
+            // and we return a short count.
+            copied += blob->mOffset;
+        }
+        return copied;
+    }
+
+    void logBufferState() {
+        auto_lock l(mLock);
+        SLBufferQueueState state;
+        SLresult res = (*mBufferQueue)->GetState(mBufferQueue, &state);
+        CheckErr(res);
+        ALOGD("logBufferState state.count:%d  state.playIndex:%d", state.count, state.playIndex);
+    }
+
+    size_t getBuffersPending() {
+        auto_lock l(mLock);
+        return mReadyQueue.size();
+    }
+
+private:
+    status_t queueBuffers() {
+        if (mBufferQueue == NULL) {
+            return INVALID_OPERATION;
+        }
+        if (mReadyQueue.size() + mDeliveredQueue.size() < mNumBuffers) {
+            // add new empty buffer
+            auto b = std::make_shared<Blob>(mBufferSize);
+            mDeliveredQueue.emplace_back(b);
+            (*mBufferQueue)->Enqueue(mBufferQueue, b->mData, b->mSize);
+        }
+        return OK;
+    }
+
+    void bufferQueueCallback(SLBufferQueueItf queueItf) {
+        auto_lock l(mLock);
+        if (queueItf != mBufferQueue) {
+            ALOGW("invalid buffer queue interface, ignoring");
+            return;
+        }
+        // logBufferState();
+
+        // remove from delivered queue
+        if (mDeliveredQueue.size()) {
+            auto b = mDeliveredQueue.front();
+            mDeliveredQueue.pop_front();
+            if (mReadBlob.get() != NULL) {
+                size_t tocopy = min(mReadBlob->mSize - mReadBlob->mOffset, b->mSize - b->mOffset);
+                memcpy((char *)mReadBlob->mData + mReadBlob->mOffset,
+                        (char *)b->mData + b->mOffset, tocopy);
+                b->mOffset += tocopy;
+                mReadBlob->mOffset += tocopy;
+                if (mReadBlob->mOffset == mReadBlob->mSize) {
+                    mReadBlob = NULL;      // we're done, clear our reference.
+                    mReadReady.openGate(); // allow read to continue.
+                }
+                if (b->mOffset == b->mSize) {
+                    b = NULL;
+                }
+            }
+            if (b.get() != NULL) {
+                if (mReadyQueue.size() + mDeliveredQueue.size() < mNumBuffers) {
+                    mReadyQueue.emplace_back(b); // save onto ready queue for future reads
+                } else {
+                    ALOGW("dropping data");
+                }
+            }
+        } else {
+            ALOGW("no delivered data!");
+        }
+        queueBuffers();
+    }
+
+    static void BufferQueueCallback(SLBufferQueueItf queueItf, void *pContext) {
+        SLresult res;
+        // naked native record
+        AudioRecordNative *record = (AudioRecordNative *)pContext;
+        record->bufferQueueCallback(queueItf);
+    }
+
+    SLObjectItf           mEngineObj;
+    SLEngineItf           mEngine;
+    SLObjectItf           mRecordObj;
+    SLRecordItf           mRecord;
+    SLBufferQueueItf      mBufferQueue;
+    SLuint32              mRecordState;
+    size_t                mBufferSize;
+    size_t                mNumBuffers;
+    std::recursive_mutex  mLock;          // monitor lock - locks public API methods and callback.
+                                          // recursive since it may call itself through API.
+    std::mutex            mReadLock;      // read lock - for blocking mode, prevents multiple
+                                          // reader threads from overlapping reads.  this is
+                                          // generally unnecessary as reads occur from
+                                          // one thread only.  acquire this before mLock.
+    std::shared_ptr<Blob> mReadBlob;
+    Gate                  mReadReady;
+    std::deque<std::shared_ptr<Blob>> mReadyQueue;     // ready for read.
+    std::deque<std::shared_ptr<Blob>> mDeliveredQueue; // delivered to BufferQueue
+};
+
+/* Java static methods.
+ *
+ * These are not directly exposed to the user, so we can assume a valid "jrecord" handle
+ * to be passed in.
+ */
+
+extern "C" jint Java_android_media_cts_AudioRecordNative_nativeTest(
+    JNIEnv * /* env */, jclass /* clazz */,
+    jint numChannels, jint sampleRate, jboolean useFloat,
+    jint msecPerBuffer, jint numBuffers)
+{
+    AudioRecordNative record;
+    const size_t frameSize = numChannels * (useFloat ? sizeof(float) : sizeof(int16_t));
+    const size_t framesPerBuffer = msecPerBuffer * sampleRate / 1000;
+
+    status_t res;
+    void *buffer = calloc(framesPerBuffer * numBuffers, frameSize);
+    for (;;) {
+        res = record.open(numChannels, sampleRate, useFloat, numBuffers);
+        if (res != OK) break;
+
+        record.logBufferState();
+        res = record.start();
+        if (res != OK) break;
+
+        size_t size = framesPerBuffer * numBuffers * frameSize;
+        for (size_t offset = 0; size - offset > 0; ) {
+            ssize_t amount = record.read((char *)buffer + offset, size -offset);
+            // ALOGD("read amount: %zd", amount);
+            if (amount < 0) break;
+            offset += amount;
+            usleep(5 * 1000 /* usec */);
+        }
+
+        res = record.stop();
+        break;
+    }
+    record.close();
+    free(buffer);
+    return res;
+}
+
+extern "C" jlong Java_android_media_cts_AudioRecordNative_nativeCreateRecord(
+    JNIEnv * /* env */, jclass /* clazz */)
+{
+    return (jlong)(new shared_pointer<AudioRecordNative>(new AudioRecordNative()));
+}
+
+extern "C" void Java_android_media_cts_AudioRecordNative_nativeDestroyRecord(
+    JNIEnv * /* env */, jclass /* clazz */, jlong jrecord)
+{
+    delete (shared_pointer<AudioRecordNative> *)jrecord;
+}
+
+extern "C" jint Java_android_media_cts_AudioRecordNative_nativeOpen(
+    JNIEnv * /* env */, jclass /* clazz */, jlong jrecord,
+    jint numChannels, jint sampleRate, jboolean useFloat, jint numBuffers)
+{
+    auto record = *(shared_pointer<AudioRecordNative> *)jrecord;
+    if (record.get() == NULL) {
+        return (jint)INVALID_OPERATION;
+    }
+    return (jint)record->open(numChannels, sampleRate, useFloat == JNI_TRUE,
+            numBuffers);
+}
+
+extern "C" void Java_android_media_cts_AudioRecordNative_nativeClose(
+    JNIEnv * /* env */, jclass /* clazz */, jlong jrecord)
+{
+    auto record = *(shared_pointer<AudioRecordNative> *)jrecord;
+    if (record.get() != NULL) {
+        record->close();
+    }
+}
+
+extern "C" jint Java_android_media_cts_AudioRecordNative_nativeStart(
+    JNIEnv * /* env */, jclass /* clazz */, jlong jrecord)
+{
+    auto record = *(shared_pointer<AudioRecordNative> *)jrecord;
+    if (record.get() == NULL) {
+        return (jint)INVALID_OPERATION;
+    }
+    return (jint)record->start();
+}
+
+extern "C" jint Java_android_media_cts_AudioRecordNative_nativeStop(
+    JNIEnv * /* env */, jclass /* clazz */, jlong jrecord)
+{
+    auto record = *(shared_pointer<AudioRecordNative> *)jrecord;
+    if (record.get() == NULL) {
+        return (jint)INVALID_OPERATION;
+    }
+    return (jint)record->stop();
+}
+
+extern "C" jint Java_android_media_cts_AudioRecordNative_nativePause(
+    JNIEnv * /* env */, jclass /* clazz */, jlong jrecord)
+{
+    auto record = *(shared_pointer<AudioRecordNative> *)jrecord;
+    if (record.get() == NULL) {
+        return (jint)INVALID_OPERATION;
+    }
+    return (jint)record->pause();
+}
+
+extern "C" jint Java_android_media_cts_AudioRecordNative_nativeFlush(
+    JNIEnv * /* env */, jclass /* clazz */, jlong jrecord)
+{
+    auto record = *(shared_pointer<AudioRecordNative> *)jrecord;
+    if (record.get() == NULL) {
+        return (jint)INVALID_OPERATION;
+    }
+    return (jint)record->flush();
+}
+
+extern "C" jint Java_android_media_cts_AudioRecordNative_nativeGetPositionInMsec(
+    JNIEnv *env, jclass /* clazz */, jlong jrecord, jlongArray jPosition)
+{
+    auto record = *(shared_pointer<AudioRecordNative> *)jrecord;
+    if (record.get() == NULL) {
+        return (jint)INVALID_OPERATION;
+    }
+    int64_t pos;
+    status_t res = record->getPositionInMsec(&pos);
+    if (res != OK) {
+        return res;
+    }
+    jlong *nPostition = (jlong *) env->GetPrimitiveArrayCritical(jPosition, NULL /* isCopy */);
+    if (nPostition == NULL) {
+        ALOGE("Unable to get array for nativeGetPositionInMsec()");
+        return BAD_VALUE;
+    }
+    nPostition[0] = (jlong)pos;
+    env->ReleasePrimitiveArrayCritical(jPosition, nPostition, 0 /* mode */);
+    return OK;
+}
+
+
+extern "C" jint Java_android_media_cts_AudioRecordNative_nativeGetBuffersPending(
+    JNIEnv * /* env */, jclass /* clazz */, jlong jrecord)
+{
+    auto record = *(shared_pointer<AudioRecordNative> *)jrecord;
+    if (record.get() == NULL) {
+        return (jint)0;
+    }
+    return (jint)record->getBuffersPending();
+}
+
+template <typename T>
+static inline jint readFromRecord(jlong jrecord, T *data,
+    jint offsetInSamples, jint sizeInSamples, jint readFlags)
+{
+    auto record = *(shared_pointer<AudioRecordNative> *)jrecord;
+    if (record.get() == NULL) {
+        return (jint)INVALID_OPERATION;
+    }
+
+    const bool isBlocking = readFlags & READ_FLAG_BLOCKING;
+    const size_t sizeInBytes = sizeInSamples * sizeof(T);
+    ssize_t ret = record->read(data + offsetInSamples, sizeInBytes, isBlocking == JNI_TRUE);
+    return (jint)(ret > 0 ? ret / sizeof(T) : ret);
+}
+
+template <typename T>
+static inline jint readArray(JNIEnv *env, jclass /* clazz */, jlong jrecord,
+        T javaAudioData, jint offsetInSamples, jint sizeInSamples, jint readFlags)
+{
+    if (javaAudioData == NULL) {
+        return (jint)BAD_VALUE;
+    }
+
+    auto cAudioData = envGetArrayElements(env, javaAudioData, NULL /* isCopy */);
+    if (cAudioData == NULL) {
+        ALOGE("Error retrieving destination of audio data to record");
+        return (jint)BAD_VALUE;
+    }
+
+    jint ret = readFromRecord(jrecord, cAudioData, offsetInSamples, sizeInSamples, readFlags);
+    envReleaseArrayElements(env, javaAudioData, cAudioData, 0 /* mode */);
+    return ret;
+}
+
+extern "C" jint Java_android_media_cts_AudioRecordNative_nativeReadByteArray(
+    JNIEnv *env, jclass clazz, jlong jrecord,
+    jbyteArray byteArray, jint offsetInSamples, jint sizeInSamples, jint readFlags)
+{
+    return readArray(env, clazz, jrecord, byteArray, offsetInSamples, sizeInSamples, readFlags);
+}
+
+extern "C" jint Java_android_media_cts_AudioRecordNative_nativeReadShortArray(
+    JNIEnv *env, jclass clazz, jlong jrecord,
+    jshortArray shortArray, jint offsetInSamples, jint sizeInSamples, jint readFlags)
+{
+    return readArray(env, clazz, jrecord, shortArray, offsetInSamples, sizeInSamples, readFlags);
+}
+
+extern "C" jint Java_android_media_cts_AudioRecordNative_nativeReadFloatArray(
+    JNIEnv *env, jclass clazz, jlong jrecord,
+    jfloatArray floatArray, jint offsetInSamples, jint sizeInSamples, jint readFlags)
+{
+    return readArray(env, clazz, jrecord, floatArray, offsetInSamples, sizeInSamples, readFlags);
+}
diff --git a/tests/tests/media/libaudiojni/audio-track-native.cpp b/tests/tests/media/libaudiojni/audio-track-native.cpp
new file mode 100644
index 0000000..d51a751
--- /dev/null
+++ b/tests/tests/media/libaudiojni/audio-track-native.cpp
@@ -0,0 +1,579 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+//#define LOG_NDEBUG 0
+#define LOG_TAG "audio-track-native"
+
+#include "Blob.h"
+#include "Gate.h"
+#include "sl-utils.h"
+
+#include <deque>
+#include <utils/Errors.h>
+
+// Select whether to use STL shared pointer or to use Android strong pointer.
+// We really don't promote any sharing of this object for its lifetime, but nevertheless could
+// change the shared pointer value on the fly if desired.
+#define USE_SHARED_POINTER
+
+#ifdef USE_SHARED_POINTER
+#include <memory>
+template <typename T> using shared_pointer = std::shared_ptr<T>;
+#else
+#include <utils/RefBase.h>
+template <typename T> using shared_pointer = android::sp<T>;
+#endif
+
+using namespace android;
+
+// Must be kept in sync with Java android.media.cts.AudioTrackNative.WriteFlags
+enum {
+    WRITE_FLAG_BLOCKING = (1 << 0),
+};
+
+// TODO: Add a single buffer blocking write mode which does not require additional memory.
+// TODO: Add internal buffer memory (e.g. use circular buffer, right now mallocs on heap).
+
+class AudioTrackNative
+#ifndef USE_SHARED_POINTER
+        : public RefBase // android strong pointers require RefBase
+#endif
+{
+public:
+    AudioTrackNative() :
+        mEngineObj(NULL),
+        mEngine(NULL),
+        mOutputMixObj(NULL),
+        mPlayerObj(NULL),
+        mPlay(NULL),
+        mBufferQueue(NULL),
+        mPlayState(SL_PLAYSTATE_STOPPED),
+        mNumBuffers(0)
+    { }
+
+    ~AudioTrackNative() {
+        close();
+    }
+
+    typedef std::lock_guard<std::recursive_mutex> auto_lock;
+
+    status_t open(uint32_t numChannels, uint32_t sampleRate, bool useFloat,
+            uint32_t numBuffers) {
+        close();
+        auto_lock l(mLock);
+        mEngineObj = OpenSLEngine();
+        if (mEngineObj == NULL) {
+            ALOGW("cannot create OpenSL ES engine");
+            return INVALID_OPERATION;
+        }
+
+        SLresult res;
+        for (;;) {
+            /* Get the SL Engine Interface which is implicit */
+            res = (*mEngineObj)->GetInterface(mEngineObj, SL_IID_ENGINE, (void *)&mEngine);
+            if (res != SL_RESULT_SUCCESS) break;
+
+            // Create Output Mix object to be used by player
+            res = (*mEngine)->CreateOutputMix(
+                    mEngine, &mOutputMixObj, 0 /* numInterfaces */,
+                    NULL /* pInterfaceIds */, NULL /* pInterfaceRequired */);
+            if (res != SL_RESULT_SUCCESS) break;
+
+            // Realizing the Output Mix object in synchronous mode.
+            res = (*mOutputMixObj)->Realize(mOutputMixObj, SL_BOOLEAN_FALSE /* async */);
+            if (res != SL_RESULT_SUCCESS) break;
+
+            /* Setup the data source structure for the buffer queue */
+            SLDataLocator_BufferQueue bufferQueue;
+            bufferQueue.locatorType = SL_DATALOCATOR_BUFFERQUEUE;
+            bufferQueue.numBuffers = numBuffers;
+            mNumBuffers = numBuffers;
+
+            /* Setup the format of the content in the buffer queue */
+
+            SLAndroidDataFormat_PCM_EX pcm;
+            pcm.formatType = useFloat ? SL_ANDROID_DATAFORMAT_PCM_EX : SL_DATAFORMAT_PCM;
+            pcm.numChannels = numChannels;
+            pcm.sampleRate = sampleRate * 1000;
+            pcm.bitsPerSample = useFloat ?
+                    SL_PCMSAMPLEFORMAT_FIXED_32 : SL_PCMSAMPLEFORMAT_FIXED_16;
+            pcm.containerSize = pcm.bitsPerSample;
+            pcm.channelMask = channelCountToMask(numChannels);
+            pcm.endianness = SL_BYTEORDER_LITTLEENDIAN;
+            // additional
+            pcm.representation = useFloat ? SL_ANDROID_PCM_REPRESENTATION_FLOAT
+                                    : SL_ANDROID_PCM_REPRESENTATION_SIGNED_INT;
+            SLDataSource audioSource;
+            audioSource.pFormat = (void *)&pcm;
+            audioSource.pLocator = (void *)&bufferQueue;
+
+            /* Setup the data sink structure */
+            SLDataLocator_OutputMix locator_outputmix;
+            locator_outputmix.locatorType = SL_DATALOCATOR_OUTPUTMIX;
+            locator_outputmix.outputMix = mOutputMixObj;
+
+            SLDataSink audioSink;
+            audioSink.pLocator = (void *)&locator_outputmix;
+            audioSink.pFormat = NULL;
+
+            SLboolean required[1];
+            SLInterfaceID iidArray[1];
+            required[0] = SL_BOOLEAN_TRUE;
+            iidArray[0] = SL_IID_BUFFERQUEUE;
+
+            res = (*mEngine)->CreateAudioPlayer(mEngine, &mPlayerObj,
+                    &audioSource, &audioSink, 1 /* numInterfaces */, iidArray, required);
+            if (res != SL_RESULT_SUCCESS) break;
+
+            res = (*mPlayerObj)->Realize(mPlayerObj, SL_BOOLEAN_FALSE /* async */);
+            if (res != SL_RESULT_SUCCESS) break;
+
+            res = (*mPlayerObj)->GetInterface(mPlayerObj, SL_IID_PLAY, (void*)&mPlay);
+            if (res != SL_RESULT_SUCCESS) break;
+
+            res = (*mPlayerObj)->GetInterface(
+                    mPlayerObj, SL_IID_BUFFERQUEUE, (void*)&mBufferQueue);
+            if (res != SL_RESULT_SUCCESS) break;
+
+            /* Setup to receive buffer queue event callbacks */
+            res = (*mBufferQueue)->RegisterCallback(mBufferQueue, BufferQueueCallback, this);
+            if (res != SL_RESULT_SUCCESS) break;
+
+            // success
+            break;
+        }
+        if (res != SL_RESULT_SUCCESS) {
+            close(); // should be safe to close even with lock held
+            ALOGW("open error %s", android::getSLErrStr(res));
+            return INVALID_OPERATION;
+        }
+        return OK;
+    }
+
+    void close() {
+        SLObjectItf engineObj;
+        SLObjectItf outputMixObj;
+        SLObjectItf playerObj;
+        {
+            auto_lock l(mLock);
+            if (mPlay != NULL && mPlayState != SL_PLAYSTATE_STOPPED) {
+                (void)stop();
+            }
+            // once stopped, we can unregister the callback
+            if (mBufferQueue != NULL) {
+                (void)(*mBufferQueue)->RegisterCallback(
+                        mBufferQueue, NULL /* callback */, NULL /* *pContext */);
+            }
+            (void)flush();
+            engineObj = mEngineObj;
+            outputMixObj = mOutputMixObj;
+            playerObj = mPlayerObj;
+            // clear out interfaces and objects
+            mPlay = NULL;
+            mBufferQueue = NULL;
+            mEngine = NULL;
+            mPlayerObj = NULL;
+            mOutputMixObj = NULL;
+            mEngineObj = NULL;
+            mPlayState = SL_PLAYSTATE_STOPPED;
+        }
+        // destroy without lock
+        if (playerObj != NULL) {
+            (*playerObj)->Destroy(playerObj);
+        }
+        if (outputMixObj != NULL) {
+            (*outputMixObj)->Destroy(outputMixObj);
+        }
+        if (engineObj != NULL) {
+            CloseSLEngine(engineObj);
+        }
+    }
+
+    status_t setPlayState(SLuint32 playState) {
+        auto_lock l(mLock);
+        if (mPlay == NULL) {
+            return INVALID_OPERATION;
+        }
+        SLresult res = (*mPlay)->SetPlayState(mPlay, playState);
+        if (res != SL_RESULT_SUCCESS) {
+            ALOGW("setPlayState %d error %s", playState, android::getSLErrStr(res));
+            return INVALID_OPERATION;
+        }
+        mPlayState = playState;
+        return OK;
+    }
+
+    SLuint32 getPlayState() {
+        auto_lock l(mLock);
+        if (mPlay == NULL) {
+            return SL_PLAYSTATE_STOPPED;
+        }
+        SLuint32 playState;
+        SLresult res = (*mPlay)->GetPlayState(mPlay, &playState);
+        if (res != SL_RESULT_SUCCESS) {
+            ALOGW("getPlayState error %s", android::getSLErrStr(res));
+            return SL_PLAYSTATE_STOPPED;
+        }
+        return playState;
+    }
+
+    status_t getPositionInMsec(int64_t *position) {
+        auto_lock l(mLock);
+        if (mPlay == NULL) {
+            return INVALID_OPERATION;
+        }
+        if (position == NULL) {
+            return BAD_VALUE;
+        }
+        SLuint32 pos;
+        SLresult res = (*mPlay)->GetPosition(mPlay, &pos);
+        if (res != SL_RESULT_SUCCESS) {
+            ALOGW("getPosition error %s", android::getSLErrStr(res));
+            return INVALID_OPERATION;
+        }
+        // only lower 32 bits valid
+        *position = pos;
+        return OK;
+    }
+
+    status_t start() {
+        return setPlayState(SL_PLAYSTATE_PLAYING);
+    }
+
+    status_t pause() {
+        return setPlayState(SL_PLAYSTATE_PAUSED);
+    }
+
+    status_t stop() {
+        return setPlayState(SL_PLAYSTATE_STOPPED);
+    }
+
+    status_t flush() {
+        auto_lock l(mLock);
+        status_t result = OK;
+        if (mBufferQueue != NULL) {
+            SLresult res = (*mBufferQueue)->Clear(mBufferQueue);
+            if (res != SL_RESULT_SUCCESS) {
+                return INVALID_OPERATION;
+            }
+        }
+
+        // possible race if the engine is in the callback
+        // safety is only achieved if the player is paused or stopped.
+        mDeliveredQueue.clear();
+        return result;
+    }
+
+    status_t write(const void *buffer, size_t size, bool isBlocking = false) {
+        std::lock_guard<std::mutex> rl(mWriteLock);
+        // not needed if we assume that a single thread is doing the reading
+        // or we always operate in non-blocking mode.
+
+        {
+            auto_lock l(mLock);
+            if (mBufferQueue == NULL) {
+                return INVALID_OPERATION;
+            }
+            if (mDeliveredQueue.size() < mNumBuffers) {
+                auto b = std::make_shared<BlobReadOnly>(buffer, size, false /* byReference */);
+                mDeliveredQueue.emplace_back(b);
+                (*mBufferQueue)->Enqueue(mBufferQueue, b->mData, b->mSize);
+                return size;
+            }
+            if (!isBlocking) {
+                return 0;
+            }
+            mWriteReady.closeGate(); // we're full.
+        }
+        if (mWriteReady.wait()) {
+            auto_lock l(mLock);
+            if (mDeliveredQueue.size() < mNumBuffers) {
+                auto b = std::make_shared<BlobReadOnly>(buffer, size, false /* byReference */);
+                mDeliveredQueue.emplace_back(b);
+                (*mBufferQueue)->Enqueue(mBufferQueue, b->mData, b->mSize);
+                return size;
+            }
+        }
+        ALOGW("unable to deliver write");
+        return 0;
+    }
+
+    void logBufferState() {
+        auto_lock l(mLock);
+        SLBufferQueueState state;
+        SLresult res = (*mBufferQueue)->GetState(mBufferQueue, &state);
+        CheckErr(res);
+        ALOGD("logBufferState state.count:%d  state.playIndex:%d", state.count, state.playIndex);
+    }
+
+    size_t getBuffersPending() {
+        auto_lock l(mLock);
+        return mDeliveredQueue.size();
+    }
+
+private:
+    void bufferQueueCallback(SLBufferQueueItf queueItf) {
+        auto_lock l(mLock);
+        if (queueItf != mBufferQueue) {
+            ALOGW("invalid buffer queue interface, ignoring");
+            return;
+        }
+        // logBufferState();
+
+        // remove from delivered queue
+        if (mDeliveredQueue.size()) {
+            mDeliveredQueue.pop_front();
+        } else {
+            ALOGW("no delivered data!");
+        }
+        if (!mWriteReady.isOpen()) {
+            mWriteReady.openGate();
+        }
+    }
+
+    static void BufferQueueCallback(SLBufferQueueItf queueItf, void *pContext) {
+        SLresult res;
+        // naked native track
+        AudioTrackNative *track = (AudioTrackNative *)pContext;
+        track->bufferQueueCallback(queueItf);
+    }
+
+    SLObjectItf          mEngineObj;
+    SLEngineItf          mEngine;
+    SLObjectItf          mOutputMixObj;
+    SLObjectItf          mPlayerObj;
+    SLPlayItf            mPlay;
+    SLBufferQueueItf     mBufferQueue;
+    SLuint32             mPlayState;
+    SLuint32             mNumBuffers;
+    std::recursive_mutex mLock;           // monitor lock - locks public API methods and callback.
+                                          // recursive since it may call itself through API.
+    std::mutex           mWriteLock;      // write lock - for blocking mode, prevents multiple
+                                          // writer threads from overlapping writes.  this is
+                                          // generally unnecessary as writes occur from
+                                          // one thread only.  acquire this before mLock.
+    Gate                 mWriteReady;
+    std::deque<std::shared_ptr<BlobReadOnly>> mDeliveredQueue; // delivered to mBufferQueue
+};
+
+/* Java static methods.
+ *
+ * These are not directly exposed to the user, so we can assume a valid "jtrack" handle
+ * to be passed in.
+ */
+
+extern "C" jint Java_android_media_cts_AudioTrackNative_nativeTest(
+    JNIEnv * /* env */, jclass /* clazz */,
+    jint numChannels, jint sampleRate, jboolean useFloat,
+    jint msecPerBuffer, jint numBuffers)
+{
+    AudioTrackNative track;
+    const size_t frameSize = numChannels * (useFloat ? sizeof(float) : sizeof(int16_t));
+    const size_t framesPerBuffer = msecPerBuffer * sampleRate / 1000;
+
+    status_t res;
+    void *buffer = calloc(framesPerBuffer * numBuffers, frameSize);
+    for (;;) {
+        res = track.open(numChannels, sampleRate, useFloat, numBuffers);
+        if (res != OK) break;
+
+        for (int i = 0; i < numBuffers; ++i) {
+            track.write((char *)buffer + i * (framesPerBuffer * frameSize),
+                    framesPerBuffer * frameSize);
+        }
+
+        track.logBufferState();
+        res = track.start();
+        if (res != OK) break;
+
+        size_t buffers;
+        while ((buffers = track.getBuffersPending()) > 0) {
+            // ALOGD("outstanding buffers: %zu", buffers);
+            usleep(5 * 1000 /* usec */);
+        }
+        res = track.stop();
+        break;
+    }
+    track.close();
+    free(buffer);
+    return res;
+}
+
+extern "C" jlong Java_android_media_cts_AudioTrackNative_nativeCreateTrack(
+    JNIEnv * /* env */, jclass /* clazz */)
+{
+    return (jlong)(new shared_pointer<AudioTrackNative>(new AudioTrackNative()));
+}
+
+extern "C" void Java_android_media_cts_AudioTrackNative_nativeDestroyTrack(
+    JNIEnv * /* env */, jclass /* clazz */, jlong jtrack)
+{
+    delete (shared_pointer<AudioTrackNative> *)jtrack;
+}
+
+extern "C" jint Java_android_media_cts_AudioTrackNative_nativeOpen(
+    JNIEnv * /* env */, jclass /* clazz */, jlong jtrack,
+    jint numChannels, jint sampleRate, jboolean useFloat, jint numBuffers)
+{
+    auto track = *(shared_pointer<AudioTrackNative> *)jtrack;
+    if (track.get() == NULL) {
+        return (jint)INVALID_OPERATION;
+    }
+    return (jint)track->open(numChannels, sampleRate, useFloat == JNI_TRUE,
+            numBuffers);
+}
+
+extern "C" void Java_android_media_cts_AudioTrackNative_nativeClose(
+    JNIEnv * /* env */, jclass /* clazz */, jlong jtrack)
+{
+    auto track = *(shared_pointer<AudioTrackNative> *)jtrack;
+    if (track.get() != NULL) {
+        track->close();
+    }
+}
+
+extern "C" jint Java_android_media_cts_AudioTrackNative_nativeStart(
+    JNIEnv * /* env */, jclass /* clazz */, jlong jtrack)
+{
+    auto track = *(shared_pointer<AudioTrackNative> *)jtrack;
+    if (track.get() == NULL) {
+        return (jint)INVALID_OPERATION;
+    }
+    return (jint)track->start();
+}
+
+extern "C" jint Java_android_media_cts_AudioTrackNative_nativeStop(
+    JNIEnv * /* env */, jclass /* clazz */, jlong jtrack)
+{
+    auto track = *(shared_pointer<AudioTrackNative> *)jtrack;
+    if (track.get() == NULL) {
+        return (jint)INVALID_OPERATION;
+    }
+    return (jint)track->stop();
+}
+
+extern "C" jint Java_android_media_cts_AudioTrackNative_nativePause(
+    JNIEnv * /* env */, jclass /* clazz */, jlong jtrack)
+{
+    auto track = *(shared_pointer<AudioTrackNative> *)jtrack;
+    if (track.get() == NULL) {
+        return (jint)INVALID_OPERATION;
+    }
+    return (jint)track->pause();
+}
+
+extern "C" jint Java_android_media_cts_AudioTrackNative_nativeFlush(
+    JNIEnv * /* env */, jclass /* clazz */, jlong jtrack)
+{
+    auto track = *(shared_pointer<AudioTrackNative> *)jtrack;
+    if (track.get() == NULL) {
+        return (jint)INVALID_OPERATION;
+    }
+    return (jint)track->flush();
+}
+
+extern "C" jint Java_android_media_cts_AudioTrackNative_nativeGetPositionInMsec(
+    JNIEnv *env, jclass /* clazz */, jlong jtrack, jlongArray jPosition)
+{
+    auto track = *(shared_pointer<AudioTrackNative> *)jtrack;
+    if (track.get() == NULL) {
+        return (jint)INVALID_OPERATION;
+    }
+    int64_t pos;
+    status_t res = track->getPositionInMsec(&pos);
+    if (res != OK) {
+        return res;
+    }
+    jlong *nPostition = (jlong *) env->GetPrimitiveArrayCritical(jPosition, NULL /* isCopy */);
+    if (nPostition == NULL) {
+        ALOGE("Unable to get array for nativeGetPositionInMsec()");
+        return BAD_VALUE;
+    }
+    nPostition[0] = (jlong)pos;
+    env->ReleasePrimitiveArrayCritical(jPosition, nPostition, 0 /* mode */);
+    return OK;
+}
+
+extern "C" jint Java_android_media_cts_AudioTrackNative_nativeGetBuffersPending(
+    JNIEnv * /* env */, jclass /* clazz */, jlong jtrack)
+{
+    auto track = *(shared_pointer<AudioTrackNative> *)jtrack;
+    if (track.get() == NULL) {
+        return (jint)0;
+    }
+    return (jint)track->getBuffersPending();
+}
+
+template <typename T>
+static inline jint writeToTrack(jlong jtrack, const T *data,
+    jint offsetInSamples, jint sizeInSamples, jint writeFlags)
+{
+    auto track = *(shared_pointer<AudioTrackNative> *)jtrack;
+    if (track.get() == NULL) {
+        return (jint)INVALID_OPERATION;
+    }
+
+    const bool isBlocking = writeFlags & WRITE_FLAG_BLOCKING;
+    const size_t sizeInBytes = sizeInSamples * sizeof(T);
+    ssize_t ret = track->write(data + offsetInSamples, sizeInBytes, isBlocking);
+    return (jint)(ret > 0 ? ret / sizeof(T) : ret);
+}
+
+template <typename T>
+static inline jint writeArray(JNIEnv *env, jclass /* clazz */, jlong jtrack,
+        T javaAudioData, jint offsetInSamples, jint sizeInSamples, jint writeFlags)
+{
+    if (javaAudioData == NULL) {
+        return (jint)INVALID_OPERATION;
+    }
+
+    auto cAudioData = envGetArrayElements(env, javaAudioData, NULL /* isCopy */);
+    if (cAudioData == NULL) {
+        ALOGE("Error retrieving source of audio data to play");
+        return (jint)BAD_VALUE;
+    }
+
+    jint ret = writeToTrack(jtrack, cAudioData, offsetInSamples, sizeInSamples, writeFlags);
+    envReleaseArrayElements(env, javaAudioData, cAudioData, 0 /* mode */);
+    return ret;
+}
+
+extern "C" jint Java_android_media_cts_AudioTrackNative_nativeWriteByteArray(
+    JNIEnv *env, jclass clazz, jlong jtrack,
+    jbyteArray byteArray, jint offsetInSamples, jint sizeInSamples, jint writeFlags)
+{
+    ALOGV("nativeWriteByteArray(%p, %d, %d, %d)",
+            byteArray, offsetInSamples, sizeInSamples, writeFlags);
+    return writeArray(env, clazz, jtrack, byteArray, offsetInSamples, sizeInSamples, writeFlags);
+}
+
+extern "C" jint Java_android_media_cts_AudioTrackNative_nativeWriteShortArray(
+    JNIEnv *env, jclass clazz, jlong jtrack,
+    jshortArray shortArray, jint offsetInSamples, jint sizeInSamples, jint writeFlags)
+{
+    ALOGV("nativeWriteShortArray(%p, %d, %d, %d)",
+            shortArray, offsetInSamples, sizeInSamples, writeFlags);
+    return writeArray(env, clazz, jtrack, shortArray, offsetInSamples, sizeInSamples, writeFlags);
+}
+
+extern "C" jint Java_android_media_cts_AudioTrackNative_nativeWriteFloatArray(
+    JNIEnv *env, jclass clazz, jlong jtrack,
+    jfloatArray floatArray, jint offsetInSamples, jint sizeInSamples, jint writeFlags)
+{
+    ALOGV("nativeWriteFloatArray(%p, %d, %d, %d)",
+            floatArray, offsetInSamples, sizeInSamples, writeFlags);
+    return writeArray(env, clazz, jtrack, floatArray, offsetInSamples, sizeInSamples, writeFlags);
+}
diff --git a/tests/tests/media/libaudiojni/sl-utils.cpp b/tests/tests/media/libaudiojni/sl-utils.cpp
new file mode 100644
index 0000000..1aa89ba
--- /dev/null
+++ b/tests/tests/media/libaudiojni/sl-utils.cpp
@@ -0,0 +1,145 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+//#define LOG_NDEBUG 0
+#define LOG_TAG "SL-Utils"
+
+#include "sl-utils.h"
+#include <utils/Mutex.h>
+
+#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
+
+// These will wind up in <SLES/OpenSLES_Android.h>
+#define SL_ANDROID_SPEAKER_QUAD (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT \
+ | SL_SPEAKER_BACK_LEFT | SL_SPEAKER_BACK_RIGHT)
+
+#define SL_ANDROID_SPEAKER_5DOT1 (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT \
+ | SL_SPEAKER_FRONT_CENTER  | SL_SPEAKER_LOW_FREQUENCY| SL_SPEAKER_BACK_LEFT \
+ | SL_SPEAKER_BACK_RIGHT)
+
+#define SL_ANDROID_SPEAKER_7DOT1 (SL_ANDROID_SPEAKER_5DOT1 | SL_SPEAKER_SIDE_LEFT \
+ |SL_SPEAKER_SIDE_RIGHT)
+
+namespace android {
+
+static Mutex gLock;
+static SLObjectItf gEngineObject;
+static unsigned gRefCount;
+
+static const char *gErrorStrings[] = {
+    "SL_RESULT_SUCCESS",                // 0
+    "SL_RESULT_PRECONDITIONS_VIOLATE",  // 1
+    "SL_RESULT_PARAMETER_INVALID",      // 2
+    "SL_RESULT_MEMORY_FAILURE",         // 3
+    "SL_RESULT_RESOURCE_ERROR",         // 4
+    "SL_RESULT_RESOURCE_LOST",          // 5
+    "SL_RESULT_IO_ERROR",               // 6
+    "SL_RESULT_BUFFER_INSUFFICIENT",    // 7
+    "SL_RESULT_CONTENT_CORRUPTED",      // 8
+    "SL_RESULT_CONTENT_UNSUPPORTED",    // 9
+    "SL_RESULT_CONTENT_NOT_FOUND",      // 10
+    "SL_RESULT_PERMISSION_DENIED",      // 11
+    "SL_RESULT_FEATURE_UNSUPPORTED",    // 12
+    "SL_RESULT_INTERNAL_ERROR",         // 13
+    "SL_RESULT_UNKNOWN_ERROR",          // 14
+    "SL_RESULT_OPERATION_ABORTED",      // 15
+    "SL_RESULT_CONTROL_LOST",           // 16
+};
+
+const char *getSLErrStr(int code) {
+    if ((size_t)code >= ARRAY_SIZE(gErrorStrings)) {
+        return "SL_RESULT_UNKNOWN";
+    }
+    return gErrorStrings[code];
+}
+
+SLuint32 channelCountToMask(unsigned channelCount) {
+    switch (channelCount) {
+    case 1:
+        return SL_SPEAKER_FRONT_LEFT; // we prefer left over center
+    case 2:
+        return SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT;
+    case 3:
+        return SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT | SL_SPEAKER_FRONT_CENTER;
+    case 4:
+        return SL_ANDROID_SPEAKER_QUAD;
+    case 5:
+        return SL_ANDROID_SPEAKER_QUAD | SL_SPEAKER_FRONT_CENTER;
+    case 6:
+        return SL_ANDROID_SPEAKER_5DOT1;
+    case 7:
+        return SL_ANDROID_SPEAKER_5DOT1 | SL_SPEAKER_BACK_CENTER;
+    case 8:
+        return SL_ANDROID_SPEAKER_7DOT1;
+    default:
+        return 0;
+    }
+}
+
+static SLObjectItf createEngine() {
+    static SLEngineOption EngineOption[] = {
+            (SLuint32) SL_ENGINEOPTION_THREADSAFE,
+            (SLuint32) SL_BOOLEAN_TRUE
+    };
+    // create engine in thread-safe mode
+    SLObjectItf engine;
+    SLresult result = slCreateEngine(&engine,
+            1 /* numOptions */, EngineOption /* pEngineOptions */,
+            0 /* numInterfaces */, NULL /* pInterfaceIds */, NULL /* pInterfaceRequired */);
+    if (result != SL_RESULT_SUCCESS) {
+        ALOGE("slCreateEngine() failed: %s", getSLErrStr(result));
+        return NULL;
+    }
+    // realize the engine
+    result = (*engine)->Realize(engine, SL_BOOLEAN_FALSE /* async */);
+    if (result != SL_RESULT_SUCCESS) {
+        ALOGE("Realize() failed: %s", getSLErrStr(result));
+        (*engine)->Destroy(engine);
+        return NULL;
+    }
+    return engine;
+}
+
+SLObjectItf OpenSLEngine(bool global) {
+
+    if (!global) {
+        return createEngine();
+    }
+    Mutex::Autolock l(gLock);
+    if (gRefCount == 0) {
+        gEngineObject = createEngine();
+    }
+    gRefCount++;
+    return gEngineObject;
+}
+
+void CloseSLEngine(SLObjectItf engine) {
+    Mutex::Autolock l(gLock);
+    if (engine == gEngineObject) {
+        if (gRefCount == 0) {
+            ALOGE("CloseSLEngine(%p): refcount already 0", engine);
+            return;
+        }
+        if (--gRefCount != 0) {
+            return;
+        }
+        gEngineObject = NULL;
+    }
+    (*engine)->Destroy(engine);
+}
+
+} // namespace android
+
diff --git a/tests/tests/media/libaudiojni/sl-utils.h b/tests/tests/media/libaudiojni/sl-utils.h
new file mode 100644
index 0000000..8582648
--- /dev/null
+++ b/tests/tests/media/libaudiojni/sl-utils.h
@@ -0,0 +1,95 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_SL_UTILS_H
+#define ANDROID_SL_UTILS_H
+
+#include <SLES/OpenSLES.h>
+#include <SLES/OpenSLES_Android.h>
+
+#include <jni.h>
+#include <mutex>
+#include <utils/Log.h>
+
+#define CheckErr(res) LOG_ALWAYS_FATAL_IF( \
+        (res) != SL_RESULT_SUCCESS, "result error %s", android::getSLErrStr(res));
+
+namespace android {
+
+// FIXME: Move to common file.
+template <typename T>
+static inline
+const T &min(const T &a, const T &b) {
+    return a < b ? a : b;
+}
+
+/* Returns the error string for the OpenSL ES error code
+ */
+const char *getSLErrStr(int code);
+
+/* Returns the OpenSL ES equivalent standard channel mask
+ * for a given channel count, 0 if no such mask is available.
+ */
+SLuint32 channelCountToMask(unsigned channelCount);
+
+/* Returns an OpenSL ES Engine object interface.
+ * The engine created will be thread safe [3.2]
+ * The underlying implementation may not support more than one engine. [4.1.1]
+ *
+ * @param global if true, return and open the global engine instance or make
+ *   a local engine instance if false.
+ * @return NULL if unsuccessful or the Engine SLObjectItf.
+ */
+SLObjectItf OpenSLEngine(bool global = true);
+
+/* Closes an OpenSL ES Engine object returned by OpenSLEngine().
+ */
+void CloseSLEngine(SLObjectItf engine);
+
+// overloaded JNI array helper functions (same as in android_media_AudioRecord)
+inline
+jbyte *envGetArrayElements(JNIEnv *env, jbyteArray array, jboolean *isCopy) {
+    return env->GetByteArrayElements(array, isCopy);
+}
+
+inline
+void envReleaseArrayElements(JNIEnv *env, jbyteArray array, jbyte *elems, jint mode) {
+    env->ReleaseByteArrayElements(array, elems, mode);
+}
+
+inline
+jshort *envGetArrayElements(JNIEnv *env, jshortArray array, jboolean *isCopy) {
+    return env->GetShortArrayElements(array, isCopy);
+}
+
+inline
+void envReleaseArrayElements(JNIEnv *env, jshortArray array, jshort *elems, jint mode) {
+    env->ReleaseShortArrayElements(array, elems, mode);
+}
+
+inline
+jfloat *envGetArrayElements(JNIEnv *env, jfloatArray array, jboolean *isCopy) {
+    return env->GetFloatArrayElements(array, isCopy);
+}
+
+inline
+void envReleaseArrayElements(JNIEnv *env, jfloatArray array, jfloat *elems, jint mode) {
+    env->ReleaseFloatArrayElements(array, elems, mode);
+}
+
+} // namespace android
+
+#endif // ANDROID_SL_UTILS_H
diff --git a/tests/tests/media/src/android/media/cts/AudioHelper.java b/tests/tests/media/src/android/media/cts/AudioHelper.java
index efee024..6707ea6 100644
--- a/tests/tests/media/src/android/media/cts/AudioHelper.java
+++ b/tests/tests/media/src/android/media/cts/AudioHelper.java
@@ -211,13 +211,13 @@
      * This affects AudioRecord timing.
      */
     public static class AudioRecordAudit extends AudioRecord {
-        AudioRecordAudit(int audioSource, int sampleRate, int channelMask,
+        public AudioRecordAudit(int audioSource, int sampleRate, int channelMask,
                 int format, int bufferSize, boolean isChannelIndex) {
             this(audioSource, sampleRate, channelMask, format, bufferSize, isChannelIndex,
                     AudioManager.STREAM_MUSIC, 500 /*delayMs*/);
         }
 
-        AudioRecordAudit(int audioSource, int sampleRate, int channelMask,
+        public AudioRecordAudit(int audioSource, int sampleRate, int channelMask,
                 int format, int bufferSize,
                 boolean isChannelIndex, int auditStreamType, int delayMs) {
             // without channel index masks, one could call:
@@ -408,4 +408,84 @@
         private int mPosition;
         private long mFinishAtMs;
     }
+
+    /* AudioRecordAudit extends AudioRecord to allow concurrent playback
+     * of read content to an AudioTrack.  This is for testing only.
+     * For general applications, it is NOT recommended to extend AudioRecord.
+     * This affects AudioRecord timing.
+     */
+    public static class AudioRecordAuditNative extends AudioRecordNative {
+        public AudioRecordAuditNative() {
+            super();
+            // Caution: delayMs too large results in buffer sizes that cannot be created.
+            mTrack = new AudioTrackNative();
+        }
+
+        @Override
+        public boolean open(int numChannels, int sampleRate, boolean useFloat, int numBuffers) {
+            if (super.open(numChannels, sampleRate, useFloat, numBuffers)) {
+                if (!mTrack.open(numChannels, sampleRate, useFloat, 2 /* numBuffers */)) {
+                    mTrack = null; // remove track
+                }
+                return true;
+            }
+            return false;
+        }
+
+        @Override
+        public void close() {
+            super.close();
+            if (mTrack != null) {
+                mTrack.close();
+            }
+        }
+
+        @Override
+        public boolean start() {
+            if (super.start()) {
+                if (mTrack != null) {
+                    mTrack.start();
+                }
+                return true;
+            }
+            return false;
+        }
+
+        @Override
+        public boolean stop() {
+            if (super.stop()) {
+                if (mTrack != null) {
+                    mTrack.stop(); // doesn't allow remaining data to play out
+                }
+                return true;
+            }
+            return false;
+        }
+
+        @Override
+        public int read(short[] audioData, int offsetInShorts, int sizeInShorts, int readFlags) {
+            int samples = super.read(audioData, offsetInShorts, sizeInShorts, readFlags);
+            if (mTrack != null) {
+                Assert.assertEquals(samples, mTrack.write(audioData, offsetInShorts, samples,
+                        AudioTrackNative.WRITE_FLAG_BLOCKING));
+                mPosition += samples / mTrack.getChannelCount();
+            }
+            return samples;
+        }
+
+        @Override
+        public int read(float[] audioData, int offsetInFloats, int sizeInFloats, int readFlags) {
+            int samples = super.read(audioData, offsetInFloats, sizeInFloats, readFlags);
+            if (mTrack != null) {
+                Assert.assertEquals(samples, mTrack.write(audioData, offsetInFloats, samples,
+                        AudioTrackNative.WRITE_FLAG_BLOCKING));
+                mPosition += samples / mTrack.getChannelCount();
+            }
+            return samples;
+        }
+
+        public AudioTrackNative mTrack;
+        private final static String TAG = "AudioRecordAuditNative";
+        private int mPosition;
+    }
 }
diff --git a/tests/tests/media/src/android/media/cts/AudioNativeTest.java b/tests/tests/media/src/android/media/cts/AudioNativeTest.java
new file mode 100644
index 0000000..b10da0c
--- /dev/null
+++ b/tests/tests/media/src/android/media/cts/AudioNativeTest.java
@@ -0,0 +1,231 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.media.cts;
+
+import android.content.pm.PackageManager;
+import android.cts.util.CtsAndroidTestCase;
+import android.util.Log;
+
+public class AudioNativeTest extends CtsAndroidTestCase {
+    public void testAppendixBBufferQueue() {
+        nativeAppendixBBufferQueue();
+    }
+
+    public void testAppendixBRecording() {
+        // better to detect presence of microphone here.
+        if (!hasMicrophone()) {
+            return;
+        }
+        nativeAppendixBRecording();
+    }
+
+    public void testStereo16Playback() {
+        assertTrue(AudioTrackNative.test(
+                2 /* numChannels */, 48000 /* sampleRate */, false /* useFloat */,
+                20 /* msecPerBuffer */, 8 /* numBuffers */));
+    }
+
+    public void testStereo16Record() {
+        assertTrue(AudioRecordNative.test(
+                2 /* numChannels */, 48000 /* sampleRate */, false /* useFloat */,
+                20 /* msecPerBuffer */, 8 /* numBuffers */));
+    }
+
+    public void testPlayStreamData() throws Exception {
+        final String TEST_NAME = "testPlayStreamData";
+        final boolean TEST_FLOAT_ARRAY[] = {
+                false,
+                true,
+        };
+        // due to downmixer algorithmic latency, source channels greater than 2 may
+        // sound shorter in duration at 4kHz sampling rate.
+        final int TEST_SR_ARRAY[] = {
+                /* 4000, */ // below limit of OpenSL ES
+                12345, // irregular sampling rate
+                44100,
+                48000,
+                96000,
+                192000,
+        };
+        // OpenSL ES Bug: MNC does not support channel counts of 3, 5, 7.
+        final int TEST_CHANNELS_ARRAY[] = {
+                1,
+                2,
+                // 3,
+                4,
+                // 5,
+                6,
+                // 7,
+                // 8  // can fail due to memory issues
+        };
+        final float TEST_SWEEP = 0; // sine wave only
+        final int TEST_TIME_IN_MSEC = 300;
+        final int TOLERANCE_MSEC = 20;
+
+        for (boolean TEST_FLOAT : TEST_FLOAT_ARRAY) {
+            double frequency = 400; // frequency changes for each test
+            for (int TEST_SR : TEST_SR_ARRAY) {
+                for (int TEST_CHANNELS : TEST_CHANNELS_ARRAY) {
+                    // OpenSL ES BUG: we run out of AudioTrack memory for this config on MNC
+                    // Log.d(TEST_NAME, "open channels:" + TEST_CHANNELS + " sr:" + TEST_SR);
+                    if (TEST_FLOAT == true && TEST_CHANNELS >= 6 && TEST_SR >= 192000) {
+                        continue;
+                    }
+                    AudioTrackNative track = new AudioTrackNative();
+                    assertTrue(TEST_NAME,
+                            track.open(TEST_CHANNELS, TEST_SR, TEST_FLOAT, 1 /* numBuffers */));
+                    assertTrue(TEST_NAME, track.start());
+
+                    final int sourceSamples =
+                            (int)((long)TEST_SR * TEST_TIME_IN_MSEC * TEST_CHANNELS / 1000);
+                    final double testFrequency = frequency / TEST_CHANNELS;
+                    if (TEST_FLOAT) {
+                        float data[] = AudioHelper.createSoundDataInFloatArray(
+                                sourceSamples, TEST_SR,
+                                testFrequency, TEST_SWEEP);
+                        assertEquals(sourceSamples,
+                                track.write(data, 0 /* offset */, sourceSamples,
+                                        AudioTrackNative.WRITE_FLAG_BLOCKING));
+                    } else {
+                        short data[] = AudioHelper.createSoundDataInShortArray(
+                                sourceSamples, TEST_SR,
+                                testFrequency, TEST_SWEEP);
+                        assertEquals(sourceSamples,
+                                track.write(data, 0 /* offset */, sourceSamples,
+                                        AudioTrackNative.WRITE_FLAG_BLOCKING));
+                    }
+
+                    while (true) {
+                        // OpenSL ES BUG: getPositionInMsec returns 0 after a data underrun.
+
+                        long position = track.getPositionInMsec();
+                        //Log.d(TEST_NAME, "position: " + position[0]);
+                        if (position >= (long)(TEST_TIME_IN_MSEC - TOLERANCE_MSEC)) {
+                            break;
+                        }
+
+                        // It is safer to use a buffer count of 0 to determine termination
+                        if (track.getBuffersPending() == 0) {
+                            break;
+                        }
+                        Thread.sleep(5 /* millis */);
+                    }
+                    track.stop();
+                    track.close();
+                    Thread.sleep(40 /* millis */);  // put a gap in the tone sequence
+                    frequency += 50; // increment test tone frequency
+                }
+            }
+        }
+    }
+
+    public void testRecordStreamData() throws Exception {
+        final String TEST_NAME = "testRecordStreamData";
+        final boolean TEST_FLOAT_ARRAY[] = {
+                false,
+                true,
+        };
+        final int TEST_SR_ARRAY[] = {
+                //4000, // below limit of OpenSL ES
+                12345, // irregular sampling rate
+                44100,
+                48000,
+                96000,
+                192000,
+        };
+        final int TEST_CHANNELS_ARRAY[] = {
+                1,
+                2,
+                // 3,
+                4,
+                // 5,
+                6,
+                // 7,
+                8,
+        };
+        final int SEGMENT_DURATION_IN_MSEC = 20;
+        final int NUMBER_SEGMENTS = 10;
+
+        for (boolean TEST_FLOAT : TEST_FLOAT_ARRAY) {
+            for (int TEST_SR : TEST_SR_ARRAY) {
+                for (int TEST_CHANNELS : TEST_CHANNELS_ARRAY) {
+                    // OpenSL ES BUG: we run out of AudioTrack memory for this config on MNC
+                    if (TEST_FLOAT == true && TEST_CHANNELS >= 8 && TEST_SR >= 192000) {
+                        continue;
+                    }
+                    AudioRecordNative record = new AudioRecordNative();
+                    doRecordTest(record, TEST_CHANNELS, TEST_SR, TEST_FLOAT,
+                            SEGMENT_DURATION_IN_MSEC, NUMBER_SEGMENTS);
+                }
+            }
+        }
+    }
+
+    public void testRecordAudit() throws Exception {
+        AudioRecordNative record = new AudioHelper.AudioRecordAuditNative();
+        doRecordTest(record, 4 /* numChannels */, 44100 /* sampleRate */, false /* useFloat */,
+                1000 /* segmentDurationMs */, 10 /* numSegments */);
+    }
+
+    static {
+        System.loadLibrary("audio_jni");
+    }
+
+    private static final String TAG = "AudioNativeTest";
+
+    private void doRecordTest(AudioRecordNative record,
+            int numChannels, int sampleRate, boolean useFloat,
+            int segmentDurationMs, int numSegments) {
+        final String TEST_NAME = "doRecordTest";
+        try {
+            // Log.d(TEST_NAME, "open numChannels:" + numChannels + " sampleRate:" + sampleRate);
+            assertTrue(TEST_NAME, record.open(numChannels, sampleRate, useFloat,
+                    numSegments /* numBuffers */));
+            assertTrue(TEST_NAME, record.start());
+
+            final int sourceSamples =
+                    (int)((long)sampleRate * segmentDurationMs * numChannels / 1000);
+
+            if (useFloat) {
+                float data[] = new float[sourceSamples];
+                for (int i = 0; i < numSegments; ++i) {
+                    assertEquals(sourceSamples,
+                            record.read(data, 0 /* offset */, sourceSamples,
+                                    AudioRecordNative.READ_FLAG_BLOCKING));
+                }
+            } else {
+                short data[] = new short[sourceSamples];
+                for (int i = 0; i < numSegments; ++i) {
+                    assertEquals(sourceSamples,
+                            record.read(data, 0 /* offset */, sourceSamples,
+                                    AudioRecordNative.READ_FLAG_BLOCKING));
+                }
+            }
+            assertTrue(TEST_NAME, record.stop());
+        } finally {
+            record.close();
+        }
+    }
+
+    private boolean hasMicrophone() {
+        return getContext().getPackageManager().hasSystemFeature(
+                PackageManager.FEATURE_MICROPHONE);
+    }
+
+    private static native void nativeAppendixBBufferQueue();
+    private static native void nativeAppendixBRecording();
+}
diff --git a/tests/tests/media/src/android/media/cts/AudioRecordNative.java b/tests/tests/media/src/android/media/cts/AudioRecordNative.java
new file mode 100644
index 0000000..18df8ee
--- /dev/null
+++ b/tests/tests/media/src/android/media/cts/AudioRecordNative.java
@@ -0,0 +1,153 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.media.cts;
+
+import android.annotation.IntDef;
+import android.annotation.NonNull;
+import android.cts.util.CtsAndroidTestCase;
+import android.util.Log;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+public class AudioRecordNative {
+    // Must be kept in sync with C++ JNI audio-record-native (AudioRecordNative) READ_FLAG_*
+    public static final int READ_FLAG_BLOCKING = 1 << 0;
+    /** @hide */
+    @IntDef(flag = true,
+            value = {
+                    READ_FLAG_BLOCKING,
+            })
+    @Retention(RetentionPolicy.SOURCE)
+    public @interface ReadFlags { }
+
+    public AudioRecordNative() {
+        mNativeRecordInJavaObj = nativeCreateRecord();
+    }
+
+    public boolean open(int numChannels, int sampleRate, boolean useFloat, int numBuffers) {
+        if (nativeOpen(mNativeRecordInJavaObj, numChannels, sampleRate, useFloat, numBuffers)
+                == STATUS_OK) {
+            mChannelCount = numChannels;
+            return true;
+        }
+        return false;
+    }
+
+    public void close() {
+        nativeClose(mNativeRecordInJavaObj);
+    }
+
+    public boolean start() {
+        return nativeStart(mNativeRecordInJavaObj) == STATUS_OK;
+    }
+
+    public boolean stop() {
+        return nativeStop(mNativeRecordInJavaObj) == STATUS_OK;
+    }
+
+    public boolean pause() {
+        return nativePause(mNativeRecordInJavaObj) == STATUS_OK;
+    }
+
+    public boolean flush() {
+        return nativeFlush(mNativeRecordInJavaObj) == STATUS_OK;
+    }
+
+    public long getPositionInMsec() {
+        long[] position = new long[1];
+        if (nativeGetPositionInMsec(mNativeRecordInJavaObj, position) != STATUS_OK) {
+            throw new IllegalStateException();
+        }
+        return position[0];
+    }
+
+    public int getBuffersPending() {
+        return nativeGetBuffersPending(mNativeRecordInJavaObj);
+    }
+
+    public int read(@NonNull byte[] byteArray,
+            int offsetInSamples, int sizeInSamples, @ReadFlags int readFlags) {
+        return nativeReadByteArray(
+                mNativeRecordInJavaObj, byteArray, offsetInSamples, sizeInSamples, readFlags);
+    }
+
+    public int read(@NonNull short[] shortArray,
+            int offsetInSamples, int sizeInSamples, @ReadFlags int readFlags) {
+        return nativeReadShortArray(
+                mNativeRecordInJavaObj, shortArray, offsetInSamples, sizeInSamples, readFlags);
+    }
+
+    public int read(@NonNull float[] floatArray,
+            int offsetInSamples, int sizeInSamples, @ReadFlags int readFlags) {
+        return nativeReadFloatArray(
+                mNativeRecordInJavaObj, floatArray, offsetInSamples, sizeInSamples, readFlags);
+    }
+
+    public int getChannelCount() {
+        return mChannelCount;
+    }
+
+    public static boolean test(int numChannels, int sampleRate, boolean useFloat,
+            int msecPerBuffer, int numBuffers) {
+        return nativeTest(numChannels, sampleRate, useFloat, msecPerBuffer, numBuffers)
+                == STATUS_OK;
+    }
+
+    @Override
+    protected void finalize() {
+        nativeClose(mNativeRecordInJavaObj);
+        nativeDestroyRecord(mNativeRecordInJavaObj);
+    }
+
+    static {
+        System.loadLibrary("audio_jni");
+    }
+
+    private static final String TAG = "AudioRecordNative";
+    private int mChannelCount;
+    private final long mNativeRecordInJavaObj;
+    private static final int STATUS_OK = 0;
+
+    // static native API.
+    // The native API uses a long "record handle" created by nativeCreateRecord.
+    // The handle must be destroyed after use by nativeDestroyRecord.
+    //
+    // Return codes from the native layer are status_t.
+    // Converted to Java booleans or exceptions at the public API layer.
+    private static native long nativeCreateRecord();
+    private static native void nativeDestroyRecord(long record);
+    private static native int nativeOpen(
+            long record, int numChannels, int sampleRate, boolean useFloat, int numBuffers);
+    private static native void nativeClose(long record);
+    private static native int nativeStart(long record);
+    private static native int nativeStop(long record);
+    private static native int nativePause(long record);
+    private static native int nativeFlush(long record);
+    private static native int nativeGetPositionInMsec(long record, @NonNull long[] position);
+    private static native int nativeGetBuffersPending(long record);
+    private static native int nativeReadByteArray(long record, @NonNull byte[] byteArray,
+            int offsetInSamples, int sizeInSamples, @ReadFlags int readFlags);
+    private static native int nativeReadShortArray(long record, @NonNull short[] shortArray,
+            int offsetInSamples, int sizeInSamples, @ReadFlags int readFlags);
+    private static native int nativeReadFloatArray(long record, @NonNull float[] floatArray,
+            int offsetInSamples, int sizeInSamples, @ReadFlags int readFlags);
+
+    // native interface for all-in-one testing, no record handle required.
+    private static native int nativeTest(
+            int numChannels, int sampleRate, boolean useFloat, int msecPerBuffer, int numBuffers);
+}
diff --git a/tests/tests/media/src/android/media/cts/AudioTrackNative.java b/tests/tests/media/src/android/media/cts/AudioTrackNative.java
new file mode 100644
index 0000000..1ce44ef
--- /dev/null
+++ b/tests/tests/media/src/android/media/cts/AudioTrackNative.java
@@ -0,0 +1,160 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.media.cts;
+
+import android.annotation.IntDef;
+import android.annotation.NonNull;
+import android.cts.util.CtsAndroidTestCase;
+import android.util.Log;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+public class AudioTrackNative {
+    // Must be kept in sync with C++ JNI audio-track-native (AudioTrackNative) WRITE_FLAG_*
+    public static final int WRITE_FLAG_BLOCKING = 1 << 0;
+    /** @hide */
+    @IntDef(flag = true,
+            value = {
+                    WRITE_FLAG_BLOCKING,
+            })
+    @Retention(RetentionPolicy.SOURCE)
+    public @interface WriteFlags { }
+
+    public AudioTrackNative() {
+        mNativeTrackInJavaObj = nativeCreateTrack();
+    }
+
+    // TODO: eventually accept AudioFormat
+    // numBuffers is the number of internal buffers before hitting the OpenSL ES.
+    // A value of 0 means that all writes are blocking.
+    public boolean open(int numChannels, int sampleRate, boolean useFloat, int numBuffers) {
+        if (nativeOpen(mNativeTrackInJavaObj, numChannels, sampleRate, useFloat, numBuffers)
+                == STATUS_OK) {
+            mChannelCount = numChannels;
+            return true;
+        }
+        return false;
+    }
+
+    public void close() {
+        nativeClose(mNativeTrackInJavaObj);
+    }
+
+    public boolean start() {
+        return nativeStart(mNativeTrackInJavaObj) == STATUS_OK;
+    }
+
+    public boolean stop() {
+        return nativeStop(mNativeTrackInJavaObj) == STATUS_OK;
+    }
+
+    public boolean pause() {
+        return nativePause(mNativeTrackInJavaObj) == STATUS_OK;
+    }
+
+    public boolean flush() {
+        return nativeFlush(mNativeTrackInJavaObj) == STATUS_OK;
+    }
+
+    public long getPositionInMsec() {
+        long[] position = new long[1];
+        if (nativeGetPositionInMsec(mNativeTrackInJavaObj, position) != STATUS_OK) {
+            throw new IllegalStateException();
+        }
+        return position[0];
+    }
+
+    public int getBuffersPending() {
+        return nativeGetBuffersPending(mNativeTrackInJavaObj);
+    }
+
+    /* returns number of samples written.
+     * 0 may be returned if !isBlocking.
+     * negative value indicates error.
+     */
+    public int write(@NonNull byte[] byteArray,
+            int offsetInSamples, int sizeInSamples, @WriteFlags int writeFlags) {
+        return nativeWriteByteArray(
+                mNativeTrackInJavaObj, byteArray, offsetInSamples, sizeInSamples, writeFlags);
+    }
+
+    public int write(@NonNull short[] shortArray,
+            int offsetInSamples, int sizeInSamples, @WriteFlags int writeFlags) {
+        return nativeWriteShortArray(
+                mNativeTrackInJavaObj, shortArray, offsetInSamples, sizeInSamples, writeFlags);
+    }
+
+    public int write(@NonNull float[] floatArray,
+            int offsetInSamples, int sizeInSamples, @WriteFlags int writeFlags) {
+        return nativeWriteFloatArray(
+                mNativeTrackInJavaObj, floatArray, offsetInSamples, sizeInSamples, writeFlags);
+    }
+
+    public int getChannelCount() {
+        return mChannelCount;
+    }
+
+    public static boolean test(int numChannels, int sampleRate, boolean useFloat,
+            int msecPerBuffer, int numBuffers) {
+        return nativeTest(numChannels, sampleRate, useFloat, msecPerBuffer, numBuffers)
+                == STATUS_OK;
+    }
+
+    @Override
+    protected void finalize() {
+        nativeClose(mNativeTrackInJavaObj);
+        nativeDestroyTrack(mNativeTrackInJavaObj);
+    }
+
+    static {
+        System.loadLibrary("audio_jni");
+    }
+
+    private static final String TAG = "AudioTrackNative";
+    private int mChannelCount;
+    private final long mNativeTrackInJavaObj;
+    private static final int STATUS_OK = 0;
+
+    // static native API.
+    // The native API uses a long "track handle" created by nativeCreateTrack.
+    // The handle must be destroyed after use by nativeDestroyTrack.
+    //
+    // Return codes from the native layer are status_t.
+    // Converted to Java booleans or exceptions at the public API layer.
+    private static native long nativeCreateTrack();
+    private static native void nativeDestroyTrack(long track);
+    private static native int nativeOpen(
+            long track, int numChannels, int sampleRate, boolean useFloat, int numBuffers);
+    private static native void nativeClose(long track);
+    private static native int nativeStart(long track);
+    private static native int nativeStop(long track);
+    private static native int nativePause(long track);
+    private static native int nativeFlush(long track);
+    private static native int nativeGetPositionInMsec(long track, @NonNull long[] position);
+    private static native int nativeGetBuffersPending(long track);
+    private static native int nativeWriteByteArray(long track, @NonNull byte[] byteArray,
+            int offsetInSamples, int sizeInSamples, @WriteFlags int writeFlags);
+    private static native int nativeWriteShortArray(long track, @NonNull short[] shortArray,
+            int offsetInSamples, int sizeInSamples, @WriteFlags int writeFlags);
+    private static native int nativeWriteFloatArray(long track, @NonNull float[] floatArray,
+            int offsetInSamples, int sizeInSamples, @WriteFlags int writeFlags);
+
+    // native interface for all-in-one testing, no track handle required.
+    private static native int nativeTest(
+            int numChannels, int sampleRate, boolean useFloat, int msecPerBuffer, int numBuffers);
+}
diff --git a/tests/tests/print/src/android/print/cts/BasePrintTest.java b/tests/tests/print/src/android/print/cts/BasePrintTest.java
index 31dfb9f..e75ec94 100644
--- a/tests/tests/print/src/android/print/cts/BasePrintTest.java
+++ b/tests/tests/print/src/android/print/cts/BasePrintTest.java
@@ -60,9 +60,13 @@
 import org.mockito.InOrder;
 import org.mockito.stubbing.Answer;
 
+import java.io.BufferedReader;
 import java.io.File;
+import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
 import java.util.List;
 import java.util.Locale;
 import java.util.concurrent.TimeoutException;
@@ -80,6 +84,12 @@
 
     private static final String PM_CLEAR_SUCCESS_OUTPUT = "Success";
 
+    private static final String COMMAND_LIST_ENABLED_IME_COMPONENTS = "ime list -s";
+
+    private static final String COMMAND_PREFIX_ENABLE_IME = "ime enable ";
+
+    private static final String COMMAND_PREFIX_DISABLE_IME = "ime disable ";
+
     private PrintDocumentActivity mActivity;
 
     private Locale mOldLocale;
@@ -91,11 +101,49 @@
     private CallCounter mPrintJobQueuedCallCounter;
     private CallCounter mDestroySessionCallCounter;
 
+    private String[] mEnabledImes;
+
+    private String[] getEnabledImes() throws IOException {
+        List<String> imeList = new ArrayList<>();
+
+        ParcelFileDescriptor pfd = getInstrumentation().getUiAutomation()
+                .executeShellCommand(COMMAND_LIST_ENABLED_IME_COMPONENTS);
+        BufferedReader reader = new BufferedReader(
+                new InputStreamReader(new FileInputStream(pfd.getFileDescriptor())));
+
+        String line;
+        while ((line = reader.readLine()) != null) {
+            imeList.add(line);
+        }
+
+        String[] imeArray = new String[imeList.size()];
+        imeList.toArray(imeArray);
+
+        return imeArray;
+    }
+
+    private void disableImes() throws Exception {
+        mEnabledImes = getEnabledImes();
+        for (String ime : mEnabledImes) {
+            String disableImeCommand = COMMAND_PREFIX_DISABLE_IME + ime;
+            SystemUtil.runShellCommand(getInstrumentation(), disableImeCommand);
+        }
+    }
+
+    private void enableImes() throws Exception {
+        for (String ime : mEnabledImes) {
+            String enableImeCommand = COMMAND_PREFIX_ENABLE_IME + ime;
+            SystemUtil.runShellCommand(getInstrumentation(), enableImeCommand);
+        }
+        mEnabledImes = null;
+    }
+
     @Override
     public void setUp() throws Exception {
         // Make sure we start with a clean slate.
         clearPrintSpoolerData();
         enablePrintServices();
+        disableImes();
 
         // Workaround for dexmaker bug: https://code.google.com/p/dexmaker/issues/detail?id=2
         // Dexmaker is used by mockito.
@@ -130,6 +178,7 @@
     public void tearDown() throws Exception {
         // Done with the activity.
         getActivity().finish();
+        enableImes();
 
         // Restore the locale if needed.
         if (mOldLocale != null) {
diff --git a/tests/tests/telecom/src/android/telecom/cts/BaseTelecomTestWithMockServices.java b/tests/tests/telecom/src/android/telecom/cts/BaseTelecomTestWithMockServices.java
index c862cc3..8423c40 100644
--- a/tests/tests/telecom/src/android/telecom/cts/BaseTelecomTestWithMockServices.java
+++ b/tests/tests/telecom/src/android/telecom/cts/BaseTelecomTestWithMockServices.java
@@ -18,6 +18,10 @@
 
 import static android.telecom.cts.TestUtils.*;
 
+import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.junit.Assert.assertThat;
+
 import android.content.ComponentName;
 import android.content.Context;
 import android.content.Intent;
@@ -37,6 +41,9 @@
 import android.text.TextUtils;
 import android.util.Log;
 
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
 import java.util.concurrent.TimeUnit;
 
 /**
@@ -69,7 +76,7 @@
     TelecomManager mTelecomManager;
     InCallServiceCallbacks mInCallCallbacks;
     String mPreviousDefaultDialer = null;
-    MockConnectionService connectionService = new MockConnectionService();
+    MockConnectionService connectionService;
 
     @Override
     protected void setUp() throws Exception {
@@ -96,13 +103,16 @@
         super.tearDown();
     }
 
-    protected PhoneAccount setupConnectionService(CtsConnectionService connectionService,
+    protected PhoneAccount setupConnectionService(MockConnectionService connectionService,
             int flags)
             throws Exception {
-        if (connectionService == null) {
-            connectionService = this.connectionService;
+        if (connectionService != null) {
+            this.connectionService = connectionService;
+        } else {
+            // Generate a vanilla mock connection service, if not provided.
+            this.connectionService = new MockConnectionService();
         }
-        CtsConnectionService.setUp(TEST_PHONE_ACCOUNT, connectionService);
+        CtsConnectionService.setUp(TEST_PHONE_ACCOUNT, this.connectionService);
 
         if ((flags & FLAG_REGISTER) != 0) {
             mTelecomManager.registerPhoneAccount(TEST_PHONE_ACCOUNT);
@@ -141,6 +151,21 @@
         mInCallCallbacks = new InCallServiceCallbacks() {
             @Override
             public void onCallAdded(Call call, int numCalls) {
+                Log.i(TAG, "onCallAdded, Call: " + call + "Num Calls: " + numCalls);
+                this.lock.release();
+            }
+            @Override
+            public void onParentChanged(Call call, Call parent) {
+                Log.i(TAG, "onParentChanged, Call: " + call + "Parent: " + parent);
+            }
+            @Override
+            public void onChildrenChanged(Call call, List<Call> children) {
+                Log.i(TAG, "onChildrenChanged, Call: " + call + "Childred: " + children);
+            }
+            @Override
+            public void onConferenceableCallsChanged(Call call, List<Call> conferenceableCalls) {
+                Log.i(TAG, "onConferenceableCallsChanged, Call: " + call + "Conferenceables: " +
+                        conferenceableCalls);
                 this.lock.release();
             }
         };
@@ -153,6 +178,11 @@
      * {@link CtsConnectionService} which can be tested.
      */
     void addAndVerifyNewIncomingCall(Uri incomingHandle, Bundle extras) {
+        int currentCallCount = 0;
+        if (mInCallCallbacks.getService() != null) {
+            currentCallCount = mInCallCallbacks.getService().getCallCount();
+        }
+
         if (extras == null) {
             extras = new Bundle();
         }
@@ -167,7 +197,8 @@
             Log.i(TAG, "Test interrupted!");
         }
 
-        assertEquals("InCallService should contain 1 call after adding a call.", 1,
+        assertEquals("InCallService should contain 1 more call after adding a call.",
+                currentCallCount + 1,
                 mInCallCallbacks.getService().getCallCount());
     }
 
@@ -202,6 +233,10 @@
      *  {@link CtsConnectionService} which can be tested.
      */
     void placeAndVerifyCall(Bundle extras, int videoState) {
+        int currentCallCount = 0;
+        if (mInCallCallbacks.getService() != null) {
+            currentCallCount = mInCallCallbacks.getService().getCallCount();
+        }
         placeNewCallWithPhoneAccount(extras, videoState);
 
         try {
@@ -212,11 +247,17 @@
             Log.i(TAG, "Test interrupted!");
         }
 
-        assertEquals("InCallService should contain 1 call after adding a call.", 1,
+        assertEquals("InCallService should contain 1 more call after adding a call.",
+                currentCallCount + 1,
                 mInCallCallbacks.getService().getCallCount());
     }
 
     MockConnection verifyConnectionForOutgoingCall() {
+        // Assuming only 1 connection present
+        return verifyConnectionForOutgoingCall(0);
+    }
+
+    MockConnection verifyConnectionForOutgoingCall(int connectionIndex) {
         try {
             if (!connectionService.lock.tryAcquire(TestUtils.WAIT_FOR_STATE_CHANGE_TIMEOUT_MS,
                     TimeUnit.MILLISECONDS)) {
@@ -226,19 +267,27 @@
             Log.i(TAG, "Test interrupted!");
         }
 
-        assertNotNull("Telecom should create outgoing connection for outgoing call",
-                connectionService.outgoingConnection);
-        assertNull("Telecom should not create incoming connection for outgoing call",
-                connectionService.incomingConnection);
+        assertThat("Telecom should create outgoing connection for outgoing call",
+                connectionService.outgoingConnections.size(), not(equalTo(0)));
+        assertEquals("Telecom should not create incoming connections for outgoing calls",
+                0, connectionService.incomingConnections.size());
+        MockConnection connection = connectionService.outgoingConnections.get(connectionIndex);
+        setAndverifyConnectionForOutgoingCall(connection);
+        return connection;
+    }
 
-        connectionService.outgoingConnection.setDialing();
-        connectionService.outgoingConnection.setActive();
-        assertEquals(Connection.STATE_ACTIVE,
-                connectionService.outgoingConnection.getState());
-        return connectionService.outgoingConnection;
+    void setAndverifyConnectionForOutgoingCall(MockConnection connection) {
+        connection.setDialing();
+        connection.setActive();
+        assertEquals(Connection.STATE_ACTIVE, connection.getState());
     }
 
     MockConnection verifyConnectionForIncomingCall() {
+        // Assuming only 1 connection present
+        return verifyConnectionForIncomingCall(0);
+    }
+
+    MockConnection verifyConnectionForIncomingCall(int connectionIndex) {
         try {
             if (!connectionService.lock.tryAcquire(TestUtils.WAIT_FOR_STATE_CHANGE_TIMEOUT_MS,
                     TimeUnit.MILLISECONDS)) {
@@ -248,15 +297,42 @@
             Log.i(TAG, "Test interrupted!");
         }
 
-        assertNull("Telecom should not create outgoing connection for outgoing call",
-                connectionService.outgoingConnection);
-        assertNotNull("Telecom should create incoming connection for outgoing call",
-                connectionService.incomingConnection);
+        assertThat("Telecom should create incoming connections for incoming calls",
+                connectionService.incomingConnections.size(), not(equalTo(0)));
+        assertEquals("Telecom should not create outgoing connections for incoming calls",
+                0, connectionService.outgoingConnections.size());
+        MockConnection connection = connectionService.incomingConnections.get(connectionIndex);
+        setAndverifyConnectionForIncomingCall(connection);
+        return connection;
+    }
 
-        connectionService.incomingConnection.setRinging();
-        assertEquals(Connection.STATE_RINGING,
-                connectionService.incomingConnection.getState());
-        return connectionService.incomingConnection;
+    void setAndverifyConnectionForIncomingCall(MockConnection connection) {
+        connection.setRinging();
+        assertEquals(Connection.STATE_RINGING, connection.getState());
+    }
+
+    void setAndVerifyConferenceablesForOutgoingConnection(int connectionIndex) {
+        /**
+         * Make all other outgoing connections as conferenceable with this
+         * new connection.
+         */
+        MockConnection connection = connectionService.outgoingConnections.get(connectionIndex);
+        List<Connection> confConnections = new ArrayList<>(connectionService.outgoingConnections.size());
+        for (Connection c : connectionService.outgoingConnections) {
+            if (c != connection) {
+                confConnections.add(c);
+            }
+        }
+        connection.setConferenceableConnections(confConnections);
+
+        try {
+            if (!mInCallCallbacks.lock.tryAcquire(3, TimeUnit.SECONDS)) {
+                fail("No call added to the conferenceables list.");
+            }
+        } catch (InterruptedException e) {
+            Log.i(TAG, "Test interrupted!");
+        }
+        assertEquals(connection.getConferenceables(), confConnections);
     }
 
     /**
@@ -314,6 +390,23 @@
     );
     }
 
+    void assertNumConferenceCalls(final MockInCallService inCallService, final int numCalls) {
+        waitUntilConditionIsTrueOrTimeout(new Condition() {
+            @Override
+            public Object expected() {
+                return numCalls;
+            }
+            @Override
+            public Object actual() {
+                return inCallService.getConferenceCallCount();
+            }
+        },
+        WAIT_FOR_STATE_CHANGE_TIMEOUT_MS,
+        "InCallService should contain " + numCalls + " conference calls."
+    );
+    }
+
+
     void assertMuteState(final InCallService incallService, final boolean isMuted) {
         waitUntilConditionIsTrueOrTimeout(
                 new Condition() {
diff --git a/tests/tests/telecom/src/android/telecom/cts/MockConference.java b/tests/tests/telecom/src/android/telecom/cts/MockConference.java
new file mode 100644
index 0000000..9d20fdd
--- /dev/null
+++ b/tests/tests/telecom/src/android/telecom/cts/MockConference.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.telecom.cts;
+
+import static android.telecom.CallAudioState.*;
+import android.telecom.CallAudioState;
+import android.telecom.Connection;
+import android.telecom.Conference;
+import android.telecom.DisconnectCause;
+import android.telecom.PhoneAccountHandle;
+import android.telecom.VideoProfile;
+import android.util.Log;
+
+/**
+ * {@link Conference} subclass that immediately performs any state changes that are a result of
+ * callbacks sent from Telecom.
+ */
+public class MockConference extends Conference {
+
+    // todo: Dummy implementation for now.
+    public MockConference(PhoneAccountHandle phoneAccount) {
+        super(phoneAccount);
+    }
+}
diff --git a/tests/tests/telecom/src/android/telecom/cts/MockConnection.java b/tests/tests/telecom/src/android/telecom/cts/MockConnection.java
index 460b060..820d6e8 100644
--- a/tests/tests/telecom/src/android/telecom/cts/MockConnection.java
+++ b/tests/tests/telecom/src/android/telecom/cts/MockConnection.java
@@ -20,6 +20,7 @@
 import android.telecom.CallAudioState;
 import android.telecom.Connection;
 import android.telecom.DisconnectCause;
+import android.telecom.PhoneAccountHandle;
 import android.telecom.VideoProfile;
 import android.util.Log;
 
@@ -35,6 +36,7 @@
     public int videoState = VideoProfile.STATE_AUDIO_ONLY;
     private String mDtmfString = "";
     private MockVideoProvider mMockVideoProvider;
+    private PhoneAccountHandle mPhoneAccountHandle;
 
     @Override
     public void onAnswer() {
@@ -154,4 +156,13 @@
     public MockVideoProvider getMockVideoProvider() {
         return mMockVideoProvider;
     }
+
+    public void setPhoneAccountHandle(PhoneAccountHandle handle)  {
+        mPhoneAccountHandle = handle;
+    }
+
+    public PhoneAccountHandle getPhoneAccountHandle()  {
+        return mPhoneAccountHandle;
+    }
+
 }
diff --git a/tests/tests/telecom/src/android/telecom/cts/MockConnectionService.java b/tests/tests/telecom/src/android/telecom/cts/MockConnectionService.java
index 250f197..6bc34d7 100644
--- a/tests/tests/telecom/src/android/telecom/cts/MockConnectionService.java
+++ b/tests/tests/telecom/src/android/telecom/cts/MockConnectionService.java
@@ -18,9 +18,12 @@
 
 import android.telecom.Connection;
 import android.telecom.ConnectionRequest;
+import android.telecom.DisconnectCause;
 import android.telecom.PhoneAccountHandle;
 import android.telecom.TelecomManager;
 
+import java.util.ArrayList;
+import java.util.List;
 import java.util.concurrent.Semaphore;
 
 /**
@@ -39,14 +42,15 @@
     private boolean mCreateVideoProvider = true;
 
     public Semaphore lock = new Semaphore(0);
-    public MockConnection outgoingConnection;
-    public MockConnection incomingConnection;
+    public List<MockConnection> outgoingConnections = new ArrayList<MockConnection>();
+    public List<MockConnection> incomingConnections = new ArrayList<MockConnection>();
 
     @Override
     public Connection onCreateOutgoingConnection(PhoneAccountHandle connectionManagerPhoneAccount,
             ConnectionRequest request) {
         final MockConnection connection = new MockConnection();
         connection.setAddress(request.getAddress(), CONNECTION_PRESENTATION);
+        connection.setPhoneAccountHandle(connectionManagerPhoneAccount);
         if (mCreateVideoProvider) {
             connection.createMockVideoProvider();
         } else {
@@ -54,7 +58,7 @@
         }
         connection.setVideoState(request.getVideoState());
 
-        outgoingConnection = connection;
+        outgoingConnections.add(connection);
         lock.release();
         return connection;
     }
@@ -67,11 +71,21 @@
         connection.createMockVideoProvider();
         connection.setVideoState(request.getVideoState());
 
-        incomingConnection = connection;
+        incomingConnections.add(connection);
         lock.release();
         return connection;
     }
 
+    @Override
+    public void onConference(Connection connection1, Connection connection2) {
+        MockConnection confHost = (MockConnection)connection1;
+        // Create conference and add to telecom
+        MockConference conference = new MockConference(confHost.getPhoneAccountHandle());
+        conference.addConnection(connection1);
+        conference.addConnection(connection2);
+        addConference(conference);
+    }
+
     public void setCreateVideoProvider(boolean createVideoProvider) {
         mCreateVideoProvider = createVideoProvider;
     }
diff --git a/tests/tests/telecom/src/android/telecom/cts/MockInCallService.java b/tests/tests/telecom/src/android/telecom/cts/MockInCallService.java
index e725466..921339e 100644
--- a/tests/tests/telecom/src/android/telecom/cts/MockInCallService.java
+++ b/tests/tests/telecom/src/android/telecom/cts/MockInCallService.java
@@ -27,6 +27,7 @@
 
 public class MockInCallService extends InCallService {
     private ArrayList<Call> mCalls = new ArrayList<>();
+    private ArrayList<Call> mConferenceCalls = new ArrayList<>();
     private static InCallServiceCallbacks sCallbacks;
     private Map<Call, MockVideoCallCallback> mVideoCallCallbacks =
             new ArrayMap<Call, MockVideoCallCallback>();
@@ -40,6 +41,9 @@
         public void onCallAdded(Call call, int numCalls) {};
         public void onCallRemoved(Call call, int numCalls) {};
         public void onCallStateChanged(Call call, int state) {};
+        public void onParentChanged(Call call, Call parent) {};
+        public void onChildrenChanged(Call call, List<Call> children) {};
+        public void onConferenceableCallsChanged(Call call, List<Call> conferenceableCalls) {};
 
         final public MockInCallService getService() {
             return mService;
@@ -68,6 +72,30 @@
             super.onVideoCallChanged(call, videoCall);
             saveVideoCall(call, videoCall);
         }
+
+        @Override
+        public void onParentChanged(Call call, Call parent) {
+            super.onParentChanged(call, parent);
+            if (getCallbacks() != null) {
+                getCallbacks().onParentChanged(call, parent);
+            }
+        }
+
+        @Override
+        public void onChildrenChanged(Call call, List<Call> children) {
+            super.onChildrenChanged(call, children);
+            if (getCallbacks() != null) {
+                getCallbacks().onChildrenChanged(call, children);
+            }
+        }
+
+        @Override
+        public void onConferenceableCallsChanged(Call call, List<Call> conferenceableCalls) {
+            super.onConferenceableCallsChanged(call, conferenceableCalls);
+            if (getCallbacks() != null) {
+                getCallbacks().onConferenceableCallsChanged(call, conferenceableCalls);
+            }
+        }
     };
 
     private void saveVideoCall(Call call, VideoCall videoCall) {
@@ -93,13 +121,19 @@
     @Override
     public void onCallAdded(Call call) {
         super.onCallAdded(call);
-        if (!mCalls.contains(call)) {
-            mCalls.add(call);
-            call.registerCallback(mCallCallback);
-
-            VideoCall videoCall = call.getVideoCall();
-            if (videoCall != null) {
-                saveVideoCall(call, videoCall);
+        if (call.getDetails().hasProperty(Call.Details.PROPERTY_CONFERENCE) == true) {
+            if (!mConferenceCalls.contains(call)) {
+                mConferenceCalls.add(call);
+                call.registerCallback(mCallCallback);
+            }
+        } else {
+            if (!mCalls.contains(call)) {
+                mCalls.add(call);
+                call.registerCallback(mCallCallback);
+                VideoCall videoCall = call.getVideoCall();
+                if (videoCall != null) {
+                    saveVideoCall(call, videoCall);
+                }
             }
         }
         if (getCallbacks() != null) {
@@ -125,15 +159,32 @@
     }
 
     /**
+     * @return the number of conference calls currently added to the {@code InCallService}.
+     */
+    public int getConferenceCallCount() {
+        return mConferenceCalls.size();
+    }
+
+    /**
      * @return the most recently added call that exists inside the {@code InCallService}
      */
     public Call getLastCall() {
-        if (mCalls.size() >= 1) {
+        if (!mCalls.isEmpty()) {
             return mCalls.get(mCalls.size() - 1);
         }
         return null;
     }
 
+    /**
+     * @return the most recently added conference call that exists inside the {@code InCallService}
+     */
+    public Call getLastConferenceCall() {
+        if (!mConferenceCalls.isEmpty()) {
+            return mConferenceCalls.get(mConferenceCalls.size() - 1);
+        }
+        return null;
+    }
+
     public void disconnectLastCall() {
         final Call call = getLastCall();
         if (call != null) {
@@ -141,6 +192,13 @@
         }
     }
 
+    public void disconnectLastConferenceCall() {
+        final Call call = getLastConferenceCall();
+        if (call != null) {
+            call.disconnect();
+        }
+    }
+
     public static void setCallbacks(InCallServiceCallbacks callbacks) {
         synchronized (sLock) {
             sCallbacks = callbacks;
diff --git a/tests/tests/telephony/src/android/telephony/cts/CellInfoTest.java b/tests/tests/telephony/src/android/telephony/cts/CellInfoTest.java
index 5b88525..9a93a60 100644
--- a/tests/tests/telephony/src/android/telephony/cts/CellInfoTest.java
+++ b/tests/tests/telephony/src/android/telephony/cts/CellInfoTest.java
@@ -18,7 +18,9 @@
 import android.content.Context;
 import android.net.ConnectivityManager;
 import android.telephony.CellInfo;
-import android.telephony.PhoneStateListener;
+import android.telephony.CellInfoGsm;
+import android.telephony.CellInfoLte;
+import android.telephony.CellInfoWcdma;
 import android.telephony.TelephonyManager;
 import android.test.AndroidTestCase;
 import android.util.Log;
@@ -36,6 +38,9 @@
     private TelephonyManager mTelephonyManager;
     private static ConnectivityManager mCm;
     private static final String TAG = "android.telephony.cts.CellInfoTest";
+    // Maximum and minimum possible RSSI values(in dbm).
+    private static final int MAX_RRSI = -10;
+    private static final int MIN_RSSI = -150;
 
     @Override
     protected void setUp() throws Exception {
@@ -57,5 +62,66 @@
         assertNotNull("TelephonyManager.getAllCellInfo() returned NULL!", allCellInfo);
         assertTrue("TelephonyManager.getAllCellInfo() returned zero-length list!",
             allCellInfo.size() > 0);
+
+        int numRegisteredCells = 0;
+        for (CellInfo cellInfo : allCellInfo) {
+            if (cellInfo.isRegistered()) {
+                ++numRegisteredCells;
+            }
+            if (cellInfo instanceof CellInfoLte) {
+                verifyLteInfo((CellInfoLte) cellInfo);
+            } else if (cellInfo instanceof CellInfoWcdma) {
+                verifyWcdmaInfo((CellInfoWcdma) cellInfo);
+            } else if (cellInfo instanceof CellInfoGsm) {
+                verifyGsmInfo((CellInfoGsm) cellInfo);
+            }
+        }
+        // At most two cells could be registered.
+        assertTrue("None or too many registered cells : " + numRegisteredCells,
+                numRegisteredCells > 0 && numRegisteredCells <= 2);
+    }
+
+    // Verify lte cell information is within correct range.
+    private void verifyLteInfo(CellInfoLte lte) {
+        verifyRssiDbm(lte.getCellSignalStrength().getDbm());
+        // Verify LTE neighbor information.
+        if (!lte.isRegistered()) {
+            // Only physical cell id is available for LTE neighbor.
+            int pci = lte.getCellIdentity().getPci();
+            // Physical cell id should be within [0, 503].
+            assertTrue("getPci() out of range [0, 503]", pci >= 0 && pci <= 503);
+        }
+    }
+
+    // Verify wcdma cell information is within correct range.
+    private void verifyWcdmaInfo(CellInfoWcdma wcdma) {
+        verifyRssiDbm(wcdma.getCellSignalStrength().getDbm());
+        // Verify wcdma neighbor.
+        if (!wcdma.isRegistered()) {
+            // For wcdma neighbor, only primary scrambling code is available.
+            // Primary scrambling code should be within [0, 511].
+            int psc = wcdma.getCellIdentity().getPsc();
+            assertTrue("getPsc() out of range [0, 511]", psc >= 0 && psc <= 511);
+        }
+    }
+
+    // Verify gsm cell information is within correct range.
+    private void verifyGsmInfo(CellInfoGsm gsm) {
+        verifyRssiDbm(gsm.getCellSignalStrength().getDbm());
+        // Verify gsm neighbor.
+        if (!gsm.isRegistered()) {
+            // lac and cid are available in GSM neighbor information.
+            // Local area code and cellid should be with [0, 65535].
+            int lac = gsm.getCellIdentity().getLac();
+            assertTrue("getLac() out of range [0, 65535]", lac >= 0 && lac <= 65535);
+            int cid = gsm.getCellIdentity().getCid();
+            assertTrue("getCid() out range [0, 65535]", cid >= 0 && cid <= 65535);
+        }
+    }
+
+    // Rssi(in dbm) should be within [MIN_RSSI, MAX_RSSI].
+    private void verifyRssiDbm(int dbm) {
+        assertTrue("getCellSignalStrength().getDbm() out of range",
+                dbm >= MIN_RSSI && dbm <= MAX_RRSI);
     }
 }
diff --git a/tests/tests/util/src/android/util/cts/ArrayMapTest.java b/tests/tests/util/src/android/util/cts/ArrayMapTest.java
index 7fdd0da..130b354 100644
--- a/tests/tests/util/src/android/util/cts/ArrayMapTest.java
+++ b/tests/tests/util/src/android/util/cts/ArrayMapTest.java
@@ -310,7 +310,7 @@
 
     private static void dump(ArrayMap map1, ArrayMap map2) {
         Log.e("test", "ArrayMap of " + map1.size() + " entries:");
-        for (int i=0; i<map2.size(); i++) {
+        for (int i=0; i<map1.size(); i++) {
             Log.e("test", "    " + map1.keyAt(i) + " -> " + map1.valueAt(i));
         }
         Log.e("test", "ArrayMap of " + map2.size() + " entries:");
diff --git a/tests/tests/util/src/android/util/cts/ArraySetTest.java b/tests/tests/util/src/android/util/cts/ArraySetTest.java
new file mode 100644
index 0000000..112459c
--- /dev/null
+++ b/tests/tests/util/src/android/util/cts/ArraySetTest.java
@@ -0,0 +1,495 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.util.cts;
+
+import android.test.AndroidTestCase;
+import android.util.ArraySet;
+import android.util.Log;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+
+// As is the case with ArraySet itself, ArraySetTest borrows heavily from ArrayMapTest.
+
+public class ArraySetTest extends AndroidTestCase {
+    private static final String TAG = "ArraySetTest";
+
+    private static final boolean DEBUG = false;
+
+    private static final int OP_ADD = 1;
+    private static final int OP_REM = 2;
+
+    private static int[] OPS = new int[] {
+            OP_ADD, OP_ADD, OP_ADD, OP_ADD, OP_ADD, OP_ADD, OP_ADD, OP_ADD, OP_ADD,
+            OP_ADD, OP_ADD, OP_ADD, OP_ADD, OP_ADD, OP_ADD, OP_ADD, OP_ADD, OP_ADD,
+            OP_REM, OP_REM, OP_REM, OP_REM, OP_REM, OP_REM, OP_REM, OP_REM, OP_REM,
+            OP_REM, OP_REM, OP_REM, OP_REM, OP_REM, OP_REM, OP_REM, OP_REM, OP_REM,
+
+            OP_ADD, OP_ADD, OP_ADD, OP_ADD, OP_ADD, OP_ADD, OP_ADD, OP_ADD, OP_ADD,
+            OP_REM, OP_REM, OP_REM, OP_REM, OP_REM, OP_REM, OP_REM, OP_REM, OP_REM,
+
+            OP_ADD, OP_ADD, OP_ADD, OP_ADD, OP_ADD, OP_ADD, OP_ADD, OP_ADD, OP_ADD,
+            OP_REM, OP_REM, OP_REM, OP_REM, OP_REM, OP_REM, OP_REM, OP_REM, OP_REM,
+
+            OP_ADD, OP_ADD, OP_ADD, OP_ADD, OP_ADD, OP_ADD, OP_ADD, OP_ADD, OP_ADD,
+            OP_REM, OP_REM, OP_REM, OP_REM, OP_REM, OP_REM, OP_REM, OP_REM, OP_REM,
+
+            OP_ADD, OP_ADD, OP_ADD, OP_ADD, OP_ADD, OP_ADD, OP_ADD, OP_ADD, OP_ADD,
+            OP_ADD, OP_ADD, OP_ADD, OP_ADD, OP_ADD, OP_ADD, OP_ADD, OP_ADD, OP_ADD,
+            OP_ADD, OP_ADD, OP_ADD,
+            OP_REM, OP_REM, OP_REM, OP_REM, OP_REM, OP_REM, OP_REM, OP_REM, OP_REM,
+            OP_REM, OP_REM, OP_REM,
+            OP_REM, OP_REM, OP_REM, OP_REM, OP_REM, OP_REM, OP_REM, OP_REM, OP_REM,
+    };
+
+    private static int[] KEYS = new int[] {
+            // General adding and removing.
+              -1,   1900,    600,    200,   1200,   1500,   1800,    100,   1900,
+            2100,    300,    800,    600,   1100,   1300,   2000,   1000,   1400,
+             600,     -1,   1900,    600,    300,   2100,    200,    800,    800,
+            1800,   1500,   1300,   1100,   2000,   1400,   1000,   1200,   1900,
+
+            // Shrink when removing item from end.
+             100,    200,    300,    400,    500,    600,    700,    800,    900,
+             900,    800,    700,    600,    500,    400,    300,    200,    100,
+
+            // Shrink when removing item from middle.
+             100,    200,    300,    400,    500,    600,    700,    800,    900,
+             900,    800,    700,    600,    500,    400,    200,    300,    100,
+
+            // Shrink when removing item from front.
+             100,    200,    300,    400,    500,    600,    700,    800,    900,
+             900,    800,    700,    600,    500,    400,    100,    200,    300,
+
+            // Test hash collisions.
+             105,    106,    108,    104,    102,    102,    107,      5,    205,
+               4,    202,    203,      3,      5,    101,    109,    200,    201,
+               0,     -1,    100,
+             106,    108,    104,    102,    103,    105,    107,    101,    109,
+              -1,    100,      0,
+               4,      5,      3,      5,    200,    203,    202,    201,    205,
+    };
+
+    public static class ControlledHash {
+        final int mValue;
+
+        ControlledHash(int value) {
+            mValue = value;
+        }
+
+        @Override
+        public final boolean equals(Object o) {
+            if (o == null) {
+                return false;
+            }
+            return mValue == ((ControlledHash)o).mValue;
+        }
+
+        @Override
+        public final int hashCode() {
+            return mValue/100;
+        }
+
+        @Override
+        public final String toString() {
+            return Integer.toString(mValue);
+        }
+    }
+
+    private static boolean compare(Object v1, Object v2) {
+        if (v1 == null) {
+            return v2 == null;
+        }
+        if (v2 == null) {
+            return false;
+        }
+        return v1.equals(v2);
+    }
+
+    private static <E> void compareSets(HashSet<E> set, ArraySet<E> array) {
+        assertEquals("Bad size", set.size(), array.size());
+
+        // Check that every entry in HashSet is in ArraySet.
+        for (E entry : set) {
+            assertTrue("ArraySet missing value: " + entry, array.contains(entry));
+        }
+
+        // Check that every entry in ArraySet is in HashSet using ArraySet.iterator().
+        for (E entry : array) {
+            assertTrue("ArraySet (via iterator) has unexpected value: " + entry,
+                    set.contains(entry));
+        }
+
+        // Check that every entry in ArraySet is in HashSet using ArraySet.valueAt().
+        for (int i = 0; i < array.size(); ++i) {
+            E entry = array.valueAt(i);
+            assertTrue("ArraySet (via valueAt) has unexpected value: " + entry,
+                    set.contains(entry));
+        }
+
+        if (set.hashCode() != array.hashCode()) {
+            assertEquals("Set hash codes differ", set.hashCode(), array.hashCode());
+        }
+
+        assertTrue("HashSet.equals(ArraySet) failed", set.equals(array));
+        assertTrue("ArraySet.equals(HashSet) failed", array.equals(set));
+
+        assertTrue("HashSet.containsAll(ArraySet) failed", set.containsAll(array));
+        assertTrue("ArraySet.containsAll(HashSet) failed", array.containsAll(set));
+    }
+
+    private static <E> void compareArraySetAndRawArray(ArraySet<E> arraySet, Object[] rawArray) {
+        assertEquals("Bad size", arraySet.size(), rawArray.length);
+        for (int i = 0; i < rawArray.length; ++i) {
+            assertEquals("ArraySet<E> and raw array unequal at index " + i,
+                    arraySet.valueAt(i), rawArray[i]);
+        }
+    }
+
+    private static <E> void validateArraySet(ArraySet<E> array) {
+        int index = 0;
+        Iterator<E> iter = array.iterator();
+        while (iter.hasNext()) {
+            E value = iter.next();
+            E realValue = array.valueAt(index);
+            if (!compare(realValue, value)) {
+                fail("Bad array set entry: expected " + realValue
+                        + ", got " + value + " at index " + index);
+            }
+            index++;
+        }
+
+        assertEquals("Length of iteration was unequal to size()", array.size(), index);
+    }
+
+    private static <E> void dump(HashSet<E> set, ArraySet<E> array) {
+        Log.e(TAG, "HashSet of " + set.size() + " entries:");
+        for (E entry : set) {
+            Log.e(TAG, "    " + entry);
+        }
+        Log.e(TAG, "ArraySet of " + array.size() + " entries:");
+        for (int i = 0; i < array.size(); i++) {
+            Log.e(TAG, "    " + array.valueAt(i));
+        }
+    }
+
+    private static void dump(ArraySet set1, ArraySet set2) {
+        Log.e(TAG, "ArraySet of " + set1.size() + " entries:");
+        for (int i = 0; i < set1.size(); i++) {
+            Log.e(TAG, "    " + set1.valueAt(i));
+        }
+        Log.e(TAG, "ArraySet of " + set2.size() + " entries:");
+        for (int i = 0; i < set2.size(); i++) {
+            Log.e(TAG, "    " + set2.valueAt(i));
+        }
+    }
+
+    public void testTest() {
+        assertEquals("OPS and KEYS must be equal length", OPS.length, KEYS.length);
+    }
+
+    public void testBasicArraySet() {
+        HashSet<ControlledHash> hashSet = new HashSet<ControlledHash>();
+        ArraySet<ControlledHash> arraySet = new ArraySet<ControlledHash>();
+
+        for (int i = 0; i < OPS.length; i++) {
+            ControlledHash key = KEYS[i] < 0 ? null : new ControlledHash(KEYS[i]);
+            String strKey = KEYS[i] < 0 ? null : Integer.toString(KEYS[i]);
+            switch (OPS[i]) {
+                case OP_ADD:
+                    if (DEBUG) Log.i(TAG, "Adding key: " + key);
+                    boolean hashAdded = hashSet.add(key);
+                    boolean arrayAdded = arraySet.add(key);
+                    assertEquals("Adding key " + key + " was not symmetric in HashSet and "
+                            + "ArraySet", hashAdded, arrayAdded);
+                    break;
+                case OP_REM:
+                    if (DEBUG) Log.i(TAG, "Removing key: " + key);
+                    boolean hashRemoved = hashSet.remove(key);
+                    boolean arrayRemoved = arraySet.remove(key);
+                    assertEquals("Removing key " + key + " was not symmetric in HashSet and "
+                            + "ArraySet", hashRemoved, arrayRemoved);
+                    break;
+                default:
+                    fail("Bad operation " + OPS[i] + " @ " + i);
+                    return;
+            }
+            if (DEBUG) dump(hashSet, arraySet);
+
+            try {
+                validateArraySet(arraySet);
+            } catch (Throwable e) {
+                Log.e(TAG, e.getMessage());
+                dump(hashSet, arraySet);
+                throw e;
+            }
+
+            try {
+                compareSets(hashSet, arraySet);
+            } catch (Throwable e) {
+                Log.e(TAG, e.getMessage());
+                dump(hashSet, arraySet);
+                throw e;
+            }
+        }
+
+        // Check to see if HashSet.iterator().remove() works as expected.
+        arraySet.add(new ControlledHash(50000));
+        ControlledHash lookup = new ControlledHash(50000);
+        Iterator<ControlledHash> it = arraySet.iterator();
+        while (it.hasNext()) {
+            if (it.next().equals(lookup)) {
+                it.remove();
+            }
+        }
+        if (arraySet.contains(lookup)) {
+            String msg = "Bad ArraySet iterator: didn't remove test key";
+            Log.e(TAG, msg);
+            dump(hashSet, arraySet);
+            fail(msg);
+        }
+
+        Log.e(TAG, "Test successful; printing final map.");
+        dump(hashSet, arraySet);
+    }
+
+    public void testCopyArraySet() {
+        // set copy constructor test
+        ArraySet newSet = new ArraySet<Integer>();
+        for (int i = 0; i < 10; ++i) {
+            newSet.add(i);
+        }
+
+        ArraySet copySet = new ArraySet(newSet);
+        if (!compare(copySet, newSet)) {
+            String msg = "ArraySet copy constructor failure: expected " +
+                    newSet + ", got " + copySet;
+            Log.e(TAG, msg);
+            dump(newSet, copySet);
+            fail(msg);
+            return;
+        }
+    }
+
+    public void testEqualsArrayMap() {
+        ArraySet<Integer> set1 = new ArraySet<Integer>();
+        ArraySet<Integer> set2 = new ArraySet<Integer>();
+        HashSet<Integer> set3 = new HashSet<Integer>();
+        if (!compare(set1, set2) || !compare(set1, set3) || !compare(set3, set2)) {
+            fail("ArraySet equals failure for empty sets " + set1 + ", " +
+                    set2 + ", " + set3);
+        }
+
+        for (int i = 0; i < 10; ++i) {
+            set1.add(i);
+            set2.add(i);
+            set3.add(i);
+        }
+        if (!compare(set1, set2) || !compare(set1, set3) || !compare(set3, set2)) {
+            fail("ArraySet equals failure for populated sets " + set1 + ", " +
+                    set2 + ", " + set3);
+        }
+
+        set1.remove(0);
+        if (compare(set1, set2) || compare(set1, set3) || compare(set3, set1)) {
+            fail("ArraySet equals failure for set size " + set1 + ", " +
+                    set2 + ", " + set3);
+        }
+    }
+
+    public void testIsEmpty() {
+        ArraySet<Integer> set = new ArraySet<Integer>();
+        assertEquals("New ArraySet should have size==0", 0, set.size());
+        assertTrue("New ArraySet should be isEmptry", set.isEmpty());
+
+        set.add(3);
+        assertEquals("ArraySet has incorrect size", 1, set.size());
+        assertFalse("ArraySet should not be isEmptry", set.isEmpty());
+
+        set.remove(3);
+        assertEquals("ArraySet should have size==0", 0, set.size());
+        assertTrue("ArraySet should be isEmptry", set.isEmpty());
+    }
+
+    public void testRemoveAt() {
+        ArraySet<Integer> set = new ArraySet<Integer>();
+
+        for (int i = 0; i < 10; ++i) {
+            set.add(i * 10);
+        }
+
+        int indexToDelete = 6;
+        assertEquals(10, set.size());
+        assertEquals(indexToDelete * 10, set.valueAt(indexToDelete).intValue());
+        assertEquals(indexToDelete * 10, set.removeAt(indexToDelete).intValue());
+        assertEquals(9, set.size());
+
+        for (int i = 0; i < 9; ++i) {
+            int expectedValue = ((i >= indexToDelete) ? (i + 1) : i) * 10;
+            assertEquals(expectedValue, set.valueAt(i).intValue());
+        }
+
+        for (int i = 9; i > 0; --i) {
+            set.removeAt(0);
+            assertEquals(i - 1, set.size());
+        }
+
+        assertTrue(set.isEmpty());
+
+        try {
+            set.removeAt(0);
+            fail("Expected ArrayIndexOutOfBoundsException");
+        } catch (ArrayIndexOutOfBoundsException expected) {
+            // expected
+        }
+    }
+
+    public void testIndexOf() {
+        ArraySet<Integer> set = new ArraySet<Integer>();
+
+        for (int i = 0; i < 10; ++i) {
+            set.add(i * 10);
+        }
+
+        for (int i = 0; i < 10; ++i) {
+            assertEquals("indexOf(" + (i * 10) + ")", i, set.indexOf(i * 10));
+        }
+    }
+
+    public void testAddAll() {
+        ArraySet<Integer> arraySet = new ArraySet<Integer>();
+        ArraySet<Integer> testArraySet = new ArraySet<Integer>();
+        ArrayList<Integer> testArrayList = new ArrayList<Integer>();
+
+        for (int i = 0; i < 10; ++i) {
+            testArraySet.add(i * 10);
+            testArrayList.add(i * 10);
+        }
+
+        assertTrue(arraySet.isEmpty());
+
+        // addAll(ArraySet) has no return value.
+        arraySet.addAll(testArraySet);
+        assertTrue("ArraySet.addAll(ArraySet) failed", arraySet.containsAll(testArraySet));
+
+        arraySet.clear();
+        assertTrue(arraySet.isEmpty());
+
+        // addAll(Collection) returns true if any items were added.
+        assertTrue(arraySet.addAll(testArrayList));
+        assertTrue("ArraySet.addAll(Container) failed", arraySet.containsAll(testArrayList));
+        assertTrue("ArraySet.addAll(Container) failed", arraySet.containsAll(testArraySet));
+        // Adding the same Collection should return false.
+        assertFalse(arraySet.addAll(testArrayList));
+        assertTrue("ArraySet.addAll(Container) failed", arraySet.containsAll(testArrayList));
+    }
+
+    public void testRemoveAll() {
+        ArraySet<Integer> arraySet = new ArraySet<Integer>();
+        ArraySet<Integer> arraySetToRemove = new ArraySet<Integer>();
+        ArrayList<Integer> arrayListToRemove = new ArrayList<Integer>();
+
+        for (int i = 0; i < 10; ++i) {
+            arraySet.add(i * 10);
+        }
+
+        for (int i = 6; i < 15; ++i) {
+            arraySetToRemove.add(i * 10);
+        }
+
+        for (int i = 3; i > -3; --i) {
+            arrayListToRemove.add(i * 10);
+        }
+
+        assertEquals(10, arraySet.size());
+
+        // Remove [6,14] (really [6,9]) via another ArraySet.
+        assertTrue(arraySet.removeAll(arraySetToRemove));
+        assertEquals(6, arraySet.size());
+        assertFalse(arraySet.removeAll(arraySetToRemove));
+        assertEquals(6, arraySet.size());
+
+        // Remove [-2,3] (really [0,3]) via an ArrayList (ie Collection).
+        assertTrue(arraySet.removeAll(arrayListToRemove));
+        assertEquals(2, arraySet.size());
+        assertFalse(arraySet.removeAll(arrayListToRemove));
+        assertEquals(2, arraySet.size());
+
+        // Remove the rest of the items.
+        ArraySet<Integer> copy = new ArraySet<Integer>(arraySet);
+        assertTrue(arraySet.removeAll(copy));
+        assertEquals(0, arraySet.size());
+        assertFalse(arraySet.removeAll(copy));
+        assertEquals(0, arraySet.size());
+    }
+
+    public void testRetainAll() {
+        ArraySet<Integer> arraySet = new ArraySet<Integer>();
+        ArrayList<Integer> arrayListToRetain = new ArrayList<Integer>();
+
+        for (int i = 0; i < 10; ++i) {
+            arraySet.add(i * 10);
+        }
+
+        arrayListToRetain.add(30);
+        arrayListToRetain.add(50);
+        arrayListToRetain.add(51); // bogus value
+
+        assertEquals(10, arraySet.size());
+
+        assertTrue(arraySet.retainAll(arrayListToRetain));
+        assertEquals(2, arraySet.size());
+
+        assertTrue(arraySet.contains(30));
+        assertTrue(arraySet.contains(50));
+        assertFalse(arraySet.contains(51));
+
+        // Nothing should change.
+        assertFalse(arraySet.retainAll(arrayListToRetain));
+        assertEquals(2, arraySet.size());
+    }
+
+    public void testToArray() {
+        ArraySet<Integer> arraySet = new ArraySet<Integer>();
+        for (int i = 0; i < 10; ++i) {
+            arraySet.add(i * 10);
+        }
+
+        // Allocate a new array with the right type given a zero-length ephemeral array.
+        Integer[] copiedArray = arraySet.toArray(new Integer[0]);
+        compareArraySetAndRawArray(arraySet, copiedArray);
+
+        // Allocate a new array with the right type given an undersized array.
+        Integer[] undersizedArray = new Integer[5];
+        copiedArray = arraySet.toArray(undersizedArray);
+        compareArraySetAndRawArray(arraySet, copiedArray);
+        assertNotSame(undersizedArray, copiedArray);
+
+        // Use the passed array that is large enough to hold the ArraySet.
+        Integer[] rightSizedArray = new Integer[10];
+        copiedArray = arraySet.toArray(rightSizedArray);
+        compareArraySetAndRawArray(arraySet, copiedArray);
+        assertSame(rightSizedArray, copiedArray);
+
+        // Create a new Object[] array.
+        Object[] objectArray = arraySet.toArray();
+        compareArraySetAndRawArray(arraySet, objectArray);
+    }
+}
diff --git a/tests/tests/view/AndroidManifest.xml b/tests/tests/view/AndroidManifest.xml
index 65e95d5..b7e0076 100644
--- a/tests/tests/view/AndroidManifest.xml
+++ b/tests/tests/view/AndroidManifest.xml
@@ -92,7 +92,7 @@
         </activity>
 
         <activity android:name="android.view.animation.cts.GridLayoutAnimCtsActivity"
-            android:label="GridLayoutAnimCtsActivity">
+            android:label="GridLayoutAnimCtsActivity" android:configChanges="orientation|screenSize">
             <intent-filter>
                 <action android:name="android.intent.action.MAIN"/>
                 <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST" />
@@ -100,7 +100,7 @@
         </activity>
 
         <activity android:name="android.view.animation.cts.LayoutAnimCtsActivity"
-            android:label="LayoutAnimCtsActivity">
+            android:label="LayoutAnimCtsActivity" android:configChanges="orientation|screenSize">
             <intent-filter>
                 <action android:name="android.intent.action.MAIN"/>
                 <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST" />
diff --git a/tools/cts-api-coverage/src/com/android/cts/apicoverage/ApiClass.java b/tools/cts-api-coverage/src/com/android/cts/apicoverage/ApiClass.java
index 31e1f8d..f5abd5e5 100644
--- a/tools/cts-api-coverage/src/com/android/cts/apicoverage/ApiClass.java
+++ b/tools/cts-api-coverage/src/com/android/cts/apicoverage/ApiClass.java
@@ -34,10 +34,25 @@
 
     private final List<ApiMethod> mApiMethods = new ArrayList<ApiMethod>();
 
-    ApiClass(String name, boolean deprecated, boolean classAbstract) {
+    private final String mSuperClassName;
+
+    private ApiClass mSuperClass;
+
+    /**
+     * @param name The name of the class
+     * @param deprecated true iff the class is marked as deprecated
+     * @param classAbstract true iff the class is abstract
+     * @param superClassName The fully qualified name of the super class
+     */
+    ApiClass(
+            String name,
+            boolean deprecated,
+            boolean classAbstract,
+            String superClassName) {
         mName = name;
         mDeprecated = deprecated;
         mAbstract = classAbstract;
+        mSuperClassName = superClassName;
     }
 
     @Override
@@ -54,22 +69,20 @@
         return mDeprecated;
     }
 
+    public String getSuperClassName() {
+        return mSuperClassName;
+    }
+
     public boolean isAbstract() {
         return mAbstract;
     }
 
+    public void setSuperClass(ApiClass superClass) { mSuperClass = superClass; }
+
     public void addConstructor(ApiConstructor constructor) {
         mApiConstructors.add(constructor);
     }
 
-    public ApiConstructor getConstructor(List<String> parameterTypes) {
-        for (ApiConstructor constructor : mApiConstructors) {
-            if (parameterTypes.equals(constructor.getParameterTypes())) {
-                return constructor;
-            }
-        }
-        return null;
-    }
 
     public Collection<ApiConstructor> getConstructors() {
         return Collections.unmodifiableList(mApiConstructors);
@@ -79,15 +92,29 @@
         mApiMethods.add(method);
     }
 
-    public ApiMethod getMethod(String name, List<String> parameterTypes, String returnType) {
-        for (ApiMethod method : mApiMethods) {
-            if (name.equals(method.getName())
-                    && parameterTypes.equals(method.getParameterTypes())
-                    && returnType.equals(method.getReturnType())) {
-                return method;
-            }
+    /** Look for a matching constructor and mark it as covered */
+    public void markConstructorCovered(List<String> parameterTypes) {
+        if (mSuperClass != null) {
+            // Mark matching constructors in the superclass
+            mSuperClass.markConstructorCovered(parameterTypes);
         }
-        return null;
+        ApiConstructor apiConstructor = getConstructor(parameterTypes);
+        if (apiConstructor != null) {
+            apiConstructor.setCovered(true);
+        }
+
+    }
+
+    /** Look for a matching method and if found and mark it as covered */
+    public void markMethodCovered(String name, List<String> parameterTypes, String returnType) {
+        if (mSuperClass != null) {
+            // Mark matching methods in the super class
+            mSuperClass.markMethodCovered(name, parameterTypes, returnType);
+        }
+        ApiMethod apiMethod = getMethod(name, parameterTypes, returnType);
+        if (apiMethod != null) {
+            apiMethod.setCovered(true);
+        }
     }
 
     public Collection<ApiMethod> getMethods() {
@@ -126,4 +153,24 @@
     public int getMemberSize() {
         return getTotalMethods();
     }
+
+    private ApiMethod getMethod(String name, List<String> parameterTypes, String returnType) {
+        for (ApiMethod method : mApiMethods) {
+            if (name.equals(method.getName())
+                    && parameterTypes.equals(method.getParameterTypes())
+                    && returnType.equals(method.getReturnType())) {
+                return method;
+            }
+        }
+        return null;
+    }
+
+    private ApiConstructor getConstructor(List<String> parameterTypes) {
+        for (ApiConstructor constructor : mApiConstructors) {
+            if (parameterTypes.equals(constructor.getParameterTypes())) {
+                return constructor;
+            }
+        }
+        return null;
+    }
 }
diff --git a/tools/cts-api-coverage/src/com/android/cts/apicoverage/ApiCoverage.java b/tools/cts-api-coverage/src/com/android/cts/apicoverage/ApiCoverage.java
index adf2ea9..953aab3 100644
--- a/tools/cts-api-coverage/src/com/android/cts/apicoverage/ApiCoverage.java
+++ b/tools/cts-api-coverage/src/com/android/cts/apicoverage/ApiCoverage.java
@@ -39,10 +39,11 @@
         return Collections.unmodifiableCollection(mPackages.values());
     }
 
-    public void removeEmptyAbstractClasses() {
+    /** Iterate through all packages and update all classes to include its superclass */
+    public void resolveSuperClasses() {
         for (Map.Entry<String, ApiPackage> entry : mPackages.entrySet()) {
             ApiPackage pkg = entry.getValue();
-            pkg.removeEmptyAbstractClasses();
+            pkg.resolveSuperClasses(mPackages);
         }
     }
 }
diff --git a/tools/cts-api-coverage/src/com/android/cts/apicoverage/ApiMethod.java b/tools/cts-api-coverage/src/com/android/cts/apicoverage/ApiMethod.java
index 053cd12..582c2b6 100644
--- a/tools/cts-api-coverage/src/com/android/cts/apicoverage/ApiMethod.java
+++ b/tools/cts-api-coverage/src/com/android/cts/apicoverage/ApiMethod.java
@@ -29,15 +29,35 @@
 
     private final String mReturnType;
 
-    private boolean mDeprecated;
+    private final boolean mDeprecated;
+
+    private final String mVisibility;
+
+    private final boolean mStaticMethod;
+
+    private final boolean mFinalMethod;
+
+    private final boolean mAbstractMethod;
 
     private boolean mIsCovered;
 
-    ApiMethod(String name, List<String> parameterTypes, String returnType, boolean deprecated) {
+    ApiMethod(
+            String name,
+            List<String> parameterTypes,
+            String returnType,
+            boolean deprecated,
+            String visibility,
+            boolean staticMethod,
+            boolean finalMethod,
+            boolean abstractMethod) {
         mName = name;
         mParameterTypes = new ArrayList<String>(parameterTypes);
         mReturnType = returnType;
         mDeprecated = deprecated;
+        mVisibility = visibility;
+        mStaticMethod = staticMethod;
+        mFinalMethod = finalMethod;
+        mAbstractMethod = abstractMethod;
     }
 
     @Override
@@ -65,6 +85,14 @@
         return mIsCovered;
     }
 
+    public String getVisibility() { return mVisibility; }
+
+    public boolean isAbstractMethod() { return mAbstractMethod; }
+
+    public boolean isStaticMethod() { return mStaticMethod; }
+
+    public boolean isFinalMethod() { return mFinalMethod; }
+
     public void setCovered(boolean covered) {
         mIsCovered = covered;
     }
diff --git a/tools/cts-api-coverage/src/com/android/cts/apicoverage/ApiPackage.java b/tools/cts-api-coverage/src/com/android/cts/apicoverage/ApiPackage.java
index e0bf73f..7be7e3c 100644
--- a/tools/cts-api-coverage/src/com/android/cts/apicoverage/ApiPackage.java
+++ b/tools/cts-api-coverage/src/com/android/cts/apicoverage/ApiPackage.java
@@ -77,14 +77,26 @@
         return getTotalMethods();
     }
 
-    public void removeEmptyAbstractClasses() {
+    /** Iterate through all classes and add superclass. */
+    public void resolveSuperClasses(Map<String, ApiPackage> packageMap) {
         Iterator<Entry<String, ApiClass>> it = mApiClassMap.entrySet().iterator();
         while (it.hasNext()) {
             Map.Entry<String, ApiClass> entry = it.next();
-            ApiClass cls = entry.getValue();
-            if (cls.isAbstract() && (cls.getTotalMethods() == 0)) {
-                // this is essentially interface
-                it.remove();
+            ApiClass apiClass = entry.getValue();
+            if (apiClass.getSuperClassName() != null) {
+                String superClassName = apiClass.getSuperClassName();
+                // Split the fully qualified class name into package and class name.
+                String packageName = superClassName.substring(0, superClassName.lastIndexOf('.'));
+                String className = superClassName.substring(
+                        superClassName.lastIndexOf('.') + 1, superClassName.length());
+                if (packageMap.containsKey(packageName)) {
+                    ApiPackage apiPackage = packageMap.get(packageName);
+                    ApiClass superClass = apiPackage.getClass(className);
+                    if (superClass != null) {
+                        // Add the super class
+                        apiClass.setSuperClass(superClass);
+                    }
+                }
             }
         }
     }
diff --git a/tools/cts-api-coverage/src/com/android/cts/apicoverage/CtsApiCoverage.java b/tools/cts-api-coverage/src/com/android/cts/apicoverage/CtsApiCoverage.java
index 05cb4e19..3f2f353 100644
--- a/tools/cts-api-coverage/src/com/android/cts/apicoverage/CtsApiCoverage.java
+++ b/tools/cts-api-coverage/src/com/android/cts/apicoverage/CtsApiCoverage.java
@@ -117,7 +117,8 @@
          */
 
         ApiCoverage apiCoverage = getEmptyApiCoverage(apiXmlPath);
-        apiCoverage.removeEmptyAbstractClasses();
+        // Add superclass information into api coverage.
+        apiCoverage.resolveSuperClasses();
         for (File testApk : testApks) {
             addApiCoverage(apiCoverage, testApk, dexDeps);
         }
diff --git a/tools/cts-api-coverage/src/com/android/cts/apicoverage/CurrentXmlHandler.java b/tools/cts-api-coverage/src/com/android/cts/apicoverage/CurrentXmlHandler.java
index b9f9e9c..de9f5d5 100644
--- a/tools/cts-api-coverage/src/com/android/cts/apicoverage/CurrentXmlHandler.java
+++ b/tools/cts-api-coverage/src/com/android/cts/apicoverage/CurrentXmlHandler.java
@@ -40,6 +40,12 @@
 
     private boolean mCurrentMethodIsAbstract;
 
+    private String mCurrentMethodVisibility;
+
+    private boolean mCurrentMethodStaticMethod;
+
+    private boolean mCurrentMethodFinalMethod;
+
     private boolean mDeprecated;
 
 
@@ -69,7 +75,9 @@
             mIgnoreCurrentClass = false;
             mCurrentClassName = getValue(attributes, "name");
             mDeprecated = isDeprecated(attributes);
-            ApiClass apiClass = new ApiClass(mCurrentClassName, mDeprecated, isAbstract(attributes));
+            String superClass = attributes.getValue("extends");
+            ApiClass apiClass = new ApiClass(
+                    mCurrentClassName, mDeprecated, is(attributes, "abstract"), superClass);
             ApiPackage apiPackage = mApiCoverage.getPackage(mCurrentPackageName);
             apiPackage.addClass(apiClass);
         } else if ("interface".equalsIgnoreCase(localName)) {
@@ -82,7 +90,10 @@
             mDeprecated = isDeprecated(attributes);
             mCurrentMethodName = getValue(attributes, "name");
             mCurrentMethodReturnType = getValue(attributes, "return");
-            mCurrentMethodIsAbstract = isAbstract(attributes);
+            mCurrentMethodIsAbstract = is(attributes, "abstract");
+            mCurrentMethodVisibility = getValue(attributes, "visibility");
+            mCurrentMethodStaticMethod = is(attributes, "static");
+            mCurrentMethodFinalMethod = is(attributes, "final");
             mCurrentParameterTypes.clear();
         } else if ("parameter".equalsIgnoreCase(localName)) {
             mCurrentParameterTypes.add(getValue(attributes, "type"));
@@ -107,11 +118,15 @@
             ApiClass apiClass = apiPackage.getClass(mCurrentClassName);
             apiClass.addConstructor(apiConstructor);
         }  else if ("method".equalsIgnoreCase(localName)) {
-            if (mCurrentMethodIsAbstract) { // do not add abstract method
-                return;
-            }
-            ApiMethod apiMethod = new ApiMethod(mCurrentMethodName, mCurrentParameterTypes,
-                    mCurrentMethodReturnType, mDeprecated);
+            ApiMethod apiMethod = new ApiMethod(
+                    mCurrentMethodName,
+                    mCurrentParameterTypes,
+                    mCurrentMethodReturnType,
+                    mDeprecated,
+                    mCurrentMethodVisibility,
+                    mCurrentMethodStaticMethod,
+                    mCurrentMethodFinalMethod,
+                    mCurrentMethodIsAbstract);
             ApiPackage apiPackage = mApiCoverage.getPackage(mCurrentPackageName);
             ApiClass apiClass = apiPackage.getClass(mCurrentClassName);
             apiClass.addMethod(apiMethod);
@@ -129,8 +144,8 @@
         return "deprecated".equals(attributes.getValue("deprecated"));
     }
 
-    private boolean isAbstract(Attributes attributes) {
-        return "true".equals(attributes.getValue("abstract"));
+    private static boolean is(Attributes attributes, String valueName) {
+        return "true".equals(attributes.getValue(valueName));
     }
 
     private boolean isEnum(Attributes attributes) {
diff --git a/tools/cts-api-coverage/src/com/android/cts/apicoverage/DexDepsXmlHandler.java b/tools/cts-api-coverage/src/com/android/cts/apicoverage/DexDepsXmlHandler.java
index 0a90bdd..3df532e 100644
--- a/tools/cts-api-coverage/src/com/android/cts/apicoverage/DexDepsXmlHandler.java
+++ b/tools/cts-api-coverage/src/com/android/cts/apicoverage/DexDepsXmlHandler.java
@@ -73,10 +73,7 @@
             if (apiPackage != null) {
                 ApiClass apiClass = apiPackage.getClass(mCurrentClassName);
                 if (apiClass != null) {
-                    ApiConstructor apiConstructor = apiClass.getConstructor(mCurrentParameterTypes);
-                    if (apiConstructor != null) {
-                        apiConstructor.setCovered(true);
-                    }
+                    apiClass.markConstructorCovered(mCurrentParameterTypes);
                 }
             }
         }  else if ("method".equalsIgnoreCase(localName)) {
@@ -84,11 +81,8 @@
             if (apiPackage != null) {
                 ApiClass apiClass = apiPackage.getClass(mCurrentClassName);
                 if (apiClass != null) {
-                    ApiMethod apiMethod = apiClass.getMethod(mCurrentMethodName,
-                            mCurrentParameterTypes, mCurrentMethodReturnType);
-                    if (apiMethod != null) {
-                        apiMethod.setCovered(true);
-                    }
+                    apiClass.markMethodCovered(
+                            mCurrentMethodName, mCurrentParameterTypes, mCurrentMethodReturnType);
                 }
             }
         }
diff --git a/tools/cts-api-coverage/src/com/android/cts/apicoverage/TextReport.java b/tools/cts-api-coverage/src/com/android/cts/apicoverage/TextReport.java
index e3e2e7c..3adc020 100644
--- a/tools/cts-api-coverage/src/com/android/cts/apicoverage/TextReport.java
+++ b/tools/cts-api-coverage/src/com/android/cts/apicoverage/TextReport.java
@@ -103,7 +103,18 @@
     private static void printMethod(ApiMethod method, PrintStream out) {
         StringBuilder builder = new StringBuilder("    [")
                 .append(method.isCovered() ? "X" : " ")
-                .append("] ").append(method.getReturnType()).append(" ")
+                .append("] ")
+                .append(method.getVisibility()).append(" ");
+        if (method.isAbstractMethod()) {
+            builder.append("abstract ");
+        }
+        if (method.isStaticMethod()) {
+            builder.append("static ");
+        }
+        if (method.isFinalMethod()) {
+            builder.append("final ");
+        }
+        builder.append(method.getReturnType()).append(" ")
                 .append(method.getName()).append("(");
         List<String> parameterTypes = method.getParameterTypes();
         int numParameterTypes = parameterTypes.size();
diff --git a/tools/cts-api-coverage/src/com/android/cts/apicoverage/XmlReport.java b/tools/cts-api-coverage/src/com/android/cts/apicoverage/XmlReport.java
index 570b316..4310d20 100644
--- a/tools/cts-api-coverage/src/com/android/cts/apicoverage/XmlReport.java
+++ b/tools/cts-api-coverage/src/com/android/cts/apicoverage/XmlReport.java
@@ -66,7 +66,7 @@
                         + "\" numCovered=\"" + pkgTotalCovered
                         + "\" numTotal=\"" + pkgTotal
                         + "\" coveragePercentage=\""
-                            + Math.round(pkg.getCoveragePercentage())
+                        + Math.round(pkg.getCoveragePercentage())
                         + "\">");
 
                 List<ApiClass> classes = new ArrayList<ApiClass>(pkg.getClasses());
@@ -103,6 +103,10 @@
                             out.println("<method name=\"" + method.getName()
                                     + "\" returnType=\"" + method.getReturnType()
                                     + "\" deprecated=\"" + method.isDeprecated()
+                                    + "\" static=\"" + method.isStaticMethod()
+                                    + "\" final=\"" + method.isFinalMethod()
+                                    + "\" visibility=\"" + method.getVisibility()
+                                    + "\" abstract=\"" + method.isAbstractMethod()
                                     + "\" covered=\"" + method.isCovered() + "\">");
                             if (method.isDeprecated()) {
                                 if (method.isCovered()) {
diff --git a/tools/cts-api-coverage/src/res/api-coverage.xsl b/tools/cts-api-coverage/src/res/api-coverage.xsl
index b11a8c4..1a56eb0 100644
--- a/tools/cts-api-coverage/src/res/api-coverage.xsl
+++ b/tools/cts-api-coverage/src/res/api-coverage.xsl
@@ -101,14 +101,17 @@
                     <xsl:for-each select="api-coverage/api/package">
                         <xsl:call-template name="packageOrClassListItem">
                             <xsl:with-param name="bulletClass" select="'package'" />
+                            <xsl:with-param name="toggleId" select="@name" />
                         </xsl:call-template>
                         <div class="packageDetails" id="{@name}" style="display: none">
                             <ul>
                                 <xsl:for-each select="class">
+                                    <xsl:variable name="packageClassId" select="concat(../@name, '.', @name)"/>
                                     <xsl:call-template name="packageOrClassListItem">
                                         <xsl:with-param name="bulletClass" select="'class'" />
+                                        <xsl:with-param name="toggleId" select="$packageClassId" />
                                     </xsl:call-template>
-                                    <div class="classDetails" id="{@name}" style="display: none">
+                                    <div class="classDetails" id="{$packageClassId}" style="display: none">
                                         <xsl:for-each select="constructor">
                                             <xsl:call-template name="methodListItem" />
                                         </xsl:for-each>
@@ -124,9 +127,10 @@
             </body>
         </html>
     </xsl:template>
-    
+
     <xsl:template name="packageOrClassListItem">
         <xsl:param name="bulletClass" />
+        <xsl:param name="toggleId"/>
 
         <xsl:variable name="colorClass">
             <xsl:choose>
@@ -135,7 +139,7 @@
                 <xsl:otherwise>green</xsl:otherwise>
             </xsl:choose>
         </xsl:variable>
-        
+
         <xsl:variable name="deprecatedClass">
             <xsl:choose>
                 <xsl:when test="@deprecated = 'true'">deprecated</xsl:when>
@@ -143,15 +147,15 @@
             </xsl:choose>
         </xsl:variable>
 
-        <li class="{$bulletClass}" onclick="toggleVisibility('{@name}')">
+        <li class="{$bulletClass}" onclick="toggleVisibility('{$toggleId}')">
             <span class="{$colorClass} {$deprecatedClass}">
                 <b><xsl:value-of select="@name" /></b>
                 &nbsp;<xsl:value-of select="@coveragePercentage" />%
                 &nbsp;(<xsl:value-of select="@numCovered" />/<xsl:value-of select="@numTotal" />)
             </span>
-        </li>   
+        </li>
     </xsl:template>
-  
+
   <xsl:template name="methodListItem">
 
     <xsl:variable name="deprecatedClass">
@@ -166,6 +170,10 @@
         <xsl:when test="@covered = 'true'">[X]</xsl:when>
         <xsl:otherwise>[ ]</xsl:otherwise>
       </xsl:choose>
+      <xsl:if test="@visibility != ''">&nbsp;<xsl:value-of select="@visibility" /></xsl:if>
+      <xsl:if test="@abstract = 'true'">&nbsp;abstract</xsl:if>
+      <xsl:if test="@static = 'true'">&nbsp;static</xsl:if>
+      <xsl:if test="@final = 'true'">&nbsp;final</xsl:if>
       <xsl:if test="@returnType != ''">&nbsp;<xsl:value-of select="@returnType" /></xsl:if>
       <b>&nbsp;<xsl:value-of select="@name" /></b><xsl:call-template name="formatParameters" />
     </span>
diff --git a/tools/utils/buildCts.py b/tools/utils/buildCts.py
index e7a2f3c..0531c49 100755
--- a/tools/utils/buildCts.py
+++ b/tools/utils/buildCts.py
@@ -503,6 +503,11 @@
           'android.content.cts.ContentResolverTest#testUnstableToStableRefs',
           'android.content.cts.ContentResolverTest#testUpdate',
           'android.content.cts.ContentResolverTest#testValidateSyncExtrasBundle',],
+      'android.bluetooth' : [
+          'android.bluetooth.cts.BluetoothLeScanTest#testBasicBleScan',
+          'android.bluetooth.cts.BluetoothLeScanTest#testBatchScan',
+          'android.bluetooth.cts.BluetoothLeScanTest#testOpportunisticScan',
+          'android.bluetooth.cts.BluetoothLeScanTest#testScanFilter',],
       '' : []}
 
 def LogGenerateDescription(name):