Merge "Updating metadata for TextSwitcher sample" into lmp-docs
diff --git a/admin/AppRestrictionEnforcer/Application/src/main/res/layout/fragment_setup_profile.xml b/admin/AppRestrictionEnforcer/Application/src/main/res/layout/fragment_setup_profile.xml
index e9e9fe8..8fde91f 100644
--- a/admin/AppRestrictionEnforcer/Application/src/main/res/layout/fragment_setup_profile.xml
+++ b/admin/AppRestrictionEnforcer/Application/src/main/res/layout/fragment_setup_profile.xml
@@ -20,7 +20,7 @@
     android:layout_height="match_parent"
     tools:context="com.example.android.basicmanagedprofile.MainActivity.MainFragment">
 
-    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    <LinearLayout
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:orientation="vertical"
diff --git a/admin/AppRestrictionEnforcer/Application/tests/src/com/example/android/apprestrictionenforcer/tests/SampleTests.java b/admin/AppRestrictionEnforcer/Application/tests/src/com/example/android/apprestrictionenforcer/tests/SampleTests.java
index fbed64a..0404d95 100644
--- a/admin/AppRestrictionEnforcer/Application/tests/src/com/example/android/apprestrictionenforcer/tests/SampleTests.java
+++ b/admin/AppRestrictionEnforcer/Application/tests/src/com/example/android/apprestrictionenforcer/tests/SampleTests.java
@@ -1,22 +1,4 @@
 /*
-* Copyright 2013 The Android Open Source Project
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-
-
-/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
@@ -43,7 +25,7 @@
 public class SampleTests extends ActivityInstrumentationTestCase2<MainActivity> {
 
     private MainActivity mTestActivity;
-    private AppRestrictionEnforcerFragment mTestFragment;
+    private SetupProfileFragment mTestFragment;
 
     public SampleTests() {
         super(MainActivity.class);
@@ -58,8 +40,8 @@
         // flags = {@link Intent#FLAG_ACTIVITY_NEW_TASK}
         // All other fields are null or empty.
         mTestActivity = getActivity();
-        mTestFragment = (AppRestrictionEnforcerFragment)
-            mTestActivity.getSupportFragmentManager().getFragments().get(1);
+        mTestFragment = (SetupProfileFragment)
+            mTestActivity.getSupportFragmentManager().getFragments().get(0);
     }
 
     /**
@@ -76,4 +58,4 @@
     * Add more tests below.
     */
 
-}
\ No newline at end of file
+}
diff --git a/admin/BasicManagedProfile/Application/src/main/res/layout/fragment_setup_profile.xml b/admin/BasicManagedProfile/Application/src/main/res/layout/fragment_setup_profile.xml
index 2aaaa93..6b1e0d3 100644
--- a/admin/BasicManagedProfile/Application/src/main/res/layout/fragment_setup_profile.xml
+++ b/admin/BasicManagedProfile/Application/src/main/res/layout/fragment_setup_profile.xml
@@ -20,7 +20,7 @@
     android:layout_height="match_parent"
     tools:context="com.example.android.basicmanagedprofile.MainActivity.MainFragment">
 
-    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    <LinearLayout
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:orientation="vertical"
diff --git a/wearable/wear/GridViewPager/Application/.gitignore b/admin/DeviceOwner/Application/.gitignore
similarity index 91%
rename from wearable/wear/GridViewPager/Application/.gitignore
rename to admin/DeviceOwner/Application/.gitignore
index 6eb878d..1bac3a5 100644
--- a/wearable/wear/GridViewPager/Application/.gitignore
+++ b/admin/DeviceOwner/Application/.gitignore
@@ -1,4 +1,4 @@
-# Copyright 2013 The Android Open Source Project
+# 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.
diff --git a/admin/DeviceOwner/Application/README-fragmentview.txt b/admin/DeviceOwner/Application/README-fragmentview.txt
new file mode 100644
index 0000000..b346a5f
--- /dev/null
+++ b/admin/DeviceOwner/Application/README-fragmentview.txt
@@ -0,0 +1,37 @@
+<!--
+        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.
+-->
+
+Steps to implement FragmentView template:
+-in template-params.xml.ftl:
+    -add the following line to common imports
+        <common src="activities"/>
+
+-Add a Fragment to show behavior.  In your MainActivity.java class, it will reference a Fragment
+ called (yourProjectName)Fragment.java.  Create that file in your project, using the "main" source
+ folder instead of "common" or "templates".
+   For instance, if your package name is com.example.foo, create the file
+   src/main/java/com/example/foo/FooFragment.java
+
+
+-Within this fragment, make sure that the onCreate method has the line
+ "setHasOptionsMenu(true);", to enable the fragment to handle menu events.
+
+-In order to override menu events, override onOptionsItemSelected.
+
+-refer to sampleSamples/fragmentViewSample for a reference implementation of a
+project built on this template.
+
+
diff --git a/admin/DeviceOwner/Application/README-singleview.txt b/admin/DeviceOwner/Application/README-singleview.txt
new file mode 100644
index 0000000..57fa134
--- /dev/null
+++ b/admin/DeviceOwner/Application/README-singleview.txt
@@ -0,0 +1,47 @@
+<#--
+        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.
+-->
+
+Steps to implement SingleView template:
+-in template-params.xml.ftl:
+    -add the following line to common imports
+        <common src="activities"/>
+
+    -add a string for the action button's text using the element name "sample_action".
+    This element should be a child of <strings>:
+        <strings>
+        ...
+        <sample_action>ButtonText</sample_action>
+        ...
+        </strings>
+
+
+
+-Add a Fragment to handle behavior.  In your MainActivity.java class, it will reference a Fragment
+ called (yourProjectName)Fragment.java.  Create that file in your project, using the "main" source
+ folder instead of "common" or "templates".
+   For instance, if your package name is com.example.foo, create the file
+   src/main/java/com/example/foo/FooFragment.java
+
+
+-Within this fragment, make sure that the onCreate method has the line
+ "setHasOptionsMenu(true);", to enable the fragment to handle menu events.
+
+-In order to override menu events, override onOptionsItemSelected.
+
+-refer to sampleSamples/singleViewSample for a reference implementation of a
+project built on this template.
+
+
diff --git a/wearable/wear/GridViewPager/Application/proguard-project.txt b/admin/DeviceOwner/Application/proguard-project.txt
similarity index 91%
rename from wearable/wear/GridViewPager/Application/proguard-project.txt
rename to admin/DeviceOwner/Application/proguard-project.txt
index 0d8f171..f2fe155 100644
--- a/wearable/wear/GridViewPager/Application/proguard-project.txt
+++ b/admin/DeviceOwner/Application/proguard-project.txt
@@ -1,4 +1,4 @@
- To enable ProGuard in your project, edit project.properties
+# To enable ProGuard in your project, edit project.properties
 # to define the proguard.config property as described in that file.
 #
 # Add project specific ProGuard rules here.
diff --git a/admin/DeviceOwner/Application/src/main/AndroidManifest.xml b/admin/DeviceOwner/Application/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..fb61ac9
--- /dev/null
+++ b/admin/DeviceOwner/Application/src/main/AndroidManifest.xml
@@ -0,0 +1,54 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ 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.
+-->
+<manifest
+    package="com.example.android.deviceowner"
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:versionCode="1"
+    android:versionName="1.0">
+
+    <application
+        android:allowBackup="true"
+        android:icon="@drawable/ic_launcher"
+        android:label="@string/app_name"
+        android:theme="@style/AppTheme">
+
+        <activity
+            android:name=".MainActivity"
+            android:label="@string/app_name">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN"/>
+                <category android:name="android.intent.category.LAUNCHER"/>
+            </intent-filter>
+        </activity>
+
+        <receiver
+            android:name=".DeviceOwnerReceiver"
+            android:description="@string/app_name"
+            android:label="@string/app_name"
+            android:permission="android.permission.BIND_DEVICE_ADMIN">
+            <meta-data
+                android:name="android.app.device_admin"
+                android:resource="@xml/device_owner_receiver"/>
+            <intent-filter>
+                <action android:name="android.app.action.PROFILE_PROVISIONING_COMPLETE"/>
+            </intent-filter>
+        </receiver>
+
+    </application>
+
+
+</manifest>
diff --git a/admin/DeviceOwner/Application/src/main/java/com/example/android/deviceowner/DeviceOwnerFragment.java b/admin/DeviceOwner/Application/src/main/java/com/example/android/deviceowner/DeviceOwnerFragment.java
new file mode 100644
index 0000000..b5c6254
--- /dev/null
+++ b/admin/DeviceOwner/Application/src/main/java/com/example/android/deviceowner/DeviceOwnerFragment.java
@@ -0,0 +1,334 @@
+/*
+ * 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.example.android.deviceowner;
+
+import android.app.Activity;
+import android.app.Fragment;
+import android.app.admin.DevicePolicyManager;
+import android.content.ComponentName;
+import android.content.ContentResolver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.SharedPreferences;
+import android.content.pm.ResolveInfo;
+import android.os.Bundle;
+import android.provider.Settings;
+import android.support.annotation.Nullable;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Button;
+import android.widget.CompoundButton;
+import android.widget.SimpleAdapter;
+import android.widget.Spinner;
+import android.widget.Switch;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+/**
+ * Demonstrates the usage of the most common device management APIs for the device owner case.
+ * In addition to various features available for profile owners, device owners can perform extra
+ * actions, such as configuring global settings and enforcing a preferred Activity for a specific
+ * IntentFilter.
+ */
+public class DeviceOwnerFragment extends Fragment {
+
+    // Keys for SharedPreferences
+    private static final String PREFS_DEVICE_OWNER = "DeviceOwnerFragment";
+    private static final String PREF_LAUNCHER = "launcher";
+
+    private DevicePolicyManager mDevicePolicyManager;
+
+    // View references
+    private Switch mSwitchAutoTime;
+    private Switch mSwitchAutoTimeZone;
+    private Spinner mAvailableLaunchers;
+    private Button mButtonLauncher;
+
+    // Adapter for the spinner to show list of available launchers
+    private LauncherAdapter mAdapter;
+
+    /**
+     * Handles events on the Switches.
+     */
+    private Switch.OnCheckedChangeListener mOnCheckedChangeListener
+            = new Switch.OnCheckedChangeListener() {
+
+        @Override
+        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
+            switch (buttonView.getId()) {
+                case R.id.switch_auto_time:
+                    setBooleanGlobalSetting(Settings.Global.AUTO_TIME, isChecked);
+                    retrieveCurrentSettings(getActivity());
+                    break;
+                case R.id.switch_auto_time_zone:
+                    setBooleanGlobalSetting(Settings.Global.AUTO_TIME_ZONE, isChecked);
+                    retrieveCurrentSettings(getActivity());
+                    break;
+            }
+        }
+
+    };
+
+    /**
+     * Handles click events on the Button.
+     */
+    private View.OnClickListener mOnClickListener
+            = new View.OnClickListener() {
+
+        @Override
+        public void onClick(View v) {
+            switch (v.getId()) {
+                case R.id.set_preferred_launcher:
+                    if (loadPersistentPreferredLauncher(getActivity()) == null) {
+                        setPreferredLauncher();
+                    } else {
+                        clearPreferredLauncher();
+                    }
+                    retrieveCurrentSettings(getActivity());
+                    break;
+            }
+        }
+
+    };
+
+    /**
+     * @return A newly instantiated {@link DeviceOwnerFragment}.
+     */
+    public static DeviceOwnerFragment newInstance() {
+        return new DeviceOwnerFragment();
+    }
+
+    @Nullable
+    @Override
+    public View onCreateView(LayoutInflater inflater, ViewGroup container,
+                             Bundle savedInstanceState) {
+        return inflater.inflate(R.layout.fragment_device_owner, container, false);
+    }
+
+    @Override
+    public void onViewCreated(View view, Bundle savedInstanceState) {
+        // Retain references
+        mSwitchAutoTime = (Switch) view.findViewById(R.id.switch_auto_time);
+        mSwitchAutoTimeZone = (Switch) view.findViewById(R.id.switch_auto_time_zone);
+        mAvailableLaunchers = (Spinner) view.findViewById(R.id.available_launchers);
+        mButtonLauncher = (Button) view.findViewById(R.id.set_preferred_launcher);
+        // Bind event handlers
+        mSwitchAutoTime.setOnCheckedChangeListener(mOnCheckedChangeListener);
+        mSwitchAutoTimeZone.setOnCheckedChangeListener(mOnCheckedChangeListener);
+        mButtonLauncher.setOnClickListener(mOnClickListener);
+    }
+
+    @Override
+    public void onAttach(Activity activity) {
+        super.onAttach(activity);
+        mDevicePolicyManager =
+                (DevicePolicyManager) activity.getSystemService(Activity.DEVICE_POLICY_SERVICE);
+    }
+
+    @Override
+    public void onDetach() {
+        mDevicePolicyManager = null;
+        super.onDetach();
+    }
+
+    @Override
+    public void onResume() {
+        super.onResume();
+        Activity activity = getActivity();
+        if (activity != null) {
+            retrieveCurrentSettings(activity);
+        }
+    }
+
+    /**
+     * Retrieves the current global settings and changes the UI accordingly.
+     *
+     * @param activity The activity
+     */
+    private void retrieveCurrentSettings(Activity activity) {
+        // Global settings
+        setCheckedSafely(mSwitchAutoTime,
+                getBooleanGlobalSetting(activity.getContentResolver(), Settings.Global.AUTO_TIME));
+        setCheckedSafely(mSwitchAutoTimeZone,
+                getBooleanGlobalSetting(activity.getContentResolver(),
+                        Settings.Global.AUTO_TIME_ZONE));
+
+        // Launcher
+        Intent intent = new Intent(Intent.ACTION_MAIN);
+        intent.addCategory(Intent.CATEGORY_HOME);
+        List<ResolveInfo> list = activity.getPackageManager()
+                .queryIntentActivities(intent, /* default flags */ 0);
+        mAdapter = new LauncherAdapter(activity, list);
+        mAvailableLaunchers.setAdapter(mAdapter);
+        String packageName = loadPersistentPreferredLauncher(activity);
+        if (packageName == null) { // No preferred launcher is set
+            mAvailableLaunchers.setEnabled(true);
+            mButtonLauncher.setText(R.string.set_as_preferred);
+        } else {
+            int position = -1;
+            for (int i = 0; i < list.size(); ++i) {
+                if (list.get(i).activityInfo.packageName.equals(packageName)) {
+                    position = i;
+                    break;
+                }
+            }
+            if (position != -1) {
+                mAvailableLaunchers.setSelection(position);
+                mAvailableLaunchers.setEnabled(false);
+                mButtonLauncher.setText(R.string.clear_preferred);
+            }
+        }
+    }
+
+    /**
+     * Retrieves the current boolean value of the specified global setting.
+     *
+     * @param resolver The ContentResolver
+     * @param setting  The setting to be retrieved
+     * @return The current boolean value
+     */
+    private static boolean getBooleanGlobalSetting(ContentResolver resolver, String setting) {
+        return 0 != Settings.Global.getInt(resolver, setting, 0);
+    }
+
+    /**
+     * Sets the boolean value of the specified global setting.
+     *
+     * @param setting The setting to be set
+     * @param value   The value to be set
+     */
+    private void setBooleanGlobalSetting(String setting, boolean value) {
+        mDevicePolicyManager.setGlobalSetting(
+                // The ComponentName of the device owner
+                DeviceOwnerReceiver.getComponentName(getActivity()),
+                // The settings to be set
+                setting,
+                // The value we write here is a string representation for SQLite
+                value ? "1" : "0");
+    }
+
+    /**
+     * A utility method to set the checked state of the button without invoking its listener.
+     *
+     * @param button  The button
+     * @param checked The value to be set
+     */
+    private void setCheckedSafely(CompoundButton button, boolean checked) {
+        button.setOnCheckedChangeListener(null);
+        button.setChecked(checked);
+        button.setOnCheckedChangeListener(mOnCheckedChangeListener);
+    }
+
+    /**
+     * Loads the package name from SharedPreferences.
+     *
+     * @param activity The activity
+     * @return The package name of the launcher currently set as preferred, or null if there is no
+     * preferred launcher.
+     */
+    private static String loadPersistentPreferredLauncher(Activity activity) {
+        return activity.getSharedPreferences(PREFS_DEVICE_OWNER, Context.MODE_PRIVATE)
+                .getString(PREF_LAUNCHER, null);
+    }
+
+    /**
+     * Saves the package name into SharedPreferences.
+     *
+     * @param activity    The activity
+     * @param packageName The package name to be saved. Pass null to remove the preferred launcher.
+     */
+    private static void savePersistentPreferredLauncher(Activity activity, String packageName) {
+        SharedPreferences.Editor editor = activity.getSharedPreferences(PREFS_DEVICE_OWNER,
+                Context.MODE_PRIVATE).edit();
+        if (packageName == null) {
+            editor.remove(PREF_LAUNCHER);
+        } else {
+            editor.putString(PREF_LAUNCHER, packageName);
+        }
+        editor.apply();
+    }
+
+    /**
+     * Sets the selected launcher as preferred.
+     */
+    private void setPreferredLauncher() {
+        Activity activity = getActivity();
+        if (activity == null) {
+            return;
+        }
+        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
+        filter.addCategory(Intent.CATEGORY_HOME);
+        filter.addCategory(Intent.CATEGORY_DEFAULT);
+        ComponentName componentName = mAdapter.getComponentName(
+                mAvailableLaunchers.getSelectedItemPosition());
+        mDevicePolicyManager.addPersistentPreferredActivity(
+                DeviceOwnerReceiver.getComponentName(activity), filter, componentName);
+        savePersistentPreferredLauncher(activity, componentName.getPackageName());
+    }
+
+    /**
+     * Clears the launcher currently set as preferred.
+     */
+    private void clearPreferredLauncher() {
+        Activity activity = getActivity();
+        if (activity == null) {
+            return;
+        }
+        mDevicePolicyManager.clearPackagePersistentPreferredActivities(
+                DeviceOwnerReceiver.getComponentName(activity),
+                loadPersistentPreferredLauncher(activity));
+        savePersistentPreferredLauncher(activity, null);
+    }
+
+    /**
+     * Shows list of {@link ResolveInfo} in a {@link Spinner}.
+     */
+    private static class LauncherAdapter extends SimpleAdapter {
+
+        private static final String KEY_PACKAGE_NAME = "package_name";
+        private static final String KEY_ACTIVITY_NAME = "activity_name";
+
+        public LauncherAdapter(Context context, List<ResolveInfo> list) {
+            super(context, createData(list), android.R.layout.simple_list_item_1,
+                    new String[]{KEY_PACKAGE_NAME},
+                    new int[]{android.R.id.text1});
+        }
+
+        private static List<HashMap<String, String>> createData(List<ResolveInfo> list) {
+            List<HashMap<String, String>> data = new ArrayList<>();
+            for (ResolveInfo info : list) {
+                HashMap<String, String> map = new HashMap<>();
+                map.put(KEY_PACKAGE_NAME, info.activityInfo.packageName);
+                map.put(KEY_ACTIVITY_NAME, info.activityInfo.name);
+                data.add(map);
+            }
+            return data;
+        }
+
+        public ComponentName getComponentName(int position) {
+            @SuppressWarnings("unchecked")
+            HashMap<String, String> map = (HashMap<String, String>) getItem(position);
+            return new ComponentName(map.get(KEY_PACKAGE_NAME), map.get(KEY_ACTIVITY_NAME));
+        }
+
+    }
+
+}
diff --git a/admin/DeviceOwner/Application/src/main/java/com/example/android/deviceowner/DeviceOwnerReceiver.java b/admin/DeviceOwner/Application/src/main/java/com/example/android/deviceowner/DeviceOwnerReceiver.java
new file mode 100644
index 0000000..f5969fc
--- /dev/null
+++ b/admin/DeviceOwner/Application/src/main/java/com/example/android/deviceowner/DeviceOwnerReceiver.java
@@ -0,0 +1,56 @@
+/*
+ * 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.example.android.deviceowner;
+
+import android.app.admin.DeviceAdminReceiver;
+import android.app.admin.DevicePolicyManager;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+
+/**
+ * Handles events related to device owner.
+ */
+public class DeviceOwnerReceiver extends DeviceAdminReceiver {
+
+    /**
+     * Called on the new profile when device owner provisioning has completed. Device owner
+     * provisioning is the process of setting up the device so that its main profile is managed by
+     * the mobile device management (MDM) application set up as the device owner.
+     */
+    @Override
+    public void onProfileProvisioningComplete(Context context, Intent intent) {
+        // Enable the profile
+        DevicePolicyManager manager =
+                (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
+        ComponentName componentName = getComponentName(context);
+        manager.setProfileName(componentName, context.getString(R.string.profile_name));
+        // Open the main screen
+        Intent launch = new Intent(context, MainActivity.class);
+        launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+        context.startActivity(launch);
+    }
+
+    /**
+     * @return A newly instantiated {@link android.content.ComponentName} for this
+     * DeviceAdminReceiver.
+     */
+    public static ComponentName getComponentName(Context context) {
+        return new ComponentName(context.getApplicationContext(), DeviceOwnerReceiver.class);
+    }
+
+}
diff --git a/admin/DeviceOwner/Application/src/main/java/com/example/android/deviceowner/InstructionFragment.java b/admin/DeviceOwner/Application/src/main/java/com/example/android/deviceowner/InstructionFragment.java
new file mode 100644
index 0000000..2a889c3
--- /dev/null
+++ b/admin/DeviceOwner/Application/src/main/java/com/example/android/deviceowner/InstructionFragment.java
@@ -0,0 +1,45 @@
+/*
+ * 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.example.android.deviceowner;
+
+import android.app.Fragment;
+import android.os.Bundle;
+import android.support.annotation.Nullable;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+
+/**
+ * Shows instruction about this device owner.
+ */
+public class InstructionFragment extends Fragment {
+
+    /**
+     * @return A newly instantiated {@link InstructionFragment}.
+     */
+    public static InstructionFragment newInstance() {
+        return new InstructionFragment();
+    }
+
+    @Nullable
+    @Override
+    public View onCreateView(LayoutInflater inflater, ViewGroup container,
+                             Bundle savedInstanceState) {
+        return inflater.inflate(R.layout.fragment_instruction, container, false);
+    }
+
+}
diff --git a/admin/DeviceOwner/Application/src/main/java/com/example/android/deviceowner/MainActivity.java b/admin/DeviceOwner/Application/src/main/java/com/example/android/deviceowner/MainActivity.java
new file mode 100644
index 0000000..5a331ab
--- /dev/null
+++ b/admin/DeviceOwner/Application/src/main/java/com/example/android/deviceowner/MainActivity.java
@@ -0,0 +1,55 @@
+/*
+ * 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.example.android.deviceowner;
+
+import android.app.Activity;
+import android.app.Fragment;
+import android.app.admin.DevicePolicyManager;
+import android.content.Context;
+import android.os.Bundle;
+import android.util.Log;
+
+public class MainActivity extends Activity {
+
+    private static final String TAG = "MainActivity";
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.activity_main_real);
+        if (savedInstanceState == null) {
+            DevicePolicyManager manager =
+                    (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
+            if (manager.isDeviceOwnerApp(getApplicationContext().getPackageName())) {
+                // This app is set up as the device owner. Show the main features.
+                Log.d(TAG, "The app is the device owner.");
+                showFragment(DeviceOwnerFragment.newInstance());
+            } else {
+                // This app is not set up as the device owner. Show instructions.
+                Log.d(TAG, "The app is not the device owner.");
+                showFragment(InstructionFragment.newInstance());
+            }
+        }
+    }
+
+    private void showFragment(Fragment fragment) {
+        getFragmentManager().beginTransaction()
+                .replace(R.id.container, fragment)
+                .commit();
+    }
+
+}
diff --git a/admin/DeviceOwner/Application/src/main/res/drawable-hdpi/ic_launcher.png b/admin/DeviceOwner/Application/src/main/res/drawable-hdpi/ic_launcher.png
new file mode 100644
index 0000000..282e540
--- /dev/null
+++ b/admin/DeviceOwner/Application/src/main/res/drawable-hdpi/ic_launcher.png
Binary files differ
diff --git a/admin/DeviceOwner/Application/src/main/res/drawable-mdpi/ic_launcher.png b/admin/DeviceOwner/Application/src/main/res/drawable-mdpi/ic_launcher.png
new file mode 100644
index 0000000..4ecfdf6
--- /dev/null
+++ b/admin/DeviceOwner/Application/src/main/res/drawable-mdpi/ic_launcher.png
Binary files differ
diff --git a/admin/DeviceOwner/Application/src/main/res/drawable-xhdpi/ic_launcher.png b/admin/DeviceOwner/Application/src/main/res/drawable-xhdpi/ic_launcher.png
new file mode 100644
index 0000000..dfb6cab
--- /dev/null
+++ b/admin/DeviceOwner/Application/src/main/res/drawable-xhdpi/ic_launcher.png
Binary files differ
diff --git a/admin/DeviceOwner/Application/src/main/res/drawable-xxhdpi/ic_launcher.png b/admin/DeviceOwner/Application/src/main/res/drawable-xxhdpi/ic_launcher.png
new file mode 100644
index 0000000..650302e
--- /dev/null
+++ b/admin/DeviceOwner/Application/src/main/res/drawable-xxhdpi/ic_launcher.png
Binary files differ
diff --git a/admin/DeviceOwner/Application/src/main/res/layout/activity_main_real.xml b/admin/DeviceOwner/Application/src/main/res/layout/activity_main_real.xml
new file mode 100644
index 0000000..384e9f9
--- /dev/null
+++ b/admin/DeviceOwner/Application/src/main/res/layout/activity_main_real.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ 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.
+-->
+<FrameLayout
+    android:id="@+id/container"
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    tools:context="com.example.android.deviceowner.MainActivity"
+    tools:ignore="MergeRootFrame"/>
diff --git a/admin/DeviceOwner/Application/src/main/res/layout/fragment_device_owner.xml b/admin/DeviceOwner/Application/src/main/res/layout/fragment_device_owner.xml
new file mode 100644
index 0000000..aeae219
--- /dev/null
+++ b/admin/DeviceOwner/Application/src/main/res/layout/fragment_device_owner.xml
@@ -0,0 +1,83 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ 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.
+-->
+<ScrollView
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    tools:context="com.example.android.deviceowner.DeviceOwnerFragment">
+
+    <LinearLayout
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:orientation="vertical">
+
+        <TextView
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:layout_margin="@dimen/margin_medium"
+            android:text="@string/label_global_settings"
+            android:textAppearance="?android:attr/textAppearanceLarge"/>
+
+        <Switch
+            android:id="@+id/switch_auto_time"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_margin="@dimen/margin_medium"
+            android:paddingEnd="@dimen/margin_medium"
+            android:paddingStart="@dimen/margin_medium"
+            android:text="@string/label_auto_time"
+            android:textAppearance="?android:attr/textAppearanceMedium"/>
+
+        <Switch
+            android:id="@+id/switch_auto_time_zone"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_margin="@dimen/margin_medium"
+            android:paddingEnd="@dimen/margin_medium"
+            android:paddingStart="@dimen/margin_medium"
+            android:text="@string/label_auto_time_zone"
+            android:textAppearance="?android:attr/textAppearanceMedium"/>
+
+        <Space
+            android:layout_width="match_parent"
+            android:layout_height="@dimen/margin_medium"/>
+
+        <TextView
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:layout_margin="@dimen/margin_medium"
+            android:text="@string/label_launcher"
+            android:textAppearance="?android:attr/textAppearanceLarge"/>
+
+        <Spinner
+            android:id="@+id/available_launchers"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_marginStart="@dimen/margin_medium"
+            android:layout_marginTop="@dimen/margin_medium"/>
+
+        <Button
+            android:id="@+id/set_preferred_launcher"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_marginStart="@dimen/margin_medium"
+            android:text="@string/set_as_preferred"/>
+
+    </LinearLayout>
+
+</ScrollView>
\ No newline at end of file
diff --git a/admin/DeviceOwner/Application/src/main/res/layout/fragment_instruction.xml b/admin/DeviceOwner/Application/src/main/res/layout/fragment_instruction.xml
new file mode 100644
index 0000000..9d09e39
--- /dev/null
+++ b/admin/DeviceOwner/Application/src/main/res/layout/fragment_instruction.xml
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ 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.
+-->
+<LinearLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:orientation="vertical"
+    tools:context="com.example.android.deviceowner.InstructionFragment">
+
+    <TextView
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_margin="@dimen/margin_medium"
+        android:text="@string/set_up_instruction"
+        android:textAppearance="?android:attr/textAppearanceMedium"/>
+
+</LinearLayout>
diff --git a/admin/DeviceOwner/Application/src/main/res/values/strings.xml b/admin/DeviceOwner/Application/src/main/res/values/strings.xml
new file mode 100644
index 0000000..af7d038
--- /dev/null
+++ b/admin/DeviceOwner/Application/src/main/res/values/strings.xml
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ 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.
+-->
+<resources>
+
+    <string name="set_up_instruction">
+        The app is not set up as the device owner of this device. Use NfcProvisioning sample to set
+        up this app as the device owner of this device (This requires factory resetting the device).
+    </string>
+
+    <string name="profile_name">Sample Device Owner</string>
+
+    <string name="label_global_settings">Global settings</string>
+    <string name="label_auto_time">Automatic date &amp; time</string>
+    <string name="label_auto_time_zone">Automatic time zone</string>
+
+    <string name="label_launcher">Home Launcher</string>
+    <string name="set_as_preferred">Set as preferred</string>
+    <string name="clear_preferred">Clear preferred</string>
+
+</resources>
diff --git a/admin/DeviceOwner/Application/src/main/res/xml/device_owner_receiver.xml b/admin/DeviceOwner/Application/src/main/res/xml/device_owner_receiver.xml
new file mode 100644
index 0000000..20109f0
--- /dev/null
+++ b/admin/DeviceOwner/Application/src/main/res/xml/device_owner_receiver.xml
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ 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.
+-->
+<device-admin>
+    <uses-policies>
+        <limit-password/>
+        <watch-login/>
+        <reset-password/>
+        <force-lock/>
+        <wipe-data/>
+        <expire-password/>
+        <encrypted-storage/>
+        <disable-camera/>
+    </uses-policies>
+</device-admin>
diff --git a/admin/DeviceOwner/build.gradle b/admin/DeviceOwner/build.gradle
new file mode 100644
index 0000000..2b8d1ef
--- /dev/null
+++ b/admin/DeviceOwner/build.gradle
@@ -0,0 +1,11 @@
+
+// BEGIN_EXCLUDE
+import com.example.android.samples.build.SampleGenPlugin
+apply plugin: SampleGenPlugin
+
+samplegen {
+  pathToBuild "../../../../build"
+  pathToSamplesCommon "../../common"
+}
+apply from: "../../../../build/build.gradle"
+// END_EXCLUDE
diff --git a/admin/DeviceOwner/buildSrc/build.gradle b/admin/DeviceOwner/buildSrc/build.gradle
new file mode 100644
index 0000000..8c294c2
--- /dev/null
+++ b/admin/DeviceOwner/buildSrc/build.gradle
@@ -0,0 +1,15 @@
+repositories {
+    mavenCentral()
+}
+dependencies {
+    compile 'org.freemarker:freemarker:2.3.20'
+}
+
+sourceSets {
+    main {
+        groovy {
+            srcDir new File(rootDir, "../../../../../build/buildSrc/src/main/groovy")
+        }
+    }
+}
+
diff --git a/admin/DeviceOwner/gradle/wrapper/gradle-wrapper.jar b/admin/DeviceOwner/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..8c0fb64
--- /dev/null
+++ b/admin/DeviceOwner/gradle/wrapper/gradle-wrapper.jar
Binary files differ
diff --git a/admin/DeviceOwner/gradle/wrapper/gradle-wrapper.properties b/admin/DeviceOwner/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..0973c31
--- /dev/null
+++ b/admin/DeviceOwner/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,6 @@
+#Tue Jan 20 16:50:15 JST 2015
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip
diff --git a/admin/DeviceOwner/gradlew b/admin/DeviceOwner/gradlew
new file mode 100755
index 0000000..91a7e26
--- /dev/null
+++ b/admin/DeviceOwner/gradlew
@@ -0,0 +1,164 @@
+#!/usr/bin/env bash
+
+##############################################################################
+##
+##  Gradle start up script for UN*X
+##
+##############################################################################
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS=""
+
+APP_NAME="Gradle"
+APP_BASE_NAME=`basename "$0"`
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD="maximum"
+
+warn ( ) {
+    echo "$*"
+}
+
+die ( ) {
+    echo
+    echo "$*"
+    echo
+    exit 1
+}
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+case "`uname`" in
+  CYGWIN* )
+    cygwin=true
+    ;;
+  Darwin* )
+    darwin=true
+    ;;
+  MINGW* )
+    msys=true
+    ;;
+esac
+
+# For Cygwin, ensure paths are in UNIX format before anything is touched.
+if $cygwin ; then
+    [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
+fi
+
+# Attempt to set APP_HOME
+# Resolve links: $0 may be a link
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+    ls=`ls -ld "$PRG"`
+    link=`expr "$ls" : '.*-> \(.*\)$'`
+    if expr "$link" : '/.*' > /dev/null; then
+        PRG="$link"
+    else
+        PRG=`dirname "$PRG"`"/$link"
+    fi
+done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >&-
+APP_HOME="`pwd -P`"
+cd "$SAVED" >&-
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+        # IBM's JDK on AIX uses strange locations for the executables
+        JAVACMD="$JAVA_HOME/jre/sh/java"
+    else
+        JAVACMD="$JAVA_HOME/bin/java"
+    fi
+    if [ ! -x "$JAVACMD" ] ; then
+        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+    fi
+else
+    JAVACMD="java"
+    which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
+    MAX_FD_LIMIT=`ulimit -H -n`
+    if [ $? -eq 0 ] ; then
+        if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
+            MAX_FD="$MAX_FD_LIMIT"
+        fi
+        ulimit -n $MAX_FD
+        if [ $? -ne 0 ] ; then
+            warn "Could not set maximum file descriptor limit: $MAX_FD"
+        fi
+    else
+        warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
+    fi
+fi
+
+# For Darwin, add options to specify how the application appears in the dock
+if $darwin; then
+    GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
+fi
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin ; then
+    APP_HOME=`cygpath --path --mixed "$APP_HOME"`
+    CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+
+    # We build the pattern for arguments to be converted via cygpath
+    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
+    SEP=""
+    for dir in $ROOTDIRSRAW ; do
+        ROOTDIRS="$ROOTDIRS$SEP$dir"
+        SEP="|"
+    done
+    OURCYGPATTERN="(^($ROOTDIRS))"
+    # Add a user-defined pattern to the cygpath arguments
+    if [ "$GRADLE_CYGPATTERN" != "" ] ; then
+        OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
+    fi
+    # Now convert the arguments - kludge to limit ourselves to /bin/sh
+    i=0
+    for arg in "$@" ; do
+        CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
+        CHECK2=`echo "$arg"|egrep -c "^-"`                                 ### Determine if an option
+
+        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition
+            eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
+        else
+            eval `echo args$i`="\"$arg\""
+        fi
+        i=$((i+1))
+    done
+    case $i in
+        (0) set -- ;;
+        (1) set -- "$args0" ;;
+        (2) set -- "$args0" "$args1" ;;
+        (3) set -- "$args0" "$args1" "$args2" ;;
+        (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
+        (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
+        (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
+        (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
+        (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
+        (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
+    esac
+fi
+
+# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
+function splitJvmOpts() {
+    JVM_OPTS=("$@")
+}
+eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
+JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
+
+exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
diff --git a/admin/DeviceOwner/gradlew.bat b/admin/DeviceOwner/gradlew.bat
new file mode 100644
index 0000000..aec9973
--- /dev/null
+++ b/admin/DeviceOwner/gradlew.bat
@@ -0,0 +1,90 @@
+@if "%DEBUG%" == "" @echo off

+@rem ##########################################################################

+@rem

+@rem  Gradle startup script for Windows

+@rem

+@rem ##########################################################################

+

+@rem Set local scope for the variables with windows NT shell

+if "%OS%"=="Windows_NT" setlocal

+

+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.

+set DEFAULT_JVM_OPTS=

+

+set DIRNAME=%~dp0

+if "%DIRNAME%" == "" set DIRNAME=.

+set APP_BASE_NAME=%~n0

+set APP_HOME=%DIRNAME%

+

+@rem Find java.exe

+if defined JAVA_HOME goto findJavaFromJavaHome

+

+set JAVA_EXE=java.exe

+%JAVA_EXE% -version >NUL 2>&1

+if "%ERRORLEVEL%" == "0" goto init

+

+echo.

+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

+echo.

+echo Please set the JAVA_HOME variable in your environment to match the

+echo location of your Java installation.

+

+goto fail

+

+:findJavaFromJavaHome

+set JAVA_HOME=%JAVA_HOME:"=%

+set JAVA_EXE=%JAVA_HOME%/bin/java.exe

+

+if exist "%JAVA_EXE%" goto init

+

+echo.

+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%

+echo.

+echo Please set the JAVA_HOME variable in your environment to match the

+echo location of your Java installation.

+

+goto fail

+

+:init

+@rem Get command-line arguments, handling Windowz variants

+

+if not "%OS%" == "Windows_NT" goto win9xME_args

+if "%@eval[2+2]" == "4" goto 4NT_args

+

+:win9xME_args

+@rem Slurp the command line arguments.

+set CMD_LINE_ARGS=

+set _SKIP=2

+

+:win9xME_args_slurp

+if "x%~1" == "x" goto execute

+

+set CMD_LINE_ARGS=%*

+goto execute

+

+:4NT_args

+@rem Get arguments from the 4NT Shell from JP Software

+set CMD_LINE_ARGS=%$

+

+:execute

+@rem Setup the command line

+

+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar

+

+@rem Execute Gradle

+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%

+

+:end

+@rem End local scope for the variables with windows NT shell

+if "%ERRORLEVEL%"=="0" goto mainEnd

+

+:fail

+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of

+rem the _cmd.exe /c_ return code!

+if  not "" == "%GRADLE_EXIT_CONSOLE%" exit 1

+exit /b 1

+

+:mainEnd

+if "%OS%"=="Windows_NT" endlocal

+

+:omega

diff --git a/admin/DeviceOwner/screenshots/1-main.png b/admin/DeviceOwner/screenshots/1-main.png
new file mode 100644
index 0000000..db827d1
--- /dev/null
+++ b/admin/DeviceOwner/screenshots/1-main.png
Binary files differ
diff --git a/admin/DeviceOwner/screenshots/icon-web.png b/admin/DeviceOwner/screenshots/icon-web.png
new file mode 100755
index 0000000..ac670da
--- /dev/null
+++ b/admin/DeviceOwner/screenshots/icon-web.png
Binary files differ
diff --git a/admin/DeviceOwner/settings.gradle b/admin/DeviceOwner/settings.gradle
new file mode 100644
index 0000000..9464a35
--- /dev/null
+++ b/admin/DeviceOwner/settings.gradle
@@ -0,0 +1 @@
+include 'Application'
diff --git a/admin/DeviceOwner/template-params.xml b/admin/DeviceOwner/template-params.xml
new file mode 100644
index 0000000..27930d0
--- /dev/null
+++ b/admin/DeviceOwner/template-params.xml
@@ -0,0 +1,82 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ 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.
+-->
+<sample>
+    <name>DeviceOwner</name>
+    <group>Admin</group>
+    <package>com.example.android.deviceowner</package>
+    <minSdk>21</minSdk>
+
+    <strings>
+        <intro>
+<![CDATA[
+This app demonstrates how to use device owner features. Use the NfcProvisioning sample to set up
+this app as the device owner of your test device (This requires wiping out the device and resseting
+it as an unprovisioned device). As a device owner, this app can configure global settings, and
+enforce use of a specific launcher.
+]]>
+        </intro>
+    </strings>
+
+    <template src="base"/>
+
+    <metadata>
+        <status>PUBLISHED</status>
+        <categories>Device Admin</categories>
+        <technologies>Android</technologies>
+        <languages>Java</languages>
+        <solutions>Mobile</solutions>
+        <level>ADVANCED</level>
+        <icon>screenshots/icon-web.png</icon>
+        <screenshots>
+            <img>screenshots/1-main.png</img>
+        </screenshots>
+        <api_refs>
+            <android>android.app.admin.DevicePolicyManager</android>
+            <android>android.provider.Settings</android>
+        </api_refs>
+
+        <description>
+<![CDATA[
+This sample demonstrates how to use some device owner features. As a device owner, you can configure
+global settings such as automatic time and timezone. You can mandate a specific launcher by
+preferred intent handler.
+]]>
+        </description>
+
+        <intro>
+<![CDATA[
+In order to set global settings, use [DevicePolicyManager#setGlobalSetting][1] and specify one of
+the [Settings.Global][2] keys available. Note that you need to specify its value as a String. As
+most of the keys accept boolean values, you will mostly use "1" for true and "0" for false.
+
+You can mandate a specific launcher by adding a persistent preferred activity for an IntentFilter
+with Intent.CATEGORY_HOME category. Call [DevicePolicyManager#addPersistentPreferredActivity][3] to
+register the activity. You can clear the registration with
+[clearPackagePersistentPreferredActivities][4].
+
+As a device owner, you can also use the features available for managed profile owner. See
+[BasicManagedProfile][5].
+
+[1]: http://developer.android.com/reference/android/app/admin/DevicePolicyManager.html#setGlobalSetting(android.content.ComponentName, java.lang.String, java.lang.String)
+[2]: http://developer.android.com/reference/android/provider/Settings.Global.html
+[3]: http://developer.android.com/reference/android/app/admin/DevicePolicyManager.html#addPersistentPreferredActivity(android.content.ComponentName, android.content.IntentFilter, android.content.ComponentName)
+[4]: http://developer.android.com/reference/android/app/admin/DevicePolicyManager.html#clearPackagePersistentPreferredActivities(android.content.ComponentName, java.lang.String)
+[5]: https://developer.android.com/samples/BasicManagedProfile/index.html
+]]>
+        </intro>
+    </metadata>
+</sample>
diff --git a/wearable/wear/GridViewPager/Application/.gitignore b/admin/NfcProvisioning/Application/.gitignore
similarity index 91%
copy from wearable/wear/GridViewPager/Application/.gitignore
copy to admin/NfcProvisioning/Application/.gitignore
index 6eb878d..1bac3a5 100644
--- a/wearable/wear/GridViewPager/Application/.gitignore
+++ b/admin/NfcProvisioning/Application/.gitignore
@@ -1,4 +1,4 @@
-# Copyright 2013 The Android Open Source Project
+# 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.
diff --git a/admin/NfcProvisioning/Application/README-fragmentview.txt b/admin/NfcProvisioning/Application/README-fragmentview.txt
new file mode 100644
index 0000000..b346a5f
--- /dev/null
+++ b/admin/NfcProvisioning/Application/README-fragmentview.txt
@@ -0,0 +1,37 @@
+<!--
+        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.
+-->
+
+Steps to implement FragmentView template:
+-in template-params.xml.ftl:
+    -add the following line to common imports
+        <common src="activities"/>
+
+-Add a Fragment to show behavior.  In your MainActivity.java class, it will reference a Fragment
+ called (yourProjectName)Fragment.java.  Create that file in your project, using the "main" source
+ folder instead of "common" or "templates".
+   For instance, if your package name is com.example.foo, create the file
+   src/main/java/com/example/foo/FooFragment.java
+
+
+-Within this fragment, make sure that the onCreate method has the line
+ "setHasOptionsMenu(true);", to enable the fragment to handle menu events.
+
+-In order to override menu events, override onOptionsItemSelected.
+
+-refer to sampleSamples/fragmentViewSample for a reference implementation of a
+project built on this template.
+
+
diff --git a/admin/NfcProvisioning/Application/README-singleview.txt b/admin/NfcProvisioning/Application/README-singleview.txt
new file mode 100644
index 0000000..57fa134
--- /dev/null
+++ b/admin/NfcProvisioning/Application/README-singleview.txt
@@ -0,0 +1,47 @@
+<#--
+        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.
+-->
+
+Steps to implement SingleView template:
+-in template-params.xml.ftl:
+    -add the following line to common imports
+        <common src="activities"/>
+
+    -add a string for the action button's text using the element name "sample_action".
+    This element should be a child of <strings>:
+        <strings>
+        ...
+        <sample_action>ButtonText</sample_action>
+        ...
+        </strings>
+
+
+
+-Add a Fragment to handle behavior.  In your MainActivity.java class, it will reference a Fragment
+ called (yourProjectName)Fragment.java.  Create that file in your project, using the "main" source
+ folder instead of "common" or "templates".
+   For instance, if your package name is com.example.foo, create the file
+   src/main/java/com/example/foo/FooFragment.java
+
+
+-Within this fragment, make sure that the onCreate method has the line
+ "setHasOptionsMenu(true);", to enable the fragment to handle menu events.
+
+-In order to override menu events, override onOptionsItemSelected.
+
+-refer to sampleSamples/singleViewSample for a reference implementation of a
+project built on this template.
+
+
diff --git a/wearable/wear/GridViewPager/Application/proguard-project.txt b/admin/NfcProvisioning/Application/proguard-project.txt
similarity index 91%
copy from wearable/wear/GridViewPager/Application/proguard-project.txt
copy to admin/NfcProvisioning/Application/proguard-project.txt
index 0d8f171..f2fe155 100644
--- a/wearable/wear/GridViewPager/Application/proguard-project.txt
+++ b/admin/NfcProvisioning/Application/proguard-project.txt
@@ -1,4 +1,4 @@
- To enable ProGuard in your project, edit project.properties
+# To enable ProGuard in your project, edit project.properties
 # to define the proguard.config property as described in that file.
 #
 # Add project specific ProGuard rules here.
diff --git a/admin/NfcProvisioning/Application/src/main/AndroidManifest.xml b/admin/NfcProvisioning/Application/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..1db70d7
--- /dev/null
+++ b/admin/NfcProvisioning/Application/src/main/AndroidManifest.xml
@@ -0,0 +1,44 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ 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.
+-->
+<manifest
+    package="com.example.android.nfcprovisioning"
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:versionCode="1"
+    android:versionName="1.0">
+
+    <uses-permission android:name="android.permission.NFC"/>
+    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
+    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
+
+    <application
+        android:allowBackup="true"
+        android:icon="@drawable/ic_launcher"
+        android:label="@string/app_name"
+        android:theme="@style/AppTheme">
+
+        <activity
+            android:name=".MainActivity"
+            android:label="@string/app_name"
+            android:windowSoftInputMode="stateHidden">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN"/>
+                <category android:name="android.intent.category.LAUNCHER"/>
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest>
diff --git a/admin/NfcProvisioning/Application/src/main/java/com/example/android/nfcprovisioning/NfcProvisioningFragment.java b/admin/NfcProvisioning/Application/src/main/java/com/example/android/nfcprovisioning/NfcProvisioningFragment.java
new file mode 100644
index 0000000..f46d0f2
--- /dev/null
+++ b/admin/NfcProvisioning/Application/src/main/java/com/example/android/nfcprovisioning/NfcProvisioningFragment.java
@@ -0,0 +1,194 @@
+/*
+ * 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.example.android.nfcprovisioning;
+
+import android.app.Activity;
+import android.app.admin.DevicePolicyManager;
+import android.nfc.NdefMessage;
+import android.nfc.NdefRecord;
+import android.nfc.NfcAdapter;
+import android.nfc.NfcEvent;
+import android.os.Bundle;
+import android.support.annotation.Nullable;
+import android.support.v4.app.Fragment;
+import android.support.v4.app.LoaderManager;
+import android.support.v4.content.Loader;
+import android.text.TextUtils;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.EditText;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.util.Map;
+import java.util.Properties;
+
+/**
+ * Provides UI and logic for NFC provisioning.
+ * <p>
+ * This fragment creates an intent, which sends parameters to a second device via an Nfc bump. If
+ * the second device is factory reset, this will start provisioning the second device to set it up
+ * as an owned device.
+ * </p>
+ */
+public class NfcProvisioningFragment extends Fragment implements
+        NfcAdapter.CreateNdefMessageCallback,
+        TextWatcherWrapper.OnTextChangedListener,
+        LoaderManager.LoaderCallbacks<Map<String, String>> {
+
+    private static final int LOADER_PROVISIONING_VALUES = 1;
+
+    // View references
+    private EditText mEditPackageName;
+    private EditText mEditLocale;
+    private EditText mEditTimezone;
+    private EditText mEditWifiSsid;
+    private EditText mEditWifiSecurityType;
+    private EditText mEditWifiPassword;
+
+    // Values to be set via NFC bump
+    private Map<String, String> mProvisioningValues;
+
+    @Override
+    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
+                             @Nullable Bundle savedInstanceState) {
+        return inflater.inflate(R.layout.fragment_nfc_provisioning, container, false);
+    }
+
+    @Override
+    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
+        // Retrieve view references
+        mEditPackageName = (EditText) view.findViewById(R.id.package_name);
+        mEditLocale = (EditText) view.findViewById(R.id.locale);
+        mEditTimezone = (EditText) view.findViewById(R.id.timezone);
+        mEditWifiSsid = (EditText) view.findViewById(R.id.wifi_ssid);
+        mEditWifiSecurityType = (EditText) view.findViewById(R.id.wifi_security_type);
+        mEditWifiPassword = (EditText) view.findViewById(R.id.wifi_password);
+        // Bind event handlers
+        mEditPackageName.addTextChangedListener(new TextWatcherWrapper(R.id.package_name, this));
+        mEditLocale.addTextChangedListener(new TextWatcherWrapper(R.id.locale, this));
+        mEditTimezone.addTextChangedListener(new TextWatcherWrapper(R.id.timezone, this));
+        mEditWifiSsid.addTextChangedListener(new TextWatcherWrapper(R.id.wifi_ssid, this));
+        mEditWifiSecurityType.addTextChangedListener(
+                new TextWatcherWrapper(R.id.wifi_security_type, this));
+        mEditWifiPassword.addTextChangedListener(new TextWatcherWrapper(R.id.wifi_password, this));
+    }
+
+    @Override
+    public void onStart() {
+        super.onStart();
+        Activity activity = getActivity();
+        NfcAdapter adapter = NfcAdapter.getDefaultAdapter(activity);
+        if (adapter != null) {
+            adapter.setNdefPushMessageCallback(this, activity);
+        }
+        getLoaderManager().initLoader(LOADER_PROVISIONING_VALUES, null, this);
+    }
+
+    @Override
+    public NdefMessage createNdefMessage(NfcEvent event) {
+        if (mProvisioningValues == null) {
+            return null;
+        }
+        ByteArrayOutputStream stream = new ByteArrayOutputStream();
+        Properties properties = new Properties();
+        // Store all the values into the Properties object
+        for (Map.Entry<String, String> e : mProvisioningValues.entrySet()) {
+            if (!TextUtils.isEmpty(e.getValue())) {
+                String value;
+                if (e.getKey().equals(DevicePolicyManager.EXTRA_PROVISIONING_WIFI_SSID)) {
+                    // Make sure to surround SSID with double quotes
+                    value = e.getValue();
+                    if (!value.startsWith("\"") || !value.endsWith("\"")) {
+                        value = "\"" + value + "\"";
+                    }
+                } else {
+                    value = e.getValue();
+                }
+                properties.put(e.getKey(), value);
+            }
+        }
+        try {
+            properties.store(stream, getString(R.string.nfc_comment));
+            NdefRecord record = NdefRecord.createMime(
+                    DevicePolicyManager.MIME_TYPE_PROVISIONING_NFC, stream.toByteArray());
+            return new NdefMessage(new NdefRecord[]{record});
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+    @Override
+    public void onTextChanged(int id, String s) {
+        if (mProvisioningValues == null) {
+            return;
+        }
+        switch (id) {
+            case R.id.package_name:
+                mProvisioningValues.put(
+                        DevicePolicyManager.EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME, s);
+                break;
+            case R.id.locale:
+                mProvisioningValues.put(DevicePolicyManager.EXTRA_PROVISIONING_LOCALE, s);
+                break;
+            case R.id.timezone:
+                mProvisioningValues.put(DevicePolicyManager.EXTRA_PROVISIONING_TIME_ZONE, s);
+                break;
+            case R.id.wifi_ssid:
+                mProvisioningValues.put(DevicePolicyManager.EXTRA_PROVISIONING_WIFI_SSID, s);
+                break;
+            case R.id.wifi_security_type:
+                mProvisioningValues.put(
+                        DevicePolicyManager.EXTRA_PROVISIONING_WIFI_SECURITY_TYPE, s);
+                break;
+            case R.id.wifi_password:
+                mProvisioningValues.put(DevicePolicyManager.EXTRA_PROVISIONING_WIFI_PASSWORD, s);
+                break;
+        }
+    }
+
+    @Override
+    public Loader<Map<String, String>> onCreateLoader(int id, Bundle args) {
+        if (id == LOADER_PROVISIONING_VALUES) {
+            return new ProvisioningValuesLoader(getActivity());
+        }
+        return null;
+    }
+
+    @Override
+    public void onLoadFinished(Loader<Map<String, String>> loader, Map<String, String> values) {
+        if (loader.getId() == LOADER_PROVISIONING_VALUES) {
+            mProvisioningValues = values;
+            mEditPackageName.setText(values.get(
+                    DevicePolicyManager.EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME));
+            mEditLocale.setText(values.get(DevicePolicyManager.EXTRA_PROVISIONING_LOCALE));
+            mEditTimezone.setText(values.get(DevicePolicyManager.EXTRA_PROVISIONING_TIME_ZONE));
+            mEditWifiSsid.setText(values.get(DevicePolicyManager.EXTRA_PROVISIONING_WIFI_SSID));
+            mEditWifiSecurityType.setText(values.get(
+                    DevicePolicyManager.EXTRA_PROVISIONING_WIFI_SECURITY_TYPE));
+            mEditWifiPassword.setText(null);
+        }
+    }
+
+    @Override
+    public void onLoaderReset(Loader<Map<String, String>> loader) {
+        // Do nothing
+    }
+
+}
diff --git a/admin/NfcProvisioning/Application/src/main/java/com/example/android/nfcprovisioning/ProvisioningValuesLoader.java b/admin/NfcProvisioning/Application/src/main/java/com/example/android/nfcprovisioning/ProvisioningValuesLoader.java
new file mode 100644
index 0000000..2203c30
--- /dev/null
+++ b/admin/NfcProvisioning/Application/src/main/java/com/example/android/nfcprovisioning/ProvisioningValuesLoader.java
@@ -0,0 +1,165 @@
+/*
+ * 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.example.android.nfcprovisioning;
+
+import android.app.Activity;
+import android.app.admin.DevicePolicyManager;
+import android.content.Context;
+import android.net.wifi.WifiInfo;
+import android.net.wifi.WifiManager;
+import android.os.Environment;
+import android.support.v4.content.AsyncTaskLoader;
+
+import com.example.android.common.logger.Log;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.TimeZone;
+
+/**
+ * Loads default values for NFC provisioning.
+ * <p/>
+ * This loader first tries to load values from a config file in SD card. Then it fills in missing
+ * values using constants and settings on the programming device.
+ */
+public class ProvisioningValuesLoader extends AsyncTaskLoader<Map<String, String>> {
+
+    private static final String FILENAME = "nfcprovisioning.txt";
+    private static final String TAG = "LoadProvisioningValuesTask";
+
+    private Map<String, String> mValues;
+
+    public ProvisioningValuesLoader(Context context) {
+        super(context);
+    }
+
+    @Override
+    public Map<String, String> loadInBackground() {
+        HashMap<String, String> values = new HashMap<>();
+        loadFromDisk(values);
+        loadSystemValues(values);
+        return values;
+    }
+
+    @Override
+    public void deliverResult(Map<String, String> values) {
+        if (isReset()) {
+            return;
+        }
+        mValues = values;
+        super.deliverResult(values);
+    }
+
+    @Override
+    protected void onStartLoading() {
+        if (mValues != null) {
+            deliverResult(mValues);
+        }
+        if (takeContentChanged() || mValues == null) {
+            forceLoad();
+        }
+    }
+
+    @Override
+    protected void onStopLoading() {
+        cancelLoad();
+    }
+
+    @Override
+    protected void onReset() {
+        super.onReset();
+        onStopLoading();
+        mValues = null;
+    }
+
+    private void loadFromDisk(HashMap<String, String> values) {
+        File directory = Environment.getExternalStorageDirectory();
+        File file = new File(directory, FILENAME);
+        if (!file.exists()) {
+            return;
+        }
+        Log.d(TAG, "Loading the config file...");
+        try {
+            loadFromFile(values, file);
+        } catch (IOException e) {
+            e.printStackTrace();
+            Log.e(TAG, "Error loading data from " + file, e);
+        }
+    }
+
+    private void loadFromFile(HashMap<String, String> values, File file) throws IOException {
+        BufferedReader reader = null;
+        try {
+            reader = new BufferedReader(new FileReader(file));
+            String line;
+            while (null != (line = reader.readLine())) {
+                if (line.startsWith("#")) {
+                    continue;
+                }
+                int position = line.indexOf("=");
+                if (position < 0) { // Not found
+                    continue;
+                }
+                String key = line.substring(0, position);
+                String value = line.substring(position + 1);
+                values.put(key, value);
+                Log.d(TAG, key + "=" + value);
+            }
+        } finally {
+            if (reader != null) {
+                reader.close();
+            }
+        }
+    }
+
+    private void loadSystemValues(HashMap<String, String> values) {
+        Context context = getContext();
+        putIfMissing(values, DevicePolicyManager.EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME,
+                "com.example.android.deviceowner");
+        putIfMissing(values, DevicePolicyManager.EXTRA_PROVISIONING_LOCALE,
+                context.getResources().getConfiguration().locale.toString());
+        putIfMissing(values, DevicePolicyManager.EXTRA_PROVISIONING_TIME_ZONE,
+                TimeZone.getDefault().getID());
+        if (!values.containsKey(DevicePolicyManager.EXTRA_PROVISIONING_WIFI_SSID)) {
+            WifiManager wifiManager = (WifiManager) context
+                    .getSystemService(Activity.WIFI_SERVICE);
+            WifiInfo info = wifiManager.getConnectionInfo();
+            values.put(DevicePolicyManager.EXTRA_PROVISIONING_WIFI_SSID, trimSsid(info.getSSID()));
+        }
+    }
+
+    /**
+     * {@link WifiInfo#getSSID} returns the WiFi SSID surrounded by double quotation marks. This
+     * method removes them if wifiSsid contains them.
+     */
+    private static String trimSsid(String wifiSsid) {
+        int head = wifiSsid.startsWith("\"") ? 1 : 0;
+        int tail = wifiSsid.endsWith("\"") ? 1 : 0;
+        return wifiSsid.substring(head, wifiSsid.length() - tail);
+    }
+
+    private static <Key, Value> void putIfMissing(HashMap<Key, Value> map, Key key, Value value) {
+        if (!map.containsKey(key)) {
+            map.put(key, value);
+        }
+    }
+
+}
diff --git a/admin/NfcProvisioning/Application/src/main/java/com/example/android/nfcprovisioning/TextWatcherWrapper.java b/admin/NfcProvisioning/Application/src/main/java/com/example/android/nfcprovisioning/TextWatcherWrapper.java
new file mode 100644
index 0000000..d36936e
--- /dev/null
+++ b/admin/NfcProvisioning/Application/src/main/java/com/example/android/nfcprovisioning/TextWatcherWrapper.java
@@ -0,0 +1,55 @@
+/*
+ * 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.example.android.nfcprovisioning;
+
+import android.text.Editable;
+import android.text.TextWatcher;
+
+/**
+ * This class wraps {@link TextWatcher} and delegates {@link TextWatcher#afterTextChanged} event to
+ * {@link OnTextChangedListener} while hiding all other unnecessary events.
+ */
+public class TextWatcherWrapper implements TextWatcher {
+
+    private final int mId;
+    private final OnTextChangedListener mListener;
+
+    public TextWatcherWrapper(int id, OnTextChangedListener listener) {
+        mId = id;
+        mListener = listener;
+    }
+
+    @Override
+    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
+        // Ignore
+    }
+
+    @Override
+    public void onTextChanged(CharSequence s, int start, int before, int count) {
+        // Ignore
+    }
+
+    @Override
+    public void afterTextChanged(Editable s) {
+        mListener.onTextChanged(mId, s.toString());
+    }
+
+    public interface OnTextChangedListener {
+        public void onTextChanged(int id, String s);
+    }
+
+}
diff --git a/admin/NfcProvisioning/Application/src/main/res/drawable-hdpi/ic_launcher.png b/admin/NfcProvisioning/Application/src/main/res/drawable-hdpi/ic_launcher.png
new file mode 100644
index 0000000..638a88d
--- /dev/null
+++ b/admin/NfcProvisioning/Application/src/main/res/drawable-hdpi/ic_launcher.png
Binary files differ
diff --git a/admin/NfcProvisioning/Application/src/main/res/drawable-mdpi/ic_launcher.png b/admin/NfcProvisioning/Application/src/main/res/drawable-mdpi/ic_launcher.png
new file mode 100644
index 0000000..cd128c9
--- /dev/null
+++ b/admin/NfcProvisioning/Application/src/main/res/drawable-mdpi/ic_launcher.png
Binary files differ
diff --git a/admin/NfcProvisioning/Application/src/main/res/drawable-xhdpi/ic_launcher.png b/admin/NfcProvisioning/Application/src/main/res/drawable-xhdpi/ic_launcher.png
new file mode 100644
index 0000000..824541a
--- /dev/null
+++ b/admin/NfcProvisioning/Application/src/main/res/drawable-xhdpi/ic_launcher.png
Binary files differ
diff --git a/admin/NfcProvisioning/Application/src/main/res/drawable-xxhdpi/ic_launcher.png b/admin/NfcProvisioning/Application/src/main/res/drawable-xxhdpi/ic_launcher.png
new file mode 100644
index 0000000..5fe9f2e
--- /dev/null
+++ b/admin/NfcProvisioning/Application/src/main/res/drawable-xxhdpi/ic_launcher.png
Binary files differ
diff --git a/admin/NfcProvisioning/Application/src/main/res/layout/fragment_nfc_provisioning.xml b/admin/NfcProvisioning/Application/src/main/res/layout/fragment_nfc_provisioning.xml
new file mode 100644
index 0000000..ee79e7a
--- /dev/null
+++ b/admin/NfcProvisioning/Application/src/main/res/layout/fragment_nfc_provisioning.xml
@@ -0,0 +1,77 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+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.
+-->
+<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
+            android:layout_width="match_parent"
+            android:layout_height="match_parent">
+
+    <LinearLayout
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:orientation="vertical"
+        android:padding="@dimen/margin_small">
+
+        <EditText
+            android:id="@+id/package_name"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:layout_margin="@dimen/margin_small"
+            android:hint="@string/hint_package_name"
+            android:inputType="textNoSuggestions"/>
+
+        <EditText
+            android:id="@+id/locale"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:layout_margin="@dimen/margin_small"
+            android:hint="@string/hint_locale"
+            android:inputType="textNoSuggestions"/>
+
+        <EditText
+            android:id="@+id/timezone"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:layout_margin="@dimen/margin_small"
+            android:hint="@string/hint_timezone"
+            android:inputType="textNoSuggestions"/>
+
+        <EditText
+            android:id="@+id/wifi_ssid"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:layout_margin="@dimen/margin_small"
+            android:hint="@string/hint_wifi_ssid"
+            android:inputType="textNoSuggestions"/>
+
+        <EditText
+            android:id="@+id/wifi_security_type"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:layout_margin="@dimen/margin_small"
+            android:hint="@string/hint_wifi_security_type"
+            android:inputType="textNoSuggestions"/>
+
+        <EditText
+            android:id="@+id/wifi_password"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:layout_margin="@dimen/margin_small"
+            android:hint="@string/hint_wifi_password"
+            android:inputType="textPassword"/>
+
+    </LinearLayout>
+
+</ScrollView>
diff --git a/admin/NfcProvisioning/Application/src/main/res/values/strings.xml b/admin/NfcProvisioning/Application/src/main/res/values/strings.xml
new file mode 100644
index 0000000..67de389
--- /dev/null
+++ b/admin/NfcProvisioning/Application/src/main/res/values/strings.xml
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+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.
+-->
+<resources>
+
+    <string name="nfc_comment">NFC provisioning sample</string>
+
+    <string name="hint_package_name">Package name of device owner</string>
+    <string name="hint_locale">Locale</string>
+    <string name="hint_timezone">Timezone</string>
+    <string name="hint_wifi_ssid">WiFi SSID</string>
+    <string name="hint_wifi_security_type">WiFi security type</string>
+    <string name="hint_wifi_password">WiFi password</string>
+
+</resources>
diff --git a/admin/NfcProvisioning/Application/tests/src/com/example/android/nfcprovisioning/tests/SampleTests.java b/admin/NfcProvisioning/Application/tests/src/com/example/android/nfcprovisioning/tests/SampleTests.java
new file mode 100644
index 0000000..57876db
--- /dev/null
+++ b/admin/NfcProvisioning/Application/tests/src/com/example/android/nfcprovisioning/tests/SampleTests.java
@@ -0,0 +1,80 @@
+/*
+ * 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.example.android.nfcprovisioning.tests;
+
+import android.test.ActivityInstrumentationTestCase2;
+import android.text.TextUtils;
+import android.view.View;
+import android.widget.EditText;
+
+import com.example.android.nfcprovisioning.MainActivity;
+import com.example.android.nfcprovisioning.NfcProvisioningFragment;
+import com.example.android.nfcprovisioning.R;
+
+/**
+ * Tests for NfcProvisioning sample.
+ */
+public class SampleTests extends ActivityInstrumentationTestCase2<MainActivity> {
+
+    private MainActivity mTestActivity;
+    private NfcProvisioningFragment mTestFragment;
+
+    public SampleTests() {
+        super(MainActivity.class);
+    }
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+
+        // Starts the activity under test using the default Intent with:
+        // action = {@link Intent#ACTION_MAIN}
+        // flags = {@link Intent#FLAG_ACTIVITY_NEW_TASK}
+        // All other fields are null or empty.
+        mTestActivity = getActivity();
+        mTestFragment = (NfcProvisioningFragment)
+                mTestActivity.getSupportFragmentManager().getFragments().get(1);
+    }
+
+    /**
+     * Test if the test fixture has been set up correctly.
+     */
+    public void testPreconditions() {
+        //Try to add a message to add context to your assertions. These messages will be shown if
+        //a tests fails and make it easy to understand why a test failed
+        assertNotNull("mTestActivity is null", mTestActivity);
+        assertNotNull("mTestFragment is null", mTestFragment);
+    }
+
+    public void testEditTexts() {
+        View view = mTestFragment.getView();
+        assertNotNull(view);
+        // Check that we have all the EditTexts on the Fragment
+        EditText locale = (EditText) view.findViewById(R.id.locale);
+        assertNotNull(locale);
+        EditText timezone = (EditText) view.findViewById(R.id.timezone);
+        assertNotNull(timezone);
+        EditText wifiSsid = (EditText) view.findViewById(R.id.wifi_ssid);
+        assertNotNull(wifiSsid);
+        EditText wifiPassword = (EditText) view.findViewById(R.id.wifi_password);
+        assertNotNull(wifiPassword);
+        // These EditTexts should be filled with some default values
+        assertFalse(TextUtils.isEmpty(locale.getText().toString()));
+        assertFalse(TextUtils.isEmpty(timezone.getText().toString()));
+    }
+
+}
diff --git a/admin/NfcProvisioning/build.gradle b/admin/NfcProvisioning/build.gradle
new file mode 100644
index 0000000..2b8d1ef
--- /dev/null
+++ b/admin/NfcProvisioning/build.gradle
@@ -0,0 +1,11 @@
+
+// BEGIN_EXCLUDE
+import com.example.android.samples.build.SampleGenPlugin
+apply plugin: SampleGenPlugin
+
+samplegen {
+  pathToBuild "../../../../build"
+  pathToSamplesCommon "../../common"
+}
+apply from: "../../../../build/build.gradle"
+// END_EXCLUDE
diff --git a/admin/NfcProvisioning/buildSrc/build.gradle b/admin/NfcProvisioning/buildSrc/build.gradle
new file mode 100644
index 0000000..8c294c2
--- /dev/null
+++ b/admin/NfcProvisioning/buildSrc/build.gradle
@@ -0,0 +1,15 @@
+repositories {
+    mavenCentral()
+}
+dependencies {
+    compile 'org.freemarker:freemarker:2.3.20'
+}
+
+sourceSets {
+    main {
+        groovy {
+            srcDir new File(rootDir, "../../../../../build/buildSrc/src/main/groovy")
+        }
+    }
+}
+
diff --git a/admin/NfcProvisioning/gradle/wrapper/gradle-wrapper.jar b/admin/NfcProvisioning/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..8c0fb64
--- /dev/null
+++ b/admin/NfcProvisioning/gradle/wrapper/gradle-wrapper.jar
Binary files differ
diff --git a/admin/NfcProvisioning/gradle/wrapper/gradle-wrapper.properties b/admin/NfcProvisioning/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..23e8e21
--- /dev/null
+++ b/admin/NfcProvisioning/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,6 @@
+#Mon Jan 05 15:04:16 JST 2015
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip
diff --git a/admin/NfcProvisioning/gradlew b/admin/NfcProvisioning/gradlew
new file mode 100755
index 0000000..91a7e26
--- /dev/null
+++ b/admin/NfcProvisioning/gradlew
@@ -0,0 +1,164 @@
+#!/usr/bin/env bash
+
+##############################################################################
+##
+##  Gradle start up script for UN*X
+##
+##############################################################################
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS=""
+
+APP_NAME="Gradle"
+APP_BASE_NAME=`basename "$0"`
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD="maximum"
+
+warn ( ) {
+    echo "$*"
+}
+
+die ( ) {
+    echo
+    echo "$*"
+    echo
+    exit 1
+}
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+case "`uname`" in
+  CYGWIN* )
+    cygwin=true
+    ;;
+  Darwin* )
+    darwin=true
+    ;;
+  MINGW* )
+    msys=true
+    ;;
+esac
+
+# For Cygwin, ensure paths are in UNIX format before anything is touched.
+if $cygwin ; then
+    [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
+fi
+
+# Attempt to set APP_HOME
+# Resolve links: $0 may be a link
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+    ls=`ls -ld "$PRG"`
+    link=`expr "$ls" : '.*-> \(.*\)$'`
+    if expr "$link" : '/.*' > /dev/null; then
+        PRG="$link"
+    else
+        PRG=`dirname "$PRG"`"/$link"
+    fi
+done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >&-
+APP_HOME="`pwd -P`"
+cd "$SAVED" >&-
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+        # IBM's JDK on AIX uses strange locations for the executables
+        JAVACMD="$JAVA_HOME/jre/sh/java"
+    else
+        JAVACMD="$JAVA_HOME/bin/java"
+    fi
+    if [ ! -x "$JAVACMD" ] ; then
+        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+    fi
+else
+    JAVACMD="java"
+    which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
+    MAX_FD_LIMIT=`ulimit -H -n`
+    if [ $? -eq 0 ] ; then
+        if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
+            MAX_FD="$MAX_FD_LIMIT"
+        fi
+        ulimit -n $MAX_FD
+        if [ $? -ne 0 ] ; then
+            warn "Could not set maximum file descriptor limit: $MAX_FD"
+        fi
+    else
+        warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
+    fi
+fi
+
+# For Darwin, add options to specify how the application appears in the dock
+if $darwin; then
+    GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
+fi
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin ; then
+    APP_HOME=`cygpath --path --mixed "$APP_HOME"`
+    CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+
+    # We build the pattern for arguments to be converted via cygpath
+    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
+    SEP=""
+    for dir in $ROOTDIRSRAW ; do
+        ROOTDIRS="$ROOTDIRS$SEP$dir"
+        SEP="|"
+    done
+    OURCYGPATTERN="(^($ROOTDIRS))"
+    # Add a user-defined pattern to the cygpath arguments
+    if [ "$GRADLE_CYGPATTERN" != "" ] ; then
+        OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
+    fi
+    # Now convert the arguments - kludge to limit ourselves to /bin/sh
+    i=0
+    for arg in "$@" ; do
+        CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
+        CHECK2=`echo "$arg"|egrep -c "^-"`                                 ### Determine if an option
+
+        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition
+            eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
+        else
+            eval `echo args$i`="\"$arg\""
+        fi
+        i=$((i+1))
+    done
+    case $i in
+        (0) set -- ;;
+        (1) set -- "$args0" ;;
+        (2) set -- "$args0" "$args1" ;;
+        (3) set -- "$args0" "$args1" "$args2" ;;
+        (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
+        (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
+        (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
+        (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
+        (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
+        (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
+    esac
+fi
+
+# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
+function splitJvmOpts() {
+    JVM_OPTS=("$@")
+}
+eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
+JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
+
+exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
diff --git a/admin/NfcProvisioning/gradlew.bat b/admin/NfcProvisioning/gradlew.bat
new file mode 100644
index 0000000..aec9973
--- /dev/null
+++ b/admin/NfcProvisioning/gradlew.bat
@@ -0,0 +1,90 @@
+@if "%DEBUG%" == "" @echo off

+@rem ##########################################################################

+@rem

+@rem  Gradle startup script for Windows

+@rem

+@rem ##########################################################################

+

+@rem Set local scope for the variables with windows NT shell

+if "%OS%"=="Windows_NT" setlocal

+

+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.

+set DEFAULT_JVM_OPTS=

+

+set DIRNAME=%~dp0

+if "%DIRNAME%" == "" set DIRNAME=.

+set APP_BASE_NAME=%~n0

+set APP_HOME=%DIRNAME%

+

+@rem Find java.exe

+if defined JAVA_HOME goto findJavaFromJavaHome

+

+set JAVA_EXE=java.exe

+%JAVA_EXE% -version >NUL 2>&1

+if "%ERRORLEVEL%" == "0" goto init

+

+echo.

+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

+echo.

+echo Please set the JAVA_HOME variable in your environment to match the

+echo location of your Java installation.

+

+goto fail

+

+:findJavaFromJavaHome

+set JAVA_HOME=%JAVA_HOME:"=%

+set JAVA_EXE=%JAVA_HOME%/bin/java.exe

+

+if exist "%JAVA_EXE%" goto init

+

+echo.

+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%

+echo.

+echo Please set the JAVA_HOME variable in your environment to match the

+echo location of your Java installation.

+

+goto fail

+

+:init

+@rem Get command-line arguments, handling Windowz variants

+

+if not "%OS%" == "Windows_NT" goto win9xME_args

+if "%@eval[2+2]" == "4" goto 4NT_args

+

+:win9xME_args

+@rem Slurp the command line arguments.

+set CMD_LINE_ARGS=

+set _SKIP=2

+

+:win9xME_args_slurp

+if "x%~1" == "x" goto execute

+

+set CMD_LINE_ARGS=%*

+goto execute

+

+:4NT_args

+@rem Get arguments from the 4NT Shell from JP Software

+set CMD_LINE_ARGS=%$

+

+:execute

+@rem Setup the command line

+

+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar

+

+@rem Execute Gradle

+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%

+

+:end

+@rem End local scope for the variables with windows NT shell

+if "%ERRORLEVEL%"=="0" goto mainEnd

+

+:fail

+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of

+rem the _cmd.exe /c_ return code!

+if  not "" == "%GRADLE_EXIT_CONSOLE%" exit 1

+exit /b 1

+

+:mainEnd

+if "%OS%"=="Windows_NT" endlocal

+

+:omega

diff --git a/admin/NfcProvisioning/nfcprovisioning.txt b/admin/NfcProvisioning/nfcprovisioning.txt
new file mode 100644
index 0000000..0bbf926
--- /dev/null
+++ b/admin/NfcProvisioning/nfcprovisioning.txt
@@ -0,0 +1,7 @@
+# Sample configuration file for NfcProvisioning
+# Place this file in the SD card:
+#   $ adb push nfcprovisioning.txt /sdcard/
+
+android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME=packagename.of.your.deviceowner
+android.app.extra.PROVISIONING_LOCALE=en_GB
+android.app.extra.PROVISIONING_TIME_ZONE=America/New_York
diff --git a/admin/NfcProvisioning/screenshots/1-main.png b/admin/NfcProvisioning/screenshots/1-main.png
new file mode 100644
index 0000000..031742e
--- /dev/null
+++ b/admin/NfcProvisioning/screenshots/1-main.png
Binary files differ
diff --git a/admin/NfcProvisioning/screenshots/icon-web.png b/admin/NfcProvisioning/screenshots/icon-web.png
new file mode 100644
index 0000000..3570fee
--- /dev/null
+++ b/admin/NfcProvisioning/screenshots/icon-web.png
Binary files differ
diff --git a/admin/NfcProvisioning/settings.gradle b/admin/NfcProvisioning/settings.gradle
new file mode 100644
index 0000000..9464a35
--- /dev/null
+++ b/admin/NfcProvisioning/settings.gradle
@@ -0,0 +1 @@
+include 'Application'
diff --git a/admin/NfcProvisioning/template-params.xml b/admin/NfcProvisioning/template-params.xml
new file mode 100644
index 0000000..e5fc074
--- /dev/null
+++ b/admin/NfcProvisioning/template-params.xml
@@ -0,0 +1,89 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ 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.
+-->
+<sample>
+    <name>NfcProvisioning</name>
+    <group>Device Admin</group>
+    <package>com.example.android.nfcprovisioning</package>
+
+    <minSdk>21</minSdk>
+
+    <strings>
+        <intro>
+            <![CDATA[
+This sample demonstrates how to provision other devices with a specified device owner using NFC.
+Install the DeviceOwner sample to an unprovisioned device. Fill in the values below, and bump the
+two devices, and tap this side to initiate the provisioning process.
+            ]]>
+        </intro>
+    </strings>
+
+    <template src="base"/>
+    <template src="FragmentView"/>
+
+    <common src="logger"/>
+    <common src="activities"/>
+
+    <metadata>
+        <status>PUBLISHED</status>
+        <categories>Device Admin</categories>
+        <technologies>Android</technologies>
+        <languages>Java</languages>
+        <solutions>Mobile</solutions>
+        <level>ADVANCED</level>
+        <icon>screenshots/icon-web.png</icon>
+        <screenshots>
+            <img>screenshots/1-main.png</img>
+        </screenshots>
+        <api_refs>
+            <android>android.app.admin.DevicePolicyManager</android>
+            <android>android.nfc.NfcAdapter</android>
+        </api_refs>
+
+        <description>
+            <![CDATA[
+This sample demonstrates how to use NFC to provision a new device with a device owner. Device owner
+is a specialized type of device administrator that can control device security and configuration.
+This sample itself is not a device owner, but it is a programming app that sends NFC message to an
+unprovisioned peer device and tells it to set up the specified device owner app.
+            ]]>
+        </description>
+
+        <intro>
+            <![CDATA[
+NFC Provisioning app is nothing but an ordinary Android Beam app that just sends out provisioning
+values to the peer device. This sample uses the values below.
+
+* [EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME] - The package name of the mobile device management
+  application that will be set as the profile owner or device owner.
+* [EXTRA_PROVISIONING_LOCALE] - The Locale that the device will be set to.
+* [EXTRA_PROVISIONING_TIME_ZONE] - The time zone AlarmManager that the device will be set to.
+* [EXTRA_PROVISIONING_WIFI_SSID] - The ssid of the wifi network that should be used during nfc
+  device owner provisioning for downloading the mobile device management application.
+* [EXTRA_PROVISIONING_WIFI_PASSWORD] - The password of the wifi network in
+  EXTRA_PROVISIONING_WIFI_SSID.
+
+Store values in an instance of Properties. Get a byte array representation of the Properties using
+ByteArrayOutputStream. Create an NdefRecord with the MIME type of
+[DevicePolicyManager.MIME_TYPE_PROVISIONING_NFC][1]. Use [NfcAdapter#setNdefPushMessage][2] to set
+the NdefMessage as the message to be sent.
+
+[1]: https://developer.android.com/reference/android/app/admin/DevicePolicyManager.html#MIME_TYPE_PROVISIONING_NFC
+[2]: http://developer.android.com/reference/android/nfc/NfcAdapter.html#setNdefPushMessage(android.nfc.NdefMessage, android.app.Activity, android.app.Activity...)
+            ]]>
+        </intro>
+    </metadata>
+</sample>
diff --git a/background/JobScheduler/Application/tests/AndroidManifest.xml b/background/JobScheduler/Application/tests/AndroidManifest.xml
index bb06508..8234be3 100644
--- a/background/JobScheduler/Application/tests/AndroidManifest.xml
+++ b/background/JobScheduler/Application/tests/AndroidManifest.xml
@@ -1,22 +1,3 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright 2013 The Android Open Source Project
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
-     http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-
-
-
 <?xml version="1.0" encoding="utf-8"?>
 <!--
   Copyright (C) 2013 The Android Open Source Project
@@ -56,4 +37,4 @@
             android:targetPackage="com.example.android.jobscheduler"
             android:label="Tests for com.example.android.jobscheduler" />
 
-</manifest>
\ No newline at end of file
+</manifest>
diff --git a/background/JobScheduler/Application/tests/src/com/example/android/jobscheduler/tests/SampleTests.java b/background/JobScheduler/Application/tests/src/com/example/android/jobscheduler/tests/SampleTests.java
index d791b6e..75287c1 100644
--- a/background/JobScheduler/Application/tests/src/com/example/android/jobscheduler/tests/SampleTests.java
+++ b/background/JobScheduler/Application/tests/src/com/example/android/jobscheduler/tests/SampleTests.java
@@ -1,22 +1,4 @@
 /*
-* Copyright 2013 The Android Open Source Project
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-
-
-/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
@@ -43,7 +25,6 @@
 public class SampleTests extends ActivityInstrumentationTestCase2<MainActivity> {
 
     private MainActivity mTestActivity;
-    private JobSchedulerFragment mTestFragment;
 
     public SampleTests() {
         super(MainActivity.class);
@@ -58,8 +39,6 @@
         // flags = {@link Intent#FLAG_ACTIVITY_NEW_TASK}
         // All other fields are null or empty.
         mTestActivity = getActivity();
-        mTestFragment = (JobSchedulerFragment)
-            mTestActivity.getSupportFragmentManager().getFragments().get(1);
     }
 
     /**
@@ -69,11 +48,10 @@
         //Try to add a message to add context to your assertions. These messages will be shown if
         //a tests fails and make it easy to understand why a test failed
         assertNotNull("mTestActivity is null", mTestActivity);
-        assertNotNull("mTestFragment is null", mTestFragment);
     }
 
     /**
     * Add more tests below.
     */
 
-}
\ No newline at end of file
+}
diff --git a/build.gradle b/build.gradle
index 082f67d..997b3de 100644
--- a/build.gradle
+++ b/build.gradle
@@ -36,6 +36,7 @@
 "renderScript/RenderScriptIntrinsic",
 "ui/views/SlidingTabs/SlidingTabsBasic",
 "ui/views/SlidingTabs/SlidingTabsColors",
+"connectivity/nfc/BeamLargeFiles",
 "connectivity/nfc/CardEmulation",
 "connectivity/nfc/CardReader",
 "sensors/BatchStepSensor",
diff --git a/connectivity/bluetooth/BluetoothChat/screenshots/1-launch.png b/connectivity/bluetooth/BluetoothChat/screenshots/1-launch.png
new file mode 100644
index 0000000..6b6741e
--- /dev/null
+++ b/connectivity/bluetooth/BluetoothChat/screenshots/1-launch.png
Binary files differ
diff --git a/connectivity/bluetooth/BluetoothChat/screenshots/2-devices.png b/connectivity/bluetooth/BluetoothChat/screenshots/2-devices.png
new file mode 100644
index 0000000..db31dc0
--- /dev/null
+++ b/connectivity/bluetooth/BluetoothChat/screenshots/2-devices.png
Binary files differ
diff --git a/connectivity/bluetooth/BluetoothChat/screenshots/3-chat.png b/connectivity/bluetooth/BluetoothChat/screenshots/3-chat.png
new file mode 100644
index 0000000..65830e8
--- /dev/null
+++ b/connectivity/bluetooth/BluetoothChat/screenshots/3-chat.png
Binary files differ
diff --git a/connectivity/bluetooth/BluetoothChat/screenshots/icon-web.png b/connectivity/bluetooth/BluetoothChat/screenshots/icon-web.png
new file mode 100644
index 0000000..737f347
--- /dev/null
+++ b/connectivity/bluetooth/BluetoothChat/screenshots/icon-web.png
Binary files differ
diff --git a/connectivity/bluetooth/BluetoothChat/template-params.xml b/connectivity/bluetooth/BluetoothChat/template-params.xml
index a4ca497..2bf81c3 100644
--- a/connectivity/bluetooth/BluetoothChat/template-params.xml
+++ b/connectivity/bluetooth/BluetoothChat/template-params.xml
@@ -47,4 +47,59 @@
     <!-- Include common code modules by uncommenting them below. -->
     <common src="logger" />
     <common src="activities"/>
+
+    <metadata>
+        <status>PUBLISHED</status>
+        <categories>Connectivity</categories>
+        <technologies>Android</technologies>
+        <languages>Java</languages>
+        <solutions>Mobile</solutions>
+        <level>ADVANCED</level>
+        <icon>screenshots/icon-web.png</icon>
+        <screenshots>
+            <img>screenshots/1-launch.png</img>
+            <img>screenshots/2-devices.png</img>
+            <img>screenshots/3-chat.png</img>
+        </screenshots>
+        <api_refs>
+            <android>android.bluetooth.BluetoothAdapter</android>
+            <android>android.bluetooth.BluetoothDevice</android>
+            <android>android.bluetooth.BluetoothServerSocket</android>
+            <android>android.bluetooth.BluetoothSocket</android>
+        </api_refs>
+
+        <description>
+<![CDATA[
+This sample shows how to implement two-way text chat over Bluetooth between two Android devices, using
+all the fundamental Bluetooth API capabilities.
+]]>
+        </description>
+
+        <intro>
+<![CDATA[
+This sample should be run on two Android devices at the same time, to establish a two-way chat over
+Bluetooth between the devices. Select "Made discoverable" in overflow menu on one device and click
+on the Bluetooth icon on the other one, to find the device and establish the connection.
+
+The sample demonstrates the following, using the [Bluetooth API][1]:
+
+1. [Setting up][2] Bluetooth
+2. [Scanning][3] for other Bluetooth devices
+3. [Querying][4] the local Bluetooth adapter for paired Bluetooth devices
+4. [Establishing RFCOMM][5] channels/sockets
+5. [Connecting][6] to a remote device
+6. [Transfering][7] data over Bluetooth
+
+[1]: http://developer.android.com/guide/topics/connectivity/bluetooth.html
+[2]: http://developer.android.com/guide/topics/connectivity/bluetooth.html#Permissions
+[3]: http://developer.android.com/guide/topics/connectivity/bluetooth.html#FindingDevices
+[4]: http://developer.android.com/guide/topics/connectivity/bluetooth.html#QueryingPairedDevices
+[5]: http://developer.android.com/guide/topics/connectivity/bluetooth.html#ConnectingDevices
+[6]: http://developer.android.com/guide/topics/connectivity/bluetooth.html#ConnectingAsAClient
+[7]: http://developer.android.com/guide/topics/connectivity/bluetooth.html#ManagingAConnection
+]]>
+        </intro>
+    </metadata>
+
+
 </sample>
diff --git a/connectivity/network/BasicNetworking/Application/tests/src/com/example/android/basicnetworking/tests/SampleTests.java b/connectivity/network/BasicNetworking/Application/tests/src/com/example/android/basicnetworking/tests/SampleTests.java
index 0cf077e..50b7ea7 100644
--- a/connectivity/network/BasicNetworking/Application/tests/src/com/example/android/basicnetworking/tests/SampleTests.java
+++ b/connectivity/network/BasicNetworking/Application/tests/src/com/example/android/basicnetworking/tests/SampleTests.java
@@ -43,7 +43,6 @@
 public class SampleTests extends ActivityInstrumentationTestCase2<MainActivity> {
 
     private MainActivity mTestActivity;
-    private BasicNetworkingFragment mTestFragment;
 
     public SampleTests() {
         super(MainActivity.class);
@@ -58,8 +57,6 @@
         // flags = {@link Intent#FLAG_ACTIVITY_NEW_TASK}
         // All other fields are null or empty.
         mTestActivity = getActivity();
-        mTestFragment = (BasicNetworkingFragment)
-            mTestActivity.getSupportFragmentManager().getFragments().get(1);
     }
 
     /**
@@ -69,11 +66,10 @@
         //Try to add a message to add context to your assertions. These messages will be shown if
         //a tests fails and make it easy to understand why a test failed
         assertNotNull("mTestActivity is null", mTestActivity);
-        assertNotNull("mTestFragment is null", mTestFragment);
     }
 
     /**
     * Add more tests below.
     */
 
-}
\ No newline at end of file
+}
diff --git a/connectivity/network/NetworkConnect/Application/tests/src/com/example/android/networkconnect/tests/SampleTests.java b/connectivity/network/NetworkConnect/Application/tests/src/com/example/android/networkconnect/tests/SampleTests.java
index a554964..ab441b2 100644
--- a/connectivity/network/NetworkConnect/Application/tests/src/com/example/android/networkconnect/tests/SampleTests.java
+++ b/connectivity/network/NetworkConnect/Application/tests/src/com/example/android/networkconnect/tests/SampleTests.java
@@ -1,22 +1,4 @@
 /*
-* Copyright 2013 The Android Open Source Project
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-
-
-/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
@@ -43,7 +25,6 @@
 public class SampleTests extends ActivityInstrumentationTestCase2<MainActivity> {
 
     private MainActivity mTestActivity;
-    private NetworkConnectFragment mTestFragment;
 
     public SampleTests() {
         super(MainActivity.class);
@@ -58,8 +39,6 @@
         // flags = {@link Intent#FLAG_ACTIVITY_NEW_TASK}
         // All other fields are null or empty.
         mTestActivity = getActivity();
-        mTestFragment = (NetworkConnectFragment)
-            mTestActivity.getSupportFragmentManager().getFragments().get(1);
     }
 
     /**
@@ -69,11 +48,10 @@
         //Try to add a message to add context to your assertions. These messages will be shown if
         //a tests fails and make it easy to understand why a test failed
         assertNotNull("mTestActivity is null", mTestActivity);
-        assertNotNull("mTestFragment is null", mTestFragment);
     }
 
     /**
     * Add more tests below.
     */
 
-}
\ No newline at end of file
+}
diff --git a/connectivity/network/NetworkConnect/screenshots/icon-web.png b/connectivity/network/NetworkConnect/screenshots/icon-web.png
new file mode 100644
index 0000000..29fb3ff
--- /dev/null
+++ b/connectivity/network/NetworkConnect/screenshots/icon-web.png
Binary files differ
diff --git a/connectivity/network/NetworkConnect/screenshots/main.png b/connectivity/network/NetworkConnect/screenshots/main.png
new file mode 100644
index 0000000..1c7ae0f
--- /dev/null
+++ b/connectivity/network/NetworkConnect/screenshots/main.png
Binary files differ
diff --git a/connectivity/network/NetworkConnect/template-params.xml b/connectivity/network/NetworkConnect/template-params.xml
index a1d5991..4c0618d 100644
--- a/connectivity/network/NetworkConnect/template-params.xml
+++ b/connectivity/network/NetworkConnect/template-params.xml
@@ -37,4 +37,37 @@
     <template src="base"/>
     <common src="logger"/>
 
+    <metadata>
+        <status>PUBLISHED</status>
+        <categories>Connectivity</categories>
+        <technologies>Android</technologies>
+        <languages>Java</languages>
+        <solutions>Mobile</solutions>
+        <level>INTERMEDIATE</level>
+        <icon>screenshots/icon-web.png</icon>
+        <screenshots>
+            <img>screenshots/main.png</img>
+        </screenshots>
+        <api_refs>
+            <android>android.os.AsyncTask</android>
+        </api_refs>
+
+        <description>
+            <![CDATA[
+This sample demonstrates how to connect to the network and fetch raw HTML using
+HttpURLConnection. AsyncTask is used to perform the fetch on a background thread.
+            ]]>
+        </description>
+
+        <intro>
+            <![CDATA[
+This sample application demonstrates how to connect to the network and fetch raw
+HTML. It uses AsyncTask, a background task manager, to perform the network fetch
+on a background thread. By using AsyncTask, the app can avoid hanging on the UI
+thread, and instead update the UI when the response is ready. To establish the
+network connection, the sample uses HttpURLConnection.
+            ]]>
+        </intro>
+    </metadata>
+
 </sample>
diff --git a/connectivity/nfc/BeamLargeFiles/Application/tests/AndroidManifest.xml b/connectivity/nfc/BeamLargeFiles/Application/tests/AndroidManifest.xml
index a046afc..bd10d6f 100644
--- a/connectivity/nfc/BeamLargeFiles/Application/tests/AndroidManifest.xml
+++ b/connectivity/nfc/BeamLargeFiles/Application/tests/AndroidManifest.xml
@@ -16,7 +16,7 @@
   -->
 <!-- package name must be unique so suffix with "tests" so package loader doesn't ignore us -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-          package="${sample.package}.tests"
+          package="com.example.android.beamlargefiles.tests"
           android:versionCode="1"
           android:versionName="1.0">
 
@@ -34,7 +34,7 @@
     -->
     <instrumentation
             android:name="android.test.InstrumentationTestRunner"
-            android:targetPackage="${sample.package}"
-            android:label="Tests for ${sample.package}" />
+            android:targetPackage="com.example.android.beamlargefiles"
+            android:label="Tests for com.example.android.beamlargefiles" />
 
 </manifest>
\ No newline at end of file
diff --git a/connectivity/nfc/CardEmulation/Application/tests/AndroidManifest.xml b/connectivity/nfc/CardEmulation/Application/tests/AndroidManifest.xml
index d1ec341..8ff5bf8 100644
--- a/connectivity/nfc/CardEmulation/Application/tests/AndroidManifest.xml
+++ b/connectivity/nfc/CardEmulation/Application/tests/AndroidManifest.xml
@@ -16,7 +16,7 @@
   -->
 <!-- package name must be unique so suffix with "tests" so package loader doesn't ignore us -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-          package="${sample.package}.tests"
+          package="com.example.android.cardemulation.tests"
           android:versionCode="1"
           android:versionName="1.0">
 
diff --git a/connectivity/nfc/CardReader/Application/tests/AndroidManifest.xml b/connectivity/nfc/CardReader/Application/tests/AndroidManifest.xml
index fd702fc..0e31a3b 100644
--- a/connectivity/nfc/CardReader/Application/tests/AndroidManifest.xml
+++ b/connectivity/nfc/CardReader/Application/tests/AndroidManifest.xml
@@ -1,22 +1,3 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright 2013 The Android Open Source Project
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
-     http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-
-
-
 <?xml version="1.0" encoding="utf-8"?>
 <!--
   Copyright (C) 2013 The Android Open Source Project
@@ -56,4 +37,4 @@
             android:targetPackage="com.example.android.cardreader"
             android:label="Tests for com.example.android.cardreader" />
 
-</manifest>
\ No newline at end of file
+</manifest>
diff --git a/connectivity/sync/BasicSyncAdapter/Application/src/main/java/com/example/android/basicsyncadapter/SyncAdapter.java b/connectivity/sync/BasicSyncAdapter/Application/src/main/java/com/example/android/basicsyncadapter/SyncAdapter.java
index da67107..78d5865 100644
--- a/connectivity/sync/BasicSyncAdapter/Application/src/main/java/com/example/android/basicsyncadapter/SyncAdapter.java
+++ b/connectivity/sync/BasicSyncAdapter/Application/src/main/java/com/example/android/basicsyncadapter/SyncAdapter.java
@@ -250,9 +250,9 @@
                     // Update existing record
                     Log.i(TAG, "Scheduling update: " + existingUri);
                     batch.add(ContentProviderOperation.newUpdate(existingUri)
-                            .withValue(FeedContract.Entry.COLUMN_NAME_TITLE, title)
-                            .withValue(FeedContract.Entry.COLUMN_NAME_LINK, link)
-                            .withValue(FeedContract.Entry.COLUMN_NAME_PUBLISHED, published)
+                            .withValue(FeedContract.Entry.COLUMN_NAME_TITLE, match.title)
+                            .withValue(FeedContract.Entry.COLUMN_NAME_LINK, match.link)
+                            .withValue(FeedContract.Entry.COLUMN_NAME_PUBLISHED, match.published)
                             .build());
                     syncResult.stats.numUpdates++;
                 } else {
diff --git a/connectivity/sync/BasicSyncAdapter/Application/tests/src/com/example/android/basicsyncadapter/tests/SampleTests.java b/connectivity/sync/BasicSyncAdapter/Application/tests/src/com/example/android/basicsyncadapter/tests/SampleTests.java
index 08798ba..eea75d7 100644
--- a/connectivity/sync/BasicSyncAdapter/Application/tests/src/com/example/android/basicsyncadapter/tests/SampleTests.java
+++ b/connectivity/sync/BasicSyncAdapter/Application/tests/src/com/example/android/basicsyncadapter/tests/SampleTests.java
@@ -1,22 +1,4 @@
 /*
-* Copyright 2013 The Android Open Source Project
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-
-
-/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
@@ -40,13 +22,13 @@
 /**
 * Tests for BasicSyncAdapter sample.
 */
-public class SampleTests extends ActivityInstrumentationTestCase2<MainActivity> {
+public class SampleTests extends ActivityInstrumentationTestCase2<EntryListActivity> {
 
-    private MainActivity mTestActivity;
-    private BasicSyncAdapterFragment mTestFragment;
+    private EntryListActivity mTestActivity;
+    private EntryListFragment mTestFragment;
 
     public SampleTests() {
-        super(MainActivity.class);
+        super(EntryListActivity.class);
     }
 
     @Override
@@ -58,8 +40,8 @@
         // flags = {@link Intent#FLAG_ACTIVITY_NEW_TASK}
         // All other fields are null or empty.
         mTestActivity = getActivity();
-        mTestFragment = (BasicSyncAdapterFragment)
-            mTestActivity.getSupportFragmentManager().getFragments().get(1);
+        mTestFragment = (EntryListFragment)
+            mTestActivity.getSupportFragmentManager().getFragments().get(0);
     }
 
     /**
@@ -76,4 +58,4 @@
     * Add more tests below.
     */
 
-}
\ No newline at end of file
+}
diff --git a/wearable/wear/Timer/Application/.gitignore b/content/WidgetData/Application/.gitignore
similarity index 100%
rename from wearable/wear/Timer/Application/.gitignore
rename to content/WidgetData/Application/.gitignore
diff --git a/content/WidgetData/Application/README-fragmentview.txt b/content/WidgetData/Application/README-fragmentview.txt
new file mode 100644
index 0000000..38d903f
--- /dev/null
+++ b/content/WidgetData/Application/README-fragmentview.txt
@@ -0,0 +1,37 @@
+<!--
+        Copyright 2013 The Android Open Source Project
+
+        Licensed under the Apache License, Version 2.0 (the "License");
+        you may not use this file except in compliance with the License.
+        You may obtain a copy of the License at
+
+        http://www.apache.org/licenses/LICENSE-2.0
+
+        Unless required by applicable law or agreed to in writing, software
+        distributed under the License is distributed on an "AS IS" BASIS,
+        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+        See the License for the specific language governing permissions and
+        limitations under the License.
+-->
+
+Steps to implement FragmentView template:
+-in template-params.xml.ftl:
+    -add the following line to common imports
+        <common src="activities"/>
+
+-Add a Fragment to show behavior.  In your MainActivity.java class, it will reference a Fragment
+ called (yourProjectName)Fragment.java.  Create that file in your project, using the "main" source
+ folder instead of "common" or "templates".
+   For instance, if your package name is com.example.foo, create the file
+   src/main/java/com/example/foo/FooFragment.java
+
+
+-Within this fragment, make sure that the onCreate method has the line
+ "setHasOptionsMenu(true);", to enable the fragment to handle menu events.
+
+-In order to override menu events, override onOptionsItemSelected.
+
+-refer to sampleSamples/fragmentViewSample for a reference implementation of a
+project built on this template.
+
+
diff --git a/wearable/wear/Timer/Application/proguard-project.txt b/content/WidgetData/Application/proguard-project.txt
similarity index 100%
rename from wearable/wear/Timer/Application/proguard-project.txt
rename to content/WidgetData/Application/proguard-project.txt
diff --git a/content/WidgetData/Application/src/main/AndroidManifest.xml b/content/WidgetData/Application/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..1c5fb74
--- /dev/null
+++ b/content/WidgetData/Application/src/main/AndroidManifest.xml
@@ -0,0 +1,59 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Copyright 2013 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+     http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.example.android.widgetdata"
+    android:versionCode="1"
+    android:versionName="1.0">
+
+    <uses-sdk android:minSdkVersion="4"
+        android:targetSdkVersion="20" />
+
+    <application android:allowBackup="true"
+        android:label="@string/app_name"
+        android:icon="@drawable/ic_launcher"
+        android:theme="@style/AppTheme">
+
+        <!-- The widget provider -->
+        <receiver android:name="WeatherWidgetProvider">
+            <intent-filter>
+                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
+            </intent-filter>
+            <!-- This specifies the widget provider info -->
+            <meta-data android:name="android.appwidget.provider"
+                android:resource="@xml/widgetinfo" />
+        </receiver>
+
+        <!-- The service serving the RemoteViews to the collection widget -->
+        <service android:name="WeatherWidgetService"
+            android:permission="android.permission.BIND_REMOTEVIEWS"
+            android:exported="false" />
+
+        <!-- The content provider serving the (fake) weather data -->
+        <provider android:name="WeatherDataProvider"
+            android:authorities="com.example.android.widgetdata.provider" android:exported="true" />
+
+        <activity android:name=".MainActivity"
+                  android:label="@string/app_name">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+
+</manifest>
diff --git a/content/WidgetData/Application/src/main/java/com/example/android/widgetdata/WeatherDataProvider.java b/content/WidgetData/Application/src/main/java/com/example/android/widgetdata/WeatherDataProvider.java
new file mode 100644
index 0000000..2508f01
--- /dev/null
+++ b/content/WidgetData/Application/src/main/java/com/example/android/widgetdata/WeatherDataProvider.java
@@ -0,0 +1,135 @@
+/*
+ * 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.example.android.widgetdata;
+
+import android.content.ContentProvider;
+import android.content.ContentValues;
+import android.database.Cursor;
+import android.database.MatrixCursor;
+import android.net.Uri;
+
+import java.util.ArrayList;
+
+/**
+ * A dummy class that we are going to use internally to store weather data.  Generally, this data
+ * will be stored in an external and persistent location (ie. File, Database, SharedPreferences) so
+ * that the data can persist if the process is ever killed.  For simplicity, in this sample the
+ * data will only be stored in memory.
+ */
+class WeatherDataPoint {
+    String day;
+    int degrees;
+
+    WeatherDataPoint(String d, int deg) {
+        day = d;
+        degrees = deg;
+    }
+}
+
+/**
+ * The AppWidgetProvider for our sample weather widget.
+ */
+public class WeatherDataProvider extends ContentProvider {
+    public static final Uri CONTENT_URI =
+        Uri.parse("content://com.example.android.widgetdata.provider");
+    public static class Columns {
+        public static final String ID = "_id";
+        public static final String DAY = "day";
+        public static final String TEMPERATURE = "temperature";
+    }
+
+    /**
+     * Generally, this data will be stored in an external and persistent location (ie. File,
+     * Database, SharedPreferences) so that the data can persist if the process is ever killed.
+     * For simplicity, in this sample the data will only be stored in memory.
+     */
+    private static final ArrayList<WeatherDataPoint> sData = new ArrayList<WeatherDataPoint>();
+
+    @Override
+    public boolean onCreate() {
+        // We are going to initialize the data provider with some default values
+        sData.add(new WeatherDataPoint("Monday", 13));
+        sData.add(new WeatherDataPoint("Tuesday", 1));
+        sData.add(new WeatherDataPoint("Wednesday", 7));
+        sData.add(new WeatherDataPoint("Thursday", 4));
+        sData.add(new WeatherDataPoint("Friday", 22));
+        sData.add(new WeatherDataPoint("Saturday", -10));
+        sData.add(new WeatherDataPoint("Sunday", -13));
+        sData.add(new WeatherDataPoint("Monday", 8));
+        sData.add(new WeatherDataPoint("Tuesday", 11));
+        sData.add(new WeatherDataPoint("Wednesday", -1));
+        sData.add(new WeatherDataPoint("Thursday", 27));
+        sData.add(new WeatherDataPoint("Friday", 27));
+        sData.add(new WeatherDataPoint("Saturday", 27));
+        sData.add(new WeatherDataPoint("Sunday", 27));
+        return true;
+    }
+
+    @Override
+    public synchronized Cursor query(Uri uri, String[] projection, String selection,
+            String[] selectionArgs, String sortOrder) {
+        assert(uri.getPathSegments().isEmpty());
+
+        // In this sample, we only query without any parameters, so we can just return a cursor to
+        // all the weather data.
+        final MatrixCursor c = new MatrixCursor(
+                new String[]{ Columns.ID, Columns.DAY, Columns.TEMPERATURE });
+        for (int i = 0; i < sData.size(); ++i) {
+            final WeatherDataPoint data = sData.get(i);
+            c.addRow(new Object[]{ new Integer(i), data.day, new Integer(data.degrees) });
+        }
+        return c;
+    }
+
+    @Override
+    public String getType(Uri uri) {
+        return "vnd.android.cursor.dir/vnd.widgetdata.temperature";
+    }
+
+    @Override
+    public Uri insert(Uri uri, ContentValues values) {
+        // This example code does not support inserting
+        return null;
+    }
+
+    @Override
+    public int delete(Uri uri, String selection, String[] selectionArgs) {
+        // This example code does not support deleting
+        return 0;
+    }
+
+    @Override
+    public synchronized int update(Uri uri, ContentValues values, String selection,
+            String[] selectionArgs) {
+        assert(uri.getPathSegments().size() == 1);
+
+        // In this sample, we only update the content provider individually for each row with new
+        // temperature values.
+        final int index = Integer.parseInt(uri.getPathSegments().get(0));
+        final MatrixCursor c = new MatrixCursor(
+                new String[]{ Columns.ID, Columns.DAY, Columns.TEMPERATURE });
+        assert(0 <= index && index < sData.size());
+        final WeatherDataPoint data = sData.get(index);
+        data.degrees = values.getAsInteger(Columns.TEMPERATURE);
+
+        // Notify any listeners that the data backing the content provider has changed, and return
+        // the number of rows affected.
+        getContext().getContentResolver().notifyChange(uri, null);
+        return 1;
+    }
+
+}
diff --git a/content/WidgetData/Application/src/main/java/com/example/android/widgetdata/WeatherWidgetProvider.java b/content/WidgetData/Application/src/main/java/com/example/android/widgetdata/WeatherWidgetProvider.java
new file mode 100644
index 0000000..cd80148
--- /dev/null
+++ b/content/WidgetData/Application/src/main/java/com/example/android/widgetdata/WeatherWidgetProvider.java
@@ -0,0 +1,234 @@
+/*
+ * 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.example.android.widgetdata;
+
+import android.app.PendingIntent;
+import android.appwidget.AppWidgetManager;
+import android.appwidget.AppWidgetProvider;
+import android.content.Context;
+import android.content.Intent;
+import android.content.ComponentName;
+import android.content.ContentValues;
+import android.content.ContentResolver;
+import android.content.ContentUris;
+import android.database.Cursor;
+import android.database.ContentObserver;
+import android.net.Uri;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.HandlerThread;
+import android.widget.RemoteViews;
+import android.widget.Toast;
+
+import java.util.Random;
+
+/**
+ * Our data observer just notifies an update for all weather widgets when it detects a change.
+ */
+class WeatherDataProviderObserver extends ContentObserver {
+    private AppWidgetManager mAppWidgetManager;
+    private ComponentName mComponentName;
+
+    WeatherDataProviderObserver(AppWidgetManager mgr, ComponentName cn, Handler h) {
+        super(h);
+        mAppWidgetManager = mgr;
+        mComponentName = cn;
+    }
+
+    @Override
+    public void onChange(boolean selfChange) {
+        // The data has changed, so notify the widget that the collection view needs to be updated.
+        // In response, the factory's onDataSetChanged() will be called which will requery the
+        // cursor for the new data.
+        mAppWidgetManager.notifyAppWidgetViewDataChanged(
+                mAppWidgetManager.getAppWidgetIds(mComponentName), R.id.weather_list);
+    }
+}
+
+/**
+ * The weather widget's AppWidgetProvider.
+ */
+public class WeatherWidgetProvider extends AppWidgetProvider {
+    public static String CLICK_ACTION = "com.example.android.widgetdata.CLICK";
+    public static String REFRESH_ACTION = "com.example.android.widgetdata.REFRESH";
+    public static String EXTRA_DAY_ID = "com.example.android.widgetdata.day";
+
+    private static HandlerThread sWorkerThread;
+    private static Handler sWorkerQueue;
+    private static WeatherDataProviderObserver sDataObserver;
+    private static final int sMaxDegrees = 96;
+
+    private boolean mIsLargeLayout = true;
+    private int mHeaderWeatherState = 0;
+
+    public WeatherWidgetProvider() {
+        // Start the worker thread
+        sWorkerThread = new HandlerThread("WeatherWidgetProvider-worker");
+        sWorkerThread.start();
+        sWorkerQueue = new Handler(sWorkerThread.getLooper());
+    }
+
+    // XXX: clear the worker queue if we are destroyed?
+
+    @Override
+    public void onEnabled(Context context) {
+        // Register for external updates to the data to trigger an update of the widget.  When using
+        // content providers, the data is often updated via a background service, or in response to
+        // user interaction in the main app.  To ensure that the widget always reflects the current
+        // state of the data, we must listen for changes and update ourselves accordingly.
+        final ContentResolver r = context.getContentResolver();
+        if (sDataObserver == null) {
+            final AppWidgetManager mgr = AppWidgetManager.getInstance(context);
+            final ComponentName cn = new ComponentName(context, WeatherWidgetProvider.class);
+            sDataObserver = new WeatherDataProviderObserver(mgr, cn, sWorkerQueue);
+            r.registerContentObserver(WeatherDataProvider.CONTENT_URI, true, sDataObserver);
+        }
+    }
+
+    @Override
+    public void onReceive(Context ctx, Intent intent) {
+        final String action = intent.getAction();
+        if (action.equals(REFRESH_ACTION)) {
+            // BroadcastReceivers have a limited amount of time to do work, so for this sample, we
+            // are triggering an update of the data on another thread.  In practice, this update
+            // can be triggered from a background service, or perhaps as a result of user actions
+            // inside the main application.
+            final Context context = ctx;
+            sWorkerQueue.removeMessages(0);
+            sWorkerQueue.post(new Runnable() {
+                @Override
+                public void run() {
+                    final ContentResolver r = context.getContentResolver();
+                    final Cursor c = r.query(WeatherDataProvider.CONTENT_URI, null, null, null, 
+                            null);
+                    final int count = c.getCount();
+
+                    // We disable the data changed observer temporarily since each of the updates
+                    // will trigger an onChange() in our data observer.
+                    r.unregisterContentObserver(sDataObserver);
+                    for (int i = 0; i < count; ++i) {
+                        final Uri uri = ContentUris.withAppendedId(WeatherDataProvider.CONTENT_URI, i);
+                        final ContentValues values = new ContentValues();
+                        values.put(WeatherDataProvider.Columns.TEMPERATURE,
+                                new Random().nextInt(sMaxDegrees));
+                        r.update(uri, values, null, null);
+                    }
+                    r.registerContentObserver(WeatherDataProvider.CONTENT_URI, true, sDataObserver);
+
+                    final AppWidgetManager mgr = AppWidgetManager.getInstance(context);
+                    final ComponentName cn = new ComponentName(context, WeatherWidgetProvider.class);
+                    mgr.notifyAppWidgetViewDataChanged(mgr.getAppWidgetIds(cn), R.id.weather_list);
+                }
+            });
+
+            final int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
+                    AppWidgetManager.INVALID_APPWIDGET_ID);
+        } else if (action.equals(CLICK_ACTION)) {
+            // Show a toast
+            final int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
+                    AppWidgetManager.INVALID_APPWIDGET_ID);
+            final String day = intent.getStringExtra(EXTRA_DAY_ID);
+            final String formatStr = ctx.getResources().getString(R.string.toast_format_string);
+            Toast.makeText(ctx, String.format(formatStr, day), Toast.LENGTH_SHORT).show();
+        }
+
+        super.onReceive(ctx, intent);
+    }
+
+    private RemoteViews buildLayout(Context context, int appWidgetId, boolean largeLayout) {
+        RemoteViews rv;
+        if (largeLayout) {
+            // Specify the service to provide data for the collection widget.  Note that we need to
+            // embed the appWidgetId via the data otherwise it will be ignored.
+            final Intent intent = new Intent(context, WeatherWidgetService.class);
+            intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
+            intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
+            rv = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
+            rv.setRemoteAdapter(appWidgetId, R.id.weather_list, intent);
+
+            // Set the empty view to be displayed if the collection is empty.  It must be a sibling
+            // view of the collection view.
+            rv.setEmptyView(R.id.weather_list, R.id.empty_view);
+
+            // Bind a click listener template for the contents of the weather list.  Note that we
+            // need to update the intent's data if we set an extra, since the extras will be
+            // ignored otherwise.
+            final Intent onClickIntent = new Intent(context, WeatherWidgetProvider.class);
+            onClickIntent.setAction(WeatherWidgetProvider.CLICK_ACTION);
+            onClickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
+            onClickIntent.setData(Uri.parse(onClickIntent.toUri(Intent.URI_INTENT_SCHEME)));
+            final PendingIntent onClickPendingIntent = PendingIntent.getBroadcast(context, 0,
+                    onClickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
+            rv.setPendingIntentTemplate(R.id.weather_list, onClickPendingIntent);
+
+            // Bind the click intent for the refresh button on the widget
+            final Intent refreshIntent = new Intent(context, WeatherWidgetProvider.class);
+            refreshIntent.setAction(WeatherWidgetProvider.REFRESH_ACTION);
+            final PendingIntent refreshPendingIntent = PendingIntent.getBroadcast(context, 0,
+                    refreshIntent, PendingIntent.FLAG_UPDATE_CURRENT);
+            rv.setOnClickPendingIntent(R.id.refresh, refreshPendingIntent);
+
+            // Restore the minimal header
+            rv.setTextViewText(R.id.city_name, context.getString(R.string.city_name));
+        } else {
+            rv = new RemoteViews(context.getPackageName(), R.layout.widget_layout_small);
+
+            // Update the header to reflect the weather for "today"
+            Cursor c = context.getContentResolver().query(WeatherDataProvider.CONTENT_URI, null,
+                    null, null, null);
+            if (c.moveToPosition(0)) {
+                int tempColIndex = c.getColumnIndex(WeatherDataProvider.Columns.TEMPERATURE);
+                int temp = c.getInt(tempColIndex);
+                String formatStr = context.getResources().getString(R.string.header_format_string);
+                String header = String.format(formatStr, temp,
+                        context.getString(R.string.city_name));
+                rv.setTextViewText(R.id.city_name, header);
+            }
+            c.close();
+        }
+        return rv;
+    }
+
+    @Override
+    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
+        // Update each of the widgets with the remote adapter
+        for (int i = 0; i < appWidgetIds.length; ++i) {
+            RemoteViews layout = buildLayout(context, appWidgetIds[i], mIsLargeLayout);
+            appWidgetManager.updateAppWidget(appWidgetIds[i], layout);
+        }
+        super.onUpdate(context, appWidgetManager, appWidgetIds);
+    }
+
+    @Override
+    public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager,
+            int appWidgetId, Bundle newOptions) {
+
+        int minWidth = newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH);
+        int maxWidth = newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH);
+        int minHeight = newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT);
+        int maxHeight = newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT);
+
+        RemoteViews layout;
+        if (minHeight < 100) {
+            mIsLargeLayout = false;
+        } else {
+            mIsLargeLayout = true;
+        }
+        layout = buildLayout(context, appWidgetId, mIsLargeLayout);
+        appWidgetManager.updateAppWidget(appWidgetId, layout);
+    }
+}
diff --git a/content/WidgetData/Application/src/main/java/com/example/android/widgetdata/WeatherWidgetService.java b/content/WidgetData/Application/src/main/java/com/example/android/widgetdata/WeatherWidgetService.java
new file mode 100644
index 0000000..b88eb5f
--- /dev/null
+++ b/content/WidgetData/Application/src/main/java/com/example/android/widgetdata/WeatherWidgetService.java
@@ -0,0 +1,119 @@
+/*
+ * 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.example.android.widgetdata;
+
+import android.appwidget.AppWidgetManager;
+import android.content.Context;
+import android.content.Intent;
+import android.database.Cursor;
+import android.os.Bundle;
+import android.widget.RemoteViews;
+import android.widget.RemoteViewsService;
+
+/**
+ * This is the service that provides the factory to be bound to the collection service.
+ */
+public class WeatherWidgetService extends RemoteViewsService {
+    @Override
+    public RemoteViewsFactory onGetViewFactory(Intent intent) {
+        return new StackRemoteViewsFactory(this.getApplicationContext(), intent);
+    }
+}
+
+/**
+ * This is the factory that will provide data to the collection widget.
+ */
+class StackRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory {
+    private Context mContext;
+    private Cursor mCursor;
+    private int mAppWidgetId;
+
+    public StackRemoteViewsFactory(Context context, Intent intent) {
+        mContext = context;
+        mAppWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
+                AppWidgetManager.INVALID_APPWIDGET_ID);
+    }
+
+    public void onCreate() {
+        // Since we reload the cursor in onDataSetChanged() which gets called immediately after
+        // onCreate(), we do nothing here.
+    }
+
+    public void onDestroy() {
+        if (mCursor != null) {
+            mCursor.close();
+        }
+    }
+
+    public int getCount() {
+        return mCursor.getCount();
+    }
+
+    public RemoteViews getViewAt(int position) {
+        // Get the data for this position from the content provider
+        String day = "Unknown Day";
+        int temp = 0;
+        if (mCursor.moveToPosition(position)) {
+            final int dayColIndex = mCursor.getColumnIndex(WeatherDataProvider.Columns.DAY);
+            final int tempColIndex = mCursor.getColumnIndex(
+                    WeatherDataProvider.Columns.TEMPERATURE);
+            day = mCursor.getString(dayColIndex);
+            temp = mCursor.getInt(tempColIndex);
+        }
+
+        // Return a proper item with the proper day and temperature
+        final String formatStr = mContext.getResources().getString(R.string.item_format_string);
+        final int itemId = R.layout.widget_item;
+        RemoteViews rv = new RemoteViews(mContext.getPackageName(), itemId);
+        rv.setTextViewText(R.id.widget_item, String.format(formatStr, temp, day));
+
+        // Set the click intent so that we can handle it and show a toast message
+        final Intent fillInIntent = new Intent();
+        final Bundle extras = new Bundle();
+        extras.putString(WeatherWidgetProvider.EXTRA_DAY_ID, day);
+        fillInIntent.putExtras(extras);
+        rv.setOnClickFillInIntent(R.id.widget_item, fillInIntent);
+
+        return rv;
+    }
+    public RemoteViews getLoadingView() {
+        // We aren't going to return a default loading view in this sample
+        return null;
+    }
+
+    public int getViewTypeCount() {
+        // Technically, we have two types of views (the dark and light background views)
+        return 2;
+    }
+
+    public long getItemId(int position) {
+        return position;
+    }
+
+    public boolean hasStableIds() {
+        return true;
+    }
+
+    public void onDataSetChanged() {
+        // Refresh the cursor
+        if (mCursor != null) {
+            mCursor.close();
+        }
+        mCursor = mContext.getContentResolver().query(WeatherDataProvider.CONTENT_URI, null, null,
+                null, null);
+    }
+}
diff --git a/content/WidgetData/Application/src/main/java/com/example/android/widgetdata/WidgetDataFragment.java b/content/WidgetData/Application/src/main/java/com/example/android/widgetdata/WidgetDataFragment.java
new file mode 100644
index 0000000..b7500a9
--- /dev/null
+++ b/content/WidgetData/Application/src/main/java/com/example/android/widgetdata/WidgetDataFragment.java
@@ -0,0 +1,19 @@
+package com.example.android.widgetdata;
+
+import android.os.Bundle;
+import android.support.annotation.Nullable;
+import android.support.v4.app.Fragment;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+
+/**
+ * A Dummy Fragment that shows the intro text from a layout.
+ */
+public class WidgetDataFragment extends Fragment {
+
+    @Override
+    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
+        return inflater.inflate(R.layout.fragment, null);
+    }
+}
diff --git a/content/WidgetData/Application/src/main/res/drawable-hdpi/ic_launcher.png b/content/WidgetData/Application/src/main/res/drawable-hdpi/ic_launcher.png
new file mode 100644
index 0000000..a602e84
--- /dev/null
+++ b/content/WidgetData/Application/src/main/res/drawable-hdpi/ic_launcher.png
Binary files differ
diff --git a/content/WidgetData/Application/src/main/res/drawable-hdpi/sunny.png b/content/WidgetData/Application/src/main/res/drawable-hdpi/sunny.png
new file mode 100644
index 0000000..42785b9
--- /dev/null
+++ b/content/WidgetData/Application/src/main/res/drawable-hdpi/sunny.png
Binary files differ
diff --git a/content/WidgetData/Application/src/main/res/drawable-mdpi/ic_launcher.png b/content/WidgetData/Application/src/main/res/drawable-mdpi/ic_launcher.png
new file mode 100644
index 0000000..c828af2
--- /dev/null
+++ b/content/WidgetData/Application/src/main/res/drawable-mdpi/ic_launcher.png
Binary files differ
diff --git a/content/WidgetData/Application/src/main/res/drawable-mdpi/sunny.png b/content/WidgetData/Application/src/main/res/drawable-mdpi/sunny.png
new file mode 100644
index 0000000..9453447
--- /dev/null
+++ b/content/WidgetData/Application/src/main/res/drawable-mdpi/sunny.png
Binary files differ
diff --git a/content/WidgetData/Application/src/main/res/drawable-nodpi/preview.png b/content/WidgetData/Application/src/main/res/drawable-nodpi/preview.png
new file mode 100644
index 0000000..b9c8780
--- /dev/null
+++ b/content/WidgetData/Application/src/main/res/drawable-nodpi/preview.png
Binary files differ
diff --git a/content/WidgetData/Application/src/main/res/drawable-xhdpi/ic_launcher.png b/content/WidgetData/Application/src/main/res/drawable-xhdpi/ic_launcher.png
new file mode 100644
index 0000000..b8911f9
--- /dev/null
+++ b/content/WidgetData/Application/src/main/res/drawable-xhdpi/ic_launcher.png
Binary files differ
diff --git a/content/WidgetData/Application/src/main/res/drawable-xxhdpi/ic_launcher.png b/content/WidgetData/Application/src/main/res/drawable-xxhdpi/ic_launcher.png
new file mode 100644
index 0000000..042438f
--- /dev/null
+++ b/content/WidgetData/Application/src/main/res/drawable-xxhdpi/ic_launcher.png
Binary files differ
diff --git a/content/WidgetData/Application/src/main/res/layout/fragment.xml b/content/WidgetData/Application/src/main/res/layout/fragment.xml
new file mode 100644
index 0000000..9281e3a
--- /dev/null
+++ b/content/WidgetData/Application/src/main/res/layout/fragment.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?><!--
+ Copyright 2014 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+     http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent">
+
+    <TextView
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_marginBottom="@dimen/vertical_page_margin"
+        android:layout_marginLeft="@dimen/horizontal_page_margin"
+        android:layout_marginRight="@dimen/horizontal_page_margin"
+        android:layout_marginTop="@dimen/vertical_page_margin"
+        android:text="@string/usage" />
+
+</ScrollView>
\ No newline at end of file
diff --git a/content/WidgetData/Application/src/main/res/layout/widget_item.xml b/content/WidgetData/Application/src/main/res/layout/widget_item.xml
new file mode 100644
index 0000000..bd3b3f5
--- /dev/null
+++ b/content/WidgetData/Application/src/main/res/layout/widget_item.xml
@@ -0,0 +1,23 @@
+<?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.
+-->
+<TextView xmlns:android="http://schemas.android.com/apk/res/android"
+    android:id="@+id/widget_item"
+    android:layout_width="match_parent"
+    android:layout_height="46dp"
+    android:background="#F0F0F0"
+    android:gravity="center_vertical"
+    android:paddingLeft="25dp"
+    android:textColor="#232323"
+    android:textSize="20sp" />
diff --git a/content/WidgetData/Application/src/main/res/layout/widget_layout.xml b/content/WidgetData/Application/src/main/res/layout/widget_layout.xml
new file mode 100644
index 0000000..8aca749
--- /dev/null
+++ b/content/WidgetData/Application/src/main/res/layout/widget_layout.xml
@@ -0,0 +1,86 @@
+<?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.
+-->
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:layout_marginBottom="@dimen/widget_margin_bottom"
+    android:layout_marginLeft="@dimen/widget_margin_left"
+    android:layout_marginRight="@dimen/widget_margin_right"
+    android:layout_marginTop="@dimen/widget_margin_top"
+    android:orientation="vertical">
+    <!-- We define separate margins to allow for flexibility in twiddling the margins
+         depending on device form factor and target SDK version. -->
+
+    <LinearLayout
+        android:layout_width="match_parent"
+        android:layout_height="80dp"
+        android:background="#F8F8F8"
+        android:orientation="horizontal">
+
+        <ImageView
+            android:id="@+id/city_weather"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:adjustViewBounds="true"
+            android:padding="12dp"
+            android:scaleType="fitStart"
+            android:src="@drawable/sunny" />
+
+        <TextView
+            android:id="@+id/city_name"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_gravity="center_vertical"
+            android:text="@string/city_name"
+            android:textAllCaps="true"
+            android:textColor="#232323"
+            android:textSize="24sp" />
+    </LinearLayout>
+
+    <FrameLayout
+        android:layout_width="match_parent"
+        android:layout_height="match_parent"
+        android:layout_gravity="center"
+        android:layout_weight="1"
+        android:background="#F8F8F8">
+
+        <ListView
+            android:id="@+id/weather_list"
+            android:layout_width="match_parent"
+            android:layout_height="match_parent" />
+
+        <TextView
+            android:id="@+id/empty_view"
+            android:layout_width="match_parent"
+            android:layout_height="match_parent"
+            android:gravity="center"
+            android:text="@string/empty_view_text"
+            android:textColor="#ffffff"
+            android:textSize="20sp"
+            android:visibility="gone" />
+    </FrameLayout>
+
+    <Button
+        android:id="@+id/refresh"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:background="#F8F8F8"
+        android:gravity="center"
+        android:padding="12dp"
+        android:text="@string/refresh"
+        android:textAllCaps="true"
+        android:textColor="#232323"
+        android:textSize="14sp" />
+</LinearLayout>
diff --git a/content/WidgetData/Application/src/main/res/layout/widget_layout_small.xml b/content/WidgetData/Application/src/main/res/layout/widget_layout_small.xml
new file mode 100644
index 0000000..40fff69
--- /dev/null
+++ b/content/WidgetData/Application/src/main/res/layout/widget_layout_small.xml
@@ -0,0 +1,49 @@
+<?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.
+-->
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:layout_marginBottom="@dimen/widget_margin_bottom"
+    android:layout_marginLeft="@dimen/widget_margin_left"
+    android:layout_marginRight="@dimen/widget_margin_right"
+    android:layout_marginTop="@dimen/widget_margin_top"
+    android:orientation="vertical">
+
+    <LinearLayout
+        android:layout_width="match_parent"
+        android:layout_height="80dp"
+        android:background="#F8F8F8"
+        android:orientation="horizontal">
+
+        <ImageView
+            android:id="@+id/city_weather"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:adjustViewBounds="true"
+            android:padding="12dp"
+            android:scaleType="fitStart"
+            android:src="@drawable/sunny" />
+
+        <TextView
+            android:id="@+id/city_name"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_gravity="center_vertical"
+            android:text="@string/city_name"
+            android:textAllCaps="true"
+            android:textColor="#232323"
+            android:textSize="24sp" />
+    </LinearLayout>
+</LinearLayout>
diff --git a/content/WidgetData/Application/src/main/res/values-v14/dimens.xml b/content/WidgetData/Application/src/main/res/values-v14/dimens.xml
new file mode 100644
index 0000000..8b5494e
--- /dev/null
+++ b/content/WidgetData/Application/src/main/res/values-v14/dimens.xml
@@ -0,0 +1,21 @@
+<?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.
+-->
+<resources>
+    <dimen name="widget_margin_top">0dp</dimen>
+    <dimen name="widget_margin_bottom">0dp</dimen>
+    <dimen name="widget_margin_left">0dp</dimen>
+    <dimen name="widget_margin_right">0dp</dimen>
+</resources>
diff --git a/content/WidgetData/Application/src/main/res/values/dimens.xml b/content/WidgetData/Application/src/main/res/values/dimens.xml
new file mode 100644
index 0000000..00257a9
--- /dev/null
+++ b/content/WidgetData/Application/src/main/res/values/dimens.xml
@@ -0,0 +1,21 @@
+<?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.
+-->
+<resources>
+    <dimen name="widget_margin_top">8dp</dimen>
+    <dimen name="widget_margin_bottom">8dp</dimen>
+    <dimen name="widget_margin_left">8dp</dimen>
+    <dimen name="widget_margin_right">8dp</dimen>
+</resources>
\ No newline at end of file
diff --git a/content/WidgetData/Application/src/main/res/values/strings.xml b/content/WidgetData/Application/src/main/res/values/strings.xml
new file mode 100644
index 0000000..00fbb9a
--- /dev/null
+++ b/content/WidgetData/Application/src/main/res/values/strings.xml
@@ -0,0 +1,25 @@
+<?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.
+-->
+<resources>
+    <string name="empty_view_text">No cities found...</string>
+    <string name="toast_format_string">%1$s!</string>
+    <string name="item_format_string">%1$d\u00B0 on %2$s</string>
+    <string name="header_format_string">%1$d\u00B0 in %2$s</string>
+
+    <string name="refresh">Refresh</string>
+    <string name="city_name">San Francisco</string>
+    <string name="usage">Add the widget named <b>Widget Data</b> to your home screen to use this sample.</string>
+</resources>
diff --git a/content/WidgetData/Application/src/main/res/xml/widgetinfo.xml b/content/WidgetData/Application/src/main/res/xml/widgetinfo.xml
new file mode 100644
index 0000000..2e41943
--- /dev/null
+++ b/content/WidgetData/Application/src/main/res/xml/widgetinfo.xml
@@ -0,0 +1,26 @@
+<?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.
+-->
+<appwidget-provider
+  xmlns:android="http://schemas.android.com/apk/res/android"
+  android:minWidth="280dp"
+  android:minHeight="180dp"
+  android:updatePeriodMillis="1800000"
+  android:initialLayout="@layout/widget_layout"
+  android:resizeMode="vertical"
+  android:minResizeWidth="280dp"
+  android:minResizeHeight="70dp"
+  android:previewImage="@drawable/preview">
+</appwidget-provider>
diff --git a/content/WidgetData/Application/tests/AndroidManifest.xml b/content/WidgetData/Application/tests/AndroidManifest.xml
new file mode 100644
index 0000000..bd7282d
--- /dev/null
+++ b/content/WidgetData/Application/tests/AndroidManifest.xml
@@ -0,0 +1,42 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  Copyright (C) 2013 The Android Open Source Project
+
+  Licensed under the Apache License, Version 2.0 (the "License");
+  you may not use this file except in compliance with the License.
+  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+  -->
+<!-- package name must be unique so suffix with "tests" so package loader doesn't ignore us -->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="com.example.android.widgetdata.tests"
+          android:versionCode="1"
+          android:versionName="1.0">
+
+    <uses-sdk
+            android:minSdkVersion="18"
+            android:targetSdkVersion="19" />
+
+    <!-- We add an application tag here just so that we can indicate that
+         this package needs to link against the android.test library,
+         which is needed when building test cases. -->
+    <application>
+        <uses-library android:name="android.test.runner" />
+    </application>
+
+    <!--
+    Specifies the instrumentation test runner used to run the tests.
+    -->
+    <instrumentation
+            android:name="android.test.InstrumentationTestRunner"
+            android:targetPackage="com.example.android.widgetdata"
+            />
+
+</manifest>
diff --git a/content/WidgetData/Application/tests/src/com/example/android/widgetdata/tests/SampleTests.java b/content/WidgetData/Application/tests/src/com/example/android/widgetdata/tests/SampleTests.java
new file mode 100644
index 0000000..2c1131a
--- /dev/null
+++ b/content/WidgetData/Application/tests/src/com/example/android/widgetdata/tests/SampleTests.java
@@ -0,0 +1,61 @@
+/*
+* Copyright (C) 2013 The Android Open Source Project
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package com.example.android.widgetdata.tests;
+
+import com.example.android.widgetdata.*;
+
+import android.test.ActivityInstrumentationTestCase2;
+
+/**
+* Tests for listwidget sample.
+*/
+public class SampleTests extends ActivityInstrumentationTestCase2<MainActivity> {
+
+    private MainActivity mTestActivity;
+    private WidgetDataFragment mTestFragment;
+
+    public SampleTests() {
+        super(MainActivity.class);
+    }
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+
+        // Starts the activity under test using the default Intent with:
+        // action = {@link Intent#ACTION_MAIN}
+        // flags = {@link Intent#FLAG_ACTIVITY_NEW_TASK}
+        // All other fields are null or empty.
+        mTestActivity = getActivity();
+        mTestFragment = (WidgetDataFragment)
+            mTestActivity.getSupportFragmentManager().getFragments().get(1);
+    }
+
+    /**
+    * Test if the test fixture has been set up correctly.
+    */
+    public void testPreconditions() {
+        //Try to add a message to add context to your assertions. These messages will be shown if
+        //a tests fails and make it easy to understand why a test failed
+        assertNotNull("mTestActivity is null", mTestActivity);
+        assertNotNull("mTestFragment is null", mTestFragment);
+    }
+
+    /**
+    * Add more tests below.
+    */
+
+}
diff --git a/content/WidgetData/LICENSE b/content/WidgetData/LICENSE
new file mode 100644
index 0000000..1af981f
--- /dev/null
+++ b/content/WidgetData/LICENSE
@@ -0,0 +1,201 @@
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright 2014 The Android Open Source Project
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
diff --git a/content/WidgetData/README.md b/content/WidgetData/README.md
new file mode 100644
index 0000000..cdba710
--- /dev/null
+++ b/content/WidgetData/README.md
@@ -0,0 +1,67 @@
+Android WidgetData Sample
+===================================
+
+Sample demonstrating how to instantiate an ActionBar on Android, define
+action items, and set an "up" navigation link. Uses the Support Library
+for compatibility with pre-3.0 devices.
+
+Introduction
+------------
+
+Long intro here.
+
+Multi-paragraph introduction to sample, from an educational point-of-view.
+*Makrdown* formatting allowed. See [Markdown Documentation][1]
+for details.
+
+[1]: http://daringfireball.net/projects/markdown/syntax
+
+Pre-requisites
+--------------
+
+- Android SDK v21
+- Android Build Tools v21.1.1
+- Android Support Repository
+
+Screenshots
+-------------
+
+<img src="screenshots/1-main.png" height="400" alt="Screenshot"/> <img src="screenshots/2-settings.png" height="400" alt="Screenshot"/> 
+
+Getting Started
+---------------
+
+This sample uses the Gradle build system. To build this project, use the
+"gradlew build" command or use "Import Project" in Android Studio.
+
+Support
+-------
+
+- Google+ Community: https://plus.google.com/communities/105153134372062985968
+- Stack Overflow: http://stackoverflow.com/questions/tagged/android
+
+If you've found an error in this sample, please file an issue:
+https://github.com/googlesamples/android-WidgetData
+
+Patches are encouraged, and may be submitted by forking this project and
+submitting a pull request through GitHub. Please see CONTRIBUTING.md for more details.
+
+License
+-------
+
+Copyright 2014 The Android Open Source Project, Inc.
+
+Licensed to the Apache Software Foundation (ASF) under one or more contributor
+license agreements.  See the NOTICE file distributed with this work for
+additional information regarding copyright ownership.  The ASF licenses this
+file to you 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.
diff --git a/content/WidgetData/build.gradle b/content/WidgetData/build.gradle
new file mode 100644
index 0000000..2b8d1ef
--- /dev/null
+++ b/content/WidgetData/build.gradle
@@ -0,0 +1,11 @@
+
+// BEGIN_EXCLUDE
+import com.example.android.samples.build.SampleGenPlugin
+apply plugin: SampleGenPlugin
+
+samplegen {
+  pathToBuild "../../../../build"
+  pathToSamplesCommon "../../common"
+}
+apply from: "../../../../build/build.gradle"
+// END_EXCLUDE
diff --git a/content/WidgetData/buildSrc/build.gradle b/content/WidgetData/buildSrc/build.gradle
new file mode 100644
index 0000000..8c294c2
--- /dev/null
+++ b/content/WidgetData/buildSrc/build.gradle
@@ -0,0 +1,15 @@
+repositories {
+    mavenCentral()
+}
+dependencies {
+    compile 'org.freemarker:freemarker:2.3.20'
+}
+
+sourceSets {
+    main {
+        groovy {
+            srcDir new File(rootDir, "../../../../../build/buildSrc/src/main/groovy")
+        }
+    }
+}
+
diff --git a/content/WidgetData/gradle/wrapper/gradle-wrapper.jar b/content/WidgetData/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..8c0fb64
--- /dev/null
+++ b/content/WidgetData/gradle/wrapper/gradle-wrapper.jar
Binary files differ
diff --git a/content/WidgetData/gradle/wrapper/gradle-wrapper.properties b/content/WidgetData/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..fe55261
--- /dev/null
+++ b/content/WidgetData/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,6 @@
+#Wed Jan 07 17:32:06 EST 2015
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip
diff --git a/content/WidgetData/gradlew b/content/WidgetData/gradlew
new file mode 100755
index 0000000..91a7e26
--- /dev/null
+++ b/content/WidgetData/gradlew
@@ -0,0 +1,164 @@
+#!/usr/bin/env bash
+
+##############################################################################
+##
+##  Gradle start up script for UN*X
+##
+##############################################################################
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS=""
+
+APP_NAME="Gradle"
+APP_BASE_NAME=`basename "$0"`
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD="maximum"
+
+warn ( ) {
+    echo "$*"
+}
+
+die ( ) {
+    echo
+    echo "$*"
+    echo
+    exit 1
+}
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+case "`uname`" in
+  CYGWIN* )
+    cygwin=true
+    ;;
+  Darwin* )
+    darwin=true
+    ;;
+  MINGW* )
+    msys=true
+    ;;
+esac
+
+# For Cygwin, ensure paths are in UNIX format before anything is touched.
+if $cygwin ; then
+    [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
+fi
+
+# Attempt to set APP_HOME
+# Resolve links: $0 may be a link
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+    ls=`ls -ld "$PRG"`
+    link=`expr "$ls" : '.*-> \(.*\)$'`
+    if expr "$link" : '/.*' > /dev/null; then
+        PRG="$link"
+    else
+        PRG=`dirname "$PRG"`"/$link"
+    fi
+done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >&-
+APP_HOME="`pwd -P`"
+cd "$SAVED" >&-
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+        # IBM's JDK on AIX uses strange locations for the executables
+        JAVACMD="$JAVA_HOME/jre/sh/java"
+    else
+        JAVACMD="$JAVA_HOME/bin/java"
+    fi
+    if [ ! -x "$JAVACMD" ] ; then
+        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+    fi
+else
+    JAVACMD="java"
+    which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
+    MAX_FD_LIMIT=`ulimit -H -n`
+    if [ $? -eq 0 ] ; then
+        if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
+            MAX_FD="$MAX_FD_LIMIT"
+        fi
+        ulimit -n $MAX_FD
+        if [ $? -ne 0 ] ; then
+            warn "Could not set maximum file descriptor limit: $MAX_FD"
+        fi
+    else
+        warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
+    fi
+fi
+
+# For Darwin, add options to specify how the application appears in the dock
+if $darwin; then
+    GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
+fi
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin ; then
+    APP_HOME=`cygpath --path --mixed "$APP_HOME"`
+    CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+
+    # We build the pattern for arguments to be converted via cygpath
+    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
+    SEP=""
+    for dir in $ROOTDIRSRAW ; do
+        ROOTDIRS="$ROOTDIRS$SEP$dir"
+        SEP="|"
+    done
+    OURCYGPATTERN="(^($ROOTDIRS))"
+    # Add a user-defined pattern to the cygpath arguments
+    if [ "$GRADLE_CYGPATTERN" != "" ] ; then
+        OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
+    fi
+    # Now convert the arguments - kludge to limit ourselves to /bin/sh
+    i=0
+    for arg in "$@" ; do
+        CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
+        CHECK2=`echo "$arg"|egrep -c "^-"`                                 ### Determine if an option
+
+        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition
+            eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
+        else
+            eval `echo args$i`="\"$arg\""
+        fi
+        i=$((i+1))
+    done
+    case $i in
+        (0) set -- ;;
+        (1) set -- "$args0" ;;
+        (2) set -- "$args0" "$args1" ;;
+        (3) set -- "$args0" "$args1" "$args2" ;;
+        (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
+        (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
+        (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
+        (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
+        (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
+        (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
+    esac
+fi
+
+# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
+function splitJvmOpts() {
+    JVM_OPTS=("$@")
+}
+eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
+JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
+
+exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
diff --git a/content/WidgetData/gradlew.bat b/content/WidgetData/gradlew.bat
new file mode 100644
index 0000000..aec9973
--- /dev/null
+++ b/content/WidgetData/gradlew.bat
@@ -0,0 +1,90 @@
+@if "%DEBUG%" == "" @echo off

+@rem ##########################################################################

+@rem

+@rem  Gradle startup script for Windows

+@rem

+@rem ##########################################################################

+

+@rem Set local scope for the variables with windows NT shell

+if "%OS%"=="Windows_NT" setlocal

+

+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.

+set DEFAULT_JVM_OPTS=

+

+set DIRNAME=%~dp0

+if "%DIRNAME%" == "" set DIRNAME=.

+set APP_BASE_NAME=%~n0

+set APP_HOME=%DIRNAME%

+

+@rem Find java.exe

+if defined JAVA_HOME goto findJavaFromJavaHome

+

+set JAVA_EXE=java.exe

+%JAVA_EXE% -version >NUL 2>&1

+if "%ERRORLEVEL%" == "0" goto init

+

+echo.

+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

+echo.

+echo Please set the JAVA_HOME variable in your environment to match the

+echo location of your Java installation.

+

+goto fail

+

+:findJavaFromJavaHome

+set JAVA_HOME=%JAVA_HOME:"=%

+set JAVA_EXE=%JAVA_HOME%/bin/java.exe

+

+if exist "%JAVA_EXE%" goto init

+

+echo.

+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%

+echo.

+echo Please set the JAVA_HOME variable in your environment to match the

+echo location of your Java installation.

+

+goto fail

+

+:init

+@rem Get command-line arguments, handling Windowz variants

+

+if not "%OS%" == "Windows_NT" goto win9xME_args

+if "%@eval[2+2]" == "4" goto 4NT_args

+

+:win9xME_args

+@rem Slurp the command line arguments.

+set CMD_LINE_ARGS=

+set _SKIP=2

+

+:win9xME_args_slurp

+if "x%~1" == "x" goto execute

+

+set CMD_LINE_ARGS=%*

+goto execute

+

+:4NT_args

+@rem Get arguments from the 4NT Shell from JP Software

+set CMD_LINE_ARGS=%$

+

+:execute

+@rem Setup the command line

+

+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar

+

+@rem Execute Gradle

+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%

+

+:end

+@rem End local scope for the variables with windows NT shell

+if "%ERRORLEVEL%"=="0" goto mainEnd

+

+:fail

+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of

+rem the _cmd.exe /c_ return code!

+if  not "" == "%GRADLE_EXIT_CONSOLE%" exit 1

+exit /b 1

+

+:mainEnd

+if "%OS%"=="Windows_NT" endlocal

+

+:omega

diff --git a/content/WidgetData/screenshots/1-widget.png b/content/WidgetData/screenshots/1-widget.png
new file mode 100644
index 0000000..3d2b8d3
--- /dev/null
+++ b/content/WidgetData/screenshots/1-widget.png
Binary files differ
diff --git a/content/WidgetData/screenshots/icon-web.png b/content/WidgetData/screenshots/icon-web.png
new file mode 100644
index 0000000..8a9d0bd
--- /dev/null
+++ b/content/WidgetData/screenshots/icon-web.png
Binary files differ
diff --git a/content/WidgetData/settings.gradle b/content/WidgetData/settings.gradle
new file mode 100644
index 0000000..9464a35
--- /dev/null
+++ b/content/WidgetData/settings.gradle
@@ -0,0 +1 @@
+include 'Application'
diff --git a/content/WidgetData/template-params.xml b/content/WidgetData/template-params.xml
new file mode 100644
index 0000000..552f3a2
--- /dev/null
+++ b/content/WidgetData/template-params.xml
@@ -0,0 +1,86 @@
+<?xml version="1.0" encoding="UTF-8"?><!--
+ Copyright 2013 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+     http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<sample>
+    <name>WidgetData</name>
+    <group>Content</group>
+    <package>com.example.android.widgetdata</package>
+
+    <!-- change minSdk if needed-->
+    <minSdk>11</minSdk>
+
+    <strings>
+        <intro>
+            <![CDATA[
+            This sample demonstrates how to create a list-based widget specifically backed by a
+            content provider.\n\n
+This sample uses a collection view (a ListView) to present some mock weather data in a widget.
+In particular, we will be using a content provider to demonstrate how the widget can retrieve data
+and update itself when you are using more complex data sources.
+When working with external data, or data which must be fetched over high latency, it is important
+to keep the data cached in a persistent location so that the widget feels responsive.
+            ]]>
+        </intro>
+    </strings>
+
+    <template src="base" />
+    <template src="FragmentView" />
+    <common src="activities"/>
+    <common src="logger" />
+
+    <metadata>
+    <status>PUBLISHED</status>
+    <categories>Content</categories>
+    <technologies>Android</technologies>
+    <languages>Java</languages>
+    <solutions>Mobile</solutions>
+    <level>INTERMEDIATE</level>
+    <icon>screenshots/icon-web.png</icon>
+    <screenshots>
+        <img>screenshots/1-widget.png</img>
+    </screenshots>
+    <api_refs>
+        <android>android.widget.RemoteViews</android>
+        <android>android.widget.RemoteViewsService</android>
+        <android>android.database.ContentObserver</android>
+        <android>android.content.ContentResolver</android>
+    </api_refs>
+    <description>
+<![CDATA[
+This sample demonstrates how to create a list-based widget specifically backed 
+by a content provider.
+]]>
+    </description>
+    <intro>
+<![CDATA[
+This sample uses a collection view (a ListView) to present some mock weather data in a widget.
+In particular, we will be using a content provider to demonstrate how the widget can retrieve data
+and update itself when you are using more complex data sources.
+When working with external data, or data which must be fetched over high latency, it is important
+to keep the data cached in a persistent location so that the widget feels responsive.
+
+We define a [ContentProvider][1] that handles queries from a [RemoteView][2] [ListView][3] widget.
+A [ContentObserver][4] notifies the widget when data changes in the ContentProvider.
+Data for the widget is provided by a [RemoteViewsService][5] that populates a RemoteView collection (the ListView).
+
+[1]: http://developer.android.com/reference/android/content/ContentProvider.html
+[2]: http://developer.android.com/reference/android/widget/RemoteViews.RemoteView.html
+[3]: http://developer.android.com/reference/android/widget/ListView.html
+[4]: http://developer.android.com/reference/android/database/ContentObserver.html
+[5]: http://developer.android.com/reference/android/widget/RemoteViewsService.html
+]]>
+    </intro>
+</metadata>
+</sample>
diff --git a/content/contacts/BasicContactables/Application/tests/src/com/example/android/basiccontactables/tests/SampleTests.java b/content/contacts/BasicContactables/Application/tests/src/com/example/android/basiccontactables/tests/SampleTests.java
index dd48bf2..b9bc1f5 100644
--- a/content/contacts/BasicContactables/Application/tests/src/com/example/android/basiccontactables/tests/SampleTests.java
+++ b/content/contacts/BasicContactables/Application/tests/src/com/example/android/basiccontactables/tests/SampleTests.java
@@ -1,22 +1,4 @@
 /*
-* Copyright 2013 The Android Open Source Project
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-
-
-/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
@@ -43,7 +25,6 @@
 public class SampleTests extends ActivityInstrumentationTestCase2<MainActivity> {
 
     private MainActivity mTestActivity;
-    private BasicContactablesFragment mTestFragment;
 
     public SampleTests() {
         super(MainActivity.class);
@@ -58,8 +39,6 @@
         // flags = {@link Intent#FLAG_ACTIVITY_NEW_TASK}
         // All other fields are null or empty.
         mTestActivity = getActivity();
-        mTestFragment = (BasicContactablesFragment)
-            mTestActivity.getSupportFragmentManager().getFragments().get(1);
     }
 
     /**
@@ -69,11 +48,10 @@
         //Try to add a message to add context to your assertions. These messages will be shown if
         //a tests fails and make it easy to understand why a test failed
         assertNotNull("mTestActivity is null", mTestActivity);
-        assertNotNull("mTestFragment is null", mTestFragment);
     }
 
     /**
     * Add more tests below.
     */
 
-}
\ No newline at end of file
+}
diff --git a/content/documentsUi/StorageClient/screenshots/icon-web.png b/content/documentsUi/StorageClient/screenshots/icon-web.png
new file mode 100644
index 0000000..004d80c
--- /dev/null
+++ b/content/documentsUi/StorageClient/screenshots/icon-web.png
Binary files differ
diff --git a/content/documentsUi/StorageClient/screenshots/main.png b/content/documentsUi/StorageClient/screenshots/main.png
new file mode 100644
index 0000000..c2912e1
--- /dev/null
+++ b/content/documentsUi/StorageClient/screenshots/main.png
Binary files differ
diff --git a/content/documentsUi/StorageClient/template-params.xml b/content/documentsUi/StorageClient/template-params.xml
index 0b2ddf2..d1ac386 100644
--- a/content/documentsUi/StorageClient/template-params.xml
+++ b/content/documentsUi/StorageClient/template-params.xml
@@ -38,4 +38,43 @@
     <common src="logger"/>
     <common src="activities"/>
 
+    <metadata>
+        <status>PUBLISHED</status>
+        <categories>Content</categories>
+        <technologies>Android</technologies>
+        <languages>Java</languages>
+        <solutions>Mobile</solutions>
+        <level>INTERMEDIATE</level>
+        <icon>screenshots/icon-web.png</icon>
+        <screenshots>
+            <img>screenshots/main.png</img>
+        </screenshots>
+        <api_refs>
+            <android>android.content.Intent</android>
+        </api_refs>
+
+        <description>
+            <![CDATA[
+Using the OPEN_DOCUMENT intent, a client app can access a list of Document Providers
+on the device, and choose a file from any of them.
+            ]]>
+        </description>
+
+        <intro>
+            <![CDATA[
+This sample aims to help you understand the OPEN_DOCUMENT intent, which allows a client
+application to access a list of Document Providers on the devices and choose a file from
+any of them.
+
+This sample first fires an intent to spin up the "file chooser" UI and select an image.
+Then, given the content:// URI of the selected image, it shows it on the screen using a
+DialogFragment. It also grabs metadata for the document specified by URI and logs that to
+the screen.
+
+To demonstrate this, click the "Show me" button to open up the Storage Access Framework
+interface, and choose an image on your device.  It will be displayed in this app.
+            ]]>
+        </intro>
+    </metadata>
+
 </sample>
diff --git a/content/webview/PermissionRequest/template-params.xml b/content/webview/PermissionRequest/template-params.xml
index 0402270..6a11636 100644
--- a/content/webview/PermissionRequest/template-params.xml
+++ b/content/webview/PermissionRequest/template-params.xml
@@ -44,7 +44,8 @@
         <level>INTERMEDIATE</level>
         <icon>screenshots/icon_web.png</icon>
         <screenshots>
-            <img>screenshots/main.png</img>
+            <img>screenshots/image1.png</img>
+            <img>screenshots/image2.png</img>
         </screenshots>
         <api_refs>
             <android>android.webkit.PermissionRequest</android>
diff --git a/input/multitouch/BasicMultitouch/screenshots/icon-web.png b/input/multitouch/BasicMultitouch/screenshots/icon-web.png
new file mode 100644
index 0000000..2f5f709
--- /dev/null
+++ b/input/multitouch/BasicMultitouch/screenshots/icon-web.png
Binary files differ
diff --git a/input/multitouch/BasicMultitouch/screenshots/intro.png b/input/multitouch/BasicMultitouch/screenshots/intro.png
new file mode 100644
index 0000000..4d1f535
--- /dev/null
+++ b/input/multitouch/BasicMultitouch/screenshots/intro.png
Binary files differ
diff --git a/input/multitouch/BasicMultitouch/screenshots/touches.png b/input/multitouch/BasicMultitouch/screenshots/touches.png
new file mode 100644
index 0000000..a771887
--- /dev/null
+++ b/input/multitouch/BasicMultitouch/screenshots/touches.png
Binary files differ
diff --git a/input/multitouch/BasicMultitouch/template-params.xml b/input/multitouch/BasicMultitouch/template-params.xml
index 7677818..40d2a18 100644
--- a/input/multitouch/BasicMultitouch/template-params.xml
+++ b/input/multitouch/BasicMultitouch/template-params.xml
@@ -28,15 +28,58 @@
     <strings>
         <intro>
             <![CDATA[
-This samples demonstrates the use of MotionEvent properties to keep track of individual touches
+This sample demonstrates the use of MotionEvent properties to keep track of individual touches
 across multiple touch events.
 \n\nTouch the screen with multiple fingers to show that the pointer id
-(also represented by a colour) does not change as new touch events are received.</string>
+(also represented by a color) does not change as new touch events are received.
             ]]>
         </intro>
     </strings>
 
     <template src="base"/>
     <common src="logger"/>
+    <metadata>
+        <status>PUBLISHED</status>
+        <categories>UI, Views, Input</categories>
+        <technologies>Android</technologies>
+        <languages>Java</languages>
+        <solutions>Mobile</solutions>
+        <level>INTERMEDIATE</level>
+        <icon>screenshots/icon-web.png</icon>
+        <screenshots>
+            <img>screenshots/intro.png</img>
+            <img>screenshots/touches.png</img>
+        </screenshots>
+        <api_refs>
+            <android>android.view.MotionEvent</android>
+        </api_refs>
+        <description>
+<![CDATA[
+Sample demonstrates the use of [MotionEvent][1] properties to keep track of
+individual touches across multiple touch events.
 
+[1]: http://developer.android.com/reference/android/view/MotionEvent.html
+]]>
+        </description>
+
+        <intro>
+<![CDATA[
+This is an example of keeping track of individual touches across multiple
+[MotionEvent][1]s.
+
+This sample uses a custom View (`TouchDisplayView`) that responds to
+touch events and draws a colored circle for each touch point. The view holds
+data related to a touch pointer, including its current position, pressure,
+and its past touch history.
+
+The View draws graphics based on data associated with each touch event to a
+canvas. A large circle indicates the current position of a touch, while smaller
+trailing circles represent previous positions for that touch.
+The size of the large circle is scaled depending on the pressure of the user's
+touch.
+
+[1]: http://developer.android.com/reference/android/view/MotionEvent.html
+]]>
+        </intro>
+    </metadata>
 </sample>
diff --git a/media/BasicMediaRouter/Application/tests/src/com/example/android/basicmediarouter/tests/SampleTests.java b/media/BasicMediaRouter/Application/tests/src/com/example/android/basicmediarouter/tests/SampleTests.java
index 5c475a3..f51dee8 100644
--- a/media/BasicMediaRouter/Application/tests/src/com/example/android/basicmediarouter/tests/SampleTests.java
+++ b/media/BasicMediaRouter/Application/tests/src/com/example/android/basicmediarouter/tests/SampleTests.java
@@ -1,22 +1,4 @@
 /*
-* Copyright 2013 The Android Open Source Project
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-
-
-/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
@@ -43,7 +25,6 @@
 public class SampleTests extends ActivityInstrumentationTestCase2<MainActivity> {
 
     private MainActivity mTestActivity;
-    private BasicMediaRouterFragment mTestFragment;
 
     public SampleTests() {
         super(MainActivity.class);
@@ -58,8 +39,6 @@
         // flags = {@link Intent#FLAG_ACTIVITY_NEW_TASK}
         // All other fields are null or empty.
         mTestActivity = getActivity();
-        mTestFragment = (BasicMediaRouterFragment)
-            mTestActivity.getSupportFragmentManager().getFragments().get(1);
     }
 
     /**
@@ -69,11 +48,10 @@
         //Try to add a message to add context to your assertions. These messages will be shown if
         //a tests fails and make it easy to understand why a test failed
         assertNotNull("mTestActivity is null", mTestActivity);
-        assertNotNull("mTestFragment is null", mTestFragment);
     }
 
     /**
     * Add more tests below.
     */
 
-}
\ No newline at end of file
+}
diff --git a/media/Camera2Basic/Application/src/main/java/com/example/android/camera2basic/Camera2BasicFragment.java b/media/Camera2Basic/Application/src/main/java/com/example/android/camera2basic/Camera2BasicFragment.java
index 4b55358..2414ed6 100644
--- a/media/Camera2Basic/Application/src/main/java/com/example/android/camera2basic/Camera2BasicFragment.java
+++ b/media/Camera2Basic/Application/src/main/java/com/example/android/camera2basic/Camera2BasicFragment.java
@@ -43,6 +43,7 @@
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.HandlerThread;
+import android.os.Message;
 import android.util.Log;
 import android.util.Size;
 import android.util.SparseIntArray;
@@ -315,6 +316,32 @@
     };
 
     /**
+     * A {@link Handler} for showing {@link Toast}s.
+     */
+    private Handler mMessageHandler = new Handler() {
+        @Override
+        public void handleMessage(Message msg) {
+            Activity activity = getActivity();
+            if (activity != null) {
+                Toast.makeText(activity, (String) msg.obj, Toast.LENGTH_SHORT).show();
+            }
+        }
+    };
+
+    /**
+     * Shows a {@link Toast} on the UI thread.
+     *
+     * @param text The message to show
+     */
+    private void showToast(String text) {
+        // We show a Toast by sending request message to mMessageHandler. This makes sure that the
+        // Toast is shown on the UI thread.
+        Message message = Message.obtain();
+        message.obj = text;
+        mMessageHandler.sendMessage(message);
+    }
+
+    /**
      * Given {@code choices} of {@code Size}s supported by a camera, chooses the smallest one whose
      * width and height are at least as large as the respective requested values, and whose aspect
      * ratio matches with the specified value.
@@ -573,10 +600,7 @@
 
                         @Override
                         public void onConfigureFailed(CameraCaptureSession cameraCaptureSession) {
-                            Activity activity = getActivity();
-                            if (null != activity) {
-                                Toast.makeText(activity, "Failed", Toast.LENGTH_SHORT).show();
-                            }
+                            showToast("Failed");
                         }
                     }, null
             );
@@ -689,7 +713,7 @@
                 @Override
                 public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request,
                                                TotalCaptureResult result) {
-                    Toast.makeText(getActivity(), "Saved: " + mFile, Toast.LENGTH_SHORT).show();
+                    showToast("Saved: " + mFile);
                     unlockFocus();
                 }
             };
diff --git a/media/Camera2Basic/Application/tests/AndroidManifest.xml b/media/Camera2Basic/Application/tests/AndroidManifest.xml
index 8b29c81..6c6aa11 100644
--- a/media/Camera2Basic/Application/tests/AndroidManifest.xml
+++ b/media/Camera2Basic/Application/tests/AndroidManifest.xml
@@ -1,22 +1,3 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright 2013 The Android Open Source Project
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
-     http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-
-
-
 <?xml version="1.0" encoding="utf-8"?>
 <!--
   Copyright (C) 2013 The Android Open Source Project
@@ -56,4 +37,4 @@
             android:targetPackage="com.example.android.camera2basic"
             android:label="Tests for com.example.android.camera2basic" />
 
-</manifest>
\ No newline at end of file
+</manifest>
diff --git a/media/Camera2Basic/Application/tests/src/com/example/android/camera2basic/tests/SampleTests.java b/media/Camera2Basic/Application/tests/src/com/example/android/camera2basic/tests/SampleTests.java
index 44cdfeb..52ee523 100644
--- a/media/Camera2Basic/Application/tests/src/com/example/android/camera2basic/tests/SampleTests.java
+++ b/media/Camera2Basic/Application/tests/src/com/example/android/camera2basic/tests/SampleTests.java
@@ -1,22 +1,4 @@
 /*
-* Copyright 2013 The Android Open Source Project
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-
-
-/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
@@ -43,7 +25,6 @@
 public class SampleTests extends ActivityInstrumentationTestCase2<CameraActivity> {
 
     private CameraActivity mTestActivity;
-    private Camera2BasicFragment mTestFragment;
 
     public SampleTests() {
         super(CameraActivity.class);
@@ -58,8 +39,6 @@
         // flags = {@link Intent#FLAG_ACTIVITY_NEW_TASK}
         // All other fields are null or empty.
         mTestActivity = getActivity();
-        mTestFragment = (Camera2BasicFragment)
-            mTestActivity.getSupportFragmentManager().getFragments().get(1);
     }
 
     /**
@@ -69,11 +48,10 @@
         //Try to add a message to add context to your assertions. These messages will be shown if
         //a tests fails and make it easy to understand why a test failed
         assertNotNull("mTestActivity is null", mTestActivity);
-        assertNotNull("mTestFragment is null", mTestFragment);
     }
 
     /**
     * Add more tests below.
     */
 
-}
\ No newline at end of file
+}
diff --git a/media/Camera2Basic/README.md b/media/Camera2Basic/README.md
index 73b9eac..b848e02 100644
--- a/media/Camera2Basic/README.md
+++ b/media/Camera2Basic/README.md
@@ -1,16 +1,55 @@
 Android Camera2Basic Sample
-==============================
+===================================
 
-This sample demonstrates the basic use of Camera2 API. Check the source code to see how you can
-display camera preview and take pictures.
+This sample demonstrates how to use basic functionalities of Camera2
+API. You can learn how to iterate through characteristics of all the
+cameras attached to the device, display a camera preview, and take
+pictures.
+
+Introduction
+------------
+
+The [Camera2 API][1] provides an interface to individual camera
+devices connected to an Android device. It replaces the deprecated
+Camera class.
+
+Use [getCameraIdList][2] to get a list of all the available
+cameras. You can then use [getCameraCharacteristics][3] and find the
+best camera that suits your need (front/rear facing, resolution etc).
+
+Create an instance of [CameraDevice.StateCallback][4] and open a
+camera. It is ready to start camera preview when the camera is opened.
+
+This sample uses TextureView to show the camera preview. Create a
+[CameraCaptureSession][5] and set a repeating [CaptureRequest][6] to it.
+
+Still image capture takes several steps. First, you need to lock the
+focus of the camera by updating the CaptureRequest for the camera
+preview. Then, in a similar way, you need to run a precapture
+sequence. After that, it is ready to capture a picture. Create a new
+CaptureRequest and call [capture][7]. Don't forget to unlock the focus
+when you are done.
+
+[1]: https://developer.android.com/reference/android/hardware/camera2/package-summary.html
+[2]: https://developer.android.com/reference/android/hardware/camera2/CameraManager.html#getCameraIdList()
+[3]: https://developer.android.com/reference/android/hardware/camera2/CameraManager.html#getCameraCharacteristics(java.lang.String)
+[4]: https://developer.android.com/reference/android/hardware/camera2/CameraDevice.StateCallback.html
+[5]: https://developer.android.com/reference/android/hardware/camera2/CameraCaptureSession.html
+[6]: https://developer.android.com/reference/android/hardware/camera2/CaptureRequest.html
+[7]: https://developer.android.com/reference/android/hardware/camera2/CameraCaptureSession.html#capture(android.hardware.camera2.CaptureRequest, android.hardware.camera2.CameraCaptureSession.CaptureCallback, android.os.Handler)
 
 Pre-requisites
 --------------
 
-- Android SDK (L Developer Preview)
-- Android Build Tools v20
+- Android SDK v21
+- Android Build Tools v21.1.1
 - Android Support Repository
 
+Screenshots
+-------------
+
+<img src="screenshots/main.png" height="400" alt="Screenshot"/> 
+
 Getting Started
 ---------------
 
@@ -32,7 +71,7 @@
 License
 -------
 
-Copyright 2014 The Android Open Source Project
+Copyright 2014 The Android Open Source Project, Inc.
 
 Licensed to the Apache Software Foundation (ASF) under one or more contributor
 license agreements.  See the NOTICE file distributed with this work for
@@ -41,7 +80,7 @@
 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
+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
diff --git a/media/MediaBrowserService/Application/src/main/AndroidManifest.xml b/media/MediaBrowserService/Application/src/main/AndroidManifest.xml
index 6d05c27..45c8de7 100644
--- a/media/MediaBrowserService/Application/src/main/AndroidManifest.xml
+++ b/media/MediaBrowserService/Application/src/main/AndroidManifest.xml
@@ -36,7 +36,7 @@
             android:resource="@xml/automotive_app_desc"/>
 
 
-        <activity android:name="com.example.android.mediabrowserservice.MusicPlayerActivity"
+        <activity android:name=".MusicPlayerActivity"
                   android:label="@string/app_name">
             <intent-filter>
                 <action android:name="android.intent.action.MAIN" />
@@ -51,8 +51,17 @@
             android:name="com.google.android.gms.car.notification.SmallIcon"
             android:resource="@drawable/ic_notification" />
 
+        <!--
+             (OPTIONAL) use this meta data to override the theme from which Android Auto will
+             look for colors. If you don't set this, Android Auto will look
+             for color attributes in your application theme.
+        -->
+        <meta-data
+            android:name="com.google.android.gms.car.application.theme"
+            android:resource="@style/CarTheme" />
+
         <service
-            android:name="com.example.android.mediabrowserservice.MusicService"
+            android:name=".MusicService"
             android:exported="true"
             >
             <intent-filter>
diff --git a/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/AlbumArtCache.java b/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/AlbumArtCache.java
new file mode 100644
index 0000000..4154381
--- /dev/null
+++ b/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/AlbumArtCache.java
@@ -0,0 +1,130 @@
+/*
+ * Copyright (C) 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.example.android.mediabrowserservice;
+
+import android.graphics.Bitmap;
+import android.os.AsyncTask;
+import android.util.LruCache;
+
+import com.example.android.mediabrowserservice.utils.BitmapHelper;
+import com.example.android.mediabrowserservice.utils.LogHelper;
+
+import java.io.IOException;
+
+/**
+ * Implements a basic cache of album arts, with async loading support.
+ */
+public final class AlbumArtCache {
+    private static final String TAG = LogHelper.makeLogTag(AlbumArtCache.class);
+
+    private static final int MAX_ALBUM_ART_CACHE_SIZE = 12*1024*1024;  // 12 MB
+    private static final int MAX_ART_WIDTH = 800;  // pixels
+    private static final int MAX_ART_HEIGHT = 480;  // pixels
+
+    // Resolution reasonable for carrying around as an icon (generally in
+    // MediaDescription.getIconBitmap). This should not be bigger than necessary, because
+    // the MediaDescription object should be lightweight. If you set it too high and try to
+    // serialize the MediaDescription, you may get FAILED BINDER TRANSACTION errors.
+    private static final int MAX_ART_WIDTH_ICON = 128;  // pixels
+    private static final int MAX_ART_HEIGHT_ICON = 128;  // pixels
+
+    private static final int BIG_BITMAP_INDEX = 0;
+    private static final int ICON_BITMAP_INDEX = 1;
+
+    private final LruCache<String, Bitmap[]> mCache;
+
+    private static final AlbumArtCache sInstance = new AlbumArtCache();
+
+    public static AlbumArtCache getInstance() {
+        return sInstance;
+    }
+
+    private AlbumArtCache() {
+        // Holds no more than MAX_ALBUM_ART_CACHE_SIZE bytes, bounded by maxmemory/4 and
+        // Integer.MAX_VALUE:
+        int maxSize = Math.min(MAX_ALBUM_ART_CACHE_SIZE,
+            (int) (Math.min(Integer.MAX_VALUE, Runtime.getRuntime().maxMemory()/4)));
+        mCache = new LruCache<String, Bitmap[]>(maxSize) {
+            @Override
+            protected int sizeOf(String key, Bitmap[] value) {
+                return value[BIG_BITMAP_INDEX].getByteCount()
+                    + value[ICON_BITMAP_INDEX].getByteCount();
+            }
+        };
+    }
+
+    public Bitmap getBigImage(String artUrl) {
+        Bitmap[] result = mCache.get(artUrl);
+        return result == null ? null : result[BIG_BITMAP_INDEX];
+    }
+
+    public Bitmap getIconImage(String artUrl) {
+        Bitmap[] result = mCache.get(artUrl);
+        return result == null ? null : result[ICON_BITMAP_INDEX];
+    }
+
+    public void fetch(final String artUrl, final FetchListener listener) {
+        // WARNING: for the sake of simplicity, simultaneous multi-thread fetch requests
+        // are not handled properly: they may cause redundant costly operations, like HTTP
+        // requests and bitmap rescales. For production-level apps, we recommend you use
+        // a proper image loading library, like Glide.
+        Bitmap[] bitmap = mCache.get(artUrl);
+        if (bitmap != null) {
+            LogHelper.d(TAG, "getOrFetch: album art is in cache, using it", artUrl);
+            listener.onFetched(artUrl, bitmap[BIG_BITMAP_INDEX], bitmap[ICON_BITMAP_INDEX]);
+            return;
+        }
+        LogHelper.d(TAG, "getOrFetch: starting asynctask to fetch ", artUrl);
+
+        new AsyncTask<Void, Void, Bitmap[]>() {
+            @Override
+            protected Bitmap[] doInBackground(Void[] objects) {
+                Bitmap[] bitmaps;
+                try {
+                    Bitmap bitmap = BitmapHelper.fetchAndRescaleBitmap(artUrl,
+                        MAX_ART_WIDTH, MAX_ART_HEIGHT);
+                    Bitmap icon = BitmapHelper.scaleBitmap(bitmap,
+                        MAX_ART_WIDTH_ICON, MAX_ART_HEIGHT_ICON);
+                    bitmaps = new Bitmap[] {bitmap, icon};
+                    mCache.put(artUrl, bitmaps);
+                } catch (IOException e) {
+                    return null;
+                }
+                LogHelper.d(TAG, "doInBackground: putting bitmap in cache. cache size=" +
+                    mCache.size());
+                return bitmaps;
+            }
+
+            @Override
+            protected void onPostExecute(Bitmap[] bitmaps) {
+                if (bitmaps == null) {
+                    listener.onError(artUrl, new IllegalArgumentException("got null bitmaps"));
+                } else {
+                    listener.onFetched(artUrl,
+                        bitmaps[BIG_BITMAP_INDEX], bitmaps[ICON_BITMAP_INDEX]);
+                }
+            }
+        }.execute();
+    }
+
+    public static abstract class FetchListener {
+        public abstract void onFetched(String artUrl, Bitmap bigImage, Bitmap iconImage);
+        public void onError(String artUrl, Exception e) {
+            LogHelper.e(TAG, e, "AlbumArtFetchListener: error while downloading " + artUrl);
+        }
+    }
+}
diff --git a/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/BrowseFragment.java b/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/BrowseFragment.java
index 726ae15..e4ccf76 100644
--- a/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/BrowseFragment.java
+++ b/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/BrowseFragment.java
@@ -47,7 +47,7 @@
  */
 public class BrowseFragment extends Fragment {
 
-    private static final String TAG = BrowseFragment.class.getSimpleName();
+    private static final String TAG = LogHelper.makeLogTag(BrowseFragment.class.getSimpleName());
 
     public static final String ARG_MEDIA_ID = "media_id";
 
diff --git a/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/MediaNotification.java b/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/MediaNotification.java
deleted file mode 100644
index 6872723..0000000
--- a/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/MediaNotification.java
+++ /dev/null
@@ -1,381 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.android.mediabrowserservice;
-
-import android.app.Notification;
-import android.app.NotificationManager;
-import android.app.PendingIntent;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.content.pm.ApplicationInfo;
-import android.content.pm.PackageManager;
-import android.content.res.Resources;
-import android.content.res.TypedArray;
-import android.graphics.Bitmap;
-import android.graphics.BitmapFactory;
-import android.graphics.Color;
-import android.media.MediaDescription;
-import android.media.MediaMetadata;
-import android.media.session.MediaController;
-import android.media.session.MediaSession;
-import android.media.session.PlaybackState;
-import android.os.AsyncTask;
-import android.util.LruCache;
-
-import com.example.android.mediabrowserservice.utils.BitmapHelper;
-import com.example.android.mediabrowserservice.utils.LogHelper;
-
-import java.io.IOException;
-
-/**
- * Keeps track of a notification and updates it automatically for a given
- * MediaSession. Maintaining a visible notification (usually) guarantees that the music service
- * won't be killed during playback.
- */
-public class MediaNotification extends BroadcastReceiver {
-    private static final String TAG = "MediaNotification";
-
-    private static final int NOTIFICATION_ID = 412;
-
-    public static final String ACTION_PAUSE = "com.example.android.mediabrowserservice.pause";
-    public static final String ACTION_PLAY = "com.example.android.mediabrowserservice.play";
-    public static final String ACTION_PREV = "com.example.android.mediabrowserservice.prev";
-    public static final String ACTION_NEXT = "com.example.android.mediabrowserservice.next";
-
-    private static final int MAX_ALBUM_ART_CACHE_SIZE = 1024*1024;
-
-    private final MusicService mService;
-    private MediaSession.Token mSessionToken;
-    private MediaController mController;
-    private MediaController.TransportControls mTransportControls;
-    private final LruCache<String, Bitmap> mAlbumArtCache;
-
-    private PlaybackState mPlaybackState;
-    private MediaMetadata mMetadata;
-
-    private Notification.Builder mNotificationBuilder;
-    private NotificationManager mNotificationManager;
-    private Notification.Action mPlayPauseAction;
-
-    private PendingIntent mPauseIntent, mPlayIntent, mPreviousIntent, mNextIntent;
-
-    private String mCurrentAlbumArt;
-    private int mNotificationColor;
-
-    private boolean mStarted = false;
-
-    public MediaNotification(MusicService service) {
-        mService = service;
-        updateSessionToken();
-
-        // simple album art cache that holds no more than
-        // MAX_ALBUM_ART_CACHE_SIZE bytes:
-        mAlbumArtCache = new LruCache<String, Bitmap>(MAX_ALBUM_ART_CACHE_SIZE) {
-            @Override
-            protected int sizeOf(String key, Bitmap value) {
-                return value.getByteCount();
-            }
-        };
-
-        mNotificationColor = getNotificationColor();
-
-        mNotificationManager = (NotificationManager) mService
-                .getSystemService(Context.NOTIFICATION_SERVICE);
-
-        String pkg = mService.getPackageName();
-        mPauseIntent = PendingIntent.getBroadcast(mService, 100,
-                new Intent(ACTION_PAUSE).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT);
-        mPlayIntent = PendingIntent.getBroadcast(mService, 100,
-                new Intent(ACTION_PLAY).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT);
-        mPreviousIntent = PendingIntent.getBroadcast(mService, 100,
-                new Intent(ACTION_PREV).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT);
-        mNextIntent = PendingIntent.getBroadcast(mService, 100,
-                new Intent(ACTION_NEXT).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT);
-    }
-
-    protected int getNotificationColor() {
-        int notificationColor = 0;
-        String packageName = mService.getPackageName();
-        try {
-            Context packageContext = mService.createPackageContext(packageName, 0);
-            ApplicationInfo applicationInfo =
-                    mService.getPackageManager().getApplicationInfo(packageName, 0);
-            packageContext.setTheme(applicationInfo.theme);
-            Resources.Theme theme = packageContext.getTheme();
-            TypedArray ta = theme.obtainStyledAttributes(
-                    new int[] {android.R.attr.colorPrimary});
-            notificationColor = ta.getColor(0, Color.DKGRAY);
-            ta.recycle();
-        } catch (PackageManager.NameNotFoundException e) {
-            e.printStackTrace();
-        }
-        return notificationColor;
-    }
-
-    /**
-     * Posts the notification and starts tracking the session to keep it
-     * updated. The notification will automatically be removed if the session is
-     * destroyed before {@link #stopNotification} is called.
-     */
-    public void startNotification() {
-        if (!mStarted) {
-            mController.registerCallback(mCb);
-            IntentFilter filter = new IntentFilter();
-            filter.addAction(ACTION_NEXT);
-            filter.addAction(ACTION_PAUSE);
-            filter.addAction(ACTION_PLAY);
-            filter.addAction(ACTION_PREV);
-            mService.registerReceiver(this, filter);
-
-            mMetadata = mController.getMetadata();
-            mPlaybackState = mController.getPlaybackState();
-
-            mStarted = true;
-            // The notification must be updated after setting started to true
-            updateNotificationMetadata();
-        }
-    }
-
-    /**
-     * Removes the notification and stops tracking the session. If the session
-     * was destroyed this has no effect.
-     */
-    public void stopNotification() {
-        mStarted = false;
-        mController.unregisterCallback(mCb);
-        try {
-            mNotificationManager.cancel(NOTIFICATION_ID);
-            mService.unregisterReceiver(this);
-        } catch (IllegalArgumentException ex) {
-            // ignore if the receiver is not registered.
-        }
-        mService.stopForeground(true);
-    }
-
-    @Override
-    public void onReceive(Context context, Intent intent) {
-        final String action = intent.getAction();
-        LogHelper.d(TAG, "Received intent with action " + action);
-        if (ACTION_PAUSE.equals(action)) {
-            mTransportControls.pause();
-        } else if (ACTION_PLAY.equals(action)) {
-            mTransportControls.play();
-        } else if (ACTION_NEXT.equals(action)) {
-            mTransportControls.skipToNext();
-        } else if (ACTION_PREV.equals(action)) {
-            mTransportControls.skipToPrevious();
-        }
-    }
-
-    /**
-     * Update the state based on a change on the session token. Called either when
-     * we are running for the first time or when the media session owner has destroyed the session
-     * (see {@link android.media.session.MediaController.Callback#onSessionDestroyed()})
-     */
-    private void updateSessionToken() {
-        MediaSession.Token freshToken = mService.getSessionToken();
-        if (mSessionToken == null || !mSessionToken.equals(freshToken)) {
-            if (mController != null) {
-                mController.unregisterCallback(mCb);
-            }
-            mSessionToken = freshToken;
-            mController = new MediaController(mService, mSessionToken);
-            mTransportControls = mController.getTransportControls();
-            if (mStarted) {
-                mController.registerCallback(mCb);
-            }
-        }
-    }
-
-    private final MediaController.Callback mCb = new MediaController.Callback() {
-        @Override
-        public void onPlaybackStateChanged(PlaybackState state) {
-            mPlaybackState = state;
-            LogHelper.d(TAG, "Received new playback state", state);
-            updateNotificationPlaybackState();
-        }
-
-        @Override
-        public void onMetadataChanged(MediaMetadata metadata) {
-            mMetadata = metadata;
-            LogHelper.d(TAG, "Received new metadata ", metadata);
-            updateNotificationMetadata();
-        }
-
-        @Override
-        public void onSessionDestroyed() {
-            super.onSessionDestroyed();
-            LogHelper.d(TAG, "Session was destroyed, resetting to the new session token");
-            updateSessionToken();
-        }
-    };
-
-    private void updateNotificationMetadata() {
-        LogHelper.d(TAG, "updateNotificationMetadata. mMetadata=" + mMetadata);
-        if (mMetadata == null || mPlaybackState == null) {
-            return;
-        }
-
-        updatePlayPauseAction();
-
-        mNotificationBuilder = new Notification.Builder(mService);
-        int playPauseActionIndex = 0;
-
-        // If skip to previous action is enabled
-        if ((mPlaybackState.getActions() & PlaybackState.ACTION_SKIP_TO_PREVIOUS) != 0) {
-            mNotificationBuilder
-                    .addAction(R.drawable.ic_skip_previous_white_24dp,
-                            mService.getString(R.string.label_previous), mPreviousIntent);
-            playPauseActionIndex = 1;
-        }
-
-        mNotificationBuilder.addAction(mPlayPauseAction);
-
-        // If skip to next action is enabled
-        if ((mPlaybackState.getActions() & PlaybackState.ACTION_SKIP_TO_NEXT) != 0) {
-            mNotificationBuilder.addAction(R.drawable.ic_skip_next_white_24dp,
-                    mService.getString(R.string.label_next), mNextIntent);
-        }
-
-        MediaDescription description = mMetadata.getDescription();
-
-        String fetchArtUrl = null;
-        Bitmap art = description.getIconBitmap();
-        if (art == null && description.getIconUri() != null) {
-            // This sample assumes the iconUri will be a valid URL formatted String, but
-            // it can actually be any valid Android Uri formatted String.
-            // async fetch the album art icon
-            String artUrl = description.getIconUri().toString();
-            art = mAlbumArtCache.get(artUrl);
-            if (art == null) {
-                fetchArtUrl = artUrl;
-                // use a placeholder art while the remote art is being downloaded
-                art = BitmapFactory.decodeResource(mService.getResources(), R.drawable.ic_default_art);
-            }
-        }
-
-        mNotificationBuilder
-                .setStyle(new Notification.MediaStyle()
-                        .setShowActionsInCompactView(playPauseActionIndex)  // only show play/pause in compact view
-                        .setMediaSession(mSessionToken))
-                .setColor(mNotificationColor)
-                .setSmallIcon(R.drawable.ic_notification)
-                .setVisibility(Notification.VISIBILITY_PUBLIC)
-                .setUsesChronometer(true)
-                .setContentTitle(description.getTitle())
-                .setContentText(description.getSubtitle())
-                .setLargeIcon(art);
-
-        updateNotificationPlaybackState();
-
-        mService.startForeground(NOTIFICATION_ID, mNotificationBuilder.build());
-        if (fetchArtUrl != null) {
-            fetchBitmapFromURLAsync(fetchArtUrl);
-        }
-    }
-
-    private void updatePlayPauseAction() {
-        LogHelper.d(TAG, "updatePlayPauseAction");
-        String label;
-        int icon;
-        PendingIntent intent;
-        if (mPlaybackState.getState() == PlaybackState.STATE_PLAYING) {
-            label = mService.getString(R.string.label_pause);
-            icon = R.drawable.ic_pause_white_24dp;
-            intent = mPauseIntent;
-        } else {
-            label = mService.getString(R.string.label_play);
-            icon = R.drawable.ic_play_arrow_white_24dp;
-            intent = mPlayIntent;
-        }
-        if (mPlayPauseAction == null) {
-            mPlayPauseAction = new Notification.Action(icon, label, intent);
-        } else {
-            mPlayPauseAction.icon = icon;
-            mPlayPauseAction.title = label;
-            mPlayPauseAction.actionIntent = intent;
-        }
-    }
-
-    private void updateNotificationPlaybackState() {
-        LogHelper.d(TAG, "updateNotificationPlaybackState. mPlaybackState=" + mPlaybackState);
-        if (mPlaybackState == null || !mStarted) {
-            LogHelper.d(TAG, "updateNotificationPlaybackState. cancelling notification!");
-            mService.stopForeground(true);
-            return;
-        }
-        if (mNotificationBuilder == null) {
-            LogHelper.d(TAG, "updateNotificationPlaybackState. there is no notificationBuilder. Ignoring request to update state!");
-            return;
-        }
-        if (mPlaybackState.getPosition() >= 0) {
-            LogHelper.d(TAG, "updateNotificationPlaybackState. updating playback position to ",
-                    (System.currentTimeMillis() - mPlaybackState.getPosition()) / 1000, " seconds");
-            mNotificationBuilder
-                    .setWhen(System.currentTimeMillis() - mPlaybackState.getPosition())
-                    .setShowWhen(true)
-                    .setUsesChronometer(true);
-            mNotificationBuilder.setShowWhen(true);
-        } else {
-            LogHelper.d(TAG, "updateNotificationPlaybackState. hiding playback position");
-            mNotificationBuilder
-                    .setWhen(0)
-                    .setShowWhen(false)
-                    .setUsesChronometer(false);
-        }
-
-        updatePlayPauseAction();
-
-        // Make sure that the notification can be dismissed by the user when we are not playing:
-        mNotificationBuilder.setOngoing(mPlaybackState.getState() == PlaybackState.STATE_PLAYING);
-
-        mNotificationManager.notify(NOTIFICATION_ID, mNotificationBuilder.build());
-    }
-
-    public void fetchBitmapFromURLAsync(final String source) {
-        LogHelper.d(TAG, "getBitmapFromURLAsync: starting asynctask to fetch ", source);
-        new AsyncTask<Void, Void, Bitmap>() {
-            @Override
-            protected Bitmap doInBackground(Void[] objects) {
-                Bitmap bitmap = null;
-                try {
-                    bitmap = BitmapHelper.fetchAndRescaleBitmap(source,
-                            BitmapHelper.MEDIA_ART_BIG_WIDTH, BitmapHelper.MEDIA_ART_BIG_HEIGHT);
-                    mAlbumArtCache.put(source, bitmap);
-                } catch (IOException e) {
-                    LogHelper.e(TAG, e, "getBitmapFromURLAsync: " + source);
-                }
-                return bitmap;
-            }
-
-            @Override
-            protected void onPostExecute(Bitmap bitmap) {
-                if (bitmap != null && mMetadata != null &&
-                        mNotificationBuilder != null && mMetadata.getDescription() != null &&
-                        !source.equals(mMetadata.getDescription().getIconUri())) {
-                    // If the media is still the same, update the notification:
-                    LogHelper.d(TAG, "getBitmapFromURLAsync: set bitmap to ", source);
-                    mNotificationBuilder.setLargeIcon(bitmap);
-                    mNotificationManager.notify(NOTIFICATION_ID, mNotificationBuilder.build());
-                }
-            }
-        }.execute();
-    }
-
-}
diff --git a/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/MediaNotificationManager.java b/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/MediaNotificationManager.java
new file mode 100644
index 0000000..59da728
--- /dev/null
+++ b/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/MediaNotificationManager.java
@@ -0,0 +1,354 @@
+/*
+ * Copyright (C) 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.example.android.mediabrowserservice;
+
+import android.app.Notification;
+import android.app.NotificationManager;
+import android.app.PendingIntent;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.graphics.Color;
+import android.media.MediaDescription;
+import android.media.MediaMetadata;
+import android.media.session.MediaController;
+import android.media.session.MediaSession;
+import android.media.session.PlaybackState;
+
+import com.example.android.mediabrowserservice.utils.LogHelper;
+import com.example.android.mediabrowserservice.utils.ResourceHelper;
+
+/**
+ * Keeps track of a notification and updates it automatically for a given
+ * MediaSession. Maintaining a visible notification (usually) guarantees that the music service
+ * won't be killed during playback.
+ */
+public class MediaNotificationManager extends BroadcastReceiver {
+    private static final String TAG = LogHelper.makeLogTag(MediaNotificationManager.class);
+
+    private static final int NOTIFICATION_ID = 412;
+    private static final int REQUEST_CODE = 100;
+
+    public static final String ACTION_PAUSE = "com.example.android.mediabrowserservice.pause";
+    public static final String ACTION_PLAY = "com.example.android.mediabrowserservice.play";
+    public static final String ACTION_PREV = "com.example.android.mediabrowserservice.prev";
+    public static final String ACTION_NEXT = "com.example.android.mediabrowserservice.next";
+
+    private final MusicService mService;
+    private MediaSession.Token mSessionToken;
+    private MediaController mController;
+    private MediaController.TransportControls mTransportControls;
+
+    private PlaybackState mPlaybackState;
+    private MediaMetadata mMetadata;
+
+    private NotificationManager mNotificationManager;
+
+    private PendingIntent mPauseIntent;
+    private PendingIntent mPlayIntent;
+    private PendingIntent mPreviousIntent;
+    private PendingIntent mNextIntent;
+
+    private int mNotificationColor;
+
+    private boolean mStarted = false;
+
+    public MediaNotificationManager(MusicService service) {
+        mService = service;
+        updateSessionToken();
+
+        mNotificationColor = ResourceHelper.getThemeColor(mService,
+            android.R.attr.colorPrimary, Color.DKGRAY);
+
+        mNotificationManager = (NotificationManager) mService
+                .getSystemService(Context.NOTIFICATION_SERVICE);
+
+        String pkg = mService.getPackageName();
+        mPauseIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE,
+                new Intent(ACTION_PAUSE).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT);
+        mPlayIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE,
+                new Intent(ACTION_PLAY).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT);
+        mPreviousIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE,
+                new Intent(ACTION_PREV).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT);
+        mNextIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE,
+                new Intent(ACTION_NEXT).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT);
+
+        // Cancel all notifications to handle the case where the Service was killed and
+        // restarted by the system.
+        mNotificationManager.cancelAll();
+    }
+
+    /**
+     * Posts the notification and starts tracking the session to keep it
+     * updated. The notification will automatically be removed if the session is
+     * destroyed before {@link #stopNotification} is called.
+     */
+    public void startNotification() {
+        if (!mStarted) {
+            mMetadata = mController.getMetadata();
+            mPlaybackState = mController.getPlaybackState();
+
+            // The notification must be updated after setting started to true
+            Notification notification = createNotification();
+            if (notification != null) {
+                mController.registerCallback(mCb);
+                IntentFilter filter = new IntentFilter();
+                filter.addAction(ACTION_NEXT);
+                filter.addAction(ACTION_PAUSE);
+                filter.addAction(ACTION_PLAY);
+                filter.addAction(ACTION_PREV);
+                mService.registerReceiver(this, filter);
+
+                mService.startForeground(NOTIFICATION_ID, notification);
+                mStarted = true;
+            }
+        }
+    }
+
+    /**
+     * Removes the notification and stops tracking the session. If the session
+     * was destroyed this has no effect.
+     */
+    public void stopNotification() {
+        if (mStarted) {
+            mStarted = false;
+            mController.unregisterCallback(mCb);
+            try {
+                mNotificationManager.cancel(NOTIFICATION_ID);
+                mService.unregisterReceiver(this);
+            } catch (IllegalArgumentException ex) {
+                // ignore if the receiver is not registered.
+            }
+            mService.stopForeground(true);
+        }
+    }
+
+    @Override
+    public void onReceive(Context context, Intent intent) {
+        final String action = intent.getAction();
+        LogHelper.d(TAG, "Received intent with action " + action);
+        switch (action) {
+            case ACTION_PAUSE:
+                mTransportControls.pause();
+                break;
+            case ACTION_PLAY:
+                mTransportControls.play();
+                break;
+            case ACTION_NEXT:
+                mTransportControls.skipToNext();
+                break;
+            case ACTION_PREV:
+                mTransportControls.skipToPrevious();
+                break;
+            default:
+                LogHelper.w(TAG, "Unknown intent ignored. Action=", action);
+        }
+    }
+
+    /**
+     * Update the state based on a change on the session token. Called either when
+     * we are running for the first time or when the media session owner has destroyed the session
+     * (see {@link android.media.session.MediaController.Callback#onSessionDestroyed()})
+     */
+    private void updateSessionToken() {
+        MediaSession.Token freshToken = mService.getSessionToken();
+        if (mSessionToken == null || !mSessionToken.equals(freshToken)) {
+            if (mController != null) {
+                mController.unregisterCallback(mCb);
+            }
+            mSessionToken = freshToken;
+            mController = new MediaController(mService, mSessionToken);
+            mTransportControls = mController.getTransportControls();
+            if (mStarted) {
+                mController.registerCallback(mCb);
+            }
+        }
+    }
+
+    private PendingIntent createContentIntent() {
+        Intent openUI = new Intent(mService, MusicPlayerActivity.class);
+        openUI.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
+        return PendingIntent.getActivity(mService, REQUEST_CODE, openUI,
+                PendingIntent.FLAG_CANCEL_CURRENT);
+    }
+
+    private final MediaController.Callback mCb = new MediaController.Callback() {
+        @Override
+        public void onPlaybackStateChanged(PlaybackState state) {
+            mPlaybackState = state;
+            LogHelper.d(TAG, "Received new playback state", state);
+            if (state != null && (state.getState() == PlaybackState.STATE_STOPPED ||
+                    state.getState() == PlaybackState.STATE_NONE)) {
+                stopNotification();
+            } else {
+                Notification notification = createNotification();
+                if (notification != null) {
+                    mNotificationManager.notify(NOTIFICATION_ID, notification);
+                }
+            }
+        }
+
+        @Override
+        public void onMetadataChanged(MediaMetadata metadata) {
+            mMetadata = metadata;
+            LogHelper.d(TAG, "Received new metadata ", metadata);
+            Notification notification = createNotification();
+            if (notification != null) {
+                mNotificationManager.notify(NOTIFICATION_ID, notification);
+            }
+        }
+
+        @Override
+        public void onSessionDestroyed() {
+            super.onSessionDestroyed();
+            LogHelper.d(TAG, "Session was destroyed, resetting to the new session token");
+            updateSessionToken();
+        }
+    };
+
+    private Notification createNotification() {
+        LogHelper.d(TAG, "updateNotificationMetadata. mMetadata=" + mMetadata);
+        if (mMetadata == null || mPlaybackState == null) {
+            return null;
+        }
+
+        Notification.Builder notificationBuilder = new Notification.Builder(mService);
+        int playPauseButtonPosition = 0;
+
+        // If skip to previous action is enabled
+        if ((mPlaybackState.getActions() & PlaybackState.ACTION_SKIP_TO_PREVIOUS) != 0) {
+            notificationBuilder.addAction(R.drawable.ic_skip_previous_white_24dp,
+                        mService.getString(R.string.label_previous), mPreviousIntent);
+
+            // If there is a "skip to previous" button, the play/pause button will
+            // be the second one. We need to keep track of it, because the MediaStyle notification
+            // requires to specify the index of the buttons (actions) that should be visible
+            // when in compact view.
+            playPauseButtonPosition = 1;
+        }
+
+        addPlayPauseAction(notificationBuilder);
+
+        // If skip to next action is enabled
+        if ((mPlaybackState.getActions() & PlaybackState.ACTION_SKIP_TO_NEXT) != 0) {
+            notificationBuilder.addAction(R.drawable.ic_skip_next_white_24dp,
+                mService.getString(R.string.label_next), mNextIntent);
+        }
+
+        MediaDescription description = mMetadata.getDescription();
+
+        String fetchArtUrl = null;
+        Bitmap art = null;
+        if (description.getIconUri() != null) {
+            // This sample assumes the iconUri will be a valid URL formatted String, but
+            // it can actually be any valid Android Uri formatted String.
+            // async fetch the album art icon
+            String artUrl = description.getIconUri().toString();
+            art = AlbumArtCache.getInstance().getBigImage(artUrl);
+            if (art == null) {
+                fetchArtUrl = artUrl;
+                // use a placeholder art while the remote art is being downloaded
+                art = BitmapFactory.decodeResource(mService.getResources(),
+                    R.drawable.ic_default_art);
+            }
+        }
+
+        notificationBuilder
+                .setStyle(new Notification.MediaStyle()
+                    .setShowActionsInCompactView(
+                        new int[]{playPauseButtonPosition})  // show only play/pause in compact view
+                    .setMediaSession(mSessionToken))
+                .setColor(mNotificationColor)
+                .setSmallIcon(R.drawable.ic_notification)
+                .setVisibility(Notification.VISIBILITY_PUBLIC)
+                .setUsesChronometer(true)
+                .setContentIntent(createContentIntent())
+                .setContentTitle(description.getTitle())
+                .setContentText(description.getSubtitle())
+                .setLargeIcon(art);
+
+        setNotificationPlaybackState(notificationBuilder);
+        if (fetchArtUrl != null) {
+            fetchBitmapFromURLAsync(fetchArtUrl, notificationBuilder);
+        }
+
+        return notificationBuilder.build();
+    }
+
+    private void addPlayPauseAction(Notification.Builder builder) {
+        LogHelper.d(TAG, "updatePlayPauseAction");
+        String label;
+        int icon;
+        PendingIntent intent;
+        if (mPlaybackState.getState() == PlaybackState.STATE_PLAYING) {
+            label = mService.getString(R.string.label_pause);
+            icon = R.drawable.ic_pause_white_24dp;
+            intent = mPauseIntent;
+        } else {
+            label = mService.getString(R.string.label_play);
+            icon = R.drawable.ic_play_arrow_white_24dp;
+            intent = mPlayIntent;
+        }
+        builder.addAction(new Notification.Action(icon, label, intent));
+    }
+
+    private void setNotificationPlaybackState(Notification.Builder builder) {
+        LogHelper.d(TAG, "updateNotificationPlaybackState. mPlaybackState=" + mPlaybackState);
+        if (mPlaybackState == null || !mStarted) {
+            LogHelper.d(TAG, "updateNotificationPlaybackState. cancelling notification!");
+            mService.stopForeground(true);
+            return;
+        }
+        if (mPlaybackState.getState() == PlaybackState.STATE_PLAYING
+                && mPlaybackState.getPosition() >= 0) {
+            LogHelper.d(TAG, "updateNotificationPlaybackState. updating playback position to ",
+                    (System.currentTimeMillis() - mPlaybackState.getPosition()) / 1000, " seconds");
+            builder
+                .setWhen(System.currentTimeMillis() - mPlaybackState.getPosition())
+                .setShowWhen(true)
+                .setUsesChronometer(true);
+        } else {
+            LogHelper.d(TAG, "updateNotificationPlaybackState. hiding playback position");
+            builder
+                .setWhen(0)
+                .setShowWhen(false)
+                .setUsesChronometer(false);
+        }
+
+        // Make sure that the notification can be dismissed by the user when we are not playing:
+        builder.setOngoing(mPlaybackState.getState() == PlaybackState.STATE_PLAYING);
+    }
+
+    private void fetchBitmapFromURLAsync(final String bitmapUrl,
+                                         final Notification.Builder builder) {
+        AlbumArtCache.getInstance().fetch(bitmapUrl, new AlbumArtCache.FetchListener() {
+            @Override
+            public void onFetched(String artUrl, Bitmap bitmap, Bitmap icon) {
+                if (mMetadata != null && mMetadata.getDescription() != null &&
+                    artUrl.equals(mMetadata.getDescription().getIconUri().toString())) {
+                    // If the media is still the same, update the notification:
+                    LogHelper.d(TAG, "fetchBitmapFromURLAsync: set bitmap to ", artUrl);
+                    builder.setLargeIcon(bitmap);
+                    mNotificationManager.notify(NOTIFICATION_ID, builder.build());
+                }
+            }
+        });
+    }
+}
diff --git a/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/MusicPlayerActivity.java b/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/MusicPlayerActivity.java
index 394b01a..ac231c7 100644
--- a/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/MusicPlayerActivity.java
+++ b/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/MusicPlayerActivity.java
@@ -25,8 +25,6 @@
 public class MusicPlayerActivity extends Activity
         implements BrowseFragment.FragmentDataHelper {
 
-    private static final String TAG = MusicPlayerActivity.class.getSimpleName();
-
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
diff --git a/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/MusicService.java b/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/MusicService.java
index b482426..83606bd 100644
--- a/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/MusicService.java
+++ b/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/MusicService.java
@@ -1,4 +1,4 @@
-/*
+ /*
  * Copyright (C) 2014 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
@@ -16,932 +16,713 @@
 
 package com.example.android.mediabrowserservice;
 
-import android.content.Context;
-import android.content.Intent;
-import android.media.AudioManager;
-import android.media.MediaDescription;
-import android.media.MediaMetadata;
-import android.media.MediaPlayer;
-import android.media.MediaPlayer.OnCompletionListener;
-import android.media.MediaPlayer.OnErrorListener;
-import android.media.MediaPlayer.OnPreparedListener;
-import android.media.browse.MediaBrowser;
-import android.media.browse.MediaBrowser.MediaItem;
-import android.media.session.MediaSession;
-import android.media.session.PlaybackState;
-import android.net.Uri;
-import android.net.wifi.WifiManager;
-import android.net.wifi.WifiManager.WifiLock;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Message;
-import android.os.PowerManager;
-import android.os.SystemClock;
-import android.service.media.MediaBrowserService;
+ import android.app.PendingIntent;
+ import android.content.Context;
+ import android.content.Intent;
+ import android.graphics.Bitmap;
+ import android.media.MediaDescription;
+ import android.media.MediaMetadata;
+ import android.media.browse.MediaBrowser.MediaItem;
+ import android.media.session.MediaSession;
+ import android.media.session.PlaybackState;
+ import android.net.Uri;
+ import android.os.Bundle;
+ import android.os.Handler;
+ import android.os.Message;
+ import android.os.SystemClock;
+ import android.service.media.MediaBrowserService;
 
-import com.example.android.mediabrowserservice.model.MusicProvider;
-import com.example.android.mediabrowserservice.utils.LogHelper;
-import com.example.android.mediabrowserservice.utils.MediaIDHelper;
-import com.example.android.mediabrowserservice.utils.QueueHelper;
+ import com.example.android.mediabrowserservice.model.MusicProvider;
+ import com.example.android.mediabrowserservice.utils.CarHelper;
+ import com.example.android.mediabrowserservice.utils.LogHelper;
+ import com.example.android.mediabrowserservice.utils.MediaIDHelper;
+ import com.example.android.mediabrowserservice.utils.QueueHelper;
 
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
+ import java.lang.ref.WeakReference;
+ import java.util.ArrayList;
+ import java.util.Collections;
+ import java.util.List;
 
-import static com.example.android.mediabrowserservice.utils.MediaIDHelper.MEDIA_ID_MUSICS_BY_GENRE;
-import static com.example.android.mediabrowserservice.utils.MediaIDHelper.MEDIA_ID_ROOT;
-import static com.example.android.mediabrowserservice.utils.MediaIDHelper.createBrowseCategoryMediaID;
-import static com.example.android.mediabrowserservice.utils.MediaIDHelper.extractBrowseCategoryFromMediaID;
+ import static com.example.android.mediabrowserservice.utils.MediaIDHelper.MEDIA_ID_MUSICS_BY_GENRE;
+ import static com.example.android.mediabrowserservice.utils.MediaIDHelper.MEDIA_ID_ROOT;
+ import static com.example.android.mediabrowserservice.utils.MediaIDHelper.createBrowseCategoryMediaID;
 
-/**
- * This class provides a MediaBrowser through a service. It exposes the media library to a browsing
- * client, through the onGetRoot and onLoadChildren methods. It also creates a MediaSession and
- * exposes it through its MediaSession.Token, which allows the client to create a MediaController
- * that connects to and send control commands to the MediaSession remotely. This is useful for
- * user interfaces that need to interact with your media session, like Android Auto. You can
- * (should) also use the same service from your app's UI, which gives a seamless playback
- * experience to the user.
- *
- * To implement a MediaBrowserService, you need to:
- *
- * <ul>
- *
- * <li> Extend {@link android.service.media.MediaBrowserService}, implementing the media browsing
- *      related methods {@link android.service.media.MediaBrowserService#onGetRoot} and
- *      {@link android.service.media.MediaBrowserService#onLoadChildren};
- * <li> In onCreate, start a new {@link android.media.session.MediaSession} and notify its parent
- *      with the session's token {@link android.service.media.MediaBrowserService#setSessionToken};
- *
- * <li> Set a callback on the
- *      {@link android.media.session.MediaSession#setCallback(android.media.session.MediaSession.Callback)}.
- *      The callback will receive all the user's actions, like play, pause, etc;
- *
- * <li> Handle all the actual music playing using any method your app prefers (for example,
- *      {@link android.media.MediaPlayer})
- *
- * <li> Update playbackState, "now playing" metadata and queue, using MediaSession proper methods
- *      {@link android.media.session.MediaSession#setPlaybackState(android.media.session.PlaybackState)}
- *      {@link android.media.session.MediaSession#setMetadata(android.media.MediaMetadata)} and
- *      {@link android.media.session.MediaSession#setQueue(java.util.List)})
- *
- * <li> Declare and export the service in AndroidManifest with an intent receiver for the action
- *      android.media.browse.MediaBrowserService
- *
- * </ul>
- *
- * To make your app compatible with Android Auto, you also need to:
- *
- * <ul>
- *
- * <li> Declare a meta-data tag in AndroidManifest.xml linking to a xml resource
- *      with a &lt;automotiveApp&gt; root element. For a media app, this must include
- *      an &lt;uses name="media"/&gt; element as a child.
- *      For example, in AndroidManifest.xml:
- *          &lt;meta-data android:name="com.google.android.gms.car.application"
- *              android:resource="@xml/automotive_app_desc"/&gt;
- *      And in res/values/automotive_app_desc.xml:
- *          &lt;automotiveApp&gt;
- *              &lt;uses name="media"/&gt;
- *          &lt;/automotiveApp&gt;
- *
- * </ul>
+ /**
+  * This class provides a MediaBrowser through a service. It exposes the media library to a browsing
+  * client, through the onGetRoot and onLoadChildren methods. It also creates a MediaSession and
+  * exposes it through its MediaSession.Token, which allows the client to create a MediaController
+  * that connects to and send control commands to the MediaSession remotely. This is useful for
+  * user interfaces that need to interact with your media session, like Android Auto. You can
+  * (should) also use the same service from your app's UI, which gives a seamless playback
+  * experience to the user.
+  *
+  * To implement a MediaBrowserService, you need to:
+  *
+  * <ul>
+  *
+  * <li> Extend {@link android.service.media.MediaBrowserService}, implementing the media browsing
+  *      related methods {@link android.service.media.MediaBrowserService#onGetRoot} and
+  *      {@link android.service.media.MediaBrowserService#onLoadChildren};
+  * <li> In onCreate, start a new {@link android.media.session.MediaSession} and notify its parent
+  *      with the session's token {@link android.service.media.MediaBrowserService#setSessionToken};
+  *
+  * <li> Set a callback on the
+  *      {@link android.media.session.MediaSession#setCallback(android.media.session.MediaSession.Callback)}.
+  *      The callback will receive all the user's actions, like play, pause, etc;
+  *
+  * <li> Handle all the actual music playing using any method your app prefers (for example,
+  *      {@link android.media.MediaPlayer})
+  *
+  * <li> Update playbackState, "now playing" metadata and queue, using MediaSession proper methods
+  *      {@link android.media.session.MediaSession#setPlaybackState(android.media.session.PlaybackState)}
+  *      {@link android.media.session.MediaSession#setMetadata(android.media.MediaMetadata)} and
+  *      {@link android.media.session.MediaSession#setQueue(java.util.List)})
+  *
+  * <li> Declare and export the service in AndroidManifest with an intent receiver for the action
+  *      android.media.browse.MediaBrowserService
+  *
+  * </ul>
+  *
+  * To make your app compatible with Android Auto, you also need to:
+  *
+  * <ul>
+  *
+  * <li> Declare a meta-data tag in AndroidManifest.xml linking to a xml resource
+  *      with a &lt;automotiveApp&gt; root element. For a media app, this must include
+  *      an &lt;uses name="media"/&gt; element as a child.
+  *      For example, in AndroidManifest.xml:
+  *          &lt;meta-data android:name="com.google.android.gms.car.application"
+  *              android:resource="@xml/automotive_app_desc"/&gt;
+  *      And in res/values/automotive_app_desc.xml:
+  *          &lt;automotiveApp&gt;
+  *              &lt;uses name="media"/&gt;
+  *          &lt;/automotiveApp&gt;
+  *
+  * </ul>
 
- * @see <a href="README.md">README.md</a> for more details.
- *
- */
+  * @see <a href="README.md">README.md</a> for more details.
+  *
+  */
 
-public class MusicService extends MediaBrowserService implements OnPreparedListener,
-        OnCompletionListener, OnErrorListener, AudioManager.OnAudioFocusChangeListener {
+ public class MusicService extends MediaBrowserService implements Playback.Callback {
 
-    private static final String TAG = "MusicService";
+     // The action of the incoming Intent indicating that it contains a command
+     // to be executed (see {@link #onStartCommand})
+     public static final String ACTION_CMD = "com.example.android.mediabrowserservice.ACTION_CMD";
+     // The key in the extras of the incoming Intent indicating the command that
+     // should be executed (see {@link #onStartCommand})
+     public static final String CMD_NAME = "CMD_NAME";
+     // A value of a CMD_NAME key in the extras of the incoming Intent that
+     // indicates that the music playback should be paused (see {@link #onStartCommand})
+     public static final String CMD_PAUSE = "CMD_PAUSE";
 
-    // Action to thumbs up a media item
-    private static final String CUSTOM_ACTION_THUMBS_UP = "thumbs_up";
-    // Delay stopSelf by using a handler.
-    private static final int STOP_DELAY = 30000;
+     private static final String TAG = LogHelper.makeLogTag(MusicService.class);
+     // Action to thumbs up a media item
+     private static final String CUSTOM_ACTION_THUMBS_UP =
+         "com.example.android.mediabrowserservice.THUMBS_UP";
+     // Delay stopSelf by using a handler.
+     private static final int STOP_DELAY = 30000;
 
-    // The volume we set the media player to when we lose audio focus, but are
-    // allowed to reduce the volume instead of stopping playback.
-    public static final float VOLUME_DUCK = 0.2f;
+     // Music catalog manager
+     private MusicProvider mMusicProvider;
+     private MediaSession mSession;
+     // "Now playing" queue:
+     private List<MediaSession.QueueItem> mPlayingQueue;
+     private int mCurrentIndexOnQueue;
+     private MediaNotificationManager mMediaNotificationManager;
+     // Indicates whether the service was started.
+     private boolean mServiceStarted;
+     private DelayedStopHandler mDelayedStopHandler = new DelayedStopHandler(this);
+     private Playback mPlayback;
+     private PackageValidator mPackageValidator;
 
-    // The volume we set the media player when we have audio focus.
-    public static final float VOLUME_NORMAL = 1.0f;
-    public static final String ANDROID_AUTO_PACKAGE_NAME = "com.google.android.projection.gearhead";
-    public static final String ANDROID_AUTO_SIMULATOR_PACKAGE_NAME = "com.google.android.mediasimulator";
+     /*
+      * (non-Javadoc)
+      * @see android.app.Service#onCreate()
+      */
+     @Override
+     public void onCreate() {
+         super.onCreate();
+         LogHelper.d(TAG, "onCreate");
 
-    // Music catalog manager
-    private MusicProvider mMusicProvider;
+         mPlayingQueue = new ArrayList<>();
+         mMusicProvider = new MusicProvider();
+         mPackageValidator = new PackageValidator(this);
 
-    private MediaSession mSession;
-    private MediaPlayer mMediaPlayer;
+         // Start a new MediaSession
+         mSession = new MediaSession(this, "MusicService");
+         setSessionToken(mSession.getSessionToken());
+         mSession.setCallback(new MediaSessionCallback());
+         mSession.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS |
+             MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
 
-    // "Now playing" queue:
-    private List<MediaSession.QueueItem> mPlayingQueue;
-    private int mCurrentIndexOnQueue;
+         mPlayback = new Playback(this, mMusicProvider);
+         mPlayback.setState(PlaybackState.STATE_NONE);
+         mPlayback.setCallback(this);
+         mPlayback.start();
 
-    // Current local media player state
-    private int mState = PlaybackState.STATE_NONE;
+         Context context = getApplicationContext();
+         Intent intent = new Intent(context, MusicPlayerActivity.class);
+         PendingIntent pi = PendingIntent.getActivity(context, 99 /*request code*/,
+                 intent, PendingIntent.FLAG_UPDATE_CURRENT);
+         mSession.setSessionActivity(pi);
 
-    // Wifi lock that we hold when streaming files from the internet, in order
-    // to prevent the device from shutting off the Wifi radio
-    private WifiLock mWifiLock;
+         Bundle extras = new Bundle();
+         CarHelper.setSlotReservationFlags(extras, true, true, true);
+         mSession.setExtras(extras);
 
-    private MediaNotification mMediaNotification;
+         updatePlaybackState(null);
 
-    // Indicates whether the service was started.
-    private boolean mServiceStarted;
+         mMediaNotificationManager = new MediaNotificationManager(this);
+     }
 
-    enum AudioFocus {
-        NoFocusNoDuck, // we don't have audio focus, and can't duck
-        NoFocusCanDuck, // we don't have focus, but can play at a low volume
-                        // ("ducking")
-        Focused // we have full audio focus
-    }
+     /**
+      * (non-Javadoc)
+      * @see android.app.Service#onStartCommand(android.content.Intent, int, int)
+      */
+     @Override
+     public int onStartCommand(Intent startIntent, int flags, int startId) {
+         if (startIntent != null) {
+             String action = startIntent.getAction();
+             String command = startIntent.getStringExtra(CMD_NAME);
+             if (ACTION_CMD.equals(action)) {
+                 if (CMD_PAUSE.equals(command)) {
+                     if (mPlayback != null && mPlayback.isPlaying()) {
+                         handlePauseRequest();
+                     }
+                 }
+             }
+         }
+         return START_STICKY;
+     }
 
-    // Type of audio focus we have:
-    private AudioFocus mAudioFocus = AudioFocus.NoFocusNoDuck;
-    private AudioManager mAudioManager;
+     /**
+      * (non-Javadoc)
+      * @see android.app.Service#onDestroy()
+      */
+     @Override
+     public void onDestroy() {
+         LogHelper.d(TAG, "onDestroy");
+         // Service is being killed, so make sure we release our resources
+         handleStopRequest(null);
 
-    // Indicates if we should start playing immediately after we gain focus.
-    private boolean mPlayOnFocusGain;
+         mDelayedStopHandler.removeCallbacksAndMessages(null);
+         // Always release the MediaSession to clean up resources
+         // and notify associated MediaController(s).
+         mSession.release();
+     }
 
-    private Handler mDelayedStopHandler = new Handler() {
-        @Override
-        public void handleMessage(Message msg) {
-            if ((mMediaPlayer != null && mMediaPlayer.isPlaying()) ||
-                    mPlayOnFocusGain) {
-                LogHelper.d(TAG, "Ignoring delayed stop since the media player is in use.");
-                return;
-            }
-            LogHelper.d(TAG, "Stopping service with delay handler.");
-            stopSelf();
-            mServiceStarted = false;
-        }
-    };
+     @Override
+     public BrowserRoot onGetRoot(String clientPackageName, int clientUid, Bundle rootHints) {
+         LogHelper.d(TAG, "OnGetRoot: clientPackageName=" + clientPackageName,
+                 "; clientUid=" + clientUid + " ; rootHints=", rootHints);
+         // To ensure you are not allowing any arbitrary app to browse your app's contents, you
+         // need to check the origin:
+         if (!mPackageValidator.isCallerAllowed(this, clientPackageName, clientUid)) {
+             // If the request comes from an untrusted package, return null. No further calls will
+             // be made to other media browsing methods.
+             LogHelper.w(TAG, "OnGetRoot: IGNORING request from untrusted package "
+                     + clientPackageName);
+             return null;
+         }
+         //noinspection StatementWithEmptyBody
+         if (CarHelper.isValidCarPackage(clientPackageName)) {
+             // Optional: if your app needs to adapt ads, music library or anything else that
+             // needs to run differently when connected to the car, this is where you should handle
+             // it.
+         }
+         return new BrowserRoot(MEDIA_ID_ROOT, null);
+     }
 
-    /*
-     * (non-Javadoc)
-     * @see android.app.Service#onCreate()
-     */
-    @Override
-    public void onCreate() {
-        super.onCreate();
-        LogHelper.d(TAG, "onCreate");
+     @Override
+     public void onLoadChildren(final String parentMediaId, final Result<List<MediaItem>> result) {
+         if (!mMusicProvider.isInitialized()) {
+             // Use result.detach to allow calling result.sendResult from another thread:
+             result.detach();
 
-        mPlayingQueue = new ArrayList<>();
+             mMusicProvider.retrieveMediaAsync(new MusicProvider.Callback() {
+                 @Override
+                 public void onMusicCatalogReady(boolean success) {
+                     if (success) {
+                         loadChildrenImpl(parentMediaId, result);
+                     } else {
+                         updatePlaybackState(getString(R.string.error_no_metadata));
+                         result.sendResult(Collections.<MediaItem>emptyList());
+                     }
+                 }
+             });
 
-        // Create the Wifi lock (this does not acquire the lock, this just creates it)
-        mWifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE))
-                .createWifiLock(WifiManager.WIFI_MODE_FULL, "MusicDemo_lock");
+         } else {
+             // If our music catalog is already loaded/cached, load them into result immediately
+             loadChildrenImpl(parentMediaId, result);
+         }
+     }
 
+     /**
+      * Actual implementation of onLoadChildren that assumes that MusicProvider is already
+      * initialized.
+      */
+     private void loadChildrenImpl(final String parentMediaId,
+                                   final Result<List<MediaItem>> result) {
+         LogHelper.d(TAG, "OnLoadChildren: parentMediaId=", parentMediaId);
 
-        // Create the music catalog metadata provider
-        mMusicProvider = new MusicProvider();
-        mMusicProvider.retrieveMedia(new MusicProvider.Callback() {
-            @Override
-            public void onMusicCatalogReady(boolean success) {
-                mState = success ? PlaybackState.STATE_NONE : PlaybackState.STATE_ERROR;
-            }
-        });
+         List<MediaItem> mediaItems = new ArrayList<>();
 
-        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
+         if (MEDIA_ID_ROOT.equals(parentMediaId)) {
+             LogHelper.d(TAG, "OnLoadChildren.ROOT");
+             mediaItems.add(new MediaItem(
+                     new MediaDescription.Builder()
+                         .setMediaId(MEDIA_ID_MUSICS_BY_GENRE)
+                         .setTitle(getString(R.string.browse_genres))
+                         .setIconUri(Uri.parse("android.resource://" +
+                             "com.example.android.mediabrowserservice/drawable/ic_by_genre"))
+                         .setSubtitle(getString(R.string.browse_genre_subtitle))
+                         .build(), MediaItem.FLAG_BROWSABLE
+             ));
 
-        // Start a new MediaSession
-        mSession = new MediaSession(this, "MusicService");
-        setSessionToken(mSession.getSessionToken());
-        mSession.setCallback(new MediaSessionCallback());
-        mSession.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS |
-                MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
+         } else if (MEDIA_ID_MUSICS_BY_GENRE.equals(parentMediaId)) {
+             LogHelper.d(TAG, "OnLoadChildren.GENRES");
+             for (String genre : mMusicProvider.getGenres()) {
+                 MediaItem item = new MediaItem(
+                     new MediaDescription.Builder()
+                         .setMediaId(createBrowseCategoryMediaID(MEDIA_ID_MUSICS_BY_GENRE, genre))
+                         .setTitle(genre)
+                         .setSubtitle(getString(R.string.browse_musics_by_genre_subtitle, genre))
+                         .build(), MediaItem.FLAG_BROWSABLE
+                 );
+                 mediaItems.add(item);
+             }
 
-        // Use these extras to reserve space for the corresponding actions, even when they are disabled
-        // in the playbackstate, so the custom actions don't reflow.
-        Bundle extras = new Bundle();
-        extras.putBoolean(
-            "com.google.android.gms.car.media.ALWAYS_RESERVE_SPACE_FOR.ACTION_SKIP_TO_NEXT",
-            true);
-        extras.putBoolean(
-            "com.google.android.gms.car.media.ALWAYS_RESERVE_SPACE_FOR.ACTION_SKIP_TO_PREVIOUS",
-            true);
-        // If you want to reserve the Queue slot when there is no queue
-        // (mSession.setQueue(emptylist)), uncomment the lines below:
-        // extras.putBoolean(
-        //   "com.google.android.gms.car.media.ALWAYS_RESERVE_SPACE_FOR.ACTION_QUEUE",
-        //   true);
-        mSession.setExtras(extras);
+         } else if (parentMediaId.startsWith(MEDIA_ID_MUSICS_BY_GENRE)) {
+             String genre = MediaIDHelper.getHierarchy(parentMediaId)[1];
+             LogHelper.d(TAG, "OnLoadChildren.SONGS_BY_GENRE  genre=", genre);
+             for (MediaMetadata track : mMusicProvider.getMusicsByGenre(genre)) {
+                 // Since mediaMetadata fields are immutable, we need to create a copy, so we
+                 // can set a hierarchy-aware mediaID. We will need to know the media hierarchy
+                 // when we get a onPlayFromMusicID call, so we can create the proper queue based
+                 // on where the music was selected from (by artist, by genre, random, etc)
+                 String hierarchyAwareMediaID = MediaIDHelper.createMediaID(
+                         track.getDescription().getMediaId(), MEDIA_ID_MUSICS_BY_GENRE, genre);
+                 MediaMetadata trackCopy = new MediaMetadata.Builder(track)
+                         .putString(MediaMetadata.METADATA_KEY_MEDIA_ID, hierarchyAwareMediaID)
+                         .build();
+                 MediaItem bItem = new MediaItem(
+                         trackCopy.getDescription(), MediaItem.FLAG_PLAYABLE);
+                 mediaItems.add(bItem);
+             }
+         } else {
+             LogHelper.w(TAG, "Skipping unmatched parentMediaId: ", parentMediaId);
+         }
+         LogHelper.d(TAG, "OnLoadChildren sending ", mediaItems.size(),
+                 " results for ", parentMediaId);
+         result.sendResult(mediaItems);
+     }
 
-        updatePlaybackState(null);
+     private final class MediaSessionCallback extends MediaSession.Callback {
+         @Override
+         public void onPlay() {
+             LogHelper.d(TAG, "play");
 
-        mMediaNotification = new MediaNotification(this);
-    }
+             if (mPlayingQueue == null || mPlayingQueue.isEmpty()) {
+                 mPlayingQueue = QueueHelper.getRandomQueue(mMusicProvider);
+                 mSession.setQueue(mPlayingQueue);
+                 mSession.setQueueTitle(getString(R.string.random_queue_title));
+                 // start playing from the beginning of the queue
+                 mCurrentIndexOnQueue = 0;
+             }
 
-    /*
-     * (non-Javadoc)
-     * @see android.app.Service#onDestroy()
-     */
-    @Override
-    public void onDestroy() {
-        LogHelper.d(TAG, "onDestroy");
+             if (mPlayingQueue != null && !mPlayingQueue.isEmpty()) {
+                 handlePlayRequest();
+             }
+         }
 
-        // Service is being killed, so make sure we release our resources
-        handleStopRequest(null);
+         @Override
+         public void onSkipToQueueItem(long queueId) {
+             LogHelper.d(TAG, "OnSkipToQueueItem:" + queueId);
 
-        mDelayedStopHandler.removeCallbacksAndMessages(null);
-        // In particular, always release the MediaSession to clean up resources
-        // and notify associated MediaController(s).
-        mSession.release();
-    }
+             if (mPlayingQueue != null && !mPlayingQueue.isEmpty()) {
+                 // set the current index on queue from the music Id:
+                 mCurrentIndexOnQueue = QueueHelper.getMusicIndexOnQueue(mPlayingQueue, queueId);
+                 // play the music
+                 handlePlayRequest();
+             }
+         }
 
+         @Override
+         public void onSeekTo(long position) {
+             LogHelper.d(TAG, "onSeekTo:", position);
+             mPlayback.seekTo((int) position);
+         }
 
-    @Override
-    public BrowserRoot onGetRoot(String clientPackageName, int clientUid, Bundle rootHints) {
-        LogHelper.d(TAG, "OnGetRoot: clientPackageName=" + clientPackageName,
-                "; clientUid=" + clientUid + " ; rootHints=", rootHints);
-        // To ensure you are not allowing any arbitrary app to browse your app's contents, you
-        // need to check the origin:
-        if (!PackageValidator.isCallerAllowed(this, clientPackageName, clientUid)) {
-            // If the request comes from an untrusted package, return null. No further calls will
-            // be made to other media browsing methods.
-            LogHelper.w(TAG, "OnGetRoot: IGNORING request from untrusted package "
-                    + clientPackageName);
-            return null;
-        }
-        if (ANDROID_AUTO_PACKAGE_NAME.equals(clientPackageName)) {
-            // Optional: if your app needs to adapt ads, music library or anything else that
-            // needs to run differently when connected to the car, this is where you should handle
-            // it.
-        }
-        return new BrowserRoot(MEDIA_ID_ROOT, null);
-    }
+         @Override
+         public void onPlayFromMediaId(String mediaId, Bundle extras) {
+             LogHelper.d(TAG, "playFromMediaId mediaId:", mediaId, "  extras=", extras);
 
-    @Override
-    public void onLoadChildren(final String parentMediaId, final Result<List<MediaItem>> result) {
-        if (!mMusicProvider.isInitialized()) {
-            // Use result.detach to allow calling result.sendResult from another thread:
-            result.detach();
+             // The mediaId used here is not the unique musicId. This one comes from the
+             // MediaBrowser, and is actually a "hierarchy-aware mediaID": a concatenation of
+             // the hierarchy in MediaBrowser and the actual unique musicID. This is necessary
+             // so we can build the correct playing queue, based on where the track was
+             // selected from.
+             mPlayingQueue = QueueHelper.getPlayingQueue(mediaId, mMusicProvider);
+             mSession.setQueue(mPlayingQueue);
+             String queueTitle = getString(R.string.browse_musics_by_genre_subtitle,
+                     MediaIDHelper.extractBrowseCategoryValueFromMediaID(mediaId));
+             mSession.setQueueTitle(queueTitle);
 
-            mMusicProvider.retrieveMedia(new MusicProvider.Callback() {
-                @Override
-                public void onMusicCatalogReady(boolean success) {
-                    if (success) {
-                        loadChildrenImpl(parentMediaId, result);
-                    } else {
-                        updatePlaybackState(getString(R.string.error_no_metadata));
-                        result.sendResult(new ArrayList<MediaItem>());
-                    }
-                }
-            });
+             if (mPlayingQueue != null && !mPlayingQueue.isEmpty()) {
+                 // set the current index on queue from the media Id:
+                 mCurrentIndexOnQueue = QueueHelper.getMusicIndexOnQueue(mPlayingQueue, mediaId);
 
-        } else {
-            // If our music catalog is already loaded/cached, load them into result immediately
-            loadChildrenImpl(parentMediaId, result);
-        }
-    }
+                 if (mCurrentIndexOnQueue < 0) {
+                     LogHelper.e(TAG, "playFromMediaId: media ID ", mediaId,
+                             " could not be found on queue. Ignoring.");
+                 } else {
+                     // play the music
+                     handlePlayRequest();
+                 }
+             }
+         }
 
-    /**
-     * Actual implementation of onLoadChildren that assumes that MusicProvider is already
-     * initialized.
-     */
-    private void loadChildrenImpl(final String parentMediaId,
-                                  final Result<List<MediaBrowser.MediaItem>> result) {
-        LogHelper.d(TAG, "OnLoadChildren: parentMediaId=", parentMediaId);
+         @Override
+         public void onPause() {
+             LogHelper.d(TAG, "pause. current state=" + mPlayback.getState());
+             handlePauseRequest();
+         }
 
-        List<MediaBrowser.MediaItem> mediaItems = new ArrayList<>();
+         @Override
+         public void onStop() {
+             LogHelper.d(TAG, "stop. current state=" + mPlayback.getState());
+             handleStopRequest(null);
+         }
 
-        if (MEDIA_ID_ROOT.equals(parentMediaId)) {
-            LogHelper.d(TAG, "OnLoadChildren.ROOT");
-            mediaItems.add(new MediaBrowser.MediaItem(
-                    new MediaDescription.Builder()
-                        .setMediaId(MEDIA_ID_MUSICS_BY_GENRE)
-                        .setTitle(getString(R.string.browse_genres))
-                        .setIconUri(Uri.parse("android.resource://" +
-                                "com.example.android.mediabrowserservice/drawable/ic_by_genre"))
-                        .setSubtitle(getString(R.string.browse_genre_subtitle))
-                        .build(), MediaBrowser.MediaItem.FLAG_BROWSABLE
-            ));
+         @Override
+         public void onSkipToNext() {
+             LogHelper.d(TAG, "skipToNext");
+             mCurrentIndexOnQueue++;
+             if (mPlayingQueue != null && mCurrentIndexOnQueue >= mPlayingQueue.size()) {
+                 // This sample's behavior: skipping to next when in last song returns to the
+                 // first song.
+                 mCurrentIndexOnQueue = 0;
+             }
+             if (QueueHelper.isIndexPlayable(mCurrentIndexOnQueue, mPlayingQueue)) {
+                 handlePlayRequest();
+             } else {
+                 LogHelper.e(TAG, "skipToNext: cannot skip to next. next Index=" +
+                         mCurrentIndexOnQueue + " queue length=" +
+                         (mPlayingQueue == null ? "null" : mPlayingQueue.size()));
+                 handleStopRequest("Cannot skip");
+             }
+         }
 
-        } else if (MEDIA_ID_MUSICS_BY_GENRE.equals(parentMediaId)) {
-            LogHelper.d(TAG, "OnLoadChildren.GENRES");
-            for (String genre: mMusicProvider.getGenres()) {
-                MediaBrowser.MediaItem item = new MediaBrowser.MediaItem(
-                    new MediaDescription.Builder()
-                        .setMediaId(createBrowseCategoryMediaID(MEDIA_ID_MUSICS_BY_GENRE, genre))
-                        .setTitle(genre)
-                        .setSubtitle(getString(R.string.browse_musics_by_genre_subtitle, genre))
-                        .build(), MediaBrowser.MediaItem.FLAG_BROWSABLE
-                );
-                mediaItems.add(item);
-            }
+         @Override
+         public void onSkipToPrevious() {
+             LogHelper.d(TAG, "skipToPrevious");
+             mCurrentIndexOnQueue--;
+             if (mPlayingQueue != null && mCurrentIndexOnQueue < 0) {
+                 // This sample's behavior: skipping to previous when in first song restarts the
+                 // first song.
+                 mCurrentIndexOnQueue = 0;
+             }
+             if (QueueHelper.isIndexPlayable(mCurrentIndexOnQueue, mPlayingQueue)) {
+                 handlePlayRequest();
+             } else {
+                 LogHelper.e(TAG, "skipToPrevious: cannot skip to previous. previous Index=" +
+                         mCurrentIndexOnQueue + " queue length=" +
+                         (mPlayingQueue == null ? "null" : mPlayingQueue.size()));
+                 handleStopRequest("Cannot skip");
+             }
+         }
 
-        } else if (parentMediaId.startsWith(MEDIA_ID_MUSICS_BY_GENRE)) {
-            String genre = extractBrowseCategoryFromMediaID(parentMediaId)[1];
-            LogHelper.d(TAG, "OnLoadChildren.SONGS_BY_GENRE  genre=", genre);
-            for (MediaMetadata track: mMusicProvider.getMusicsByGenre(genre)) {
-                // Since mediaMetadata fields are immutable, we need to create a copy, so we
-                // can set a hierarchy-aware mediaID. We will need to know the media hierarchy
-                // when we get a onPlayFromMusicID call, so we can create the proper queue based
-                // on where the music was selected from (by artist, by genre, random, etc)
-                String hierarchyAwareMediaID = MediaIDHelper.createTrackMediaID(
-                        MEDIA_ID_MUSICS_BY_GENRE, genre, track);
-                MediaMetadata trackCopy = new MediaMetadata.Builder(track)
-                        .putString(MediaMetadata.METADATA_KEY_MEDIA_ID, hierarchyAwareMediaID)
-                        .build();
-                MediaBrowser.MediaItem bItem = new MediaBrowser.MediaItem(
-                        trackCopy.getDescription(), MediaItem.FLAG_PLAYABLE);
-                mediaItems.add(bItem);
-            }
-        } else {
-            LogHelper.w(TAG, "Skipping unmatched parentMediaId: ", parentMediaId);
-        }
-        result.sendResult(mediaItems);
-    }
+         @Override
+         public void onCustomAction(String action, Bundle extras) {
+             if (CUSTOM_ACTION_THUMBS_UP.equals(action)) {
+                 LogHelper.i(TAG, "onCustomAction: favorite for current track");
+                 MediaMetadata track = getCurrentPlayingMusic();
+                 if (track != null) {
+                     String musicId = track.getString(MediaMetadata.METADATA_KEY_MEDIA_ID);
+                     mMusicProvider.setFavorite(musicId, !mMusicProvider.isFavorite(musicId));
+                 }
+                 // playback state needs to be updated because the "Favorite" icon on the
+                 // custom action will change to reflect the new favorite state.
+                 updatePlaybackState(null);
+             } else {
+                 LogHelper.e(TAG, "Unsupported action: ", action);
+             }
+         }
 
+         @Override
+         public void onPlayFromSearch(String query, Bundle extras) {
+             LogHelper.d(TAG, "playFromSearch  query=", query);
 
+             mPlayingQueue = QueueHelper.getPlayingQueueFromSearch(query, mMusicProvider);
+             LogHelper.d(TAG, "playFromSearch  playqueue.length=" + mPlayingQueue.size());
+             mSession.setQueue(mPlayingQueue);
 
-    private final class MediaSessionCallback extends MediaSession.Callback {
-        @Override
-        public void onPlay() {
-            LogHelper.d(TAG, "play");
+             if (mPlayingQueue != null && !mPlayingQueue.isEmpty()) {
+                 // start playing from the beginning of the queue
+                 mCurrentIndexOnQueue = 0;
 
-            if (mPlayingQueue == null || mPlayingQueue.isEmpty()) {
-                mPlayingQueue = QueueHelper.getRandomQueue(mMusicProvider);
-                mSession.setQueue(mPlayingQueue);
-                mSession.setQueueTitle(getString(R.string.random_queue_title));
-                // start playing from the beginning of the queue
-                mCurrentIndexOnQueue = 0;
-            }
+                 handlePlayRequest();
+             }
+         }
+     }
 
-            if (mPlayingQueue != null && !mPlayingQueue.isEmpty()) {
-                handlePlayRequest();
-            }
-        }
+     /**
+      * Handle a request to play music
+      */
+     private void handlePlayRequest() {
+         LogHelper.d(TAG, "handlePlayRequest: mState=" + mPlayback.getState());
 
-        @Override
-        public void onSkipToQueueItem(long queueId) {
-            LogHelper.d(TAG, "OnSkipToQueueItem:" + queueId);
+         mDelayedStopHandler.removeCallbacksAndMessages(null);
+         if (!mServiceStarted) {
+             LogHelper.v(TAG, "Starting service");
+             // The MusicService needs to keep running even after the calling MediaBrowser
+             // is disconnected. Call startService(Intent) and then stopSelf(..) when we no longer
+             // need to play media.
+             startService(new Intent(getApplicationContext(), MusicService.class));
+             mServiceStarted = true;
+         }
 
-            if (mState == PlaybackState.STATE_PAUSED) {
-                mState = PlaybackState.STATE_STOPPED;
-            }
+         if (!mSession.isActive()) {
+             mSession.setActive(true);
+         }
 
-            if (mPlayingQueue != null && !mPlayingQueue.isEmpty()) {
+         if (QueueHelper.isIndexPlayable(mCurrentIndexOnQueue, mPlayingQueue)) {
+             updateMetadata();
+             mPlayback.play(mPlayingQueue.get(mCurrentIndexOnQueue));
+         }
+     }
 
-                // set the current index on queue from the music Id:
-                mCurrentIndexOnQueue = QueueHelper.getMusicIndexOnQueue(mPlayingQueue, queueId);
-
-                // play the music
-                handlePlayRequest();
-            }
-        }
-
-        @Override
-        public void onPlayFromMediaId(String mediaId, Bundle extras) {
-            LogHelper.d(TAG, "playFromMediaId mediaId:", mediaId, "  extras=", extras);
-
-            if (mState == PlaybackState.STATE_PAUSED) {
-                mState = PlaybackState.STATE_STOPPED;
-            }
-
-            // The mediaId used here is not the unique musicId. This one comes from the
-            // MediaBrowser, and is actually a "hierarchy-aware mediaID": a concatenation of
-            // the hierarchy in MediaBrowser and the actual unique musicID. This is necessary
-            // so we can build the correct playing queue, based on where the track was
-            // selected from.
-            mPlayingQueue = QueueHelper.getPlayingQueue(mediaId, mMusicProvider);
-            mSession.setQueue(mPlayingQueue);
-            String queueTitle = getString(R.string.browse_musics_by_genre_subtitle,
-                    MediaIDHelper.extractBrowseCategoryValueFromMediaID(mediaId));
-            mSession.setQueueTitle(queueTitle);
-
-            if (mPlayingQueue != null && !mPlayingQueue.isEmpty()) {
-                String uniqueMusicID = MediaIDHelper.extractMusicIDFromMediaID(mediaId);
-
-                // set the current index on queue from the music Id:
-                mCurrentIndexOnQueue = QueueHelper.getMusicIndexOnQueue(
-                        mPlayingQueue, uniqueMusicID);
-
-                // play the music
-                handlePlayRequest();
-            }
-        }
-
-        @Override
-        public void onPause() {
-            LogHelper.d(TAG, "pause. current state=" + mState);
-            handlePauseRequest();
-        }
-
-        @Override
-        public void onStop() {
-            LogHelper.d(TAG, "stop. current state=" + mState);
-            handleStopRequest(null);
-        }
-
-        @Override
-        public void onSkipToNext() {
-            LogHelper.d(TAG, "skipToNext");
-            mCurrentIndexOnQueue++;
-            if (mPlayingQueue != null && mCurrentIndexOnQueue >= mPlayingQueue.size()) {
-                mCurrentIndexOnQueue = 0;
-            }
-            if (QueueHelper.isIndexPlayable(mCurrentIndexOnQueue, mPlayingQueue)) {
-                mState = PlaybackState.STATE_STOPPED;
-                handlePlayRequest();
-            } else {
-                LogHelper.e(TAG, "skipToNext: cannot skip to next. next Index=" +
-                        mCurrentIndexOnQueue + " queue length=" +
-                        (mPlayingQueue == null ? "null" : mPlayingQueue.size()));
-                handleStopRequest("Cannot skip");
-            }
-        }
-
-        @Override
-        public void onSkipToPrevious() {
-            LogHelper.d(TAG, "skipToPrevious");
-            mCurrentIndexOnQueue--;
-            if (mPlayingQueue != null && mCurrentIndexOnQueue < 0) {
-                // This sample's behavior: skipping to previous when in first song restarts the
-                // first song.
-                mCurrentIndexOnQueue = 0;
-            }
-            if (QueueHelper.isIndexPlayable(mCurrentIndexOnQueue, mPlayingQueue)) {
-                mState = PlaybackState.STATE_STOPPED;
-                handlePlayRequest();
-            } else {
-                LogHelper.e(TAG, "skipToPrevious: cannot skip to previous. previous Index=" +
-                        mCurrentIndexOnQueue + " queue length=" +
-                        (mPlayingQueue == null ? "null" : mPlayingQueue.size()));
-                handleStopRequest("Cannot skip");
-            }
-        }
-
-        @Override
-        public void onCustomAction(String action, Bundle extras) {
-            if (CUSTOM_ACTION_THUMBS_UP.equals(action)) {
-                LogHelper.i(TAG, "onCustomAction: favorite for current track");
-                MediaMetadata track = getCurrentPlayingMusic();
-                if (track != null) {
-                    String mediaId = track.getString(MediaMetadata.METADATA_KEY_MEDIA_ID);
-                    mMusicProvider.setFavorite(mediaId, !mMusicProvider.isFavorite(mediaId));
-                }
-                updatePlaybackState(null);
-            } else {
-                LogHelper.e(TAG, "Unsupported action: ", action);
-            }
-
-        }
-
-        @Override
-        public void onPlayFromSearch(String query, Bundle extras) {
-            LogHelper.d(TAG, "playFromSearch  query=", query);
-
-            if (mState == PlaybackState.STATE_PAUSED) {
-                mState = PlaybackState.STATE_STOPPED;
-            }
-
-            mPlayingQueue = QueueHelper.getPlayingQueueFromSearch(query, mMusicProvider);
-            LogHelper.d(TAG, "playFromSearch  playqueue.length=" + mPlayingQueue.size());
-            mSession.setQueue(mPlayingQueue);
-
-            if (mPlayingQueue != null && !mPlayingQueue.isEmpty()) {
-                // start playing from the beginning of the queue
-                mCurrentIndexOnQueue = 0;
-
-                handlePlayRequest();
-            }
-        }
-    }
-
-
-
-    /*
-     * Called when media player is done playing current song.
-     * @see android.media.MediaPlayer.OnCompletionListener
-     */
-    @Override
-    public void onCompletion(MediaPlayer player) {
-        LogHelper.d(TAG, "onCompletion from MediaPlayer");
-        // The media player finished playing the current song, so we go ahead
-        // and start the next.
-        if (mPlayingQueue != null && !mPlayingQueue.isEmpty()) {
-            // In this sample, we restart the playing queue when it gets to the end:
-            mCurrentIndexOnQueue++;
-            if (mCurrentIndexOnQueue >= mPlayingQueue.size()) {
-                mCurrentIndexOnQueue = 0;
-            }
-            handlePlayRequest();
-        } else {
-            // If there is nothing to play, we stop and release the resources:
-            handleStopRequest(null);
-        }
-    }
-
-    /*
-     * Called when media player is done preparing.
-     * @see android.media.MediaPlayer.OnPreparedListener
-     */
-    @Override
-    public void onPrepared(MediaPlayer player) {
-        LogHelper.d(TAG, "onPrepared from MediaPlayer");
-        // The media player is done preparing. That means we can start playing if we
-        // have audio focus.
-        configMediaPlayerState();
-    }
-
-    /**
-     * Called when there's an error playing media. When this happens, the media
-     * player goes to the Error state. We warn the user about the error and
-     * reset the media player.
-     *
-     * @see android.media.MediaPlayer.OnErrorListener
-     */
-    @Override
-    public boolean onError(MediaPlayer mp, int what, int extra) {
-        LogHelper.e(TAG, "Media player error: what=" + what + ", extra=" + extra);
-        handleStopRequest("MediaPlayer error " + what + " (" + extra + ")");
-        return true; // true indicates we handled the error
-    }
-
-
-
-
-    /**
-     * Called by AudioManager on audio focus changes.
-     */
-    @Override
-    public void onAudioFocusChange(int focusChange) {
-        LogHelper.d(TAG, "onAudioFocusChange. focusChange=" + focusChange);
-        if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
-            // We have gained focus:
-            mAudioFocus = AudioFocus.Focused;
-
-        } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS ||
-                focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT ||
-                focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
-            // We have lost focus. If we can duck (low playback volume), we can keep playing.
-            // Otherwise, we need to pause the playback.
-            boolean canDuck = focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK;
-            mAudioFocus = canDuck ? AudioFocus.NoFocusCanDuck : AudioFocus.NoFocusNoDuck;
-
-            // If we are playing, we need to reset media player by calling configMediaPlayerState
-            // with mAudioFocus properly set.
-            if (mState == PlaybackState.STATE_PLAYING && !canDuck) {
-                // If we don't have audio focus and can't duck, we save the information that
-                // we were playing, so that we can resume playback once we get the focus back.
-                mPlayOnFocusGain = true;
-            }
-        } else {
-            LogHelper.e(TAG, "onAudioFocusChange: Ignoring unsupported focusChange: " + focusChange);
-        }
-
-        configMediaPlayerState();
-    }
-
-
-
-    /**
-     * Handle a request to play music
-     */
-    private void handlePlayRequest() {
-        LogHelper.d(TAG, "handlePlayRequest: mState=" + mState);
-
-        mDelayedStopHandler.removeCallbacksAndMessages(null);
-        if (!mServiceStarted) {
-            LogHelper.v(TAG, "Starting service");
-            // The MusicService needs to keep running even after the calling MediaBrowser
-            // is disconnected. Call startService(Intent) and then stopSelf(..) when we no longer
-            // need to play media.
-            startService(new Intent(getApplicationContext(), MusicService.class));
-            mServiceStarted = true;
-        }
-
-        mPlayOnFocusGain = true;
-        tryToGetAudioFocus();
-
-        if (!mSession.isActive()) {
-            mSession.setActive(true);
-        }
-
-        // actually play the song
-        if (mState == PlaybackState.STATE_PAUSED) {
-            // If we're paused, just continue playback and restore the
-            // 'foreground service' state.
-            configMediaPlayerState();
-        } else {
-            // If we're stopped or playing a song,
-            // just go ahead to the new song and (re)start playing
-            playCurrentSong();
-        }
-    }
-
-
-    /**
-     * Handle a request to pause music
-     */
-    private void handlePauseRequest() {
-        LogHelper.d(TAG, "handlePauseRequest: mState=" + mState);
-
-        if (mState == PlaybackState.STATE_PLAYING) {
-            // Pause media player and cancel the 'foreground service' state.
-            mState = PlaybackState.STATE_PAUSED;
-            if (mMediaPlayer.isPlaying()) {
-                mMediaPlayer.pause();
-            }
-            // while paused, retain the MediaPlayer but give up audio focus
-            relaxResources(false);
-            giveUpAudioFocus();
-        }
-        updatePlaybackState(null);
-    }
-
-    /**
-     * Handle a request to stop music
-     */
-    private void handleStopRequest(String withError) {
-        LogHelper.d(TAG, "handleStopRequest: mState=" + mState + " error=", withError);
-        mState = PlaybackState.STATE_STOPPED;
-
-        // let go of all resources...
-        relaxResources(true);
-        giveUpAudioFocus();
-        updatePlaybackState(withError);
-
-        mMediaNotification.stopNotification();
-
-        // service is no longer necessary. Will be started again if needed.
-        stopSelf();
-        mServiceStarted = false;
-    }
-
-    /**
-     * Releases resources used by the service for playback. This includes the
-     * "foreground service" status, the wake locks and possibly the MediaPlayer.
-     *
-     * @param releaseMediaPlayer Indicates whether the Media Player should also
-     *            be released or not
-     */
-    private void relaxResources(boolean releaseMediaPlayer) {
-        LogHelper.d(TAG, "relaxResources. releaseMediaPlayer=" + releaseMediaPlayer);
-        // stop being a foreground service
-        stopForeground(true);
-
-        // reset the delayed stop handler.
-        mDelayedStopHandler.removeCallbacksAndMessages(null);
-        mDelayedStopHandler.sendEmptyMessageDelayed(0, STOP_DELAY);
-
-        // stop and release the Media Player, if it's available
-        if (releaseMediaPlayer && mMediaPlayer != null) {
-            mMediaPlayer.reset();
-            mMediaPlayer.release();
-            mMediaPlayer = null;
-        }
-
-        // we can also release the Wifi lock, if we're holding it
-        if (mWifiLock.isHeld()) {
-            mWifiLock.release();
-        }
-    }
-
-    /**
-     * Reconfigures MediaPlayer according to audio focus settings and
-     * starts/restarts it. This method starts/restarts the MediaPlayer
-     * respecting the current audio focus state. So if we have focus, it will
-     * play normally; if we don't have focus, it will either leave the
-     * MediaPlayer paused or set it to a low volume, depending on what is
-     * allowed by the current focus settings. This method assumes mPlayer !=
-     * null, so if you are calling it, you have to do so from a context where
-     * you are sure this is the case.
-     */
-    private void configMediaPlayerState() {
-        LogHelper.d(TAG, "configAndStartMediaPlayer. mAudioFocus=" + mAudioFocus);
-        if (mAudioFocus == AudioFocus.NoFocusNoDuck) {
-            // If we don't have audio focus and can't duck, we have to pause,
-            if (mState == PlaybackState.STATE_PLAYING) {
-                handlePauseRequest();
-            }
-        } else {  // we have audio focus:
-            if (mAudioFocus == AudioFocus.NoFocusCanDuck) {
-                mMediaPlayer.setVolume(VOLUME_DUCK, VOLUME_DUCK); // we'll be relatively quiet
-            } else {
-                mMediaPlayer.setVolume(VOLUME_NORMAL, VOLUME_NORMAL); // we can be loud again
-            }
-            // If we were playing when we lost focus, we need to resume playing.
-            if (mPlayOnFocusGain) {
-                if (!mMediaPlayer.isPlaying()) {
-                    LogHelper.d(TAG, "configAndStartMediaPlayer startMediaPlayer.");
-                    mMediaPlayer.start();
-                }
-                mPlayOnFocusGain = false;
-                mState = PlaybackState.STATE_PLAYING;
-            }
-        }
-        updatePlaybackState(null);
-    }
-
-    /**
-     * Makes sure the media player exists and has been reset. This will create
-     * the media player if needed, or reset the existing media player if one
-     * already exists.
-     */
-    private void createMediaPlayerIfNeeded() {
-        LogHelper.d(TAG, "createMediaPlayerIfNeeded. needed? " + (mMediaPlayer==null));
-        if (mMediaPlayer == null) {
-            mMediaPlayer = new MediaPlayer();
-
-            // Make sure the media player will acquire a wake-lock while
-            // playing. If we don't do that, the CPU might go to sleep while the
-            // song is playing, causing playback to stop.
-            mMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
+     /**
+      * Handle a request to pause music
+      */
+     private void handlePauseRequest() {
+         LogHelper.d(TAG, "handlePauseRequest: mState=" + mPlayback.getState());
+         mPlayback.pause();
+         // reset the delayed stop handler.
+         mDelayedStopHandler.removeCallbacksAndMessages(null);
+         mDelayedStopHandler.sendEmptyMessageDelayed(0, STOP_DELAY);
+     }
 
-            // we want the media player to notify us when it's ready preparing,
-            // and when it's done playing:
-            mMediaPlayer.setOnPreparedListener(this);
-            mMediaPlayer.setOnCompletionListener(this);
-            mMediaPlayer.setOnErrorListener(this);
-        } else {
-            mMediaPlayer.reset();
-        }
-    }
+     /**
+      * Handle a request to stop music
+      */
+     private void handleStopRequest(String withError) {
+         LogHelper.d(TAG, "handleStopRequest: mState=" + mPlayback.getState() + " error=", withError);
+         mPlayback.stop(true);
+         // reset the delayed stop handler.
+         mDelayedStopHandler.removeCallbacksAndMessages(null);
+         mDelayedStopHandler.sendEmptyMessageDelayed(0, STOP_DELAY);
 
-    /**
-     * Starts playing the current song in the playing queue.
-     */
-    void playCurrentSong() {
-        MediaMetadata track = getCurrentPlayingMusic();
-        if (track == null) {
-            LogHelper.e(TAG, "playSong:  ignoring request to play next song, because cannot" +
-                    " find it." +
-                    " currentIndex=" + mCurrentIndexOnQueue +
-                    " playQueue.size=" + (mPlayingQueue==null?"null": mPlayingQueue.size()));
-            return;
-        }
-        String source = track.getString(MusicProvider.CUSTOM_METADATA_TRACK_SOURCE);
-        LogHelper.d(TAG, "playSong:  current (" + mCurrentIndexOnQueue + ") in playingQueue. " +
-                " musicId=" + track.getString(MediaMetadata.METADATA_KEY_MEDIA_ID) +
-                " source=" + source);
+         updatePlaybackState(withError);
 
-        mState = PlaybackState.STATE_STOPPED;
-        relaxResources(false); // release everything except MediaPlayer
+         // service is no longer necessary. Will be started again if needed.
+         stopSelf();
+         mServiceStarted = false;
+     }
 
-        try {
-            createMediaPlayerIfNeeded();
+     private void updateMetadata() {
+         if (!QueueHelper.isIndexPlayable(mCurrentIndexOnQueue, mPlayingQueue)) {
+             LogHelper.e(TAG, "Can't retrieve current metadata.");
+             updatePlaybackState(getResources().getString(R.string.error_no_metadata));
+             return;
+         }
+         MediaSession.QueueItem queueItem = mPlayingQueue.get(mCurrentIndexOnQueue);
+         String musicId = MediaIDHelper.extractMusicIDFromMediaID(
+                 queueItem.getDescription().getMediaId());
+         MediaMetadata track = mMusicProvider.getMusic(musicId);
+         final String trackId = track.getString(MediaMetadata.METADATA_KEY_MEDIA_ID);
+         if (!musicId.equals(trackId)) {
+             IllegalStateException e = new IllegalStateException("track ID should match musicId.");
+             LogHelper.e(TAG, "track ID should match musicId.",
+                 " musicId=", musicId, " trackId=", trackId,
+                 " mediaId from queueItem=", queueItem.getDescription().getMediaId(),
+                 " title from queueItem=", queueItem.getDescription().getTitle(),
+                 " mediaId from track=", track.getDescription().getMediaId(),
+                 " title from track=", track.getDescription().getTitle(),
+                 " source.hashcode from track=", track.getString(
+                     MusicProvider.CUSTOM_METADATA_TRACK_SOURCE).hashCode(),
+                 e);
+             throw e;
+         }
+         LogHelper.d(TAG, "Updating metadata for MusicID= " + musicId);
+         mSession.setMetadata(track);
 
-            mState = PlaybackState.STATE_BUFFERING;
+         // Set the proper album artwork on the media session, so it can be shown in the
+         // locked screen and in other places.
+         if (track.getDescription().getIconBitmap() == null &&
+                 track.getDescription().getIconUri() != null) {
+             String albumUri = track.getDescription().getIconUri().toString();
+             AlbumArtCache.getInstance().fetch(albumUri, new AlbumArtCache.FetchListener() {
+                 @Override
+                 public void onFetched(String artUrl, Bitmap bitmap, Bitmap icon) {
+                     MediaSession.QueueItem queueItem = mPlayingQueue.get(mCurrentIndexOnQueue);
+                     MediaMetadata track = mMusicProvider.getMusic(trackId);
+                     track = new MediaMetadata.Builder(track)
 
-            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
-            mMediaPlayer.setDataSource(source);
+                         // set high resolution bitmap in METADATA_KEY_ALBUM_ART. This is used, for
+                         // example, on the lockscreen background when the media session is active.
+                         .putBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART, bitmap)
 
-            // Starts preparing the media player in the background. When
-            // it's done, it will call our OnPreparedListener (that is,
-            // the onPrepared() method on this class, since we set the
-            // listener to 'this'). Until the media player is prepared,
-            // we *cannot* call start() on it!
-            mMediaPlayer.prepareAsync();
+                         // set small version of the album art in the DISPLAY_ICON. This is used on
+                         // the MediaDescription and thus it should be small to be serialized if
+                         // necessary..
+                         .putBitmap(MediaMetadata.METADATA_KEY_DISPLAY_ICON, icon)
 
-            // If we are streaming from the internet, we want to hold a
-            // Wifi lock, which prevents the Wifi radio from going to
-            // sleep while the song is playing.
-            mWifiLock.acquire();
+                         .build();
 
-            updatePlaybackState(null);
-            updateMetadata();
+                     mMusicProvider.updateMusic(trackId, track);
 
-        } catch (IOException ex) {
-            LogHelper.e(TAG, ex, "IOException playing song");
-            updatePlaybackState(ex.getMessage());
-        }
-    }
+                     // If we are still playing the same music
+                     String currentPlayingId = MediaIDHelper.extractMusicIDFromMediaID(
+                         queueItem.getDescription().getMediaId());
+                     if (trackId.equals(currentPlayingId)) {
+                         mSession.setMetadata(track);
+                     }
+                 }
+             });
+         }
+     }
 
+     /**
+      * Update the current media player state, optionally showing an error message.
+      *
+      * @param error if not null, error message to present to the user.
+      */
+     private void updatePlaybackState(String error) {
+         LogHelper.d(TAG, "updatePlaybackState, playback state=" + mPlayback.getState());
+         long position = PlaybackState.PLAYBACK_POSITION_UNKNOWN;
+         if (mPlayback != null && mPlayback.isConnected()) {
+             position = mPlayback.getCurrentStreamPosition();
+         }
 
+         PlaybackState.Builder stateBuilder = new PlaybackState.Builder()
+                 .setActions(getAvailableActions());
 
-    private void updateMetadata() {
-        if (!QueueHelper.isIndexPlayable(mCurrentIndexOnQueue, mPlayingQueue)) {
-            LogHelper.e(TAG, "Can't retrieve current metadata.");
-            mState = PlaybackState.STATE_ERROR;
-            updatePlaybackState(getResources().getString(R.string.error_no_metadata));
-            return;
-        }
-        MediaSession.QueueItem queueItem = mPlayingQueue.get(mCurrentIndexOnQueue);
-        String mediaId = queueItem.getDescription().getMediaId();
-        MediaMetadata track = mMusicProvider.getMusic(mediaId);
-        String trackId = track.getString(MediaMetadata.METADATA_KEY_MEDIA_ID);
-        if (!mediaId.equals(trackId)) {
-            throw new IllegalStateException("track ID (" + trackId + ") " +
-                    "should match mediaId (" + mediaId + ")");
-        }
-        LogHelper.d(TAG, "Updating metadata for MusicID= " + mediaId);
-        mSession.setMetadata(track);
-    }
+         setCustomAction(stateBuilder);
+         int state = mPlayback.getState();
 
+         // If there is an error message, send it to the playback state:
+         if (error != null) {
+             // Error states are really only supposed to be used for errors that cause playback to
+             // stop unexpectedly and persist until the user takes action to fix it.
+             stateBuilder.setErrorMessage(error);
+             state = PlaybackState.STATE_ERROR;
+         }
+         stateBuilder.setState(state, position, 1.0f, SystemClock.elapsedRealtime());
 
-    /**
-     * Update the current media player state, optionally showing an error message.
-     *
-     * @param error if not null, error message to present to the user.
-     *
-     */
-    private void updatePlaybackState(String error) {
+         // Set the activeQueueItemId if the current index is valid.
+         if (QueueHelper.isIndexPlayable(mCurrentIndexOnQueue, mPlayingQueue)) {
+             MediaSession.QueueItem item = mPlayingQueue.get(mCurrentIndexOnQueue);
+             stateBuilder.setActiveQueueItemId(item.getQueueId());
+         }
 
-        LogHelper.d(TAG, "updatePlaybackState, setting session playback state to " + mState);
-        long position = PlaybackState.PLAYBACK_POSITION_UNKNOWN;
-        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
-            position = mMediaPlayer.getCurrentPosition();
-        }
-        PlaybackState.Builder stateBuilder = new PlaybackState.Builder()
-                .setActions(getAvailableActions());
+         mSession.setPlaybackState(stateBuilder.build());
 
-        setCustomAction(stateBuilder);
+         if (state == PlaybackState.STATE_PLAYING || state == PlaybackState.STATE_PAUSED) {
+             mMediaNotificationManager.startNotification();
+         }
+     }
 
-        // If there is an error message, send it to the playback state:
-        if (error != null) {
-            // Error states are really only supposed to be used for errors that cause playback to
-            // stop unexpectedly and persist until the user takes action to fix it.
-            stateBuilder.setErrorMessage(error);
-            mState = PlaybackState.STATE_ERROR;
-        }
-        stateBuilder.setState(mState, position, 1.0f, SystemClock.elapsedRealtime());
+     private void setCustomAction(PlaybackState.Builder stateBuilder) {
+         MediaMetadata currentMusic = getCurrentPlayingMusic();
+         if (currentMusic != null) {
+             // Set appropriate "Favorite" icon on Custom action:
+             String musicId = currentMusic.getString(MediaMetadata.METADATA_KEY_MEDIA_ID);
+             int favoriteIcon = R.drawable.ic_star_off;
+             if (mMusicProvider.isFavorite(musicId)) {
+                 favoriteIcon = R.drawable.ic_star_on;
+             }
+             LogHelper.d(TAG, "updatePlaybackState, setting Favorite custom action of music ",
+                     musicId, " current favorite=", mMusicProvider.isFavorite(musicId));
+             stateBuilder.addCustomAction(CUSTOM_ACTION_THUMBS_UP, getString(R.string.favorite),
+                 favoriteIcon);
+         }
+     }
 
-        // Set the activeQueueItemId if the current index is valid.
-        if (QueueHelper.isIndexPlayable(mCurrentIndexOnQueue, mPlayingQueue)) {
-            MediaSession.QueueItem item = mPlayingQueue.get(mCurrentIndexOnQueue);
-            stateBuilder.setActiveQueueItemId(item.getQueueId());
-        }
+     private long getAvailableActions() {
+         long actions = PlaybackState.ACTION_PLAY | PlaybackState.ACTION_PLAY_FROM_MEDIA_ID |
+                 PlaybackState.ACTION_PLAY_FROM_SEARCH;
+         if (mPlayingQueue == null || mPlayingQueue.isEmpty()) {
+             return actions;
+         }
+         if (mPlayback.isPlaying()) {
+             actions |= PlaybackState.ACTION_PAUSE;
+         }
+         if (mCurrentIndexOnQueue > 0) {
+             actions |= PlaybackState.ACTION_SKIP_TO_PREVIOUS;
+         }
+         if (mCurrentIndexOnQueue < mPlayingQueue.size() - 1) {
+             actions |= PlaybackState.ACTION_SKIP_TO_NEXT;
+         }
+         return actions;
+     }
 
-        mSession.setPlaybackState(stateBuilder.build());
+     private MediaMetadata getCurrentPlayingMusic() {
+         if (QueueHelper.isIndexPlayable(mCurrentIndexOnQueue, mPlayingQueue)) {
+             MediaSession.QueueItem item = mPlayingQueue.get(mCurrentIndexOnQueue);
+             if (item != null) {
+                 LogHelper.d(TAG, "getCurrentPlayingMusic for musicId=",
+                         item.getDescription().getMediaId());
+                 return mMusicProvider.getMusic(
+                         MediaIDHelper.extractMusicIDFromMediaID(item.getDescription().getMediaId()));
+             }
+         }
+         return null;
+     }
 
-        if (mState == PlaybackState.STATE_PLAYING || mState == PlaybackState.STATE_PAUSED) {
-            mMediaNotification.startNotification();
-        }
-    }
+     /**
+      * Implementation of the Playback.Callback interface
+      */
+     @Override
+     public void onCompletion() {
+         // The media player finished playing the current song, so we go ahead
+         // and start the next.
+         if (mPlayingQueue != null && !mPlayingQueue.isEmpty()) {
+             // In this sample, we restart the playing queue when it gets to the end:
+             mCurrentIndexOnQueue++;
+             if (mCurrentIndexOnQueue >= mPlayingQueue.size()) {
+                 mCurrentIndexOnQueue = 0;
+             }
+             handlePlayRequest();
+         } else {
+             // If there is nothing to play, we stop and release the resources:
+             handleStopRequest(null);
+         }
+     }
 
-    private void setCustomAction(PlaybackState.Builder stateBuilder) {
-        MediaMetadata currentMusic = getCurrentPlayingMusic();
-        if (currentMusic != null) {
-            // Set appropriate "Favorite" icon on Custom action:
-            String mediaId = currentMusic.getString(MediaMetadata.METADATA_KEY_MEDIA_ID);
-            int favoriteIcon = R.drawable.ic_star_off;
-            if (mMusicProvider.isFavorite(mediaId)) {
-                favoriteIcon = R.drawable.ic_star_on;
-            }
-            LogHelper.d(TAG, "updatePlaybackState, setting Favorite custom action of music ",
-                    mediaId, " current favorite=", mMusicProvider.isFavorite(mediaId));
-            stateBuilder.addCustomAction(CUSTOM_ACTION_THUMBS_UP, getString(R.string.favorite),
-                    favoriteIcon);
-        }
-    }
+     @Override
+     public void onPlaybackStatusChanged(int state) {
+         updatePlaybackState(null);
+     }
 
-    private long getAvailableActions() {
-        long actions = PlaybackState.ACTION_PLAY | PlaybackState.ACTION_PLAY_FROM_MEDIA_ID |
-                PlaybackState.ACTION_PLAY_FROM_SEARCH;
-        if (mPlayingQueue == null || mPlayingQueue.isEmpty()) {
-            return actions;
-        }
-        if (mState == PlaybackState.STATE_PLAYING) {
-            actions |= PlaybackState.ACTION_PAUSE;
-        }
-        if (mCurrentIndexOnQueue > 0) {
-            actions |= PlaybackState.ACTION_SKIP_TO_PREVIOUS;
-        }
-        if (mCurrentIndexOnQueue < mPlayingQueue.size() - 1) {
-            actions |= PlaybackState.ACTION_SKIP_TO_NEXT;
-        }
-        return actions;
-    }
+     @Override
+     public void onError(String error) {
+         updatePlaybackState(error);
+     }
 
-    private MediaMetadata getCurrentPlayingMusic() {
-        if (QueueHelper.isIndexPlayable(mCurrentIndexOnQueue, mPlayingQueue)) {
-            MediaSession.QueueItem item = mPlayingQueue.get(mCurrentIndexOnQueue);
-            if (item != null) {
-                LogHelper.d(TAG, "getCurrentPlayingMusic for musicId=",
-                        item.getDescription().getMediaId());
-                return mMusicProvider.getMusic(item.getDescription().getMediaId());
-            }
-        }
-        return null;
-    }
+     /**
+      * A simple handler that stops the service if playback is not active (playing)
+      */
+     private static class DelayedStopHandler extends Handler {
+         private final WeakReference<MusicService> mWeakReference;
 
-    /**
-     * Try to get the system audio focus.
-     */
-    void tryToGetAudioFocus() {
-        LogHelper.d(TAG, "tryToGetAudioFocus");
-        if (mAudioFocus != AudioFocus.Focused) {
-            int result = mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
-                    AudioManager.AUDIOFOCUS_GAIN);
-            if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
-                mAudioFocus = AudioFocus.Focused;
-            }
-        }
-    }
+         private DelayedStopHandler(MusicService service) {
+             mWeakReference = new WeakReference<>(service);
+         }
 
-    /**
-     * Give up the audio focus.
-     */
-    void giveUpAudioFocus() {
-        LogHelper.d(TAG, "giveUpAudioFocus");
-        if (mAudioFocus == AudioFocus.Focused) {
-            if (mAudioManager.abandonAudioFocus(this) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
-                mAudioFocus = AudioFocus.NoFocusNoDuck;
-            }
-        }
-    }
-}
+         @Override
+         public void handleMessage(Message msg) {
+             MusicService service = mWeakReference.get();
+             if (service != null && service.mPlayback != null) {
+                 if (service.mPlayback.isPlaying()) {
+                     LogHelper.d(TAG, "Ignoring delayed stop since the media player is in use.");
+                     return;
+                 }
+                 LogHelper.d(TAG, "Stopping service with delay handler.");
+                 service.stopSelf();
+                 service.mServiceStarted = false;
+             }
+         }
+     }
+ }
diff --git a/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/PackageValidator.java b/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/PackageValidator.java
index 090b6a4..c2bce54 100644
--- a/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/PackageValidator.java
+++ b/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/PackageValidator.java
@@ -15,202 +15,145 @@
  */
 package com.example.android.mediabrowserservice;
 
-import java.io.UnsupportedEncodingException;
-import java.util.Arrays;
-
 import android.content.Context;
 import android.content.pm.PackageInfo;
 import android.content.pm.PackageManager;
-import android.os.Build;
+import android.content.res.XmlResourceParser;
 import android.os.Process;
 import android.util.Base64;
-import android.util.Log;
+
+import com.example.android.mediabrowserservice.utils.LogHelper;
+
+import org.xmlpull.v1.XmlPullParserException;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
 
 /**
- * Validates that the calling package is authorized to use this
+ * Validates that the calling package is authorized to browse a
  * {@link android.service.media.MediaBrowserService}.
+ *
+ * The list of allowed signing certificates and their corresponding package names is defined in
+ * res/xml/allowed_media_browser_callers.xml.
  */
 public class PackageValidator {
-    public static final String TAG = "PackageValidator";
-
-    // Replace with your package whitelist
-    static final byte[][] VALID_PUBLIC_SIGNATURES = new byte[][]{
-        // Android Auto release public key
-        extractKey(
-        "\060\202\003\275\060\202\002\245\240\003\002\001\002\002\011\000\307\217\236\113" +
-        "\223\101\060\006\060\015\006\011\052\206\110\206\367\015\001\001\005\005\000\060" +
-        "\165\061\013\060\011\006\003\125\004\006\023\002\125\123\061\023\060\021\006\003" +
-        "\125\004\010\014\012\103\141\154\151\146\157\162\156\151\141\061\026\060\024\006" +
-        "\003\125\004\007\014\015\115\157\165\156\164\141\151\156\040\126\151\145\167\061" +
-        "\024\060\022\006\003\125\004\012\014\013\107\157\157\147\154\145\040\111\156\143" +
-        "\056\061\020\060\016\006\003\125\004\013\014\007\101\156\144\162\157\151\144\061" +
-        "\021\060\017\006\003\125\004\003\014\010\147\145\141\162\150\145\141\144\060\036" +
-        "\027\015\061\064\060\065\062\067\062\063\060\065\063\064\132\027\015\064\061\061" +
-        "\060\061\062\062\063\060\065\063\064\132\060\165\061\013\060\011\006\003\125\004" +
-        "\006\023\002\125\123\061\023\060\021\006\003\125\004\010\014\012\103\141\154\151" +
-        "\146\157\162\156\151\141\061\026\060\024\006\003\125\004\007\014\015\115\157\165" +
-        "\156\164\141\151\156\040\126\151\145\167\061\024\060\022\006\003\125\004\012\014" +
-        "\013\107\157\157\147\154\145\040\111\156\143\056\061\020\060\016\006\003\125\004" +
-        "\013\014\007\101\156\144\162\157\151\144\061\021\060\017\006\003\125\004\003\014" +
-        "\010\147\145\141\162\150\145\141\144\060\202\001\042\060\015\006\011\052\206\110" +
-        "\206\367\015\001\001\001\005\000\003\202\001\017\000\060\202\001\012\002\202\001" +
-        "\001\000\323\235\027\016\103\110\261\124\114\137\154\023\275\132\145\244\053\270" +
-        "\072\331\362\064\255\257\344\036\317\113\340\340\202\141\366\312\346\142\302\224" +
-        "\356\255\322\203\103\324\175\123\074\107\365\116\045\260\057\246\043\025\344\210" +
-        "\026\012\041\143\125\200\313\142\116\014\144\023\056\334\201\153\335\140\170\015" +
-        "\142\221\156\360\214\131\051\200\362\135\353\076\323\152\137\276\233\272\334\302" +
-        "\001\017\363\347\275\121\142\246\215\150\122\266\337\172\330\376\232\272\004\246" +
-        "\071\300\357\130\024\113\103\244\370\176\227\131\153\046\157\314\105\035\005\114" +
-        "\241\225\204\043\073\024\047\151\341\233\301\034\234\371\000\075\363\131\000\157" +
-        "\276\134\263\321\072\204\120\011\253\060\311\213\035\343\142\156\140\003\367\013" +
-        "\006\156\204\067\024\154\305\246\223\272\301\213\320\125\103\310\046\222\266\360" +
-        "\252\217\170\003\272\222\264\265\051\334\334\202\232\122\222\130\166\231\323\224" +
-        "\254\244\103\360\261\367\055\221\255\050\134\156\133\206\004\372\353\261\014\013" +
-        "\064\076\142\301\115\326\202\121\057\264\052\372\143\020\214\122\154\337\002\003" +
-        "\001\000\001\243\120\060\116\060\035\006\003\125\035\016\004\026\004\024\032\360" +
-        "\137\140\327\256\350\224\211\122\162\131\012\046\201\032\311\327\316\333\060\037" +
-        "\006\003\125\035\043\004\030\060\026\200\024\032\360\137\140\327\256\350\224\211" +
-        "\122\162\131\012\046\201\032\311\327\316\333\060\014\006\003\125\035\023\004\005" +
-        "\060\003\001\001\377\060\015\006\011\052\206\110\206\367\015\001\001\005\005\000" +
-        "\003\202\001\001\000\224\153\003\143\101\017\273\163\101\110\176\144\352\054\077" +
-        "\300\230\175\173\174\114\301\055\173\022\262\206\226\034\226\242\014\111\063\062" +
-        "\343\000\336\240\321\240\217\037\020\170\320\204\002\373\312\200\227\344\113\355" +
-        "\124\061\352\214\155\265\375\046\337\134\224\031\003\334\065\206\355\330\054\101" +
-        "\114\040\053\363\316\150\054\256\155\331\060\042\346\324\063\205\336\231\021\210" +
-        "\241\131\045\026\121\337\327\360\024\021\242\354\133\242\313\075\101\260\100\376" +
-        "\042\061\320\352\103\153\030\200\162\256\302\157\256\323\205\345\331\017\021\256" +
-        "\103\307\346\035\206\313\307\316\051\022\371\267\015\003\201\374\262\014\222\112" +
-        "\120\111\361\002\325\377\250\077\134\301\336\352\317\123\367\122\274\100\377\054" +
-        "\050\016\166\272\161\147\227\142\355\054\022\312\347\276\126\257\323\145\014\267" +
-        "\342\323\362\200\114\303\331\337\041\026\130\177\311\370\126\220\310\263\071\342" +
-        "\027\161\254\225\001\007\115\237\234\351\006\113\232\313\133\044\030\350\320\103" +
-        "\231\023\154\067\003\316\050\016\331\035\253\252\176\207\011\337\145\345\235\026" +
-        "\041"),
-
-        // Android Auto debug public key
-        extractKey(
-        "\060\202\003\275\060\202\002\245\240\003\002\001\002\002\011\000\347\344\006\360" +
-        "\327\303\226\363\060\015\006\011\052\206\110\206\367\015\001\001\005\005\000\060" +
-        "\165\061\013\060\011\006\003\125\004\006\023\002\125\123\061\023\060\021\006\003" +
-        "\125\004\010\014\012\103\141\154\151\146\157\162\156\151\141\061\026\060\024\006" +
-        "\003\125\004\007\014\015\115\157\165\156\164\141\151\156\040\126\151\145\167\061" +
-        "\024\060\022\006\003\125\004\012\014\013\107\157\157\147\154\145\040\111\156\143" +
-        "\056\061\020\060\016\006\003\125\004\013\014\007\101\156\144\162\157\151\144\061" +
-        "\021\060\017\006\003\125\004\003\014\010\147\145\141\162\150\145\141\144\060\036" +
-        "\027\015\061\064\060\065\062\067\062\063\060\062\065\061\132\027\015\064\061\061" +
-        "\060\061\062\062\063\060\062\065\061\132\060\165\061\013\060\011\006\003\125\004" +
-        "\006\023\002\125\123\061\023\060\021\006\003\125\004\010\014\012\103\141\154\151" +
-        "\146\157\162\156\151\141\061\026\060\024\006\003\125\004\007\014\015\115\157\165" +
-        "\156\164\141\151\156\040\126\151\145\167\061\024\060\022\006\003\125\004\012\014" +
-        "\013\107\157\157\147\154\145\040\111\156\143\056\061\020\060\016\006\003\125\004" +
-        "\013\014\007\101\156\144\162\157\151\144\061\021\060\017\006\003\125\004\003\014" +
-        "\010\147\145\141\162\150\145\141\144\060\202\001\042\060\015\006\011\052\206\110" +
-        "\206\367\015\001\001\001\005\000\003\202\001\017\000\060\202\001\012\002\202\001" +
-        "\001\000\242\356\360\300\022\205\313\071\352\245\032\336\264\235\304\126\236\171" +
-        "\375\212\364\343\320\040\347\011\106\276\260\247\214\203\374\016\263\053\123\353" +
-        "\044\174\247\265\016\154\051\260\263\155\236\030\142\064\177\211\323\115\013\242" +
-        "\115\341\163\310\335\130\247\212\072\212\163\050\140\315\274\277\307\276\164\273" +
-        "\321\234\244\333\250\043\366\073\114\060\174\375\331\246\135\246\154\003\353\261" +
-        "\115\231\071\106\330\121\021\257\344\360\060\076\132\201\243\347\260\124\166\316" +
-        "\126\272\272\005\057\034\154\363\353\226\003\306\220\231\261\017\323\243\014\203" +
-        "\056\174\140\061\250\057\206\364\276\071\354\167\312\035\205\067\272\111\177\004" +
-        "\264\334\247\106\166\105\217\154\272\237\364\127\246\323\333\071\216\067\231\133" +
-        "\363\267\106\011\312\241\023\310\047\204\013\053\275\036\176\060\031\250\234\201" +
-        "\031\300\331\311\003\060\072\317\274\034\211\047\255\247\374\371\304\131\044\074" +
-        "\352\073\036\353\266\331\174\063\162\206\007\141\005\226\064\351\353\361\162\304" +
-        "\222\347\002\216\220\225\171\373\032\266\032\225\062\064\310\265\075\165\002\003" +
-        "\001\000\001\243\120\060\116\060\035\006\003\125\035\016\004\026\004\024\365\003" +
-        "\311\347\022\104\014\017\014\015\003\053\217\110\146\333\360\066\005\031\060\037" +
-        "\006\003\125\035\043\004\030\060\026\200\024\365\003\311\347\022\104\014\017\014" +
-        "\015\003\053\217\110\146\333\360\066\005\031\060\014\006\003\125\035\023\004\005" +
-        "\060\003\001\001\377\060\015\006\011\052\206\110\206\367\015\001\001\005\005\000" +
-        "\003\202\001\001\000\015\312\371\207\121\121\360\212\146\067\210\122\261\100\075" +
-        "\112\160\220\127\045\332\324\144\041\316\224\040\105\261\176\236\231\040\072\175" +
-        "\214\171\272\174\155\335\274\126\227\340\242\200\366\070\023\120\134\045\034\146" +
-        "\111\373\245\150\376\372\353\175\036\023\233\035\126\225\344\123\140\322\227\103" +
-        "\250\271\332\365\006\175\143\212\022\371\232\342\214\256\364\135\237\304\216\126" +
-        "\024\036\370\156\322\222\043\144\006\303\360\051\202\026\132\060\111\036\171\250" +
-        "\044\243\063\230\222\337\262\331\007\175\222\062\275\101\006\046\053\064\013\347" +
-        "\160\250\330\101\122\274\162\324\321\316\032\115\101\003\301\201\160\100\367\305" +
-        "\345\371\335\103\077\055\064\045\144\056\027\113\054\232\022\234\046\353\337\164" +
-        "\111\305\027\261\357\153\034\377\200\044\075\237\066\253\100\215\302\044\037\035" +
-        "\071\165\160\027\311\234\310\064\101\317\202\121\371\200\351\136\216\201\017\347" +
-        "\306\267\136\150\277\354\346\250\057\061\151\077\117\327\362\140\240\065\342\062" +
-        "\034\277\352\274\040\166\057\126\304\367\374\231\276\323\234\020\276\012\113\027" +
-        "\320"),
-    };
+    private static final String TAG = LogHelper.makeLogTag(PackageValidator.class);
 
     /**
-     * Disallow instantiation of this helper class.
+     * Map allowed callers' certificate keys to the expected caller information.
+     *
      */
-    private PackageValidator() {}
+    private final Map<String, ArrayList<CallerInfo>> mValidCertificates;
 
-    /**
-     * Throws when the caller is not authorized to get data from this MediaBrowserService
-     */
-    public static void checkCallerAllowed(Context context, String callingPackage, int callingUid) {
-        if (!isCallerAllowed(context, callingPackage, callingUid)) {
-            throw new SecurityException("signature check failed.");
+    public PackageValidator(Context ctx) {
+        mValidCertificates = readValidCertificates(ctx.getResources().getXml(
+            R.xml.allowed_media_browser_callers));
+    }
+
+    private Map<String, ArrayList<CallerInfo>> readValidCertificates(XmlResourceParser parser) {
+        HashMap<String, ArrayList<CallerInfo>> validCertificates = new HashMap<>();
+        try {
+            int eventType = parser.next();
+            while (eventType != XmlResourceParser.END_DOCUMENT) {
+                if (eventType == XmlResourceParser.START_TAG
+                        && parser.getName().equals("signing_certificate")) {
+
+                    String name = parser.getAttributeValue(null, "name");
+                    String packageName = parser.getAttributeValue(null, "package");
+                    boolean isRelease = parser.getAttributeBooleanValue(null, "release", false);
+                    String certificate = parser.nextText().replaceAll("\\s|\\n", "");
+
+                    CallerInfo info = new CallerInfo(name, packageName, isRelease, certificate);
+
+                    ArrayList<CallerInfo> infos = validCertificates.get(certificate);
+                    if (infos == null) {
+                        infos = new ArrayList<>();
+                        validCertificates.put(certificate, infos);
+                    }
+                    LogHelper.v(TAG, "Adding allowed caller: ", info.name,
+                        " package=", info.packageName, " release=", info.release,
+                        " certificate=", certificate);
+                    infos.add(info);
+                }
+                eventType = parser.next();
+            }
+        } catch (XmlPullParserException | IOException e) {
+            LogHelper.e(TAG, e, "Could not read allowed callers from XML.");
         }
+        return validCertificates;
     }
 
     /**
      * @return false if the caller is not authorized to get data from this MediaBrowserService
      */
-    public static boolean isCallerAllowed(Context context, String callingPackage, int callingUid) {
-        // Always allow calls from the framework or development environment.
+    @SuppressWarnings("BooleanMethodIsAlwaysInverted")
+    public boolean isCallerAllowed(Context context, String callingPackage, int callingUid) {
+        // Always allow calls from the framework, self app or development environment.
         if (Process.SYSTEM_UID == callingUid || Process.myUid() == callingUid) {
             return true;
         }
-        if (BuildConfig.DEBUG) {
-            // When your app is built in debug mode, any app is allowed to connect to it and browse
-            // its media library. If you want to test the behavior of your app when it gets
-            // released, either build a release version or remove this clause.
-            Log.i(TAG, "Allowing caller '"+callingPackage+" because app was built in debug mode.");
-            return true;
-        }
+        PackageManager packageManager = context.getPackageManager();
         PackageInfo packageInfo;
-        final PackageManager packageManager = context.getPackageManager();
         try {
             packageInfo = packageManager.getPackageInfo(
                     callingPackage, PackageManager.GET_SIGNATURES);
-        } catch (PackageManager.NameNotFoundException ignored) {
-            if (Log.isLoggable(TAG, Log.DEBUG)) {
-                Log.d(TAG, "Package manager can't find package " + callingPackage
-                        + ", defaulting to false");
+        } catch (PackageManager.NameNotFoundException e) {
+            LogHelper.w(TAG, e, "Package manager can't find package: ", callingPackage);
+            return false;
+        }
+        if (packageInfo.signatures.length != 1) {
+            LogHelper.w(TAG, "Caller has more than one signature certificate!");
+            return false;
+        }
+        String signature = Base64.encodeToString(
+            packageInfo.signatures[0].toByteArray(), Base64.NO_WRAP);
+
+        // Test for known signatures:
+        ArrayList<CallerInfo> validCallers = mValidCertificates.get(signature);
+        if (validCallers == null) {
+            LogHelper.v(TAG, "Signature for caller ", callingPackage, " is not valid: \n"
+                , signature);
+            if (mValidCertificates.isEmpty()) {
+                LogHelper.w(TAG, "The list of valid certificates is empty. Either your file ",
+                        "res/xml/allowed_media_browser_callers.xml is empty or there was an error ",
+                        "while reading it. Check previous log messages.");
             }
             return false;
         }
-        if (packageInfo == null) {
-            Log.w(TAG, "Package manager can't find package: " + callingPackage);
-            return false;
-        }
 
-        if (packageInfo.signatures.length != 1) {
-            Log.w(TAG, "Package has more than one signature.");
-            return false;
-        }
-        final byte[] signature = packageInfo.signatures[0].toByteArray();
-
-        for (int i = 0; i < VALID_PUBLIC_SIGNATURES.length; i++) {
-            byte[] validSignature = VALID_PUBLIC_SIGNATURES[i];
-            if (Arrays.equals(validSignature, signature)) {
+        // Check if the package name is valid for the certificate:
+        StringBuffer expectedPackages = new StringBuffer();
+        for (CallerInfo info: validCallers) {
+            if (callingPackage.equals(info.packageName)) {
+                LogHelper.v(TAG, "Valid caller: ", info.name, "  package=", info.packageName,
+                    " release=", info.release);
                 return true;
             }
+            expectedPackages.append(info.packageName).append(' ');
         }
 
-        if (Log.isLoggable(TAG, Log.VERBOSE)) {
-            Log.v(TAG, "Signature not valid.  Found: \n" +
-                    Base64.encodeToString(signature, 0));
-        }
+        LogHelper.i(TAG, "Caller has a valid certificate, but its package doesn't match any ",
+            "expected package for the given certificate. Caller's package is ", callingPackage,
+            ". Expected packages as defined in res/xml/allowed_media_browser_callers.xml are (",
+            expectedPackages, "). This caller's certificate is: \n", signature);
+
         return false;
     }
 
-    private static byte[] extractKey(String keyString) {
-        try {
-            return keyString.getBytes("ISO-8859-1");
-        } catch (UnsupportedEncodingException e) {
-            throw new AssertionError(e);
+    private final static class CallerInfo {
+        final String name;
+        final String packageName;
+        final boolean release;
+        final String signingCertificate;
+
+        public CallerInfo(String name, String packageName, boolean release,
+                          String signingCertificate) {
+            this.name = name;
+            this.packageName = packageName;
+            this.release = release;
+            this.signingCertificate = signingCertificate;
         }
     }
 }
diff --git a/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/Playback.java b/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/Playback.java
new file mode 100644
index 0000000..fb3ff28
--- /dev/null
+++ b/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/Playback.java
@@ -0,0 +1,489 @@
+/*
+ * Copyright (C) 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.example.android.mediabrowserservice;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.media.AudioManager;
+import android.media.MediaMetadata;
+import android.media.MediaPlayer;
+import android.media.session.PlaybackState;
+import android.net.wifi.WifiManager;
+import android.os.PowerManager;
+import android.text.TextUtils;
+
+import com.example.android.mediabrowserservice.model.MusicProvider;
+import com.example.android.mediabrowserservice.utils.LogHelper;
+import com.example.android.mediabrowserservice.utils.MediaIDHelper;
+
+import java.io.IOException;
+
+import static android.media.MediaPlayer.OnCompletionListener;
+import static android.media.MediaPlayer.OnErrorListener;
+import static android.media.MediaPlayer.OnPreparedListener;
+import static android.media.MediaPlayer.OnSeekCompleteListener;
+import static android.media.session.MediaSession.QueueItem;
+
+/**
+ * A class that implements local media playback using {@link android.media.MediaPlayer}
+ */
+public class Playback implements AudioManager.OnAudioFocusChangeListener,
+        OnCompletionListener, OnErrorListener, OnPreparedListener, OnSeekCompleteListener {
+
+    private static final String TAG = LogHelper.makeLogTag(Playback.class);
+
+    // The volume we set the media player to when we lose audio focus, but are
+    // allowed to reduce the volume instead of stopping playback.
+    public static final float VOLUME_DUCK = 0.2f;
+    // The volume we set the media player when we have audio focus.
+    public static final float VOLUME_NORMAL = 1.0f;
+
+    // we don't have audio focus, and can't duck (play at a low volume)
+    private static final int AUDIO_NO_FOCUS_NO_DUCK = 0;
+    // we don't have focus, but can duck (play at a low volume)
+    private static final int AUDIO_NO_FOCUS_CAN_DUCK = 1;
+    // we have full audio focus
+    private static final int AUDIO_FOCUSED  = 2;
+
+    private final MusicService mService;
+    private final WifiManager.WifiLock mWifiLock;
+    private int mState;
+    private boolean mPlayOnFocusGain;
+    private Callback mCallback;
+    private MusicProvider mMusicProvider;
+    private volatile boolean mAudioNoisyReceiverRegistered;
+    private volatile int mCurrentPosition;
+    private volatile String mCurrentMediaId;
+
+    // Type of audio focus we have:
+    private int mAudioFocus = AUDIO_NO_FOCUS_NO_DUCK;
+    private AudioManager mAudioManager;
+    private MediaPlayer mMediaPlayer;
+
+    private IntentFilter mAudioNoisyIntentFilter =
+            new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
+
+    private BroadcastReceiver mAudioNoisyReceiver = new BroadcastReceiver() {
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(intent.getAction())) {
+                LogHelper.d(TAG, "Headphones disconnected.");
+                if (isPlaying()) {
+                    Intent i = new Intent(context, MusicService.class);
+                    i.setAction(MusicService.ACTION_CMD);
+                    i.putExtra(MusicService.CMD_NAME, MusicService.CMD_PAUSE);
+                    mService.startService(i);
+                }
+            }
+        }
+    };
+
+    public Playback(MusicService service, MusicProvider musicProvider) {
+        this.mService = service;
+        this.mMusicProvider = musicProvider;
+        this.mAudioManager = (AudioManager) service.getSystemService(Context.AUDIO_SERVICE);
+        // Create the Wifi lock (this does not acquire the lock, this just creates it)
+        this.mWifiLock = ((WifiManager) service.getSystemService(Context.WIFI_SERVICE))
+                .createWifiLock(WifiManager.WIFI_MODE_FULL, "sample_lock");
+    }
+
+    public void start() {
+    }
+
+    public void stop(boolean notifyListeners) {
+        mState = PlaybackState.STATE_STOPPED;
+        if (notifyListeners && mCallback != null) {
+            mCallback.onPlaybackStatusChanged(mState);
+        }
+        mCurrentPosition = getCurrentStreamPosition();
+        // Give up Audio focus
+        giveUpAudioFocus();
+        unregisterAudioNoisyReceiver();
+        // Relax all resources
+        relaxResources(true);
+        if (mWifiLock.isHeld()) {
+            mWifiLock.release();
+        }
+    }
+
+    public void setState(int state) {
+        this.mState = state;
+    }
+
+    public int getState() {
+        return mState;
+    }
+
+    public boolean isConnected() {
+        return true;
+    }
+
+    public boolean isPlaying() {
+        return mPlayOnFocusGain || (mMediaPlayer != null && mMediaPlayer.isPlaying());
+    }
+
+    public int getCurrentStreamPosition() {
+        return mMediaPlayer != null ?
+                mMediaPlayer.getCurrentPosition() : mCurrentPosition;
+    }
+
+    public void play(QueueItem item) {
+        mPlayOnFocusGain = true;
+        tryToGetAudioFocus();
+        registerAudioNoisyReceiver();
+        String mediaId = item.getDescription().getMediaId();
+        boolean mediaHasChanged = !TextUtils.equals(mediaId, mCurrentMediaId);
+        if (mediaHasChanged) {
+            mCurrentPosition = 0;
+            mCurrentMediaId = mediaId;
+        }
+
+        if (mState == PlaybackState.STATE_PAUSED && !mediaHasChanged && mMediaPlayer != null) {
+            configMediaPlayerState();
+        } else {
+            mState = PlaybackState.STATE_STOPPED;
+            relaxResources(false); // release everything except MediaPlayer
+            MediaMetadata track = mMusicProvider.getMusic(
+                    MediaIDHelper.extractMusicIDFromMediaID(item.getDescription().getMediaId()));
+
+            String source = track.getString(MusicProvider.CUSTOM_METADATA_TRACK_SOURCE);
+
+            try {
+                createMediaPlayerIfNeeded();
+
+                mState = PlaybackState.STATE_BUFFERING;
+
+                mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
+                mMediaPlayer.setDataSource(source);
+
+                // Starts preparing the media player in the background. When
+                // it's done, it will call our OnPreparedListener (that is,
+                // the onPrepared() method on this class, since we set the
+                // listener to 'this'). Until the media player is prepared,
+                // we *cannot* call start() on it!
+                mMediaPlayer.prepareAsync();
+
+                // If we are streaming from the internet, we want to hold a
+                // Wifi lock, which prevents the Wifi radio from going to
+                // sleep while the song is playing.
+                mWifiLock.acquire();
+
+                if (mCallback != null) {
+                    mCallback.onPlaybackStatusChanged(mState);
+                }
+
+            } catch (IOException ex) {
+                LogHelper.e(TAG, ex, "Exception playing song");
+                if (mCallback != null) {
+                    mCallback.onError(ex.getMessage());
+                }
+            }
+        }
+    }
+
+    public void pause() {
+        if (mState == PlaybackState.STATE_PLAYING) {
+            // Pause media player and cancel the 'foreground service' state.
+            if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
+                mMediaPlayer.pause();
+                mCurrentPosition = mMediaPlayer.getCurrentPosition();
+            }
+            // while paused, retain the MediaPlayer but give up audio focus
+            relaxResources(false);
+            giveUpAudioFocus();
+        }
+        mState = PlaybackState.STATE_PAUSED;
+        if (mCallback != null) {
+            mCallback.onPlaybackStatusChanged(mState);
+        }
+        unregisterAudioNoisyReceiver();
+    }
+
+    public void seekTo(int position) {
+        LogHelper.d(TAG, "seekTo called with ", position);
+
+        if (mMediaPlayer == null) {
+            // If we do not have a current media player, simply update the current position
+            mCurrentPosition = position;
+        } else {
+            if (mMediaPlayer.isPlaying()) {
+                mState = PlaybackState.STATE_BUFFERING;
+            }
+            mMediaPlayer.seekTo(position);
+            if (mCallback != null) {
+                mCallback.onPlaybackStatusChanged(mState);
+            }
+        }
+    }
+
+    public void setCallback(Callback callback) {
+        this.mCallback = callback;
+    }
+
+    /**
+     * Try to get the system audio focus.
+     */
+    private void tryToGetAudioFocus() {
+        LogHelper.d(TAG, "tryToGetAudioFocus");
+        if (mAudioFocus != AUDIO_FOCUSED) {
+            int result = mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
+                    AudioManager.AUDIOFOCUS_GAIN);
+            if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
+                mAudioFocus = AUDIO_FOCUSED;
+            }
+        }
+    }
+
+    /**
+     * Give up the audio focus.
+     */
+    private void giveUpAudioFocus() {
+        LogHelper.d(TAG, "giveUpAudioFocus");
+        if (mAudioFocus == AUDIO_FOCUSED) {
+            if (mAudioManager.abandonAudioFocus(this) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
+                mAudioFocus = AUDIO_NO_FOCUS_NO_DUCK;
+            }
+        }
+    }
+
+    /**
+     * Reconfigures MediaPlayer according to audio focus settings and
+     * starts/restarts it. This method starts/restarts the MediaPlayer
+     * respecting the current audio focus state. So if we have focus, it will
+     * play normally; if we don't have focus, it will either leave the
+     * MediaPlayer paused or set it to a low volume, depending on what is
+     * allowed by the current focus settings. This method assumes mPlayer !=
+     * null, so if you are calling it, you have to do so from a context where
+     * you are sure this is the case.
+     */
+    private void configMediaPlayerState() {
+        LogHelper.d(TAG, "configMediaPlayerState. mAudioFocus=", mAudioFocus);
+        if (mAudioFocus == AUDIO_NO_FOCUS_NO_DUCK) {
+            // If we don't have audio focus and can't duck, we have to pause,
+            if (mState == PlaybackState.STATE_PLAYING) {
+                pause();
+            }
+        } else {  // we have audio focus:
+            if (mAudioFocus == AUDIO_NO_FOCUS_CAN_DUCK) {
+                mMediaPlayer.setVolume(VOLUME_DUCK, VOLUME_DUCK); // we'll be relatively quiet
+            } else {
+                if (mMediaPlayer != null) {
+                    mMediaPlayer.setVolume(VOLUME_NORMAL, VOLUME_NORMAL); // we can be loud again
+                } // else do something for remote client.
+            }
+            // If we were playing when we lost focus, we need to resume playing.
+            if (mPlayOnFocusGain) {
+                if (mMediaPlayer != null && !mMediaPlayer.isPlaying()) {
+                    LogHelper.d(TAG,"configMediaPlayerState startMediaPlayer. seeking to ",
+                        mCurrentPosition);
+                    if (mCurrentPosition == mMediaPlayer.getCurrentPosition()) {
+                        mMediaPlayer.start();
+                        mState = PlaybackState.STATE_PLAYING;
+                    } else {
+                        mMediaPlayer.seekTo(mCurrentPosition);
+                        mState = PlaybackState.STATE_BUFFERING;
+                    }
+                }
+                mPlayOnFocusGain = false;
+            }
+        }
+        if (mCallback != null) {
+            mCallback.onPlaybackStatusChanged(mState);
+        }
+    }
+
+    /**
+     * Called by AudioManager on audio focus changes.
+     * Implementation of {@link android.media.AudioManager.OnAudioFocusChangeListener}
+     */
+    @Override
+    public void onAudioFocusChange(int focusChange) {
+        LogHelper.d(TAG, "onAudioFocusChange. focusChange=", focusChange);
+        if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
+            // We have gained focus:
+            mAudioFocus = AUDIO_FOCUSED;
+
+        } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS ||
+                focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT ||
+                focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
+            // We have lost focus. If we can duck (low playback volume), we can keep playing.
+            // Otherwise, we need to pause the playback.
+            boolean canDuck = focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK;
+            mAudioFocus = canDuck ? AUDIO_NO_FOCUS_CAN_DUCK : AUDIO_NO_FOCUS_NO_DUCK;
+
+            // If we are playing, we need to reset media player by calling configMediaPlayerState
+            // with mAudioFocus properly set.
+            if (mState == PlaybackState.STATE_PLAYING && !canDuck) {
+                // If we don't have audio focus and can't duck, we save the information that
+                // we were playing, so that we can resume playback once we get the focus back.
+                mPlayOnFocusGain = true;
+            }
+        } else {
+            LogHelper.e(TAG, "onAudioFocusChange: Ignoring unsupported focusChange: ", focusChange);
+        }
+        configMediaPlayerState();
+    }
+
+    /**
+     * Called when MediaPlayer has completed a seek
+     *
+     * @see android.media.MediaPlayer.OnSeekCompleteListener
+     */
+    @Override
+    public void onSeekComplete(MediaPlayer mp) {
+        LogHelper.d(TAG, "onSeekComplete from MediaPlayer:", mp.getCurrentPosition());
+        mCurrentPosition = mp.getCurrentPosition();
+        if (mState == PlaybackState.STATE_BUFFERING) {
+            mMediaPlayer.start();
+            mState = PlaybackState.STATE_PLAYING;
+        }
+        if (mCallback != null) {
+            mCallback.onPlaybackStatusChanged(mState);
+        }
+    }
+
+    /**
+     * Called when media player is done playing current song.
+     *
+     * @see android.media.MediaPlayer.OnCompletionListener
+     */
+    @Override
+    public void onCompletion(MediaPlayer player) {
+        LogHelper.d(TAG, "onCompletion from MediaPlayer");
+        // The media player finished playing the current song, so we go ahead
+        // and start the next.
+        if (mCallback != null) {
+            mCallback.onCompletion();
+        }
+    }
+
+    /**
+     * Called when media player is done preparing.
+     *
+     * @see android.media.MediaPlayer.OnPreparedListener
+     */
+    @Override
+    public void onPrepared(MediaPlayer player) {
+        LogHelper.d(TAG, "onPrepared from MediaPlayer");
+        // The media player is done preparing. That means we can start playing if we
+        // have audio focus.
+        configMediaPlayerState();
+    }
+
+    /**
+     * Called when there's an error playing media. When this happens, the media
+     * player goes to the Error state. We warn the user about the error and
+     * reset the media player.
+     *
+     * @see android.media.MediaPlayer.OnErrorListener
+     */
+    @Override
+    public boolean onError(MediaPlayer mp, int what, int extra) {
+        LogHelper.e(TAG, "Media player error: what=" + what + ", extra=" + extra);
+        if (mCallback != null) {
+            mCallback.onError("MediaPlayer error " + what + " (" + extra + ")");
+        }
+        return true; // true indicates we handled the error
+    }
+
+    /**
+     * Makes sure the media player exists and has been reset. This will create
+     * the media player if needed, or reset the existing media player if one
+     * already exists.
+     */
+    private void createMediaPlayerIfNeeded() {
+        LogHelper.d(TAG, "createMediaPlayerIfNeeded. needed? ", (mMediaPlayer==null));
+        if (mMediaPlayer == null) {
+            mMediaPlayer = new MediaPlayer();
+
+            // Make sure the media player will acquire a wake-lock while
+            // playing. If we don't do that, the CPU might go to sleep while the
+            // song is playing, causing playback to stop.
+            mMediaPlayer.setWakeMode(mService.getApplicationContext(),
+                    PowerManager.PARTIAL_WAKE_LOCK);
+
+            // we want the media player to notify us when it's ready preparing,
+            // and when it's done playing:
+            mMediaPlayer.setOnPreparedListener(this);
+            mMediaPlayer.setOnCompletionListener(this);
+            mMediaPlayer.setOnErrorListener(this);
+            mMediaPlayer.setOnSeekCompleteListener(this);
+        } else {
+            mMediaPlayer.reset();
+        }
+    }
+
+    /**
+     * Releases resources used by the service for playback. This includes the
+     * "foreground service" status, the wake locks and possibly the MediaPlayer.
+     *
+     * @param releaseMediaPlayer Indicates whether the Media Player should also
+     *            be released or not
+     */
+    private void relaxResources(boolean releaseMediaPlayer) {
+        LogHelper.d(TAG, "relaxResources. releaseMediaPlayer=", releaseMediaPlayer);
+
+        mService.stopForeground(true);
+
+        // stop and release the Media Player, if it's available
+        if (releaseMediaPlayer && mMediaPlayer != null) {
+            mMediaPlayer.reset();
+            mMediaPlayer.release();
+            mMediaPlayer = null;
+        }
+
+        // we can also release the Wifi lock, if we're holding it
+        if (mWifiLock.isHeld()) {
+            mWifiLock.release();
+        }
+    }
+
+    private void registerAudioNoisyReceiver() {
+        if (!mAudioNoisyReceiverRegistered) {
+            mService.registerReceiver(mAudioNoisyReceiver, mAudioNoisyIntentFilter);
+            mAudioNoisyReceiverRegistered = true;
+        }
+    }
+
+    private void unregisterAudioNoisyReceiver() {
+        if (mAudioNoisyReceiverRegistered) {
+            mService.unregisterReceiver(mAudioNoisyReceiver);
+            mAudioNoisyReceiverRegistered = false;
+        }
+    }
+
+    interface Callback {
+        /**
+         * On current music completed.
+         */
+        void onCompletion();
+        /**
+         * on Playback status changed
+         * Implementations can use this callback to update
+         * playback state on the media sessions.
+         */
+        void onPlaybackStatusChanged(int state);
+
+        /**
+         * @param error to be added to the PlaybackState
+         */
+        void onError(String error);
+
+    }
+
+}
diff --git a/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/QueueFragment.java b/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/QueueFragment.java
index f6076bc..98b40e7 100644
--- a/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/QueueFragment.java
+++ b/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/QueueFragment.java
@@ -38,7 +38,7 @@
  */
 public class QueueFragment extends Fragment {
 
-    private static final String TAG = QueueFragment.class.getSimpleName();
+    private static final String TAG = LogHelper.makeLogTag(QueueFragment.class.getSimpleName());
 
     private ImageButton mSkipNext;
     private ImageButton mSkipPrevious;
diff --git a/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/model/MusicProvider.java b/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/model/MusicProvider.java
index d0e2e0b..b56bf2a 100644
--- a/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/model/MusicProvider.java
+++ b/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/model/MusicProvider.java
@@ -30,12 +30,14 @@
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.InputStreamReader;
+import java.net.URL;
 import java.net.URLConnection;
 import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
+import java.util.Collections;
 import java.util.List;
-import java.util.concurrent.locks.ReentrantLock;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
 
 /**
  * Utility class to get a list of MusicTrack's based on a server-side JSON
@@ -43,56 +45,54 @@
  */
 public class MusicProvider {
 
-    private static final String TAG = "MusicProvider";
+    private static final String TAG = LogHelper.makeLogTag(MusicProvider.class);
 
-    private static final String CATALOG_URL = "http://storage.googleapis.com/automotive-media/music.json";
+    private static final String CATALOG_URL =
+        "http://storage.googleapis.com/automotive-media/music.json";
 
     public static final String CUSTOM_METADATA_TRACK_SOURCE = "__SOURCE__";
 
-    private static String JSON_MUSIC = "music";
-    private static String JSON_TITLE = "title";
-    private static String JSON_ALBUM = "album";
-    private static String JSON_ARTIST = "artist";
-    private static String JSON_GENRE = "genre";
-    private static String JSON_SOURCE = "source";
-    private static String JSON_IMAGE = "image";
-    private static String JSON_TRACK_NUMBER = "trackNumber";
-    private static String JSON_TOTAL_TRACK_COUNT = "totalTrackCount";
-    private static String JSON_DURATION = "duration";
-
-    private final ReentrantLock initializationLock = new ReentrantLock();
+    private static final String JSON_MUSIC = "music";
+    private static final String JSON_TITLE = "title";
+    private static final String JSON_ALBUM = "album";
+    private static final String JSON_ARTIST = "artist";
+    private static final String JSON_GENRE = "genre";
+    private static final String JSON_SOURCE = "source";
+    private static final String JSON_IMAGE = "image";
+    private static final String JSON_TRACK_NUMBER = "trackNumber";
+    private static final String JSON_TOTAL_TRACK_COUNT = "totalTrackCount";
+    private static final String JSON_DURATION = "duration";
 
     // Categorized caches for music track data:
-    private final HashMap<String, List<MediaMetadata>> mMusicListByGenre;
-    private final HashMap<String, MediaMetadata> mMusicListById;
+    private ConcurrentMap<String, List<MediaMetadata>> mMusicListByGenre;
+    private final ConcurrentMap<String, MutableMediaMetadata> mMusicListById;
 
-    private final HashSet<String> mFavoriteTracks;
+    private final Set<String> mFavoriteTracks;
 
     enum State {
-        NON_INITIALIZED, INITIALIZING, INITIALIZED;
+        NON_INITIALIZED, INITIALIZING, INITIALIZED
     }
 
-    private State mCurrentState = State.NON_INITIALIZED;
-
+    private volatile State mCurrentState = State.NON_INITIALIZED;
 
     public interface Callback {
         void onMusicCatalogReady(boolean success);
     }
 
     public MusicProvider() {
-        mMusicListByGenre = new HashMap<>();
-        mMusicListById = new HashMap<>();
-        mFavoriteTracks = new HashSet<>();
+        mMusicListByGenre = new ConcurrentHashMap<>();
+        mMusicListById = new ConcurrentHashMap<>();
+        mFavoriteTracks = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());
     }
 
     /**
      * Get an iterator over the list of genres
      *
-     * @return
+     * @return genres
      */
     public Iterable<String> getGenres() {
         if (mCurrentState != State.INITIALIZED) {
-            return new ArrayList<String>(0);
+            return Collections.emptyList();
         }
         return mMusicListByGenre.keySet();
     }
@@ -100,11 +100,10 @@
     /**
      * Get music tracks of the given genre
      *
-     * @return
      */
     public Iterable<MediaMetadata> getMusicsByGenre(String genre) {
         if (mCurrentState != State.INITIALIZED || !mMusicListByGenre.containsKey(genre)) {
-            return new ArrayList<MediaMetadata>();
+            return Collections.emptyList();
         }
         return mMusicListByGenre.get(genre);
     }
@@ -113,32 +112,53 @@
      * Very basic implementation of a search that filter music tracks which title containing
      * the given query.
      *
-     * @return
      */
-    public Iterable<MediaMetadata> searchMusics(String titleQuery) {
-        ArrayList<MediaMetadata> result = new ArrayList<>();
+    public Iterable<MediaMetadata> searchMusic(String titleQuery) {
         if (mCurrentState != State.INITIALIZED) {
-            return result;
+            return Collections.emptyList();
         }
+        ArrayList<MediaMetadata> result = new ArrayList<>();
         titleQuery = titleQuery.toLowerCase();
-        for (MediaMetadata track: mMusicListById.values()) {
-            if (track.getString(MediaMetadata.METADATA_KEY_TITLE).toLowerCase()
+        for (MutableMediaMetadata track : mMusicListById.values()) {
+            if (track.metadata.getString(MediaMetadata.METADATA_KEY_TITLE).toLowerCase()
                     .contains(titleQuery)) {
-                result.add(track);
+                result.add(track.metadata);
             }
         }
         return result;
     }
 
-    public MediaMetadata getMusic(String mediaId) {
-        return mMusicListById.get(mediaId);
+    /**
+     * Return the MediaMetadata for the given musicID.
+     *
+     * @param musicId The unique, non-hierarchical music ID.
+     */
+    public MediaMetadata getMusic(String musicId) {
+        return mMusicListById.containsKey(musicId) ? mMusicListById.get(musicId).metadata : null;
     }
 
-    public void setFavorite(String mediaId, boolean favorite) {
+    public synchronized void updateMusic(String musicId, MediaMetadata metadata) {
+        MutableMediaMetadata track = mMusicListById.get(musicId);
+        if (track == null) {
+            return;
+        }
+
+        String oldGenre = track.metadata.getString(MediaMetadata.METADATA_KEY_GENRE);
+        String newGenre = metadata.getString(MediaMetadata.METADATA_KEY_GENRE);
+
+        track.metadata = metadata;
+
+        // if genre has changed, we need to rebuild the list by genre
+        if (!oldGenre.equals(newGenre)) {
+            buildListsByGenre();
+        }
+    }
+
+    public void setFavorite(String musicId, boolean favorite) {
         if (favorite) {
-            mFavoriteTracks.add(mediaId);
+            mFavoriteTracks.add(musicId);
         } else {
-            mFavoriteTracks.remove(mediaId);
+            mFavoriteTracks.remove(musicId);
         }
     }
 
@@ -152,12 +172,10 @@
 
     /**
      * Get the list of music tracks from a server and caches the track information
-     * for future reference, keying tracks by mediaId and grouping by genre.
-     *
-     * @return
+     * for future reference, keying tracks by musicId and grouping by genre.
      */
-    public void retrieveMedia(final Callback callback) {
-
+    public void retrieveMediaAsync(final Callback callback) {
+        LogHelper.d(TAG, "retrieveMediaAsync called");
         if (mCurrentState == State.INITIALIZED) {
             // Nothing to do, execute callback immediately
             callback.onMusicCatalogReady(true);
@@ -165,44 +183,60 @@
         }
 
         // Asynchronously load the music catalog in a separate thread
-        new AsyncTask() {
+        new AsyncTask<Void, Void, State>() {
             @Override
-            protected Object doInBackground(Object[] objects) {
-                retrieveMediaAsync(callback);
-                return null;
+            protected State doInBackground(Void... params) {
+                retrieveMedia();
+                return mCurrentState;
+            }
+
+            @Override
+            protected void onPostExecute(State current) {
+                if (callback != null) {
+                    callback.onMusicCatalogReady(current == State.INITIALIZED);
+                }
             }
         }.execute();
     }
 
-    private void retrieveMediaAsync(Callback callback) {
-        initializationLock.lock();
+    private synchronized void buildListsByGenre() {
+        ConcurrentMap<String, List<MediaMetadata>> newMusicListByGenre = new ConcurrentHashMap<>();
 
+        for (MutableMediaMetadata m : mMusicListById.values()) {
+            String genre = m.metadata.getString(MediaMetadata.METADATA_KEY_GENRE);
+            List<MediaMetadata> list = newMusicListByGenre.get(genre);
+            if (list == null) {
+                list = new ArrayList<>();
+                newMusicListByGenre.put(genre, list);
+            }
+            list.add(m.metadata);
+        }
+        mMusicListByGenre = newMusicListByGenre;
+    }
+
+    private synchronized void retrieveMedia() {
         try {
             if (mCurrentState == State.NON_INITIALIZED) {
                 mCurrentState = State.INITIALIZING;
 
                 int slashPos = CATALOG_URL.lastIndexOf('/');
                 String path = CATALOG_URL.substring(0, slashPos + 1);
-                JSONObject jsonObj = parseUrl(CATALOG_URL);
-
+                JSONObject jsonObj = fetchJSONFromUrl(CATALOG_URL);
+                if (jsonObj == null) {
+                    return;
+                }
                 JSONArray tracks = jsonObj.getJSONArray(JSON_MUSIC);
                 if (tracks != null) {
                     for (int j = 0; j < tracks.length(); j++) {
                         MediaMetadata item = buildFromJSON(tracks.getJSONObject(j), path);
-                        String genre = item.getString(MediaMetadata.METADATA_KEY_GENRE);
-                        List<MediaMetadata> list = mMusicListByGenre.get(genre);
-                        if (list == null) {
-                            list = new ArrayList<>();
-                        }
-                        list.add(item);
-                        mMusicListByGenre.put(genre, list);
-                        mMusicListById.put(item.getString(MediaMetadata.METADATA_KEY_MEDIA_ID),
-                                item);
+                        String musicId = item.getString(MediaMetadata.METADATA_KEY_MEDIA_ID);
+                        mMusicListById.put(musicId, new MutableMediaMetadata(musicId, item));
                     }
+                    buildListsByGenre();
                 }
                 mCurrentState = State.INITIALIZED;
             }
-        } catch (RuntimeException | JSONException e) {
+        } catch (JSONException e) {
             LogHelper.e(TAG, e, "Could not retrieve music list");
         } finally {
             if (mCurrentState != State.INITIALIZED) {
@@ -210,10 +244,6 @@
                 // retries (eg if the network connection is temporary unavailable)
                 mCurrentState = State.NON_INITIALIZED;
             }
-            initializationLock.unlock();
-            if (callback != null) {
-                callback.onMusicCatalogReady(mCurrentState == State.INITIALIZED);
-            }
         }
     }
 
@@ -263,19 +293,18 @@
      * Download a JSON file from a server, parse the content and return the JSON
      * object.
      *
-     * @param urlString
-     * @return
+     * @return result JSONObject containing the parsed representation.
      */
-    private JSONObject parseUrl(String urlString) {
+    private JSONObject fetchJSONFromUrl(String urlString) {
         InputStream is = null;
         try {
-            java.net.URL url = new java.net.URL(urlString);
+            URL url = new URL(urlString);
             URLConnection urlConnection = url.openConnection();
             is = new BufferedInputStream(urlConnection.getInputStream());
             BufferedReader reader = new BufferedReader(new InputStreamReader(
                     urlConnection.getInputStream(), "iso-8859-1"));
             StringBuilder sb = new StringBuilder();
-            String line = null;
+            String line;
             while ((line = reader.readLine()) != null) {
                 sb.append(line);
             }
@@ -293,4 +322,4 @@
             }
         }
     }
-}
\ No newline at end of file
+}
diff --git a/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/model/MutableMediaMetadata.java b/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/model/MutableMediaMetadata.java
new file mode 100644
index 0000000..1ee9d61
--- /dev/null
+++ b/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/model/MutableMediaMetadata.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.example.android.mediabrowserservice.model;
+
+import android.media.MediaMetadata;
+import android.text.TextUtils;
+
+/**
+ * Holder class that encapsulates a MediaMetadata and allows the actual metadata to be modified
+ * without requiring to rebuild the collections the metadata is in.
+ */
+public class MutableMediaMetadata {
+
+    public MediaMetadata metadata;
+    public final String trackId;
+
+    public MutableMediaMetadata(String trackId, MediaMetadata metadata) {
+        this.metadata = metadata;
+        this.trackId = trackId;
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) {
+            return true;
+        }
+        if (o == null || o.getClass() != MutableMediaMetadata.class) {
+            return false;
+        }
+
+        MutableMediaMetadata that = (MutableMediaMetadata) o;
+
+        return TextUtils.equals(trackId, that.trackId);
+    }
+
+    @Override
+    public int hashCode() {
+        return trackId.hashCode();
+    }
+}
diff --git a/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/utils/BitmapHelper.java b/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/utils/BitmapHelper.java
index 5f0e767..7325130 100644
--- a/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/utils/BitmapHelper.java
+++ b/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/utils/BitmapHelper.java
@@ -18,22 +18,26 @@
 import android.graphics.Bitmap;
 import android.graphics.BitmapFactory;
 
+import java.io.BufferedInputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.net.HttpURLConnection;
 import java.net.URL;
 
 public class BitmapHelper {
+    private static final String TAG = LogHelper.makeLogTag(BitmapHelper.class);
 
-    // Bitmap size for album art in media notifications when there are more than 3 playback actions
-    public static final int MEDIA_ART_SMALL_WIDTH=64;
-    public static final int MEDIA_ART_SMALL_HEIGHT=64;
+    // Max read limit that we allow our input stream to mark/reset.
+    private static final int MAX_READ_LIMIT_PER_IMG = 1024 * 1024;
 
-    // Bitmap size for album art in media notifications when there are no more than 3 playback actions
-    public static final int MEDIA_ART_BIG_WIDTH=128;
-    public static final int MEDIA_ART_BIG_HEIGHT=128;
+    public static Bitmap scaleBitmap(Bitmap src, int maxWidth, int maxHeight) {
+       double scaleFactor = Math.min(
+           ((double) maxWidth)/src.getWidth(), ((double) maxHeight)/src.getHeight());
+        return Bitmap.createScaledBitmap(src,
+            (int) (src.getWidth() * scaleFactor), (int) (src.getHeight() * scaleFactor), false);
+    }
 
-    public static final Bitmap scaleBitmap(int scaleFactor, InputStream is) {
+    public static Bitmap scaleBitmap(int scaleFactor, InputStream is) {
         // Get the dimensions of the bitmap
         BitmapFactory.Options bmOptions = new BitmapFactory.Options();
 
@@ -41,11 +45,10 @@
         bmOptions.inJustDecodeBounds = false;
         bmOptions.inSampleSize = scaleFactor;
 
-        Bitmap bitmap = BitmapFactory.decodeStream(is, null, bmOptions);
-        return bitmap;
+        return BitmapFactory.decodeStream(is, null, bmOptions);
     }
 
-    public static final int findScaleFactor(int targetW, int targetH, InputStream is) {
+    public static int findScaleFactor(int targetW, int targetH, InputStream is) {
         // Get the dimensions of the bitmap
         BitmapFactory.Options bmOptions = new BitmapFactory.Options();
         bmOptions.inJustDecodeBounds = true;
@@ -57,21 +60,24 @@
         return Math.min(actualW/targetW, actualH/targetH);
     }
 
-    public static final Bitmap fetchAndRescaleBitmap(String uri, int width, int height)
+    @SuppressWarnings("SameParameterValue")
+    public static Bitmap fetchAndRescaleBitmap(String uri, int width, int height)
             throws IOException {
         URL url = new URL(uri);
-        HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
-        httpConnection.setDoInput(true);
-        httpConnection.connect();
-        InputStream inputStream = httpConnection.getInputStream();
-        int scaleFactor = findScaleFactor(width, height, inputStream);
-
-        httpConnection = (HttpURLConnection) url.openConnection();
-        httpConnection.setDoInput(true);
-        httpConnection.connect();
-        inputStream = httpConnection.getInputStream();
-        Bitmap bitmap = scaleBitmap(scaleFactor, inputStream);
-        return bitmap;
+        BufferedInputStream is = null;
+        try {
+            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
+            is = new BufferedInputStream(urlConnection.getInputStream());
+            is.mark(MAX_READ_LIMIT_PER_IMG);
+            int scaleFactor = findScaleFactor(width, height, is);
+            LogHelper.d(TAG, "Scaling bitmap ", uri, " by factor ", scaleFactor, " to support ",
+                    width, "x", height, "requested dimension");
+            is.reset();
+            return scaleBitmap(scaleFactor, is);
+        } finally {
+            if (is != null) {
+                is.close();
+            }
+        }
     }
-
 }
diff --git a/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/utils/CarHelper.java b/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/utils/CarHelper.java
new file mode 100644
index 0000000..74861ba
--- /dev/null
+++ b/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/utils/CarHelper.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.example.android.mediabrowserservice.utils;
+
+import android.os.Bundle;
+
+public class CarHelper {
+    private static final String AUTO_APP_PACKAGE_NAME = "com.google.android.projection.gearhead";
+
+    // Use these extras to reserve space for the corresponding actions, even when they are disabled
+    // in the playbackstate, so the custom actions don't reflow.
+    private static final String SLOT_RESERVATION_SKIP_TO_NEXT =
+            "com.google.android.gms.car.media.ALWAYS_RESERVE_SPACE_FOR.ACTION_SKIP_TO_NEXT";
+    private static final String SLOT_RESERVATION_SKIP_TO_PREV =
+            "com.google.android.gms.car.media.ALWAYS_RESERVE_SPACE_FOR.ACTION_SKIP_TO_PREVIOUS";
+    private static final String SLOT_RESERVATION_QUEUE =
+            "com.google.android.gms.car.media.ALWAYS_RESERVE_SPACE_FOR.ACTION_QUEUE";
+
+
+    public static boolean isValidCarPackage(String packageName) {
+        return AUTO_APP_PACKAGE_NAME.equals(packageName);
+    }
+
+    public static void setSlotReservationFlags(Bundle extras, boolean reservePlayingQueueSlot,
+          boolean reserveSkipToNextSlot, boolean reserveSkipToPrevSlot) {
+        if (reservePlayingQueueSlot) {
+            extras.putBoolean(SLOT_RESERVATION_QUEUE, true);
+        } else {
+            extras.remove(SLOT_RESERVATION_QUEUE);
+        }
+        if (reserveSkipToPrevSlot) {
+            extras.putBoolean(SLOT_RESERVATION_SKIP_TO_PREV, true);
+        } else {
+            extras.remove(SLOT_RESERVATION_SKIP_TO_PREV);
+        }
+        if (reserveSkipToNextSlot) {
+            extras.putBoolean(SLOT_RESERVATION_SKIP_TO_NEXT, true);
+        } else {
+            extras.remove(SLOT_RESERVATION_SKIP_TO_NEXT);
+        }
+    }
+}
diff --git a/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/utils/LogHelper.java b/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/utils/LogHelper.java
index 92b2e09..09d14d2 100644
--- a/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/utils/LogHelper.java
+++ b/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/utils/LogHelper.java
@@ -17,13 +17,42 @@
 
 import android.util.Log;
 
+import com.example.android.mediabrowserservice.BuildConfig;
+
 public class LogHelper {
+
+    private static final String LOG_PREFIX = "sample_";
+    private static final int LOG_PREFIX_LENGTH = LOG_PREFIX.length();
+    private static final int MAX_LOG_TAG_LENGTH = 23;
+
+    public static String makeLogTag(String str) {
+        if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
+            return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
+        }
+
+        return LOG_PREFIX + str;
+    }
+
+    /**
+     * Don't use this when obfuscating class names!
+     */
+    public static String makeLogTag(Class cls) {
+        return makeLogTag(cls.getSimpleName());
+    }
+
+
     public static void v(String tag, Object... messages) {
-        log(tag, Log.VERBOSE, null, messages);
+        // Only log VERBOSE if build type is DEBUG
+        if (BuildConfig.DEBUG) {
+            log(tag, Log.VERBOSE, null, messages);
+        }
     }
 
     public static void d(String tag, Object... messages) {
-        log(tag, Log.DEBUG, null, messages);
+        // Only log DEBUG if build type is DEBUG
+        if (BuildConfig.DEBUG) {
+            log(tag, Log.DEBUG, null, messages);
+        }
     }
 
     public static void i(String tag, Object... messages) {
@@ -47,13 +76,14 @@
     }
 
     public static void log(String tag, int level, Throwable t, Object... messages) {
-        if (messages != null && Log.isLoggable(tag, level)) {
+        if (Log.isLoggable(tag, level)) {
             String message;
-            if (messages.length == 1) {
-                message = messages[0] == null ? null : messages[0].toString();
+            if (t == null && messages != null && messages.length == 1) {
+                // handle this common case without the extra cost of creating a stringbuffer:
+                message = messages[0].toString();
             } else {
                 StringBuilder sb = new StringBuilder();
-                for (Object m: messages) {
+                if (messages != null) for (Object m : messages) {
                     sb.append(m);
                 }
                 if (t != null) {
diff --git a/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/utils/MediaIDHelper.java b/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/utils/MediaIDHelper.java
index f66a010..604cf8a 100644
--- a/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/utils/MediaIDHelper.java
+++ b/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/utils/MediaIDHelper.java
@@ -16,32 +16,44 @@
 
 package com.example.android.mediabrowserservice.utils;
 
-import android.media.MediaMetadata;
+import java.util.Arrays;
 
 /**
  * Utility class to help on queue related tasks.
  */
 public class MediaIDHelper {
 
-    private static final String TAG = "MediaIDHelper";
+    private static final String TAG = LogHelper.makeLogTag(MediaIDHelper.class);
 
     // Media IDs used on browseable items of MediaBrowser
     public static final String MEDIA_ID_ROOT = "__ROOT__";
     public static final String MEDIA_ID_MUSICS_BY_GENRE = "__BY_GENRE__";
+    public static final String MEDIA_ID_MUSICS_BY_SEARCH = "__BY_SEARCH__";
 
-    public static final String createTrackMediaID(String categoryType, String categoryValue,
-              MediaMetadata track) {
-        // MediaIDs are of the form <categoryType>/<categoryValue>|<musicUniqueId>, to make it easy to
-        // find the category (like genre) that a music was selected from, so we
+    private static final char CATEGORY_SEPARATOR = '/';
+    private static final char LEAF_SEPARATOR = '|';
+
+    public static String createMediaID(String musicID, String... categories) {
+        // MediaIDs are of the form <categoryType>/<categoryValue>|<musicUniqueId>, to make it easy
+        // to find the category (like genre) that a music was selected from, so we
         // can correctly build the playing queue. This is specially useful when
         // one music can appear in more than one list, like "by genre -> genre_1"
         // and "by artist -> artist_1".
-        return categoryType + "/" + categoryValue + "|" +
-                track.getString(MediaMetadata.METADATA_KEY_MEDIA_ID);
+        StringBuilder sb = new StringBuilder();
+        if (categories != null && categories.length > 0) {
+            sb.append(categories[0]);
+            for (int i=1; i < categories.length; i++) {
+                sb.append(CATEGORY_SEPARATOR).append(categories[i]);
+            }
+        }
+        if (musicID != null) {
+            sb.append(LEAF_SEPARATOR).append(musicID);
+        }
+        return sb.toString();
     }
 
-    public static final String createBrowseCategoryMediaID(String categoryType, String categoryValue) {
-        return categoryType + "/" + categoryValue;
+    public static String createBrowseCategoryMediaID(String categoryType, String categoryValue) {
+        return categoryType + CATEGORY_SEPARATOR + categoryValue;
     }
 
     /**
@@ -50,12 +62,15 @@
      * musicID. This is necessary so we know where the user selected the music from, when the music
      * exists in more than one music list, and thus we are able to correctly build the playing queue.
      *
-     * @param musicID
-     * @return
+     * @param mediaID that contains the musicID
+     * @return musicID
      */
-    public static final String extractMusicIDFromMediaID(String musicID) {
-        String[] segments = musicID.split("\\|", 2);
-        return segments.length == 2 ? segments[1] : null;
+    public static String extractMusicIDFromMediaID(String mediaID) {
+        int pos = mediaID.indexOf(LEAF_SEPARATOR);
+        if (pos >= 0) {
+            return mediaID.substring(pos+1);
+        }
+        return null;
     }
 
     /**
@@ -64,25 +79,37 @@
      * mediaID. This is necessary so we know where the user selected the music from, when the music
      * exists in more than one music list, and thus we are able to correctly build the playing queue.
      *
-     * @param mediaID
-     * @return
+     * @param mediaID that contains a category and categoryValue.
      */
-    public static final String[] extractBrowseCategoryFromMediaID(String mediaID) {
-        if (mediaID.indexOf('|') >= 0) {
-            mediaID = mediaID.split("\\|")[0];
+    public static String[] getHierarchy(String mediaID) {
+        int pos = mediaID.indexOf(LEAF_SEPARATOR);
+        if (pos >= 0) {
+            mediaID = mediaID.substring(0, pos);
         }
-        if (mediaID.indexOf('/') == 0) {
-            return new String[]{mediaID, null};
-        } else {
-            return mediaID.split("/", 2);
-        }
+        return mediaID.split(String.valueOf(CATEGORY_SEPARATOR));
     }
 
-    public static final String extractBrowseCategoryValueFromMediaID(String mediaID) {
-        String[] categoryAndValue = extractBrowseCategoryFromMediaID(mediaID);
-        if (categoryAndValue != null && categoryAndValue.length == 2) {
-            return categoryAndValue[1];
+    public static String extractBrowseCategoryValueFromMediaID(String mediaID) {
+        String[] hierarchy = getHierarchy(mediaID);
+        if (hierarchy != null && hierarchy.length == 2) {
+            return hierarchy[1];
         }
         return null;
     }
-}
\ No newline at end of file
+
+    private static boolean isBrowseable(String mediaID) {
+        return mediaID.indexOf(LEAF_SEPARATOR) < 0;
+    }
+
+    public static String getParentMediaID(String mediaID) {
+        String[] hierarchy = getHierarchy(mediaID);
+        if (!isBrowseable(mediaID)) {
+            return createMediaID(null, hierarchy);
+        }
+        if (hierarchy == null || hierarchy.length <= 1) {
+            return MEDIA_ID_ROOT;
+        }
+        String[] parentHierarchy = Arrays.copyOf(hierarchy, hierarchy.length-1);
+        return createMediaID(null, parentHierarchy);
+    }
+}
diff --git a/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/utils/QueueHelper.java b/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/utils/QueueHelper.java
index 980efaa..9a2caa8 100644
--- a/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/utils/QueueHelper.java
+++ b/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/utils/QueueHelper.java
@@ -22,52 +22,64 @@
 import com.example.android.mediabrowserservice.model.MusicProvider;
 
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.Iterator;
 import java.util.List;
 
 import static com.example.android.mediabrowserservice.utils.MediaIDHelper.MEDIA_ID_MUSICS_BY_GENRE;
+import static com.example.android.mediabrowserservice.utils.MediaIDHelper.MEDIA_ID_MUSICS_BY_SEARCH;
 
 /**
  * Utility class to help on queue related tasks.
  */
 public class QueueHelper {
 
-    private static final String TAG = "QueueHelper";
+    private static final String TAG = LogHelper.makeLogTag(QueueHelper.class);
 
-    public static final List<MediaSession.QueueItem> getPlayingQueue(String mediaId,
+    public static List<MediaSession.QueueItem> getPlayingQueue(String mediaId,
             MusicProvider musicProvider) {
 
-        // extract the category and unique music ID from the media ID:
-        String[] category = MediaIDHelper.extractBrowseCategoryFromMediaID(mediaId);
+        // extract the browsing hierarchy from the media ID:
+        String[] hierarchy = MediaIDHelper.getHierarchy(mediaId);
 
-        // This sample only supports genre category.
-        if (!category[0].equals(MEDIA_ID_MUSICS_BY_GENRE) || category.length != 2) {
+        if (hierarchy.length != 2) {
             LogHelper.e(TAG, "Could not build a playing queue for this mediaId: ", mediaId);
             return null;
         }
 
-        String categoryValue = category[1];
-        LogHelper.e(TAG, "Creating playing queue for musics of genre ", categoryValue);
+        String categoryType = hierarchy[0];
+        String categoryValue = hierarchy[1];
+        LogHelper.d(TAG, "Creating playing queue for ", categoryType, ",  ", categoryValue);
 
-        List<MediaSession.QueueItem> queue = convertToQueue(
-                musicProvider.getMusicsByGenre(categoryValue));
+        Iterable<MediaMetadata> tracks = null;
+        // This sample only supports genre and by_search category types.
+        if (categoryType.equals(MEDIA_ID_MUSICS_BY_GENRE)) {
+            tracks = musicProvider.getMusicsByGenre(categoryValue);
+        } else if (categoryType.equals(MEDIA_ID_MUSICS_BY_SEARCH)) {
+            tracks = musicProvider.searchMusic(categoryValue);
+        }
 
-        return queue;
+        if (tracks == null) {
+            LogHelper.e(TAG, "Unrecognized category type: ", categoryType, " for mediaId ", mediaId);
+            return null;
+        }
+
+        return convertToQueue(tracks, hierarchy[0], hierarchy[1]);
     }
 
-    public static final List<MediaSession.QueueItem> getPlayingQueueFromSearch(String query,
+    public static List<MediaSession.QueueItem> getPlayingQueueFromSearch(String query,
             MusicProvider musicProvider) {
 
-        LogHelper.e(TAG, "Creating playing queue for musics from search ", query);
+        LogHelper.d(TAG, "Creating playing queue for musics from search ", query);
 
-        return convertToQueue(musicProvider.searchMusics(query));
+        return convertToQueue(musicProvider.searchMusic(query), MEDIA_ID_MUSICS_BY_SEARCH, query);
     }
 
 
-    public static final int getMusicIndexOnQueue(Iterable<MediaSession.QueueItem> queue,
+    public static int getMusicIndexOnQueue(Iterable<MediaSession.QueueItem> queue,
              String mediaId) {
         int index = 0;
-        for (MediaSession.QueueItem item: queue) {
+        for (MediaSession.QueueItem item : queue) {
             if (mediaId.equals(item.getDescription().getMediaId())) {
                 return index;
             }
@@ -76,10 +88,10 @@
         return -1;
     }
 
-    public static final int getMusicIndexOnQueue(Iterable<MediaSession.QueueItem> queue,
+    public static int getMusicIndexOnQueue(Iterable<MediaSession.QueueItem> queue,
              long queueId) {
         int index = 0;
-        for (MediaSession.QueueItem item: queue) {
+        for (MediaSession.QueueItem item : queue) {
             if (queueId == item.getQueueId()) {
                 return index;
             }
@@ -88,15 +100,25 @@
         return -1;
     }
 
-    private static final List<MediaSession.QueueItem> convertToQueue(
-            Iterable<MediaMetadata> tracks) {
+    private static List<MediaSession.QueueItem> convertToQueue(
+            Iterable<MediaMetadata> tracks, String... categories) {
         List<MediaSession.QueueItem> queue = new ArrayList<>();
         int count = 0;
         for (MediaMetadata track : tracks) {
+
+            // We create a hierarchy-aware mediaID, so we know what the queue is about by looking
+            // at the QueueItem media IDs.
+            String hierarchyAwareMediaID = MediaIDHelper.createMediaID(
+                    track.getDescription().getMediaId(), categories);
+
+            MediaMetadata trackCopy = new MediaMetadata.Builder(track)
+                    .putString(MediaMetadata.METADATA_KEY_MEDIA_ID, hierarchyAwareMediaID)
+                    .build();
+
             // We don't expect queues to change after created, so we use the item index as the
             // queueId. Any other number unique in the queue would work.
             MediaSession.QueueItem item = new MediaSession.QueueItem(
-                    track.getDescription(), count++);
+                    trackCopy.getDescription(), count++);
             queue.add(item);
         }
         return queue;
@@ -105,25 +127,23 @@
 
     /**
      * Create a random queue. For simplicity sake, instead of a random queue, we create a
-     * queue using the first genre,
+     * queue using the first genre.
      *
-     * @param musicProvider
-     * @return
+     * @param musicProvider the provider used for fetching music.
+     * @return list containing {@link android.media.session.MediaSession.QueueItem}'s
      */
-    public static final List<MediaSession.QueueItem> getRandomQueue(MusicProvider musicProvider) {
+    public static List<MediaSession.QueueItem> getRandomQueue(MusicProvider musicProvider) {
         Iterator<String> genres = musicProvider.getGenres().iterator();
         if (!genres.hasNext()) {
-            return new ArrayList<>();
+            return Collections.emptyList();
         }
         String genre = genres.next();
         Iterable<MediaMetadata> tracks = musicProvider.getMusicsByGenre(genre);
 
-        return convertToQueue(tracks);
+        return convertToQueue(tracks, MEDIA_ID_MUSICS_BY_GENRE, genre);
     }
 
-
-
-    public static final boolean isIndexPlayable(int index, List<MediaSession.QueueItem> queue) {
+    public static boolean isIndexPlayable(int index, List<MediaSession.QueueItem> queue) {
         return (queue != null && index >= 0 && index < queue.size());
     }
 }
diff --git a/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/utils/ResourceHelper.java b/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/utils/ResourceHelper.java
new file mode 100644
index 0000000..ed4dcd0
--- /dev/null
+++ b/media/MediaBrowserService/Application/src/main/java/com/example/android/mediabrowserservice/utils/ResourceHelper.java
@@ -0,0 +1,53 @@
+/*
+* Copyright (C) 2014 The Android Open Source Project
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+package com.example.android.mediabrowserservice.utils;
+
+import android.content.Context;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageManager;
+import android.content.res.Resources;
+import android.content.res.TypedArray;
+
+/**
+ * Generic reusable methods to handle resources.
+ */
+public class ResourceHelper {
+    /**
+     * Get a color value from a theme attribute.
+     * @param context used for getting the color.
+     * @param attribute theme attribute.
+     * @param defaultColor default to use.
+     * @return color value
+     */
+    public static int getThemeColor(Context context, int attribute, int defaultColor) {
+        int themeColor = 0;
+        String packageName = context.getPackageName();
+        try {
+            Context packageContext = context.createPackageContext(packageName, 0);
+            ApplicationInfo applicationInfo =
+                context.getPackageManager().getApplicationInfo(packageName, 0);
+            packageContext.setTheme(applicationInfo.theme);
+            Resources.Theme theme = packageContext.getTheme();
+            TypedArray ta = theme.obtainStyledAttributes(new int[] {attribute});
+            themeColor = ta.getColor(0, defaultColor);
+            ta.recycle();
+        } catch (PackageManager.NameNotFoundException e) {
+            e.printStackTrace();
+        }
+        return themeColor;
+    }
+}
diff --git a/media/MediaBrowserService/Application/src/main/res/drawable-hdpi/ic_notification.png b/media/MediaBrowserService/Application/src/main/res/drawable-hdpi/ic_notification.png
index d8ea5a9..a8cba40 100644
--- a/media/MediaBrowserService/Application/src/main/res/drawable-hdpi/ic_notification.png
+++ b/media/MediaBrowserService/Application/src/main/res/drawable-hdpi/ic_notification.png
Binary files differ
diff --git a/media/MediaBrowserService/Application/src/main/res/values-v21/styles.xml b/media/MediaBrowserService/Application/src/main/res/values-v21/styles.xml
deleted file mode 100644
index 21bb211..0000000
--- a/media/MediaBrowserService/Application/src/main/res/values-v21/styles.xml
+++ /dev/null
@@ -1,33 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  Copyright (C) 2014 The Android Open Source Project
-
-  Licensed under the Apache License, Version 2.0 (the "License");
-  you may not use this file except in compliance with the License.
-  You may obtain a copy of the License at
-
-       http://www.apache.org/licenses/LICENSE-2.0
-
-  Unless required by applicable law or agreed to in writing, software
-  distributed under the License is distributed on an "AS IS" BASIS,
-  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-  See the License for the specific language governing permissions and
-  limitations under the License.
--->
-<resources>
-
-    <style name="AppBaseTheme" parent="android:Theme.Material">
-        <!-- colorPrimary is used for Notification icon and bottom facet bar icons
-        and overflow actions -->
-        <item name="android:colorPrimary">#ffff5722</item>
-
-        <!-- colorPrimaryDark is used for background -->
-        <item name="android:colorPrimaryDark">#ffbf360c</item>
-
-        <!-- colorAccent is sparingly used for accents, like floating action button highlight,
-        progress on playbar-->
-        <item name="android:colorAccent">#ffff5722</item>
-
-    </style>
-
-</resources>
diff --git a/media/MediaBrowserService/Application/src/main/res/values/styles.xml b/media/MediaBrowserService/Application/src/main/res/values/styles.xml
index 3be59c1..35a3e7a 100644
--- a/media/MediaBrowserService/Application/src/main/res/values/styles.xml
+++ b/media/MediaBrowserService/Application/src/main/res/values/styles.xml
@@ -15,12 +15,27 @@
   limitations under the License.
 -->
 <resources>
-
-
-    <style name="AppTheme" parent="AppBaseTheme">
+    <style name="AppTheme" parent="android:Theme.Material">
+        <item name="android:colorPrimary">#ffff5722</item>
+        <item name="android:colorPrimaryDark">#ffbf360c</item>
+        <item name="android:colorAccent">#ffff5722</item>
     </style>
 
-    <style name="AppBaseTheme" parent="android:Theme.Light">
+    <style name="CarTheme" parent="AppTheme">
+        <!-- colorPrimaryDark is currently used in Android Auto for:
+             - App background
+             - Drawer right side ("more" custom actions) background
+             - Notification icon badge tinting
+             - Overview “now playing” icon tinting
+         -->
+        <item name="android:colorPrimaryDark">#ffbf360c</item>
+
+        <!-- colorAccent is used in Android Auto for:
+             - Spinner
+             - progress bar
+             - floating action button background (Play/Pause in media apps)
+         -->
+        <item name="android:colorAccent">#ffff5722</item>
     </style>
 
 </resources>
\ No newline at end of file
diff --git a/media/MediaBrowserService/Application/src/main/res/xml/allowed_media_browser_callers.xml b/media/MediaBrowserService/Application/src/main/res/xml/allowed_media_browser_callers.xml
new file mode 100644
index 0000000..5c326cf
--- /dev/null
+++ b/media/MediaBrowserService/Application/src/main/res/xml/allowed_media_browser_callers.xml
@@ -0,0 +1,174 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+Copyright (C) 2014 The Android Open Source Project
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+   http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+-->
+<allowed_callers>
+    <signing_certificate name="Android Auto" release="false"
+                         package="com.google.android.projection.gearhead">
+        MIIEqDCCA5CgAwIBAgIJANWFuGx90071MA0GCSqGSIb3DQEBBAUAMIGUMQswCQYD
+        VQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNTW91bnRhaW4g
+        VmlldzEQMA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UE
+        AxMHQW5kcm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbTAe
+        Fw0wODA0MTUyMzM2NTZaFw0zNTA5MDEyMzM2NTZaMIGUMQswCQYDVQQGEwJVUzET
+        MBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNTW91bnRhaW4gVmlldzEQMA4G
+        A1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5kcm9p
+        ZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbTCCASAwDQYJKoZI
+        hvcNAQEBBQADggENADCCAQgCggEBANbOLggKv+IxTdGNs8/TGFy0PTP6DHThvbbR
+        24kT9ixcOd9W+EaBPWW+wPPKQmsHxajtWjmQwWfna8mZuSeJS48LIgAZlKkpFeVy
+        xW0qMBujb8X8ETrWy550NaFtI6t9+u7hZeTfHwqNvacKhp1RbE6dBRGWynwMVX8X
+        W8N1+UjFaq6GCJukT4qmpN2afb8sCjUigq0GuMwYXrFVee74bQgLHWGJwPmvmLHC
+        69EH6kWr22ijx4OKXlSIx2xT1AsSHee70w5iDBiK4aph27yH3TxkXy9V89TDdexA
+        cKk/cVHYNnDBapcavl7y0RiQ4biu8ymM8Ga/nmzhRKya6G0cGw8CAQOjgfwwgfkw
+        HQYDVR0OBBYEFI0cxb6VTEM8YYY6FbBMvAPyT+CyMIHJBgNVHSMEgcEwgb6AFI0c
+        xb6VTEM8YYY6FbBMvAPyT+CyoYGapIGXMIGUMQswCQYDVQQGEwJVUzETMBEGA1UE
+        CBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNTW91bnRhaW4gVmlldzEQMA4GA1UEChMH
+        QW5kcm9pZDEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEiMCAG
+        CSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbYIJANWFuGx90071MAwGA1Ud
+        EwQFMAMBAf8wDQYJKoZIhvcNAQEEBQADggEBABnTDPEF+3iSP0wNfdIjIz1AlnrP
+        zgAIHVvXxunW7SBrDhEglQZBbKJEk5kT0mtKoOD1JMrSu1xuTKEBahWRbqHsXcla
+        XjoBADb0kkjVEJu/Lh5hgYZnOjvlba8Ld7HCKePCVePoTJBdI4fvugnL8TsgK05a
+        IskyY0hKI9L8KfqfGTl1lzOv2KoWD0KWwtAWPoGChZxmQ+nBli+gwYMzM1vAkP+a
+        ayLe0a1EQimlOalO762r0GXO0ks+UeXde2Z4e+8S/pf7pITEI/tP+MxJTALw9QUW
+        Ev9lKTk+jkbqxbsh8nfBUapfKqYn0eidpwq2AzVp3juYl7//fKnaPhJD9gs=
+    </signing_certificate>
+    <signing_certificate name="Android Auto" release="false"
+                         package="com.google.android.projection.gearhead">
+        MIIDvTCCAqWgAwIBAgIJAOfkBvDXw5bzMA0GCSqGSIb3DQEBBQUAMHUxCzAJBgNV
+        BAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1Nb3VudGFpbiBW
+        aWV3MRQwEgYDVQQKDAtHb29nbGUgSW5jLjEQMA4GA1UECwwHQW5kcm9pZDERMA8G
+        A1UEAwwIZ2VhcmhlYWQwHhcNMTQwNTI3MjMwMjUxWhcNNDExMDEyMjMwMjUxWjB1
+        MQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91
+        bnRhaW4gVmlldzEUMBIGA1UECgwLR29vZ2xlIEluYy4xEDAOBgNVBAsMB0FuZHJv
+        aWQxETAPBgNVBAMMCGdlYXJoZWFkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
+        CgKCAQEAou7wwBKFyznqpRretJ3EVp55/Yr049Ag5wlGvrCnjIP8DrMrU+skfKe1
+        DmwpsLNtnhhiNH+J000Lok3hc8jdWKeKOopzKGDNvL/HvnS70Zyk26gj9jtMMHz9
+        2aZdpmwD67FNmTlG2FERr+TwMD5agaPnsFR2zla6ugUvHGzz65YDxpCZsQ/TowyD
+        LnxgMagvhvS+Oex3yh2FN7pJfwS03KdGdkWPbLqf9Fem09s5jjeZW/O3RgnKoRPI
+        J4QLK70efjAZqJyBGcDZyQMwOs+8HIknraf8+cRZJDzqOx7rttl8M3KGB2EFljTp
+        6/FyxJLnAo6QlXn7GrYalTI0yLU9dQIDAQABo1AwTjAdBgNVHQ4EFgQU9QPJ5xJE
+        DA8MDQMrj0hm2/A2BRkwHwYDVR0jBBgwFoAU9QPJ5xJEDA8MDQMrj0hm2/A2BRkw
+        DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAQEADcr5h1FR8IpmN4hSsUA9
+        SnCQVyXa1GQhzpQgRbF+npkgOn2Mebp8bd28VpfgooD2OBNQXCUcZkn7pWj++ut9
+        HhObHVaV5FNg0pdDqLna9QZ9Y4oS+ZrijK70XZ/EjlYUHvhu0pIjZAbD8CmCFlow
+        SR55qCSjM5iS37LZB32SMr1BBiYrNAvncKjYQVK8ctTRzhpNQQPBgXBA98Xl+d1D
+        Py00JWQuF0ssmhKcJuvfdEnFF7Hvaxz/gCQ9nzarQI3CJB8dOXVwF8mcyDRBz4JR
+        +YDpXo6BD+fGt15ov+zmqC8xaT9P1/JgoDXiMhy/6rwgdi9WxPf8mb7TnBC+CksX
+        0A==
+    </signing_certificate>
+    <signing_certificate name="Android Auto" release="true"
+                         package="com.google.android.projection.gearhead">
+        MIIDvTCCAqWgAwIBAgIJAMePnkuTQTAGMA0GCSqGSIb3DQEBBQUAMHUxCzAJBgNV
+        BAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1Nb3VudGFpbiBW
+        aWV3MRQwEgYDVQQKDAtHb29nbGUgSW5jLjEQMA4GA1UECwwHQW5kcm9pZDERMA8G
+        A1UEAwwIZ2VhcmhlYWQwHhcNMTQwNTI3MjMwNTM0WhcNNDExMDEyMjMwNTM0WjB1
+        MQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91
+        bnRhaW4gVmlldzEUMBIGA1UECgwLR29vZ2xlIEluYy4xEDAOBgNVBAsMB0FuZHJv
+        aWQxETAPBgNVBAMMCGdlYXJoZWFkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
+        CgKCAQEA050XDkNIsVRMX2wTvVplpCu4OtnyNK2v5B7PS+DggmH2yuZiwpTurdKD
+        Q9R9UzxH9U4lsC+mIxXkiBYKIWNVgMtiTgxkEy7cgWvdYHgNYpFu8IxZKYDyXes+
+        02pfvpu63MIBD/PnvVFipo1oUrbfetj+mroEpjnA71gUS0Ok+H6XWWsmb8xFHQVM
+        oZWEIzsUJ2nhm8EcnPkAPfNZAG++XLPROoRQCaswyYsd42JuYAP3CwZuhDcUbMWm
+        k7rBi9BVQ8gmkrbwqo94A7qStLUp3NyCmlKSWHaZ05SspEPwsfctka0oXG5bhgT6
+        67EMCzQ+YsFN1oJRL7Qq+mMQjFJs3wIDAQABo1AwTjAdBgNVHQ4EFgQUGvBfYNeu
+        6JSJUnJZCiaBGsnXztswHwYDVR0jBBgwFoAUGvBfYNeu6JSJUnJZCiaBGsnXztsw
+        DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAQEAlGsDY0EPu3NBSH5k6iw/
+        wJh9e3xMwS17ErKGlhyWogxJMzLjAN6g0aCPHxB40IQC+8qAl+RL7VQx6oxttf0m
+        31yUGQPcNYbt2CxBTCAr885oLK5t2TAi5tQzhd6ZEYihWSUWUd/X8BQRouxboss9
+        QbBA/iIx0OpDaxiAcq7Cb67TheXZDxGuQ8fmHYbLx84pEvm3DQOB/LIMkkpQSfEC
+        1f+oP1zB3urPU/dSvED/LCgOdrpxZ5di7SwSyue+Vq/TZQy34tPygEzD2d8hFlh/
+        yfhWkMizOeIXcayVAQdNn5zpBkuay1skGOjQQ5kTbDcDzigO2R2rqn6HCd9l5Z0W
+        IQ==
+    </signing_certificate>
+    <signing_certificate name="Media Browser Service Simulator" release="true"
+                         package="com.google.android.mediasimulator">
+        MIIDvTCCAqWgAwIBAgIJAMePnkuTQTAGMA0GCSqGSIb3DQEBBQUAMHUxCzAJBgNV
+        BAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1Nb3VudGFpbiBW
+        aWV3MRQwEgYDVQQKDAtHb29nbGUgSW5jLjEQMA4GA1UECwwHQW5kcm9pZDERMA8G
+        A1UEAwwIZ2VhcmhlYWQwHhcNMTQwNTI3MjMwNTM0WhcNNDExMDEyMjMwNTM0WjB1
+        MQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91
+        bnRhaW4gVmlldzEUMBIGA1UECgwLR29vZ2xlIEluYy4xEDAOBgNVBAsMB0FuZHJv
+        aWQxETAPBgNVBAMMCGdlYXJoZWFkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
+        CgKCAQEA050XDkNIsVRMX2wTvVplpCu4OtnyNK2v5B7PS+DggmH2yuZiwpTurdKD
+        Q9R9UzxH9U4lsC+mIxXkiBYKIWNVgMtiTgxkEy7cgWvdYHgNYpFu8IxZKYDyXes+
+        02pfvpu63MIBD/PnvVFipo1oUrbfetj+mroEpjnA71gUS0Ok+H6XWWsmb8xFHQVM
+        oZWEIzsUJ2nhm8EcnPkAPfNZAG++XLPROoRQCaswyYsd42JuYAP3CwZuhDcUbMWm
+        k7rBi9BVQ8gmkrbwqo94A7qStLUp3NyCmlKSWHaZ05SspEPwsfctka0oXG5bhgT6
+        67EMCzQ+YsFN1oJRL7Qq+mMQjFJs3wIDAQABo1AwTjAdBgNVHQ4EFgQUGvBfYNeu
+        6JSJUnJZCiaBGsnXztswHwYDVR0jBBgwFoAUGvBfYNeu6JSJUnJZCiaBGsnXztsw
+        DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAQEAlGsDY0EPu3NBSH5k6iw/
+        wJh9e3xMwS17ErKGlhyWogxJMzLjAN6g0aCPHxB40IQC+8qAl+RL7VQx6oxttf0m
+        31yUGQPcNYbt2CxBTCAr885oLK5t2TAi5tQzhd6ZEYihWSUWUd/X8BQRouxboss9
+        QbBA/iIx0OpDaxiAcq7Cb67TheXZDxGuQ8fmHYbLx84pEvm3DQOB/LIMkkpQSfEC
+        1f+oP1zB3urPU/dSvED/LCgOdrpxZ5di7SwSyue+Vq/TZQy34tPygEzD2d8hFlh/
+        yfhWkMizOeIXcayVAQdNn5zpBkuay1skGOjQQ5kTbDcDzigO2R2rqn6HCd9l5Z0W
+        IQ==
+    </signing_certificate>
+    <signing_certificate name="Android Auto Simulator" release="true"
+                         package="com.google.android.autosimulator">
+        MIIEqDCCA5CgAwIBAgIJANWFuGx90071MA0GCSqGSIb3DQEBBAUAMIGUMQswCQYD
+        VQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNTW91bnRhaW4g
+        VmlldzEQMA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UE
+        AxMHQW5kcm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbTAe
+        Fw0wODA0MTUyMzM2NTZaFw0zNTA5MDEyMzM2NTZaMIGUMQswCQYDVQQGEwJVUzET
+        MBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNTW91bnRhaW4gVmlldzEQMA4G
+        A1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5kcm9p
+        ZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbTCCASAwDQYJKoZI
+        hvcNAQEBBQADggENADCCAQgCggEBANbOLggKv+IxTdGNs8/TGFy0PTP6DHThvbbR
+        24kT9ixcOd9W+EaBPWW+wPPKQmsHxajtWjmQwWfna8mZuSeJS48LIgAZlKkpFeVy
+        xW0qMBujb8X8ETrWy550NaFtI6t9+u7hZeTfHwqNvacKhp1RbE6dBRGWynwMVX8X
+        W8N1+UjFaq6GCJukT4qmpN2afb8sCjUigq0GuMwYXrFVee74bQgLHWGJwPmvmLHC
+        69EH6kWr22ijx4OKXlSIx2xT1AsSHee70w5iDBiK4aph27yH3TxkXy9V89TDdexA
+        cKk/cVHYNnDBapcavl7y0RiQ4biu8ymM8Ga/nmzhRKya6G0cGw8CAQOjgfwwgfkw
+        HQYDVR0OBBYEFI0cxb6VTEM8YYY6FbBMvAPyT+CyMIHJBgNVHSMEgcEwgb6AFI0c
+        xb6VTEM8YYY6FbBMvAPyT+CyoYGapIGXMIGUMQswCQYDVQQGEwJVUzETMBEGA1UE
+        CBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNTW91bnRhaW4gVmlldzEQMA4GA1UEChMH
+        QW5kcm9pZDEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEiMCAG
+        CSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbYIJANWFuGx90071MAwGA1Ud
+        EwQFMAMBAf8wDQYJKoZIhvcNAQEEBQADggEBABnTDPEF+3iSP0wNfdIjIz1AlnrP
+        zgAIHVvXxunW7SBrDhEglQZBbKJEk5kT0mtKoOD1JMrSu1xuTKEBahWRbqHsXcla
+        XjoBADb0kkjVEJu/Lh5hgYZnOjvlba8Ld7HCKePCVePoTJBdI4fvugnL8TsgK05a
+        IskyY0hKI9L8KfqfGTl1lzOv2KoWD0KWwtAWPoGChZxmQ+nBli+gwYMzM1vAkP+a
+        ayLe0a1EQimlOalO762r0GXO0ks+UeXde2Z4e+8S/pf7pITEI/tP+MxJTALw9QUW
+        Ev9lKTk+jkbqxbsh8nfBUapfKqYn0eidpwq2AzVp3juYl7//fKnaPhJD9gs=
+    </signing_certificate>
+    <signing_certificate name="Media Browser Simulator" release="true"
+                         package="com.google.android.mediasimulator">
+        MIIEqDCCA5CgAwIBAgIJANWFuGx90071MA0GCSqGSIb3DQEBBAUAMIGUMQswCQYD
+        VQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNTW91bnRhaW4g
+        VmlldzEQMA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UE
+        AxMHQW5kcm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbTAe
+        Fw0wODA0MTUyMzM2NTZaFw0zNTA5MDEyMzM2NTZaMIGUMQswCQYDVQQGEwJVUzET
+        MBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNTW91bnRhaW4gVmlldzEQMA4G
+        A1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5kcm9p
+        ZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbTCCASAwDQYJKoZI
+        hvcNAQEBBQADggENADCCAQgCggEBANbOLggKv+IxTdGNs8/TGFy0PTP6DHThvbbR
+        24kT9ixcOd9W+EaBPWW+wPPKQmsHxajtWjmQwWfna8mZuSeJS48LIgAZlKkpFeVy
+        xW0qMBujb8X8ETrWy550NaFtI6t9+u7hZeTfHwqNvacKhp1RbE6dBRGWynwMVX8X
+        W8N1+UjFaq6GCJukT4qmpN2afb8sCjUigq0GuMwYXrFVee74bQgLHWGJwPmvmLHC
+        69EH6kWr22ijx4OKXlSIx2xT1AsSHee70w5iDBiK4aph27yH3TxkXy9V89TDdexA
+        cKk/cVHYNnDBapcavl7y0RiQ4biu8ymM8Ga/nmzhRKya6G0cGw8CAQOjgfwwgfkw
+        HQYDVR0OBBYEFI0cxb6VTEM8YYY6FbBMvAPyT+CyMIHJBgNVHSMEgcEwgb6AFI0c
+        xb6VTEM8YYY6FbBMvAPyT+CyoYGapIGXMIGUMQswCQYDVQQGEwJVUzETMBEGA1UE
+        CBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNTW91bnRhaW4gVmlldzEQMA4GA1UEChMH
+        QW5kcm9pZDEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEiMCAG
+        CSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbYIJANWFuGx90071MAwGA1Ud
+        EwQFMAMBAf8wDQYJKoZIhvcNAQEEBQADggEBABnTDPEF+3iSP0wNfdIjIz1AlnrP
+        zgAIHVvXxunW7SBrDhEglQZBbKJEk5kT0mtKoOD1JMrSu1xuTKEBahWRbqHsXcla
+        XjoBADb0kkjVEJu/Lh5hgYZnOjvlba8Ld7HCKePCVePoTJBdI4fvugnL8TsgK05a
+        IskyY0hKI9L8KfqfGTl1lzOv2KoWD0KWwtAWPoGChZxmQ+nBli+gwYMzM1vAkP+a
+        ayLe0a1EQimlOalO762r0GXO0ks+UeXde2Z4e+8S/pf7pITEI/tP+MxJTALw9QUW
+        Ev9lKTk+jkbqxbsh8nfBUapfKqYn0eidpwq2AzVp3juYl7//fKnaPhJD9gs=
+    </signing_certificate>
+</allowed_callers>
diff --git a/media/MediaBrowserService/template-params.xml b/media/MediaBrowserService/template-params.xml
index 8f9b2e6..9c8a11c 100644
--- a/media/MediaBrowserService/template-params.xml
+++ b/media/MediaBrowserService/template-params.xml
@@ -38,7 +38,8 @@
     </strings>
 
     <!-- The basic templates have already been enabled. Uncomment more as desired. -->
-    <template src="basebuild" />
+    <template src="base-build" />
+    <template src="base-application" />
     <metadata>
     <status>PUBLISHED</status>
     <categories>Media</categories>
diff --git a/media/MediaRouter/Application/tests/AndroidManifest.xml b/media/MediaRouter/Application/tests/AndroidManifest.xml
index 0f9258a..1c88614 100644
--- a/media/MediaRouter/Application/tests/AndroidManifest.xml
+++ b/media/MediaRouter/Application/tests/AndroidManifest.xml
@@ -1,22 +1,3 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright 2013 The Android Open Source Project
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
-     http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-
-
-
 <?xml version="1.0" encoding="utf-8"?>
 <!--
   Copyright (C) 2013 The Android Open Source Project
@@ -56,4 +37,4 @@
             android:targetPackage="com.example.android.mediarouter"
             android:label="Tests for com.example.android.mediarouter" />
 
-</manifest>
\ No newline at end of file
+</manifest>
diff --git a/media/MediaRouter/Application/tests/src/com/example/android/mediarouter/tests/SampleTests.java b/media/MediaRouter/Application/tests/src/com/example/android/mediarouter/tests/SampleTests.java
index e62998a..0b657ea 100644
--- a/media/MediaRouter/Application/tests/src/com/example/android/mediarouter/tests/SampleTests.java
+++ b/media/MediaRouter/Application/tests/src/com/example/android/mediarouter/tests/SampleTests.java
@@ -1,22 +1,4 @@
 /*
-* Copyright 2013 The Android Open Source Project
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-
-
-/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
@@ -33,7 +15,7 @@
 */
 package com.example.android.mediarouter.tests;
 
-import com.example.android.mediarouter.*;
+import com.example.android.mediarouter.player.MainActivity;
 
 import android.test.ActivityInstrumentationTestCase2;
 
@@ -43,7 +25,6 @@
 public class SampleTests extends ActivityInstrumentationTestCase2<MainActivity> {
 
     private MainActivity mTestActivity;
-    private MediaRouterFragment mTestFragment;
 
     public SampleTests() {
         super(MainActivity.class);
@@ -58,8 +39,6 @@
         // flags = {@link Intent#FLAG_ACTIVITY_NEW_TASK}
         // All other fields are null or empty.
         mTestActivity = getActivity();
-        mTestFragment = (MediaRouterFragment)
-            mTestActivity.getSupportFragmentManager().getFragments().get(1);
     }
 
     /**
@@ -69,11 +48,10 @@
         //Try to add a message to add context to your assertions. These messages will be shown if
         //a tests fails and make it easy to understand why a test failed
         assertNotNull("mTestActivity is null", mTestActivity);
-        assertNotNull("mTestFragment is null", mTestFragment);
     }
 
     /**
     * Add more tests below.
     */
 
-}
\ No newline at end of file
+}
diff --git a/notification/BasicNotifications/Application/tests/src/com/example/android/basicnotifications/tests/SampleTests.java b/notification/BasicNotifications/Application/tests/src/com/example/android/basicnotifications/tests/SampleTests.java
index ffe5840..59df3b7 100644
--- a/notification/BasicNotifications/Application/tests/src/com/example/android/basicnotifications/tests/SampleTests.java
+++ b/notification/BasicNotifications/Application/tests/src/com/example/android/basicnotifications/tests/SampleTests.java
@@ -1,22 +1,4 @@
 /*
-* Copyright 2013 The Android Open Source Project
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-
-
-/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
@@ -43,7 +25,6 @@
 public class SampleTests extends ActivityInstrumentationTestCase2<MainActivity> {
 
     private MainActivity mTestActivity;
-    private BasicNotificationsFragment mTestFragment;
 
     public SampleTests() {
         super(MainActivity.class);
@@ -58,8 +39,6 @@
         // flags = {@link Intent#FLAG_ACTIVITY_NEW_TASK}
         // All other fields are null or empty.
         mTestActivity = getActivity();
-        mTestFragment = (BasicNotificationsFragment)
-            mTestActivity.getSupportFragmentManager().getFragments().get(1);
     }
 
     /**
@@ -69,11 +48,10 @@
         //Try to add a message to add context to your assertions. These messages will be shown if
         //a tests fails and make it easy to understand why a test failed
         assertNotNull("mTestActivity is null", mTestActivity);
-        assertNotNull("mTestFragment is null", mTestFragment);
     }
 
     /**
     * Add more tests below.
     */
 
-}
\ No newline at end of file
+}
diff --git a/notification/LNotifications/Application/tests/AndroidManifest.xml b/notification/LNotifications/Application/tests/AndroidManifest.xml
index 46a65af..6eb8621 100644
--- a/notification/LNotifications/Application/tests/AndroidManifest.xml
+++ b/notification/LNotifications/Application/tests/AndroidManifest.xml
@@ -34,7 +34,6 @@
     -->
     <instrumentation
         android:name="android.test.InstrumentationTestRunner"
-        android:label="Tests for L notifications sample"
         android:targetPackage="com.example.android.lnotifications"/>
 
-</manifest>
\ No newline at end of file
+</manifest>
diff --git a/notification/LNotifications/screenshots/1-headsup.png b/notification/LNotifications/screenshots/1-headsup.png
new file mode 100644
index 0000000..e84f7ec
--- /dev/null
+++ b/notification/LNotifications/screenshots/1-headsup.png
Binary files differ
diff --git a/notification/LNotifications/screenshots/2-visibility.png b/notification/LNotifications/screenshots/2-visibility.png
new file mode 100644
index 0000000..5450110
--- /dev/null
+++ b/notification/LNotifications/screenshots/2-visibility.png
Binary files differ
diff --git a/notification/LNotifications/screenshots/3-others.png b/notification/LNotifications/screenshots/3-others.png
new file mode 100644
index 0000000..453c383
--- /dev/null
+++ b/notification/LNotifications/screenshots/3-others.png
Binary files differ
diff --git a/notification/LNotifications/screenshots/icon-web.png b/notification/LNotifications/screenshots/icon-web.png
new file mode 100644
index 0000000..41a1511
--- /dev/null
+++ b/notification/LNotifications/screenshots/icon-web.png
Binary files differ
diff --git a/notification/LNotifications/template-params.xml b/notification/LNotifications/template-params.xml
index 6257c81..88b2b13 100644
--- a/notification/LNotifications/template-params.xml
+++ b/notification/LNotifications/template-params.xml
@@ -35,4 +35,49 @@
 
     <template src="base"/>
 
+    <metadata>
+        <status>PUBLISHED</status>
+        <categories>Notification</categories>
+        <technologies>Android</technologies>
+        <languages>Java</languages>
+        <solutions>Mobile</solutions>
+        <level>INTERMEDIATE</level>
+        <icon>screenshots/icon-web.png</icon>
+        <screenshots>
+            <img>screenshots/1-headsup.png</img>
+            <img>screenshots/2-visibility.png</img>
+            <img>screenshots/3-others.png</img>
+        </screenshots>
+        <api_refs>
+            <android>android.app.Notification</android>
+            <android>android.app.Notification.Builder</android>
+            <android>android.app.NotificationManager</android>
+        </api_refs>
+
+        <description>
+<![CDATA[
+This sample demonstrates new features for notifications introduced in Android L.
+These features include heads-up notifications, visibility, people, category and priority
+metadata.
+]]>
+        </description>
+
+        <intro>
+<![CDATA[
+Android 5.0 (Lollipop, API level 21) introduced additional features to the Notification API.
+Specifically, it allows developers to specify the priority and visibility level for
+notifications. This metadata allows the system to provide enhanced security for notifications
+while the lock screen is active, allows high-priority notifications to appear even when
+the notification bar is closed, and provides users to silence low-priority notifications
+when they're busy.
+
+This metadata is provided via additional arguments to the `Notification.Builder` class.
+
+Specifically, this sample demonstrates how to generate a heads-up notification
+(`HeadsUpNotificationFragment`), how to control visibility on the lock screen
+(`VisibilityMetadataFragment`), and how to set the category, priority, and associated contact
+for a notification (`OtherMetadataFragment`).
+]]>
+        </intro>
+    </metadata>
 </sample>
diff --git a/notification/MessagingService/template-params.xml b/notification/MessagingService/template-params.xml
index e83c845..9a68d74 100644
--- a/notification/MessagingService/template-params.xml
+++ b/notification/MessagingService/template-params.xml
@@ -32,7 +32,8 @@
         </intro>
     </strings>
 
-    <template src="basebuild" />
+    <template src="base-build" />
+    <template src="base-application" />
     <metadata>
         <status>PUBLISHED</status>
         <categories>UI, Notification</categories>
diff --git a/renderScript/BasicRenderScript/Application/tests/src/com/example/android/basicrenderscript/tests/SampleTests.java b/renderScript/BasicRenderScript/Application/tests/src/com/example/android/basicrenderscript/tests/SampleTests.java
index b361507..90d0c77 100644
--- a/renderScript/BasicRenderScript/Application/tests/src/com/example/android/basicrenderscript/tests/SampleTests.java
+++ b/renderScript/BasicRenderScript/Application/tests/src/com/example/android/basicrenderscript/tests/SampleTests.java
@@ -1,22 +1,4 @@
 /*
-* Copyright 2013 The Android Open Source Project
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-
-
-/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
@@ -43,7 +25,6 @@
 public class SampleTests extends ActivityInstrumentationTestCase2<MainActivity> {
 
     private MainActivity mTestActivity;
-    private BasicRenderScriptFragment mTestFragment;
 
     public SampleTests() {
         super(MainActivity.class);
@@ -58,8 +39,6 @@
         // flags = {@link Intent#FLAG_ACTIVITY_NEW_TASK}
         // All other fields are null or empty.
         mTestActivity = getActivity();
-        mTestFragment = (BasicRenderScriptFragment)
-            mTestActivity.getSupportFragmentManager().getFragments().get(1);
     }
 
     /**
@@ -69,11 +48,10 @@
         //Try to add a message to add context to your assertions. These messages will be shown if
         //a tests fails and make it easy to understand why a test failed
         assertNotNull("mTestActivity is null", mTestActivity);
-        assertNotNull("mTestFragment is null", mTestFragment);
     }
 
     /**
     * Add more tests below.
     */
 
-}
\ No newline at end of file
+}
diff --git a/renderScript/BasicRenderScript/screenshots/icon-web.png b/renderScript/BasicRenderScript/screenshots/icon-web.png
new file mode 100644
index 0000000..eb47ea1
--- /dev/null
+++ b/renderScript/BasicRenderScript/screenshots/icon-web.png
Binary files differ
diff --git a/renderScript/BasicRenderScript/screenshots/main.png b/renderScript/BasicRenderScript/screenshots/main.png
new file mode 100644
index 0000000..a9f2a72
--- /dev/null
+++ b/renderScript/BasicRenderScript/screenshots/main.png
Binary files differ
diff --git a/renderScript/BasicRenderScript/template-params.xml b/renderScript/BasicRenderScript/template-params.xml
index ec98254..d0d3be2 100644
--- a/renderScript/BasicRenderScript/template-params.xml
+++ b/renderScript/BasicRenderScript/template-params.xml
@@ -35,8 +35,9 @@
     <strings>
         <intro>
             <![CDATA[
-            BasicRenderScript sample demonstrates basic steps how to use renderScript.
-			In the sample, it performs graphical filter operation on a image with renderScript.
+            This sample demonstrates using RenderScript to perform basic image manipulation. Specifically, it allows users
+            to dynamically adjust the saturation for an image using a slider. A custom RenderScript kernel performs the saturation
+            adjustment, running the computation on the device\'s GPU or other compute hardware as deemed appropriate by the system.
             ]]>
         </intro>
     </strings>
@@ -44,4 +45,48 @@
     <template src="base"/>
     <common src="media"/>
 
+    <metadata>
+        <status>PUBLISHED</status>
+        <categories>RenderScript</categories>
+        <technologies>Android</technologies>
+        <languages>Java</languages>
+        <solutions>Mobile</solutions>
+        <level>EXPERT</level>
+        <icon>screenshots/icon-web.png</icon>
+        <screenshots>
+            <img>screenshots/main.png</img>
+        </screenshots>
+        <api_refs>
+            <android>android.renderscript.RenderScript</android>
+            <android>android.renderscript.Allocation</android>
+        </api_refs>
+
+        <description>
+<![CDATA[
+This sample demonstrates using RenderScript to perform basic image manipulation. Specifically, it allows users
+to dynamically adjust the saturation for an image using a slider. A custom RenderScript kernel performs the saturation
+adjustment, running the computation on the device\'s GPU or other compute hardware as deemed appropriate by the system.
+]]>
+        </description>
+
+        <intro>
+<![CDATA[
+[RenderScript][1] is a framework for running computationally intensive tasks at high performance on Android. RenderScript is
+primarily oriented for use with data-parallel computation, although serial computationally intensive workloads can
+benefit as well.
+
+The RenderScript runtime will parallelize work across all processors available on a device, such as multi-core CPUs,
+GPUs, or DSPs, allowing you to focus on expressing algorithms rather than scheduling work or load balancing.
+RenderScript is especially useful for applications performing image processing, computational photography, or computer
+vision.
+
+This sample demonstrates the fundamentals of writing a RenderScript compute kernel, and using it to perform basic image
+manipulation. In this case, each pixel is transformed based on a liner interpolation between its original
+RGB value and it's luminance (black-and-white) value, weighted based on the user's specified saturation target.
+
+[1]: http://developer.android.com/guide/topics/renderscript/compute.html
+[2]: http://developer.android.com/reference/renderscript/rs__cl_8rsh.html#a254612a612ff7539b01a1478e03d8697
+]]>
+        </intro>
+    </metadata>
 </sample>
diff --git a/renderScript/RenderScriptIntrinsic/Application/tests/src/com/example/android/renderscriptintrinsic/tests/SampleTests.java b/renderScript/RenderScriptIntrinsic/Application/tests/src/com/example/android/renderscriptintrinsic/tests/SampleTests.java
index c1864f0..f0c20ff 100644
--- a/renderScript/RenderScriptIntrinsic/Application/tests/src/com/example/android/renderscriptintrinsic/tests/SampleTests.java
+++ b/renderScript/RenderScriptIntrinsic/Application/tests/src/com/example/android/renderscriptintrinsic/tests/SampleTests.java
@@ -1,22 +1,4 @@
 /*
-* Copyright 2013 The Android Open Source Project
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-
-
-/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
@@ -43,7 +25,6 @@
 public class SampleTests extends ActivityInstrumentationTestCase2<MainActivity> {
 
     private MainActivity mTestActivity;
-    private RenderScriptIntrinsicFragment mTestFragment;
 
     public SampleTests() {
         super(MainActivity.class);
@@ -58,8 +39,6 @@
         // flags = {@link Intent#FLAG_ACTIVITY_NEW_TASK}
         // All other fields are null or empty.
         mTestActivity = getActivity();
-        mTestFragment = (RenderScriptIntrinsicFragment)
-            mTestActivity.getSupportFragmentManager().getFragments().get(1);
     }
 
     /**
@@ -69,11 +48,10 @@
         //Try to add a message to add context to your assertions. These messages will be shown if
         //a tests fails and make it easy to understand why a test failed
         assertNotNull("mTestActivity is null", mTestActivity);
-        assertNotNull("mTestFragment is null", mTestFragment);
     }
 
     /**
     * Add more tests below.
     */
 
-}
\ No newline at end of file
+}
diff --git a/renderScript/RenderScriptIntrinsic/screenshots/icon-web.png b/renderScript/RenderScriptIntrinsic/screenshots/icon-web.png
new file mode 100644
index 0000000..87f9dac
--- /dev/null
+++ b/renderScript/RenderScriptIntrinsic/screenshots/icon-web.png
Binary files differ
diff --git a/renderScript/RenderScriptIntrinsic/screenshots/main.png b/renderScript/RenderScriptIntrinsic/screenshots/main.png
new file mode 100644
index 0000000..1a81389
--- /dev/null
+++ b/renderScript/RenderScriptIntrinsic/screenshots/main.png
Binary files differ
diff --git a/renderScript/RenderScriptIntrinsic/template-params.xml b/renderScript/RenderScriptIntrinsic/template-params.xml
index d5d1656..8b80bb2 100644
--- a/renderScript/RenderScriptIntrinsic/template-params.xml
+++ b/renderScript/RenderScriptIntrinsic/template-params.xml
@@ -15,8 +15,6 @@
  limitations under the License.
 -->
 
-
-
 <sample>
     <name>RenderScriptIntrinsic</name>
     <group>RenderScript</group>
@@ -45,4 +43,59 @@
     <template src="base"/>
     <common src="logger"/>
 
+    <metadata>
+        <status>PUBLISHED</status>
+        <categories>RenderScript</categories>
+        <technologies>Android</technologies>
+        <languages>Java</languages>
+        <solutions>Mobile</solutions>
+        <level>EXPERT</level>
+        <icon>screenshots/icon-web.png</icon>
+        <screenshots>
+            <img>screenshots/main.png</img>
+        </screenshots>
+        <api_refs>
+            <android>android.renderscript.RenderScript</android>
+            <android>android.renderscript.ScriptIntrinsicBlur</android>
+            <android>android.renderscript.ScriptIntrinsicConvolve5x5</android>
+            <android>android.renderscript.ScriptIntrinsicColorMatrix</android>
+            <android></android>
+        </api_refs>
+
+        <description>
+<![CDATA[
+RenderScriptIntrinsic sample that demonstrates how to use RenderScript intrinsics.
+Creates several RenderScript intrinsics and shows a filtering result with various parameters.
+Also shows how to extends RedioButton with StateListDrawable.
+]]>
+        </description>
+
+        <intro>
+<![CDATA[
+[RenderScript][1] is a framework for running computationally intensive tasks at high performance on Android. RenderScript is
+primarily oriented for use with data-parallel computation, although serial computationally intensive workloads can
+benefit as well.
+
+RenderScript **intrinsics** are built-in functions that perform well-defined operations often seen
+in image processing. Intrinsics provide extremely high-performance implementations of standard
+functions with a minimal amount of code.
+
+This sample shows how to access and use the blur, convolve, and matrix intrinsics:
+
+```java
+mScriptBlur = ScriptIntrinsicBlur.create(mRS, Element.U8_4(mRS));
+mScriptConvolve = ScriptIntrinsicConvolve5x5.create(mRS,
+        Element.U8_4(mRS));
+mScriptMatrix = ScriptIntrinsicColorMatrix.create(mRS,
+        Element.U8_4(mRS));
+```
+
+RenderScript intrinsics will usually be the fastest possible way for a developer to perform these operations. The
+Android team works closely with our partners to ensure that the intrinsics perform as fast as possible on their
+architectures — often far beyond anything that can be achieved in a general-purpose language.
+
+[1]: http://developer.android.com/guide/topics/renderscript/compute.html
+]]>
+        </intro>
+    </metadata>
 </sample>
diff --git a/system/AppUsageStatistics/Application/tests/src/com/example/android/appusagestatistics/AppUsageStatisticsFragmentTests.java b/system/AppUsageStatistics/Application/tests/src/com/example/android/appusagestatistics/AppUsageStatisticsFragmentTests.java
index d8adb1c..68f9711 100644
--- a/system/AppUsageStatistics/Application/tests/src/com/example/android/appusagestatistics/AppUsageStatisticsFragmentTests.java
+++ b/system/AppUsageStatistics/Application/tests/src/com/example/android/appusagestatistics/AppUsageStatisticsFragmentTests.java
@@ -21,6 +21,7 @@
 import android.app.usage.UsageStats;
 import android.app.usage.UsageStatsManager;
 import android.test.ActivityInstrumentationTestCase2;
+import android.test.UiThreadTest;
 
 import java.util.List;
 
@@ -31,6 +32,7 @@
         extends ActivityInstrumentationTestCase2<AppUsageStatisticsActivity> {
 
     private AppUsageStatisticsActivity mTestActivity;
+
     private AppUsageStatisticsFragment mTestFragment;
 
     public AppUsageStatisticsFragmentTests() {
@@ -80,12 +82,11 @@
         assertNotNull(usageStatsList);
     }
 
+    @UiThreadTest
     public void testUpdateAppsList() {
         List<UsageStats> usageStatsList = mTestFragment
                 .getUsageStatistics(UsageStatsManager.INTERVAL_DAILY);
-
         mTestFragment.updateAppsList(usageStatsList);
-        getInstrumentation().waitForIdleSync();
 
         // The result depends on if the app is granted the access to App usage statistics.
         if (usageStatsList.size() == 0) {
diff --git a/ui/Interpolator/Application/tests/AndroidManifest.xml b/ui/Interpolator/Application/tests/AndroidManifest.xml
index 5e43ab9..16b567b 100644
--- a/ui/Interpolator/Application/tests/AndroidManifest.xml
+++ b/ui/Interpolator/Application/tests/AndroidManifest.xml
@@ -17,7 +17,7 @@
 
 <!-- package name must be unique so suffix with "tests" so package loader doesn't ignore us -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-          package="com.example.android.interpolatorplayground.tests"
+          package="com.example.android.interpolator.tests"
           android:versionCode="1"
           android:versionName="1.0">
 
@@ -35,7 +35,7 @@
     -->
     <instrumentation
             android:name="android.test.InstrumentationTestRunner"
-            android:targetPackage="com.example.android.interpolatorplayground"
-            android:label="Tests for com.example.android.interpolatorplayground" />
+            android:targetPackage="com.example.android.interpolator"
+            />
 
-</manifest>
\ No newline at end of file
+</manifest>
diff --git a/ui/Interpolator/Application/tests/src/com/example/android/interpolatorplayground/tests/SampleTests.java b/ui/Interpolator/Application/tests/src/com/example/android/interpolator/tests/SampleTests.java
similarity index 97%
rename from ui/Interpolator/Application/tests/src/com/example/android/interpolatorplayground/tests/SampleTests.java
rename to ui/Interpolator/Application/tests/src/com/example/android/interpolator/tests/SampleTests.java
index 7a0264b..07c1623 100644
--- a/ui/Interpolator/Application/tests/src/com/example/android/interpolatorplayground/tests/SampleTests.java
+++ b/ui/Interpolator/Application/tests/src/com/example/android/interpolator/tests/SampleTests.java
@@ -17,7 +17,8 @@
 package com.example.android.interpolatorplayground.tests;
 
 import com.example.android.interpolator.InterpolatorFragment;
-import com.example.android.interpolatorplayground.*;
+import com.example.android.interpolator.MainActivity;
+import com.example.android.interpolator.R;
 
 import android.animation.ObjectAnimator;
 import android.test.ActivityInstrumentationTestCase2;
@@ -112,4 +113,4 @@
             animator.cancel();
         }
     }
-}
\ No newline at end of file
+}
diff --git a/ui/Interpolator/after.png b/ui/Interpolator/after.png
new file mode 100644
index 0000000..0373014
--- /dev/null
+++ b/ui/Interpolator/after.png
Binary files differ
diff --git a/ui/Interpolator/before.png b/ui/Interpolator/before.png
new file mode 100644
index 0000000..e28e4f9
--- /dev/null
+++ b/ui/Interpolator/before.png
Binary files differ
diff --git a/ui/Interpolator/screenshots/icon-web.png b/ui/Interpolator/screenshots/icon-web.png
new file mode 100644
index 0000000..172851b
--- /dev/null
+++ b/ui/Interpolator/screenshots/icon-web.png
Binary files differ
diff --git a/ui/Interpolator/template-params.xml b/ui/Interpolator/template-params.xml
index 268ee8a..2433b5a 100644
--- a/ui/Interpolator/template-params.xml
+++ b/ui/Interpolator/template-params.xml
@@ -40,5 +40,46 @@
 
     <common src="logger"/>
     <common src="activities"/>
+    <metadata>
+        <status>PUBLISHED</status>
+        <categories>Design, Transitions, Input</categories>
+        <technologies>Android</technologies>
+        <languages>Java</languages>
+        <solutions>Mobile</solutions>
+        <level>INTERMEDIATE</level>
+        <icon>screenshots/icon-web.png</icon>
+        <screenshots>
+            <img>screenshots/before.png</img>
+            <img>screenshots/after.png</img>
+        </screenshots>
+        <api_refs>
+            <android>android.animation.ObjectAnimator</android>
+            <android>android.view.animation.Interpolator</android>
+        </api_refs>
+        <description>
+<![CDATA[
+This sample demonstrates the use of animation interpolators and path animations for
+`Material Design`.
+]]>
+        </description>
+        <intro>
+<![CDATA[
+Material design is a comprehensive guide for visual, motion, and interaction
+design across platforms and devices. Starting with API level 21,
+[Android includes support for material design][1] apps.
+
+This sample demonstrates the use of `Material Design` animation interpolators
+and path animations. It uses an [ObjectAnimator][2] to animate two view properties,
+`Scale_X` and `Scale_Y`. Users can pick from a set of interpolator options. They
+can also define the duration of the animation.
+
+[1]: https://developer.android.com/training/material/index.html
+[2]: https://developer.android.com/guide/topics/graphics/prop-animation.html#object-animator
+
+]]>
+        </intro>
+    </metadata>
+
+
 
 </sample>
diff --git a/ui/accessibility/BasicAccessibility/Application/tests/src/com/example/android/basicaccessibility/tests/SampleTests.java b/ui/accessibility/BasicAccessibility/Application/tests/src/com/example/android/basicaccessibility/tests/SampleTests.java
index 0c9a152..18a144d 100644
--- a/ui/accessibility/BasicAccessibility/Application/tests/src/com/example/android/basicaccessibility/tests/SampleTests.java
+++ b/ui/accessibility/BasicAccessibility/Application/tests/src/com/example/android/basicaccessibility/tests/SampleTests.java
@@ -1,22 +1,4 @@
 /*
-* Copyright 2013 The Android Open Source Project
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-
-
-/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
@@ -43,7 +25,6 @@
 public class SampleTests extends ActivityInstrumentationTestCase2<MainActivity> {
 
     private MainActivity mTestActivity;
-    private BasicAccessibilityFragment mTestFragment;
 
     public SampleTests() {
         super(MainActivity.class);
@@ -58,8 +39,6 @@
         // flags = {@link Intent#FLAG_ACTIVITY_NEW_TASK}
         // All other fields are null or empty.
         mTestActivity = getActivity();
-        mTestFragment = (BasicAccessibilityFragment)
-            mTestActivity.getSupportFragmentManager().getFragments().get(1);
     }
 
     /**
@@ -69,11 +48,10 @@
         //Try to add a message to add context to your assertions. These messages will be shown if
         //a tests fails and make it easy to understand why a test failed
         assertNotNull("mTestActivity is null", mTestActivity);
-        assertNotNull("mTestFragment is null", mTestFragment);
     }
 
     /**
     * Add more tests below.
     */
 
-}
\ No newline at end of file
+}
diff --git a/ui/actionbar/DoneBar/Application/tests/src/com/example/android/donebar/tests/SampleTests.java b/ui/actionbar/DoneBar/Application/tests/src/com/example/android/donebar/tests/SampleTests.java
index c019ef8..b9b8443 100644
--- a/ui/actionbar/DoneBar/Application/tests/src/com/example/android/donebar/tests/SampleTests.java
+++ b/ui/actionbar/DoneBar/Application/tests/src/com/example/android/donebar/tests/SampleTests.java
@@ -1,22 +1,4 @@
 /*
-* Copyright 2013 The Android Open Source Project
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-
-
-/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
@@ -43,7 +25,6 @@
 public class SampleTests extends ActivityInstrumentationTestCase2<MainActivity> {
 
     private MainActivity mTestActivity;
-    private DoneBarFragment mTestFragment;
 
     public SampleTests() {
         super(MainActivity.class);
@@ -58,8 +39,6 @@
         // flags = {@link Intent#FLAG_ACTIVITY_NEW_TASK}
         // All other fields are null or empty.
         mTestActivity = getActivity();
-        mTestFragment = (DoneBarFragment)
-            mTestActivity.getSupportFragmentManager().getFragments().get(1);
     }
 
     /**
@@ -69,11 +48,10 @@
         //Try to add a message to add context to your assertions. These messages will be shown if
         //a tests fails and make it easy to understand why a test failed
         assertNotNull("mTestActivity is null", mTestActivity);
-        assertNotNull("mTestFragment is null", mTestFragment);
     }
 
     /**
     * Add more tests below.
     */
 
-}
\ No newline at end of file
+}
diff --git a/ui/actionbarcompat/ActionBarCompat-Basic/Application/tests/src/com/example/android/actionbarcompat/basic/tests/SampleTests.java b/ui/actionbarcompat/ActionBarCompat-Basic/Application/tests/src/com/example/android/actionbarcompat/basic/tests/SampleTests.java
index 8c1b2be..767dbbb 100644
--- a/ui/actionbarcompat/ActionBarCompat-Basic/Application/tests/src/com/example/android/actionbarcompat/basic/tests/SampleTests.java
+++ b/ui/actionbarcompat/ActionBarCompat-Basic/Application/tests/src/com/example/android/actionbarcompat/basic/tests/SampleTests.java
@@ -1,22 +1,4 @@
 /*
-* Copyright 2013 The Android Open Source Project
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-
-
-/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
@@ -43,7 +25,6 @@
 public class SampleTests extends ActivityInstrumentationTestCase2<MainActivity> {
 
     private MainActivity mTestActivity;
-    private BasicFragment mTestFragment;
 
     public SampleTests() {
         super(MainActivity.class);
@@ -58,8 +39,6 @@
         // flags = {@link Intent#FLAG_ACTIVITY_NEW_TASK}
         // All other fields are null or empty.
         mTestActivity = getActivity();
-        mTestFragment = (BasicFragment)
-            mTestActivity.getSupportFragmentManager().getFragments().get(1);
     }
 
     /**
@@ -69,11 +48,10 @@
         //Try to add a message to add context to your assertions. These messages will be shown if
         //a tests fails and make it easy to understand why a test failed
         assertNotNull("mTestActivity is null", mTestActivity);
-        assertNotNull("mTestFragment is null", mTestFragment);
     }
 
     /**
     * Add more tests below.
     */
 
-}
\ No newline at end of file
+}
diff --git a/ui/actionbarcompat/ActionBarCompat-ListPopupMenu/Application/tests/src/com/example/android/actionbarcompat/listpopupmenu/tests/SampleTests.java b/ui/actionbarcompat/ActionBarCompat-ListPopupMenu/Application/tests/src/com/example/android/actionbarcompat/listpopupmenu/tests/SampleTests.java
index c91ae2e..adc025a 100644
--- a/ui/actionbarcompat/ActionBarCompat-ListPopupMenu/Application/tests/src/com/example/android/actionbarcompat/listpopupmenu/tests/SampleTests.java
+++ b/ui/actionbarcompat/ActionBarCompat-ListPopupMenu/Application/tests/src/com/example/android/actionbarcompat/listpopupmenu/tests/SampleTests.java
@@ -1,22 +1,4 @@
 /*
-* Copyright 2013 The Android Open Source Project
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-
-
-/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
@@ -43,7 +25,7 @@
 public class SampleTests extends ActivityInstrumentationTestCase2<MainActivity> {
 
     private MainActivity mTestActivity;
-    private ListPopupMenuFragment mTestFragment;
+    private PopupListFragment mTestFragment;
 
     public SampleTests() {
         super(MainActivity.class);
@@ -58,8 +40,8 @@
         // flags = {@link Intent#FLAG_ACTIVITY_NEW_TASK}
         // All other fields are null or empty.
         mTestActivity = getActivity();
-        mTestFragment = (ListPopupMenuFragment)
-            mTestActivity.getSupportFragmentManager().getFragments().get(1);
+        mTestFragment = (PopupListFragment)
+            mTestActivity.getSupportFragmentManager().getFragments().get(0);
     }
 
     /**
@@ -76,4 +58,4 @@
     * Add more tests below.
     */
 
-}
\ No newline at end of file
+}
diff --git a/ui/actionbarcompat/ActionBarCompat-ListViewModalSelect/Application/tests/AndroidManifest.xml b/ui/actionbarcompat/ActionBarCompat-ListViewModalSelect/Application/tests/AndroidManifest.xml
index 979b955..2d6482b 100644
--- a/ui/actionbarcompat/ActionBarCompat-ListViewModalSelect/Application/tests/AndroidManifest.xml
+++ b/ui/actionbarcompat/ActionBarCompat-ListViewModalSelect/Application/tests/AndroidManifest.xml
@@ -1,22 +1,3 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright 2013 The Android Open Source Project
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
-     http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-
-
-
 <?xml version="1.0" encoding="utf-8"?>
 <!--
   Copyright (C) 2013 The Android Open Source Project
@@ -56,4 +37,4 @@
             android:targetPackage="com.example.android.actionbarcompat.listviewmodalselect"
             android:label="Tests for com.example.android.actionbarcompat.listviewmodalselect" />
 
-</manifest>
\ No newline at end of file
+</manifest>
diff --git a/ui/actionbarcompat/ActionBarCompat-ListViewModalSelect/Application/tests/src/com/example/android/actionbarcompat/listviewmodalselect/tests/SampleTests.java b/ui/actionbarcompat/ActionBarCompat-ListViewModalSelect/Application/tests/src/com/example/android/actionbarcompat/listviewmodalselect/tests/SampleTests.java
index 9e592f5..a6ee4ae 100644
--- a/ui/actionbarcompat/ActionBarCompat-ListViewModalSelect/Application/tests/src/com/example/android/actionbarcompat/listviewmodalselect/tests/SampleTests.java
+++ b/ui/actionbarcompat/ActionBarCompat-ListViewModalSelect/Application/tests/src/com/example/android/actionbarcompat/listviewmodalselect/tests/SampleTests.java
@@ -1,22 +1,4 @@
 /*
-* Copyright 2013 The Android Open Source Project
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-
-
-/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
@@ -43,7 +25,7 @@
 public class SampleTests extends ActivityInstrumentationTestCase2<MainActivity> {
 
     private MainActivity mTestActivity;
-    private ActionBarCompat-ListViewModalSelectFragment mTestFragment;
+    private CheeseListFragment mTestFragment;
 
     public SampleTests() {
         super(MainActivity.class);
@@ -58,8 +40,8 @@
         // flags = {@link Intent#FLAG_ACTIVITY_NEW_TASK}
         // All other fields are null or empty.
         mTestActivity = getActivity();
-        mTestFragment = (ActionBarCompat-ListViewModalSelectFragment)
-            mTestActivity.getSupportFragmentManager().getFragments().get(1);
+        mTestFragment = (CheeseListFragment)
+            mTestActivity.getSupportFragmentManager().getFragments().get(0);
     }
 
     /**
@@ -76,4 +58,4 @@
     * Add more tests below.
     */
 
-}
\ No newline at end of file
+}
diff --git a/ui/actionbarcompat/ActionBarCompat-ShareActionProvider/Application/tests/src/com/example/android/actionbarcompat/shareactionprovider/tests/SampleTests.java b/ui/actionbarcompat/ActionBarCompat-ShareActionProvider/Application/tests/src/com/example/android/actionbarcompat/shareactionprovider/tests/SampleTests.java
index e655bcf..2d56881 100644
--- a/ui/actionbarcompat/ActionBarCompat-ShareActionProvider/Application/tests/src/com/example/android/actionbarcompat/shareactionprovider/tests/SampleTests.java
+++ b/ui/actionbarcompat/ActionBarCompat-ShareActionProvider/Application/tests/src/com/example/android/actionbarcompat/shareactionprovider/tests/SampleTests.java
@@ -1,22 +1,4 @@
 /*
-* Copyright 2013 The Android Open Source Project
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-
-
-/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
@@ -43,7 +25,6 @@
 public class SampleTests extends ActivityInstrumentationTestCase2<MainActivity> {
 
     private MainActivity mTestActivity;
-    private ShareActionProviderFragment mTestFragment;
 
     public SampleTests() {
         super(MainActivity.class);
@@ -58,8 +39,6 @@
         // flags = {@link Intent#FLAG_ACTIVITY_NEW_TASK}
         // All other fields are null or empty.
         mTestActivity = getActivity();
-        mTestFragment = (ShareActionProviderFragment)
-            mTestActivity.getSupportFragmentManager().getFragments().get(1);
     }
 
     /**
@@ -69,11 +48,10 @@
         //Try to add a message to add context to your assertions. These messages will be shown if
         //a tests fails and make it easy to understand why a test failed
         assertNotNull("mTestActivity is null", mTestActivity);
-        assertNotNull("mTestFragment is null", mTestFragment);
     }
 
     /**
     * Add more tests below.
     */
 
-}
\ No newline at end of file
+}
diff --git a/ui/actionbarcompat/ActionBarCompat-Styled/Application/tests/src/com/example/android/actionbarcompat/styled/tests/SampleTests.java b/ui/actionbarcompat/ActionBarCompat-Styled/Application/tests/src/com/example/android/actionbarcompat/styled/tests/SampleTests.java
index 204afdc..1e99f20 100644
--- a/ui/actionbarcompat/ActionBarCompat-Styled/Application/tests/src/com/example/android/actionbarcompat/styled/tests/SampleTests.java
+++ b/ui/actionbarcompat/ActionBarCompat-Styled/Application/tests/src/com/example/android/actionbarcompat/styled/tests/SampleTests.java
@@ -1,22 +1,4 @@
 /*
-* Copyright 2013 The Android Open Source Project
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-
-
-/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
@@ -43,7 +25,6 @@
 public class SampleTests extends ActivityInstrumentationTestCase2<MainActivity> {
 
     private MainActivity mTestActivity;
-    private StyledFragment mTestFragment;
 
     public SampleTests() {
         super(MainActivity.class);
@@ -58,8 +39,6 @@
         // flags = {@link Intent#FLAG_ACTIVITY_NEW_TASK}
         // All other fields are null or empty.
         mTestActivity = getActivity();
-        mTestFragment = (StyledFragment)
-            mTestActivity.getSupportFragmentManager().getFragments().get(1);
     }
 
     /**
@@ -69,11 +48,10 @@
         //Try to add a message to add context to your assertions. These messages will be shown if
         //a tests fails and make it easy to understand why a test failed
         assertNotNull("mTestActivity is null", mTestActivity);
-        assertNotNull("mTestFragment is null", mTestFragment);
     }
 
     /**
     * Add more tests below.
     */
 
-}
\ No newline at end of file
+}
diff --git a/ui/activityscenetransition/ActivitySceneTransitionBasic/Application/tests/src/com/example/android/activityscenetransitionbasic/tests/SampleTests.java b/ui/activityscenetransition/ActivitySceneTransitionBasic/Application/tests/src/com/example/android/activityscenetransitionbasic/tests/SampleTests.java
index f06d1ae..09dd1a1 100644
--- a/ui/activityscenetransition/ActivitySceneTransitionBasic/Application/tests/src/com/example/android/activityscenetransitionbasic/tests/SampleTests.java
+++ b/ui/activityscenetransition/ActivitySceneTransitionBasic/Application/tests/src/com/example/android/activityscenetransitionbasic/tests/SampleTests.java
@@ -25,7 +25,6 @@
 public class SampleTests extends ActivityInstrumentationTestCase2<MainActivity> {
 
     private MainActivity mTestActivity;
-    private ActivitySceneTransitionBasicFragment mTestFragment;
 
     public SampleTests() {
         super(MainActivity.class);
@@ -40,8 +39,6 @@
         // flags = {@link Intent#FLAG_ACTIVITY_NEW_TASK}
         // All other fields are null or empty.
         mTestActivity = getActivity();
-        mTestFragment = (ActivitySceneTransitionBasicFragment)
-            mTestActivity.getSupportFragmentManager().getFragments().get(1);
     }
 
     /**
@@ -51,7 +48,6 @@
         //Try to add a message to add context to your assertions. These messages will be shown if
         //a tests fails and make it easy to understand why a test failed
         assertNotNull("mTestActivity is null", mTestActivity);
-        assertNotNull("mTestFragment is null", mTestFragment);
     }
 
     /**
diff --git a/ui/activitytasks/DocumentCentricApps/Application/src/main/res/drawable-hdpi/ic_launcher.png b/ui/activitytasks/DocumentCentricApps/Application/src/main/res/drawable-hdpi/ic_launcher.png
index b1efaf4..15e44c5 100644
--- a/ui/activitytasks/DocumentCentricApps/Application/src/main/res/drawable-hdpi/ic_launcher.png
+++ b/ui/activitytasks/DocumentCentricApps/Application/src/main/res/drawable-hdpi/ic_launcher.png
Binary files differ
diff --git a/ui/activitytasks/DocumentCentricApps/Application/src/main/res/drawable-mdpi/ic_launcher.png b/ui/activitytasks/DocumentCentricApps/Application/src/main/res/drawable-mdpi/ic_launcher.png
index f5f9244..ba0bd22 100644
--- a/ui/activitytasks/DocumentCentricApps/Application/src/main/res/drawable-mdpi/ic_launcher.png
+++ b/ui/activitytasks/DocumentCentricApps/Application/src/main/res/drawable-mdpi/ic_launcher.png
Binary files differ
diff --git a/ui/activitytasks/DocumentCentricApps/Application/src/main/res/drawable-xhdpi/ic_launcher.png b/ui/activitytasks/DocumentCentricApps/Application/src/main/res/drawable-xhdpi/ic_launcher.png
index 5d07b3f..42d49b8 100644
--- a/ui/activitytasks/DocumentCentricApps/Application/src/main/res/drawable-xhdpi/ic_launcher.png
+++ b/ui/activitytasks/DocumentCentricApps/Application/src/main/res/drawable-xhdpi/ic_launcher.png
Binary files differ
diff --git a/ui/activitytasks/DocumentCentricApps/Application/src/main/res/drawable-xxhdpi/ic_launcher.png b/ui/activitytasks/DocumentCentricApps/Application/src/main/res/drawable-xxhdpi/ic_launcher.png
index 6ef21e1..3624eef 100644
--- a/ui/activitytasks/DocumentCentricApps/Application/src/main/res/drawable-xxhdpi/ic_launcher.png
+++ b/ui/activitytasks/DocumentCentricApps/Application/src/main/res/drawable-xxhdpi/ic_launcher.png
Binary files differ
diff --git a/ui/activitytasks/DocumentCentricApps/screenshots/1-activity.png b/ui/activitytasks/DocumentCentricApps/screenshots/1-activity.png
new file mode 100644
index 0000000..9c6c411
--- /dev/null
+++ b/ui/activitytasks/DocumentCentricApps/screenshots/1-activity.png
Binary files differ
diff --git a/ui/activitytasks/DocumentCentricApps/screenshots/2-overview.png b/ui/activitytasks/DocumentCentricApps/screenshots/2-overview.png
new file mode 100644
index 0000000..36ad9df
--- /dev/null
+++ b/ui/activitytasks/DocumentCentricApps/screenshots/2-overview.png
Binary files differ
diff --git a/ui/activitytasks/DocumentCentricApps/screenshots/big_icon.png b/ui/activitytasks/DocumentCentricApps/screenshots/big_icon.png
new file mode 100644
index 0000000..84ce4cf
--- /dev/null
+++ b/ui/activitytasks/DocumentCentricApps/screenshots/big_icon.png
Binary files differ
diff --git a/ui/activitytasks/DocumentCentricApps/template-params.xml b/ui/activitytasks/DocumentCentricApps/template-params.xml
index 589e9f1..0df82b9 100644
--- a/ui/activitytasks/DocumentCentricApps/template-params.xml
+++ b/ui/activitytasks/DocumentCentricApps/template-params.xml
@@ -15,8 +15,6 @@
  limitations under the License.
 -->
 
-
-
 <sample>
     <name>DocumentCentricRecents</name>
     <group>UI</group>
@@ -38,4 +36,44 @@
 
     <template src="base"/>
 
+<metadata>
+    <status>PUBLISHED</status>
+    <categories>UI</categories>
+    <technologies>Android</technologies>
+    <languages>Java</languages>
+    <solutions>Mobile</solutions>
+    <level>INTERMEDIATE</level>
+    <icon>screenshots/big_icon.png</icon>
+    <screenshots>
+        <img>screenshots/1-activity.png</img>
+        <img>screenshots/2-overview.png</img>
+    </screenshots>
+    <api_refs>
+        <android>android.app.Activity</android>
+        <android>android.content.Intent.FLAG_ACTIVITY_NEW_DOCUMENT</android>
+    </api_refs>
+    <description>
+<![CDATA[
+Sample demonstrating the basic usage of the new 'Document Centric Apps' API.
+It let's you create new documents in the system overview menu and persists its
+state through reboots.
+]]>
+    </description>
+    <intro>
+<![CDATA[
+This sample shows the basic usage of the new Document-Centric Apps API. The new
+API modifies the meaning of the Intent#FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET flag, which is
+now deprecated. In versions before L it serves to define a boundary between the main task and a
+subtask. The subtask holds a different thumbnail and all activities in it are finished when the
+task is reset. In L this flag causes a full break with the task that launched it. As such it has
+been renamed to Intent#FLAG_ACTIVITY_NEW_DOCUMENT.
+
+This sample mainly uses Intent flags in code. But Activities can also specify in their manifests
+that they shall always be launched into a new task in the above manner using the new activity
+attribute documentLaunchMode which may take on one of three values, “intoExisting” equivalent to
+NEW_DOCUMENT, “always” equivalent to NEW_DOCUMENT | MULTIPLE_TASK, “none” the default, and
+“never” which will negate the effect of any attempt to launch the activity with NEW_DOCUMENT.
+]]>
+    </intro>
+</metadata>
 </sample>
diff --git a/ui/graphics/DisplayingBitmaps/Application/tests/AndroidManifest.xml b/ui/graphics/DisplayingBitmaps/Application/tests/AndroidManifest.xml
index a93e21f..779a3e3 100644
--- a/ui/graphics/DisplayingBitmaps/Application/tests/AndroidManifest.xml
+++ b/ui/graphics/DisplayingBitmaps/Application/tests/AndroidManifest.xml
@@ -1,22 +1,3 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright 2013 The Android Open Source Project
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
-     http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-
-
-
 <?xml version="1.0" encoding="utf-8"?>
 <!--
   Copyright (C) 2013 The Android Open Source Project
@@ -56,4 +37,4 @@
             android:targetPackage="com.example.android.displayingbitmaps"
             android:label="Tests for com.example.android.displayingbitmaps" />
 
-</manifest>
\ No newline at end of file
+</manifest>
diff --git a/ui/graphics/DisplayingBitmaps/Application/tests/src/com/example/android/displayingbitmaps/tests/SampleTests.java b/ui/graphics/DisplayingBitmaps/Application/tests/src/com/example/android/displayingbitmaps/tests/SampleTests.java
index f295856..2d2ca68 100644
--- a/ui/graphics/DisplayingBitmaps/Application/tests/src/com/example/android/displayingbitmaps/tests/SampleTests.java
+++ b/ui/graphics/DisplayingBitmaps/Application/tests/src/com/example/android/displayingbitmaps/tests/SampleTests.java
@@ -1,22 +1,4 @@
 /*
-* Copyright 2013 The Android Open Source Project
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-
-
-/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
@@ -33,20 +15,19 @@
 */
 package com.example.android.displayingbitmaps.tests;
 
-import com.example.android.displayingbitmaps.*;
+import com.example.android.displayingbitmaps.ui.ImageGridActivity;
 
 import android.test.ActivityInstrumentationTestCase2;
 
 /**
 * Tests for DisplayingBitmaps sample.
 */
-public class SampleTests extends ActivityInstrumentationTestCase2<MainActivity> {
+public class SampleTests extends ActivityInstrumentationTestCase2<ImageGridActivity> {
 
-    private MainActivity mTestActivity;
-    private DisplayingBitmapsFragment mTestFragment;
+    private ImageGridActivity mTestActivity;
 
     public SampleTests() {
-        super(MainActivity.class);
+        super(ImageGridActivity.class);
     }
 
     @Override
@@ -58,8 +39,6 @@
         // flags = {@link Intent#FLAG_ACTIVITY_NEW_TASK}
         // All other fields are null or empty.
         mTestActivity = getActivity();
-        mTestFragment = (DisplayingBitmapsFragment)
-            mTestActivity.getSupportFragmentManager().getFragments().get(1);
     }
 
     /**
@@ -69,11 +48,10 @@
         //Try to add a message to add context to your assertions. These messages will be shown if
         //a tests fails and make it easy to understand why a test failed
         assertNotNull("mTestActivity is null", mTestActivity);
-        assertNotNull("mTestFragment is null", mTestFragment);
     }
 
     /**
     * Add more tests below.
     */
 
-}
\ No newline at end of file
+}
diff --git a/ui/holo/BorderlessButtons/Application/src/main/res/drawable-hdpi/ic_launcher.png b/ui/holo/BorderlessButtons/Application/src/main/res/drawable-hdpi/ic_launcher.png
index b1efaf4..bb97e43 100644
--- a/ui/holo/BorderlessButtons/Application/src/main/res/drawable-hdpi/ic_launcher.png
+++ b/ui/holo/BorderlessButtons/Application/src/main/res/drawable-hdpi/ic_launcher.png
Binary files differ
diff --git a/ui/holo/BorderlessButtons/Application/src/main/res/drawable-mdpi/ic_launcher.png b/ui/holo/BorderlessButtons/Application/src/main/res/drawable-mdpi/ic_launcher.png
index f5f9244..4ee8ad3 100644
--- a/ui/holo/BorderlessButtons/Application/src/main/res/drawable-mdpi/ic_launcher.png
+++ b/ui/holo/BorderlessButtons/Application/src/main/res/drawable-mdpi/ic_launcher.png
Binary files differ
diff --git a/ui/holo/BorderlessButtons/Application/src/main/res/drawable-xhdpi/ic_launcher.png b/ui/holo/BorderlessButtons/Application/src/main/res/drawable-xhdpi/ic_launcher.png
index 5d07b3f..b3b78e9 100644
--- a/ui/holo/BorderlessButtons/Application/src/main/res/drawable-xhdpi/ic_launcher.png
+++ b/ui/holo/BorderlessButtons/Application/src/main/res/drawable-xhdpi/ic_launcher.png
Binary files differ
diff --git a/ui/holo/BorderlessButtons/Application/src/main/res/drawable-xxhdpi/ic_launcher.png b/ui/holo/BorderlessButtons/Application/src/main/res/drawable-xxhdpi/ic_launcher.png
index 6ef21e1..82a4165 100644
--- a/ui/holo/BorderlessButtons/Application/src/main/res/drawable-xxhdpi/ic_launcher.png
+++ b/ui/holo/BorderlessButtons/Application/src/main/res/drawable-xxhdpi/ic_launcher.png
Binary files differ
diff --git a/ui/holo/BorderlessButtons/README.md b/ui/holo/BorderlessButtons/README.md
index 7db92f5..3177580 100644
--- a/ui/holo/BorderlessButtons/README.md
+++ b/ui/holo/BorderlessButtons/README.md
@@ -1,16 +1,37 @@
 Android BorderlessButtons Sample
-==============================
+===================================
 
-This sample demonstrates the use of borderless buttons, bottom button bars
-(OK and Cancel) and dividers to establish visual structure.
+This sample demonstrates the borderless button styling from the Holo visual language.
+Styling is applied in the XML resource layout definitions, referecing the styling attributes
+from the Holo theme.
+
+Introduction
+------------
+
+This sample shows how to style widgets in an Activity using [borderless elements][1].
+This includes a ListView with custom rows and buttons, using dividing lines to create
+visual separatation.
+
+Style definitions are provided by the Holo theme, which includes references to the 
+'?android:buttonBarButtonStyle' for buttons and references to the appropriate divider 
+attribute and style 'android:dividerVertical'.
+
+Styles are directly applied to widgets in their XML layout definitions.
+
+[1]: http://developer.android.com/design/building-blocks/buttons.html#borderless
 
 Pre-requisites
 --------------
 
-- Android SDK v20
-- Android Build Tools v20
+- Android SDK v21
+- Android Build Tools v21.1.1
 - Android Support Repository
 
+Screenshots
+-------------
+
+<img src="screenshots/1-activity.png" height="400" alt="Screenshot"/> 
+
 Getting Started
 ---------------
 
@@ -41,7 +62,7 @@
 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
+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
diff --git a/ui/holo/BorderlessButtons/screenshots/1-activity.png.png b/ui/holo/BorderlessButtons/screenshots/1-activity.png.png
new file mode 100644
index 0000000..6b85b13
--- /dev/null
+++ b/ui/holo/BorderlessButtons/screenshots/1-activity.png.png
Binary files differ
diff --git a/ui/holo/BorderlessButtons/screenshots/big_icon.png b/ui/holo/BorderlessButtons/screenshots/big_icon.png
new file mode 100644
index 0000000..b0fae79
--- /dev/null
+++ b/ui/holo/BorderlessButtons/screenshots/big_icon.png
Binary files differ
diff --git a/ui/holo/BorderlessButtons/template-params.xml b/ui/holo/BorderlessButtons/template-params.xml
index c0d9aeb..09274c1 100644
--- a/ui/holo/BorderlessButtons/template-params.xml
+++ b/ui/holo/BorderlessButtons/template-params.xml
@@ -34,4 +34,44 @@
     <template src="base"/>
     <common src="logger"/>
 
+<metadata>
+    <status>PUBLISHED</status>
+    <categories>Design, UI</categories>
+    <technologies>Android</technologies>
+    <languages>Java</languages>
+    <solutions>Mobile</solutions>
+    <level>INTERMEDIATE</level>
+    <icon>screenshots/big_icon.png</icon>
+    <screenshots>
+        <img>screenshots/1-activity.png</img>
+    </screenshots>
+    <api_refs>
+        <android>android.widget.Button</android>
+        <android>android.widget.ListView</android>
+        <android>android.app.ListActivity</android>
+    </api_refs>
+
+    <description>
+<![CDATA[
+This sample demonstrates the borderless button styling from the Holo visual language.
+Styling is applied in the XML resource layout definitions, referecing the styling attributes
+from the Holo theme.
+]]>
+    </description>
+    <intro>
+<![CDATA[
+This sample shows how to style widgets in an Activity using [borderless elements][1].
+This includes a ListView with custom rows and buttons, using dividing lines to create
+visual separatation.
+
+Style definitions are provided by the Holo theme, which includes references to the 
+'?android:buttonBarButtonStyle' for buttons and references to the appropriate divider 
+attribute and style 'android:dividerVertical'.
+
+Styles are directly applied to widgets in their XML layout definitions.
+
+[1]: http://developer.android.com/design/building-blocks/buttons.html#borderless
+]]>
+    </intro>
+</metadata>
 </sample>
diff --git a/ui/lists/CustomChoiceList/screenshots/icon-web.png b/ui/lists/CustomChoiceList/screenshots/icon-web.png
new file mode 100644
index 0000000..9e61e21
--- /dev/null
+++ b/ui/lists/CustomChoiceList/screenshots/icon-web.png
Binary files differ
diff --git a/ui/lists/CustomChoiceList/screenshots/main.png b/ui/lists/CustomChoiceList/screenshots/main.png
new file mode 100644
index 0000000..f52ee6d
--- /dev/null
+++ b/ui/lists/CustomChoiceList/screenshots/main.png
Binary files differ
diff --git a/ui/lists/CustomChoiceList/template-params.xml b/ui/lists/CustomChoiceList/template-params.xml
index 407aa0b..35626fc 100644
--- a/ui/lists/CustomChoiceList/template-params.xml
+++ b/ui/lists/CustomChoiceList/template-params.xml
@@ -34,4 +34,66 @@
     <template src="base"/>
     <common src="logger"/>
 
+
+    <metadata>
+        <status>PUBLISHED</status>
+        <categories>Widgets</categories>
+        <technologies>Android</technologies>
+        <languages>Java</languages>
+        <solutions>Mobile</solutions>
+        <level>BEGINNER</level>
+        <icon>screenshots/icon-web.png</icon>
+        <screenshots>
+            <img>screenshots/1-main.png</img>
+            <img>screenshots/2-settings.png</img>
+        </screenshots>
+        <api_refs>
+            <android>android.widget.Checkable</android>
+            <android>android.widget.ListView</android>
+        </api_refs>
+
+        <description>
+<![CDATA[
+This sample demonstrates how to create custom checkable layouts, for use with ListView's choiceMode
+attribute.
+]]>
+        </description>
+
+        <!-- Multi-paragraph introduction to sample, from an educational point-of-view.
+        Makrdown formatting allowed. This will be used to generate a mini-article for the
+        sample on DAC. -->
+        <intro>
+<![CDATA[
+This sample demonstrates how to create custom single- or multi-choice [ListView][1] UIs on Android.
+
+When a ListView has a `android:choiceMode` attribute set, it will allow users to "choose" one or more items. For
+exmaple, refer to `res/layout/sample_main.xml` in this project:
+
+```xml
+<ListView android:id="@android:id/list"
+    android:layout_width="match_parent"
+    android:layout_height="0dp"
+    android:layout_weight="1"
+    android:paddingLeft="@dimen/page_margin"
+    android:paddingRight="@dimen/page_margin"
+    android:scrollbarStyle="outsideOverlay"
+    android:choiceMode="multipleChoice" />
+```
+
+The framework provides these default list item layouts that show standard radio buttons or check boxes next to a single
+line of text:
+
+- android.R.layout.simple_list_item_single_choice
+- android.R.layout.simple_list_item_multiple_choice.
+
+In some cases, you may want to customize this layout. When doing so, the root view must implement the Checkable
+interface. For an example, see this sample's `CheckableLinearLayout` class.
+
+Lastly, remember to use padding on your ListViews to adhere to the standard metrics described in the Android Design
+guidelines. When doing so, you should set the `android:scrollbarStyle` attribute such that the scrollbar doesn't inset.
+
+[1]: http://developer.android.com/reference/android/widget/ListView.html
+]]>
+        </intro>
+    </metadata>
 </sample>
diff --git a/ui/views/CardView/Application/tests/AndroidManifest.xml b/ui/views/CardView/Application/tests/AndroidManifest.xml
index 92cfd40..8f1171d 100644
--- a/ui/views/CardView/Application/tests/AndroidManifest.xml
+++ b/ui/views/CardView/Application/tests/AndroidManifest.xml
@@ -34,7 +34,6 @@
     -->
     <instrumentation
         android:name="android.test.InstrumentationTestRunner"
-        android:label="Tests for CardView sample"
         android:targetPackage="com.example.android.cardview"/>
 
-</manifest>
\ No newline at end of file
+</manifest>
diff --git a/ui/views/Elevation/ElevationBasic/screenshots/fixed.png b/ui/views/Elevation/ElevationBasic/screenshots/fixed.png
new file mode 100644
index 0000000..9864b90
--- /dev/null
+++ b/ui/views/Elevation/ElevationBasic/screenshots/fixed.png
Binary files differ
diff --git a/ui/views/Elevation/ElevationBasic/screenshots/icon-web.png b/ui/views/Elevation/ElevationBasic/screenshots/icon-web.png
new file mode 100644
index 0000000..7f2dbe5
--- /dev/null
+++ b/ui/views/Elevation/ElevationBasic/screenshots/icon-web.png
Binary files differ
diff --git a/ui/views/Elevation/ElevationBasic/screenshots/raised.png b/ui/views/Elevation/ElevationBasic/screenshots/raised.png
new file mode 100644
index 0000000..af81493
--- /dev/null
+++ b/ui/views/Elevation/ElevationBasic/screenshots/raised.png
Binary files differ
diff --git a/ui/views/Elevation/ElevationBasic/template-params.xml b/ui/views/Elevation/ElevationBasic/template-params.xml
index 3ef4ec2..bcaa253 100644
--- a/ui/views/Elevation/ElevationBasic/template-params.xml
+++ b/ui/views/Elevation/ElevationBasic/template-params.xml
@@ -44,5 +44,59 @@
     <template src="FragmentView"/>
     <common src="logger"/>
     <common src="activities"/>
+    <metadata>
+        <status>PUBLISHED</status>
+        <categories>UI, Input</categories>
+        <technologies>Android</technologies>
+        <languages>Java</languages>
+        <solutions>Mobile</solutions>
+        <level>BEGINNER</level>
+        <icon>screenshots/icon-web.png</icon>
+        <screenshots>
+            <img>screenshots/fixed.png</img>
+            <img>screenshots/raised.png</img>
+        </screenshots>
+        <api_refs>
+            <android>android.view.MotionEvent</android>
+        </api_refs>
+        <description>
+<![CDATA[
+This sample demonstrates ways to move a view in the z-axis using
+`setTranslationZ()`. This method was introduced in API Level 21 ('Lollipop').
+]]>
+        </description>
+        <intro>
+<![CDATA[
+This sample uses two shapes, a circle and a square, and it demonstrates two
+alternative ways to move a view in the z-axis. The first shape, the circle,
+has a fixed elevation, which is defined in XML. The second view, the square,
+changes its elevation using [setTranslationZ()][1] when a user touches it:
 
+    shape2.setOnTouchListener(new View.OnTouchListener() {
+        @Override
+        public boolean onTouch(View view, MotionEvent motionEvent) {
+            int action = motionEvent.getActionMasked();
+            /* Raise view on ACTION_DOWN and lower it on ACTION_UP. */
+            switch (action) {
+                case MotionEvent.ACTION_DOWN:
+                    Log.d(TAG, "ACTION_DOWN on view.");
+                    view.setTranslationZ(120);
+                    break;
+                case MotionEvent.ACTION_UP:
+                    Log.d(TAG, "ACTION_UP on view.");
+                    view.setTranslationZ(0);
+                    break;
+                default:
+                    return false;
+            }
+            return true;
+        }
+    });
+
+The elevation reverts back once the touch is removed.
+
+[1]: https://developer.android.com/training/material/shadows-clipping.html#Elevation
+]]>
+        </intro>
+    </metadata>
 </sample>
diff --git a/ui/views/Elevation/ElevationDrag/Application/tests/AndroidManifest.xml b/ui/views/Elevation/ElevationDrag/Application/tests/AndroidManifest.xml
index 60c9a19..fdde8fa 100644
--- a/ui/views/Elevation/ElevationDrag/Application/tests/AndroidManifest.xml
+++ b/ui/views/Elevation/ElevationDrag/Application/tests/AndroidManifest.xml
@@ -1,22 +1,3 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright 2013 The Android Open Source Project
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
-     http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-
-
-
 <?xml version="1.0" encoding="utf-8"?>
 <!--
   Copyright (C) 2013 The Android Open Source Project
@@ -56,4 +37,4 @@
             android:targetPackage="com.example.android.elevationdrag"
             android:label="Tests for com.example.android.elevationdrag" />
 
-</manifest>
\ No newline at end of file
+</manifest>
diff --git a/ui/views/Elevation/ElevationDrag/Application/tests/src/com/example/android/elevationdrag/tests/SampleTests.java b/ui/views/Elevation/ElevationDrag/Application/tests/src/com/example/android/elevationdrag/tests/SampleTests.java
index 5e7acc0..4727233 100644
--- a/ui/views/Elevation/ElevationDrag/Application/tests/src/com/example/android/elevationdrag/tests/SampleTests.java
+++ b/ui/views/Elevation/ElevationDrag/Application/tests/src/com/example/android/elevationdrag/tests/SampleTests.java
@@ -1,22 +1,4 @@
 /*
-* Copyright 2013 The Android Open Source Project
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-
-
-/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
@@ -110,4 +92,4 @@
             }
         });
     }
-}
\ No newline at end of file
+}
diff --git a/ui/views/FloatingActionButton/FloatingActionButtonBasic/Application/tests/src/com/example/android/floatingactionbuttonbasic/tests/SampleTests.java b/ui/views/FloatingActionButton/FloatingActionButtonBasic/Application/tests/src/com/example/android/floatingactionbuttonbasic/tests/SampleTests.java
index a900485..976e71c 100644
--- a/ui/views/FloatingActionButton/FloatingActionButtonBasic/Application/tests/src/com/example/android/floatingactionbuttonbasic/tests/SampleTests.java
+++ b/ui/views/FloatingActionButton/FloatingActionButtonBasic/Application/tests/src/com/example/android/floatingactionbuttonbasic/tests/SampleTests.java
@@ -17,16 +17,17 @@
 package com.example.android.floatingactionbuttonbasic.tests;
 
 import com.example.android.floatingactionbuttonbasic.*;
+import com.example.android.common.logger.LogFragment;
 
 import android.test.ActivityInstrumentationTestCase2;
 
 /**
-* Tests for FloatingActionButtonBasic sample.
+* Tests for FloatingActionButton sample.
 */
 public class SampleTests extends ActivityInstrumentationTestCase2<MainActivity> {
 
     private MainActivity mTestActivity;
-    private FloatingActionButton mTestFragment;
+    private LogFragment mTestFragment;
 
     public SampleTests() {
         super(MainActivity.class);
@@ -41,8 +42,8 @@
         // flags = {@link Intent#FLAG_ACTIVITY_NEW_TASK}
         // All other fields are null or empty.
         mTestActivity = getActivity();
-        mTestFragment = (FloatingActionButton)
-            mTestActivity.getSupportFragmentManager().getFragments().get(1);
+        mTestFragment = (LogFragment)
+            mTestActivity.getSupportFragmentManager().getFragments().get(0);
     }
 
     /**
@@ -59,4 +60,4 @@
     * Add more tests below.
     */
 
-}
\ No newline at end of file
+}
diff --git a/ui/views/HorizontalPaging/Application/tests/src/com/example/android/horizontalpaging/tests/SampleTests.java b/ui/views/HorizontalPaging/Application/tests/src/com/example/android/horizontalpaging/tests/SampleTests.java
index 206eea9..ba4d76c 100644
--- a/ui/views/HorizontalPaging/Application/tests/src/com/example/android/horizontalpaging/tests/SampleTests.java
+++ b/ui/views/HorizontalPaging/Application/tests/src/com/example/android/horizontalpaging/tests/SampleTests.java
@@ -1,22 +1,4 @@
 /*
-* Copyright 2013 The Android Open Source Project
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-
-
-/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
@@ -43,7 +25,6 @@
 public class SampleTests extends ActivityInstrumentationTestCase2<MainActivity> {
 
     private MainActivity mTestActivity;
-    private HorizontalPagingFragment mTestFragment;
 
     public SampleTests() {
         super(MainActivity.class);
@@ -58,8 +39,6 @@
         // flags = {@link Intent#FLAG_ACTIVITY_NEW_TASK}
         // All other fields are null or empty.
         mTestActivity = getActivity();
-        mTestFragment = (HorizontalPagingFragment)
-            mTestActivity.getSupportFragmentManager().getFragments().get(1);
     }
 
     /**
@@ -69,11 +48,10 @@
         //Try to add a message to add context to your assertions. These messages will be shown if
         //a tests fails and make it easy to understand why a test failed
         assertNotNull("mTestActivity is null", mTestActivity);
-        assertNotNull("mTestFragment is null", mTestFragment);
     }
 
     /**
     * Add more tests below.
     */
 
-}
\ No newline at end of file
+}
diff --git a/ui/views/NavigationDrawer/Application/tests/AndroidManifest.xml b/ui/views/NavigationDrawer/Application/tests/AndroidManifest.xml
index 6a651a5..6c32f27 100644
--- a/ui/views/NavigationDrawer/Application/tests/AndroidManifest.xml
+++ b/ui/views/NavigationDrawer/Application/tests/AndroidManifest.xml
@@ -1,22 +1,3 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright 2013 The Android Open Source Project
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
-     http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-
-
-
 <?xml version="1.0" encoding="utf-8"?>
 <!--
   Copyright (C) 2013 The Android Open Source Project
@@ -56,4 +37,4 @@
             android:targetPackage="com.example.android.navigationdrawer"
             android:label="Tests for com.example.android.navigationdrawer" />
 
-</manifest>
\ No newline at end of file
+</manifest>
diff --git a/ui/views/NavigationDrawer/Application/tests/src/com/example/android/navigationdrawer/tests/SampleTests.java b/ui/views/NavigationDrawer/Application/tests/src/com/example/android/navigationdrawer/tests/SampleTests.java
index eca6b61..e945d2c 100644
--- a/ui/views/NavigationDrawer/Application/tests/src/com/example/android/navigationdrawer/tests/SampleTests.java
+++ b/ui/views/NavigationDrawer/Application/tests/src/com/example/android/navigationdrawer/tests/SampleTests.java
@@ -1,22 +1,4 @@
 /*
-* Copyright 2013 The Android Open Source Project
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-
-
-/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
@@ -40,13 +22,12 @@
 /**
 * Tests for NavigationDrawer sample.
 */
-public class SampleTests extends ActivityInstrumentationTestCase2<MainActivity> {
+public class SampleTests extends ActivityInstrumentationTestCase2<NavigationDrawerActivity> {
 
-    private MainActivity mTestActivity;
-    private NavigationDrawerFragment mTestFragment;
+    private NavigationDrawerActivity mTestActivity;
 
     public SampleTests() {
-        super(MainActivity.class);
+        super(NavigationDrawerActivity.class);
     }
 
     @Override
@@ -58,8 +39,6 @@
         // flags = {@link Intent#FLAG_ACTIVITY_NEW_TASK}
         // All other fields are null or empty.
         mTestActivity = getActivity();
-        mTestFragment = (NavigationDrawerFragment)
-            mTestActivity.getSupportFragmentManager().getFragments().get(1);
     }
 
     /**
@@ -69,11 +48,10 @@
         //Try to add a message to add context to your assertions. These messages will be shown if
         //a tests fails and make it easy to understand why a test failed
         assertNotNull("mTestActivity is null", mTestActivity);
-        assertNotNull("mTestFragment is null", mTestFragment);
     }
 
     /**
     * Add more tests below.
     */
 
-}
\ No newline at end of file
+}
diff --git a/ui/views/RevealEffect/RevealEffectBasic/Application/tests/AndroidManifest.xml b/ui/views/RevealEffect/RevealEffectBasic/Application/tests/AndroidManifest.xml
index a0d25c1..07e8dea 100644
--- a/ui/views/RevealEffect/RevealEffectBasic/Application/tests/AndroidManifest.xml
+++ b/ui/views/RevealEffect/RevealEffectBasic/Application/tests/AndroidManifest.xml
@@ -1,22 +1,3 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright 2013 The Android Open Source Project
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
-     http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-
-
-
 <?xml version="1.0" encoding="utf-8"?>
 <!--
   Copyright (C) 2013 The Android Open Source Project
@@ -56,4 +37,4 @@
             android:targetPackage="com.example.android.revealeffectbasic"
             android:label="Tests for com.example.android.revealeffectbasic" />
 
-</manifest>
\ No newline at end of file
+</manifest>
diff --git a/ui/views/RevealEffect/RevealEffectBasic/Application/tests/src/com/example/android/revealeffectbasic/tests/SampleTests.java b/ui/views/RevealEffect/RevealEffectBasic/Application/tests/src/com/example/android/revealeffectbasic/tests/SampleTests.java
index 249f1ef..de85851 100644
--- a/ui/views/RevealEffect/RevealEffectBasic/Application/tests/src/com/example/android/revealeffectbasic/tests/SampleTests.java
+++ b/ui/views/RevealEffect/RevealEffectBasic/Application/tests/src/com/example/android/revealeffectbasic/tests/SampleTests.java
@@ -1,22 +1,4 @@
 /*
-* Copyright 2013 The Android Open Source Project
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-
-
-/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
@@ -72,4 +54,4 @@
         assertNotNull("mTestFragment is null", mTestFragment);
         assertNotNull("Circle view is null", mTestActivity.findViewById(R.id.circle));
     }
-}
\ No newline at end of file
+}
diff --git a/ui/views/SlidingTabs/SlidingTabsBasic/Application/tests/AndroidManifest.xml b/ui/views/SlidingTabs/SlidingTabsBasic/Application/tests/AndroidManifest.xml
index 3b7394c..7b727ba 100644
--- a/ui/views/SlidingTabs/SlidingTabsBasic/Application/tests/AndroidManifest.xml
+++ b/ui/views/SlidingTabs/SlidingTabsBasic/Application/tests/AndroidManifest.xml
@@ -1,22 +1,3 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright 2013 The Android Open Source Project
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
-     http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-
-
-
 <?xml version="1.0" encoding="utf-8"?>
 <!--
   Copyright (C) 2013 The Android Open Source Project
@@ -56,4 +37,4 @@
             android:targetPackage="com.example.android.slidingtabsbasic"
             android:label="Tests for com.example.android.slidingtabsbasic" />
 
-</manifest>
\ No newline at end of file
+</manifest>
diff --git a/ui/views/SlidingTabs/SlidingTabsBasic/Application/tests/src/com/example/android/slidingtabsbasic/tests/SampleTests.java b/ui/views/SlidingTabs/SlidingTabsBasic/Application/tests/src/com/example/android/slidingtabsbasic/tests/SampleTests.java
index 6ab9c73..3206049 100644
--- a/ui/views/SlidingTabs/SlidingTabsBasic/Application/tests/src/com/example/android/slidingtabsbasic/tests/SampleTests.java
+++ b/ui/views/SlidingTabs/SlidingTabsBasic/Application/tests/src/com/example/android/slidingtabsbasic/tests/SampleTests.java
@@ -1,22 +1,4 @@
 /*
-* Copyright 2013 The Android Open Source Project
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-
-
-/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
@@ -76,4 +58,4 @@
     * Add more tests below.
     */
 
-}
\ No newline at end of file
+}
diff --git a/ui/views/SwipeRefreshLayout/SwipeRefreshLayoutBasic/Application/tests/AndroidManifest.xml b/ui/views/SwipeRefreshLayout/SwipeRefreshLayoutBasic/Application/tests/AndroidManifest.xml
index 9455da6..dbbe8c7 100644
--- a/ui/views/SwipeRefreshLayout/SwipeRefreshLayoutBasic/Application/tests/AndroidManifest.xml
+++ b/ui/views/SwipeRefreshLayout/SwipeRefreshLayoutBasic/Application/tests/AndroidManifest.xml
@@ -1,22 +1,3 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright 2013 The Android Open Source Project
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
-     http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-
-
-
 <?xml version="1.0" encoding="utf-8"?>
 <!--
   Copyright (C) 2013 The Android Open Source Project
@@ -56,4 +37,4 @@
             android:targetPackage="com.example.android.swiperefreshlayoutbasic"
             android:label="Tests for com.example.android.swiperefreshlayoutbasic" />
 
-</manifest>
\ No newline at end of file
+</manifest>
diff --git a/ui/views/SwipeRefreshLayout/SwipeRefreshListFragment/Application/tests/AndroidManifest.xml b/ui/views/SwipeRefreshLayout/SwipeRefreshListFragment/Application/tests/AndroidManifest.xml
index 8326b36..b91e31e 100644
--- a/ui/views/SwipeRefreshLayout/SwipeRefreshListFragment/Application/tests/AndroidManifest.xml
+++ b/ui/views/SwipeRefreshLayout/SwipeRefreshListFragment/Application/tests/AndroidManifest.xml
@@ -1,22 +1,3 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright 2013 The Android Open Source Project
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
-     http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-
-
-
 <?xml version="1.0" encoding="utf-8"?>
 <!--
   Copyright (C) 2013 The Android Open Source Project
@@ -56,4 +37,4 @@
             android:targetPackage="com.example.android.swiperefreshlistfragment"
             android:label="Tests for com.example.android.swiperefreshlistfragment" />
 
-</manifest>
\ No newline at end of file
+</manifest>
diff --git a/ui/views/SwipeRefreshLayout/SwipeRefreshListFragment/screenshots/icon-web.png b/ui/views/SwipeRefreshLayout/SwipeRefreshListFragment/screenshots/icon-web.png
new file mode 100644
index 0000000..f9819f2
--- /dev/null
+++ b/ui/views/SwipeRefreshLayout/SwipeRefreshListFragment/screenshots/icon-web.png
Binary files differ
diff --git a/ui/views/SwipeRefreshLayout/SwipeRefreshListFragment/screenshots/refresh.png b/ui/views/SwipeRefreshLayout/SwipeRefreshListFragment/screenshots/refresh.png
new file mode 100644
index 0000000..6af7af2
--- /dev/null
+++ b/ui/views/SwipeRefreshLayout/SwipeRefreshListFragment/screenshots/refresh.png
Binary files differ
diff --git a/ui/views/SwipeRefreshLayout/SwipeRefreshListFragment/template-params.xml b/ui/views/SwipeRefreshLayout/SwipeRefreshListFragment/template-params.xml
index e209c33..4210182 100644
--- a/ui/views/SwipeRefreshLayout/SwipeRefreshListFragment/template-params.xml
+++ b/ui/views/SwipeRefreshLayout/SwipeRefreshListFragment/template-params.xml
@@ -21,10 +21,7 @@
     <name>SwipeRefreshListFragment</name>
     <group>UI</group>
     <package>com.example.android.swiperefreshlistfragment</package>
-
-    <!-- change minSdk if needed-->
     <minSdk>10</minSdk>
-
     <strings>
         <intro>
             <![CDATA[
@@ -43,4 +40,43 @@
     <common src="view"/>
     <common src="dummydata"/>
 
+    <metadata>
+        <status>PUBLISHED</status>
+        <categories>UI, Input</categories>
+        <technologies>Android</technologies>
+        <languages>Java</languages>
+        <solutions>Mobile</solutions>
+        <level>INTERMEDIATE</level>
+        <icon>screenshots/icon-web.png</icon>
+        <screenshots>
+            <img>screenshots/refresh.png</img>
+        </screenshots>
+        <api_refs>
+            <android>android.support.v4.widget.SwipeRefreshLayout</android>
+            <android>android.widget.ArrayAdapter</android>
+            <android>android.widget.ListAdapter</android>
+            <android>android.support.v4.app.ListFragment</android>
+        </api_refs>
+        <description>
+<![CDATA[
+A sample which shows how to use `SwipeRefreshLayout` to add
+'swipe-to-refresh' gesture to a ListView, enabling the ability to trigger a refresh
+from swiping down on that view.
+]]>
+        </description>
+        <intro>
+<![CDATA[
+A sample which shows how to use
+[SwipeRefreshLayout][1] within a `ListFragment` to add the 'swipe-to-refresh'
+gesture to a `ListView`. The sample provides this functionality by defining a
+re-usable `SwipeRefreshListFragment` class.
+
+The sample displays a list of cheeses. When the user initiates a downward swipe,
+that list refreshes with randomly generated items. Selecting the `Refresh`
+action from the action bar also refreshes the list.
+
+[1]: https://developer.android.com/reference/android/support/v4/widget/SwipeRefreshLayout.html
+]]>
+        </intro>
+    </metadata>
 </sample>
diff --git a/ui/views/SwipeRefreshLayout/SwipeRefreshMultipleViews/Application/tests/AndroidManifest.xml b/ui/views/SwipeRefreshLayout/SwipeRefreshMultipleViews/Application/tests/AndroidManifest.xml
index dea1d96..9b06dd0 100644
--- a/ui/views/SwipeRefreshLayout/SwipeRefreshMultipleViews/Application/tests/AndroidManifest.xml
+++ b/ui/views/SwipeRefreshLayout/SwipeRefreshMultipleViews/Application/tests/AndroidManifest.xml
@@ -1,22 +1,3 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright 2014 The Android Open Source Project
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
-     http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-
-
-
 <?xml version="1.0" encoding="utf-8"?>
 <!--
   Copyright (C) 2013 The Android Open Source Project
@@ -56,4 +37,4 @@
             android:targetPackage="com.example.android.swiperefreshmultipleviews"
             android:label="Tests for com.example.android.swiperefreshmultipleviews" />
 
-</manifest>
\ No newline at end of file
+</manifest>
diff --git a/ui/window/AdvancedImmersiveMode/screenshots/icon-web.png b/ui/window/AdvancedImmersiveMode/screenshots/icon-web.png
new file mode 100644
index 0000000..fc00d92
--- /dev/null
+++ b/ui/window/AdvancedImmersiveMode/screenshots/icon-web.png
Binary files differ
diff --git a/ui/window/AdvancedImmersiveMode/screenshots/immersion.png b/ui/window/AdvancedImmersiveMode/screenshots/immersion.png
new file mode 100644
index 0000000..a6c310b
--- /dev/null
+++ b/ui/window/AdvancedImmersiveMode/screenshots/immersion.png
Binary files differ
diff --git a/ui/window/AdvancedImmersiveMode/template-params.xml b/ui/window/AdvancedImmersiveMode/template-params.xml
index 2ed54fd..6e19aa2 100644
--- a/ui/window/AdvancedImmersiveMode/template-params.xml
+++ b/ui/window/AdvancedImmersiveMode/template-params.xml
@@ -19,9 +19,7 @@
     <group>UI</group>
     <package>com.example.android.advancedimmersivemode</package>
 
-
-    <!-- change minSdk if needed-->
-    <minSdk>4</minSdk>
+    <minSdk>19</minSdk>
 
     <strings>
         <intro>
@@ -39,5 +37,46 @@
     <template src="FragmentView"/>
     <common src="logger"/>
     <common src="activities"/>
+    <metadata>
+        <status>PUBLISHED</status>
+        <categories>Window</categories>
+        <technologies>Android</technologies>
+        <languages>Java</languages>
+        <solutions>Mobile</solutions>
+        <level>INTERMEDIATE</level>
+        <icon>screenshots/icon-web.png</icon>
+        <screenshots>
+            <img>screenshots/immersion.png</img>
+            <img>screenshots/leanback.png</img>
+        </screenshots>
+        <api_refs>
+            <android>android.view.Window</android>
+        </api_refs>
 
+        <description>
+<![CDATA[
+Immersive Mode, added in Android 4.4, improves the "hide full screen" and
+"hide nav bar" modes by letting users swipe the bars in and out.  This sample
+lets the user experiment with immersive mode by seeing how it interacts
+with some of the other UI flags related to full-screen apps.
+]]>
+        </description>
+
+        <intro>
+<![CDATA[
+Android 4.4 (API Level 19) introduces a new `SYSTEM_UI_FLAG_IMMERSIVE`
+flag for [setSystemUiVisibility()][1] that lets your app go truly "full
+screen." This flag, when combined with the `SYSTEM_UI_FLAG_HIDE_NAVIGATION` and
+`SYSTEM_UI_FLAG_FULLSCREEN` flags, hides the navigation and status bars
+and lets your app capture all touch events on the screen.
+
+When immersive full-screen mode is enabled, your activity continues
+to receive all touch events. The user can reveal the system bars with
+an inward swipe along the region where the system bars normally
+appear.
+
+[1]: http://developer.android.com/reference/android/view/View.html#setSystemUiVisibility(int)
+]]>
+        </intro>
+    </metadata>
 </sample>
diff --git a/ui/window/BasicImmersiveMode/Application/src/main/res/drawable-hdpi/ic_launcher.png b/ui/window/BasicImmersiveMode/Application/src/main/res/drawable-hdpi/ic_launcher.png
index b1efaf4..63dfb38 100644
--- a/ui/window/BasicImmersiveMode/Application/src/main/res/drawable-hdpi/ic_launcher.png
+++ b/ui/window/BasicImmersiveMode/Application/src/main/res/drawable-hdpi/ic_launcher.png
Binary files differ
diff --git a/ui/window/BasicImmersiveMode/Application/src/main/res/drawable-mdpi/ic_launcher.png b/ui/window/BasicImmersiveMode/Application/src/main/res/drawable-mdpi/ic_launcher.png
index f5f9244..f7c06d0 100644
--- a/ui/window/BasicImmersiveMode/Application/src/main/res/drawable-mdpi/ic_launcher.png
+++ b/ui/window/BasicImmersiveMode/Application/src/main/res/drawable-mdpi/ic_launcher.png
Binary files differ
diff --git a/ui/window/BasicImmersiveMode/Application/src/main/res/drawable-xhdpi/ic_launcher.png b/ui/window/BasicImmersiveMode/Application/src/main/res/drawable-xhdpi/ic_launcher.png
index 5d07b3f..22d9247 100644
--- a/ui/window/BasicImmersiveMode/Application/src/main/res/drawable-xhdpi/ic_launcher.png
+++ b/ui/window/BasicImmersiveMode/Application/src/main/res/drawable-xhdpi/ic_launcher.png
Binary files differ
diff --git a/ui/window/BasicImmersiveMode/Application/src/main/res/drawable-xxhdpi/ic_launcher.png b/ui/window/BasicImmersiveMode/Application/src/main/res/drawable-xxhdpi/ic_launcher.png
index 6ef21e1..4c4c037 100644
--- a/ui/window/BasicImmersiveMode/Application/src/main/res/drawable-xxhdpi/ic_launcher.png
+++ b/ui/window/BasicImmersiveMode/Application/src/main/res/drawable-xxhdpi/ic_launcher.png
Binary files differ
diff --git a/ui/window/BasicImmersiveMode/README.md b/ui/window/BasicImmersiveMode/README.md
index 66f74b1..87ec7b8 100644
--- a/ui/window/BasicImmersiveMode/README.md
+++ b/ui/window/BasicImmersiveMode/README.md
@@ -1,17 +1,32 @@
 Android BasicImmersiveMode Sample
-==============================
+===================================
 
-"Immersive Mode" is a new UI mode which improves "hide full screen" and
-"hide nav bar" modes, by letting users swipe the bars in and out.This sample
-demonstrates how to enable and disable immersive mode programmatically.
+Sample demonstrating the use of immersive mode to hide the system and navigation bars for
+full screen applications.
+
+Introduction
+------------
+
+'Immersive Mode' is a new UI mode which improves 'hide full screen' and 'hide nav bar' 
+modes, by letting users swipe the bars in and out.
+
+This sample demonstrates how to enable and disable immersive mode programmatically.
+
+Immersive mode was introduced in Android 4.4 (Api Level 19). It is toggled using the 
+SYSTEM_UI_FLAG_IMMERSIVE system ui flag. When combined with the SYSTEM_UI_FLAG_HIDE_NAVIGATION and SYSTEM_UI_FLAG_FULLSCREEN  flags, hides the navigation and status bars and lets your app capture all touch events on the screen.
 
 Pre-requisites
 --------------
 
-- Android SDK v20
-- Android Build Tools v20
+- Android SDK v21
+- Android Build Tools v21.1.1
 - Android Support Repository
 
+Screenshots
+-------------
+
+<img src="screenshots/1-activity.png" height="400" alt="Screenshot"/> <img src="screenshots/2-immersive.png" height="400" alt="Screenshot"/> 
+
 Getting Started
 ---------------
 
@@ -42,7 +57,7 @@
 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
+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
diff --git a/ui/window/BasicImmersiveMode/screenshots/1-activity.png b/ui/window/BasicImmersiveMode/screenshots/1-activity.png
new file mode 100644
index 0000000..c7bfeca
--- /dev/null
+++ b/ui/window/BasicImmersiveMode/screenshots/1-activity.png
Binary files differ
diff --git a/ui/window/BasicImmersiveMode/screenshots/2-immersive.png b/ui/window/BasicImmersiveMode/screenshots/2-immersive.png
new file mode 100644
index 0000000..61cef5c
--- /dev/null
+++ b/ui/window/BasicImmersiveMode/screenshots/2-immersive.png
Binary files differ
diff --git a/ui/window/BasicImmersiveMode/screenshots/big_icon.png b/ui/window/BasicImmersiveMode/screenshots/big_icon.png
new file mode 100644
index 0000000..f8e74be
--- /dev/null
+++ b/ui/window/BasicImmersiveMode/screenshots/big_icon.png
Binary files differ
diff --git a/ui/window/BasicImmersiveMode/template-params.xml b/ui/window/BasicImmersiveMode/template-params.xml
index cc663ab..ec26964 100644
--- a/ui/window/BasicImmersiveMode/template-params.xml
+++ b/ui/window/BasicImmersiveMode/template-params.xml
@@ -38,4 +38,39 @@
     <common src="logger"/>
     <common src="activities"/>
 
+<metadata>
+    <status>PUBLISHED</status>
+    <categories>UI</categories>
+    <technologies>Android</technologies>
+    <languages>Java</languages>
+    <solutions>Mobile</solutions>
+    <level>INTERMEDIATE</level>
+    <icon>screenshots/big_icon.png</icon>
+    <screenshots>
+        <img>screenshots/1-activity.png</img>
+        <img>screenshots/2-immersive.png</img>
+    </screenshots>
+    <api_refs>
+        <android>android.view.View</android>
+        <android>android.view.View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY</android>
+
+    </api_refs>
+    <description>
+<![CDATA[
+Sample demonstrating the use of immersive mode to hide the system and navigation bars for
+full screen applications.
+]]>
+    </description>
+    <intro>
+<![CDATA[
+'Immersive Mode' is a new UI mode which improves 'hide full screen' and 'hide nav bar' 
+modes, by letting users swipe the bars in and out.
+
+This sample demonstrates how to enable and disable immersive mode programmatically.
+
+Immersive mode was introduced in Android 4.4 (Api Level 19). It is toggled using the 
+SYSTEM_UI_FLAG_IMMERSIVE system ui flag. When combined with the SYSTEM_UI_FLAG_HIDE_NAVIGATION and SYSTEM_UI_FLAG_FULLSCREEN  flags, hides the navigation and status bars and lets your app capture all touch events on the screen.
+]]>
+    </intro>
+</metadata>
 </sample>
diff --git a/views/TextLinkify/Application/tests/src/com/example/android/textlinkify/tests/SampleTests.java b/views/TextLinkify/Application/tests/src/com/example/android/textlinkify/tests/SampleTests.java
index 90a91cc..d0a196f 100644
--- a/views/TextLinkify/Application/tests/src/com/example/android/textlinkify/tests/SampleTests.java
+++ b/views/TextLinkify/Application/tests/src/com/example/android/textlinkify/tests/SampleTests.java
@@ -1,22 +1,4 @@
 /*
-* Copyright 2013 The Android Open Source Project
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-
-
-/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
@@ -43,7 +25,6 @@
 public class SampleTests extends ActivityInstrumentationTestCase2<MainActivity> {
 
     private MainActivity mTestActivity;
-    private TextLinkifyFragment mTestFragment;
 
     public SampleTests() {
         super(MainActivity.class);
@@ -58,8 +39,6 @@
         // flags = {@link Intent#FLAG_ACTIVITY_NEW_TASK}
         // All other fields are null or empty.
         mTestActivity = getActivity();
-        mTestFragment = (TextLinkifyFragment)
-            mTestActivity.getSupportFragmentManager().getFragments().get(1);
     }
 
     /**
@@ -69,11 +48,10 @@
         //Try to add a message to add context to your assertions. These messages will be shown if
         //a tests fails and make it easy to understand why a test failed
         assertNotNull("mTestActivity is null", mTestActivity);
-        assertNotNull("mTestFragment is null", mTestFragment);
     }
 
     /**
     * Add more tests below.
     */
 
-}
\ No newline at end of file
+}
diff --git a/views/TextLinkify/screenshots/icon-web.png b/views/TextLinkify/screenshots/icon-web.png
new file mode 100644
index 0000000..47f96e4
--- /dev/null
+++ b/views/TextLinkify/screenshots/icon-web.png
Binary files differ
diff --git a/views/TextLinkify/screenshots/main.png b/views/TextLinkify/screenshots/main.png
new file mode 100644
index 0000000..5f483f5
--- /dev/null
+++ b/views/TextLinkify/screenshots/main.png
Binary files differ
diff --git a/views/TextLinkify/template-params.xml b/views/TextLinkify/template-params.xml
index c703b8b..72c3437 100644
--- a/views/TextLinkify/template-params.xml
+++ b/views/TextLinkify/template-params.xml
@@ -35,4 +35,57 @@
     <template src="base"/>
     <common src="logger"/>
 
+    <metadata>
+        <status>PUBLISHED</status>
+        <categories>Views</categories>
+        <technologies>Android</technologies>
+        <languages>Java</languages>
+        <solutions>Mobile</solutions>
+        <level>INTERMEDIATE</level>
+        <icon>screenshots/icon-web.png</icon>
+        <screenshots>
+            <img>screenshots/main.png</img>
+        </screenshots>
+        <api_refs>
+            <android>android.widget.TextView</android>
+            <android>android.text.util.Linkify</android>
+            <android>android.text.Html</android>
+            <android>android.text.SpannableString</android>
+            <android>android.text.style.StyleSpan</android>
+            <android>android.text.style.URLSpan</android>
+            <android>android.text.SpannableString</android>
+        </api_refs>
+
+        <description>
+<![CDATA[
+This sample illustrates how links can be added to a TextView. This can be done either
+automatically by setting the "autoLink" property or explicitly.
+]]>
+        </description>
+
+        <intro>
+<![CDATA[
+This sample demonstrates how clickable links can be added to a `TextView` in Android.
+
+This can be done in three ways:
+
+- **Automatically:** Text added to a TextView can automatically be linkified by enabling
+autoLinking. In XML, use the `android:autoLink` property, programatically call
+[android.widget.TextView#setAutoLinkMask(int)][1] using an option from
+[android.text.util.Linkify][2].
+- **Parsing a String as HTML:** See [android.text.Html#fromHtml(String)][3].
+- **Manually by constructing a [android.text.SpannableString][4]:** Consisting of
+[android.text.style.StyleSpan][5] and [android.text.style.URLSpan][6] objects that
+are contained within a [android.text.SpannableString][7].
+
+[1]: http://developer.android.com/reference/android/widget/TextView.html#setAutoLinkMask(int)
+[2]: http://developer.android.com/reference/android/text/util/Linkify.html
+[3]: http://developer.android.com/reference/android/text/Html.html#fromHtml(java.lang.String)
+[4]: http://developer.android.com/reference/android/text/SpannableString.html
+[5]: http://developer.android.com/reference/android/text/style/StyleSpan.html
+[6]: http://developer.android.com/reference/android/text/style/URLSpan.html
+[7]: http://developer.android.com/reference/android/text/SpannableString.html
+]]>
+        </intro>
+    </metadata>
 </sample>
diff --git a/wearable/wear/AgendaData/template-params.xml b/wearable/wear/AgendaData/template-params.xml
index 83126ca..1414944 100644
--- a/wearable/wear/AgendaData/template-params.xml
+++ b/wearable/wear/AgendaData/template-params.xml
@@ -22,11 +22,11 @@
     <group>Wearable</group>
     <package>com.example.android.wearable.agendadata</package>
 
-
-
-    <!-- change minSdk if needed-->
     <minSdk>18</minSdk>
 
+    <wearable>
+        <has_handheld_app>true</has_handheld_app>
+    </wearable>
 
     <strings>
         <intro>
diff --git a/wearable/wear/DataLayer/template-params.xml b/wearable/wear/DataLayer/template-params.xml
index 6c68e1d..8f89d67 100644
--- a/wearable/wear/DataLayer/template-params.xml
+++ b/wearable/wear/DataLayer/template-params.xml
@@ -18,8 +18,13 @@
     <name>DataLayer</name>
     <group>Wearable</group>
     <package>com.example.android.wearable.datalayer</package>
-    <!-- change minSdk if needed-->
+
     <minSdk>18</minSdk>
+
+    <wearable>
+        <has_handheld_app>true</has_handheld_app>
+    </wearable>
+
     <strings>
         <intro>
             <![CDATA[
diff --git a/wearable/wear/DelayedConfirmation/template-params.xml b/wearable/wear/DelayedConfirmation/template-params.xml
index 302c610..0b2f014 100644
--- a/wearable/wear/DelayedConfirmation/template-params.xml
+++ b/wearable/wear/DelayedConfirmation/template-params.xml
@@ -22,11 +22,11 @@
     <group>Wearable</group>
     <package>com.example.android.wearable.delayedconfirmation</package>
 
-
-
-    <!-- change minSdk if needed-->
     <minSdk>18</minSdk>
 
+    <wearable>
+        <has_handheld_app>true</has_handheld_app>
+    </wearable>
 
     <strings>
         <intro>
diff --git a/wearable/wear/ElizaChat/settings.gradle b/wearable/wear/ElizaChat/settings.gradle
index 360755c..0f81951 100644
--- a/wearable/wear/ElizaChat/settings.gradle
+++ b/wearable/wear/ElizaChat/settings.gradle
@@ -1 +1 @@
-include ':Application', ':Shared'
+include ':Application'
\ No newline at end of file
diff --git a/wearable/wear/ElizaChat/template-params.xml b/wearable/wear/ElizaChat/template-params.xml
index 29ff39d..76ed57f 100644
--- a/wearable/wear/ElizaChat/template-params.xml
+++ b/wearable/wear/ElizaChat/template-params.xml
@@ -22,12 +22,8 @@
     <group>Wearable</group>
     <package>com.example.android.wearable.elizachat</package>
 
-
-
-    <!-- change minSdk if needed-->
     <minSdk>18</minSdk>
 
-
     <strings>
         <intro>
             <![CDATA[
diff --git a/wearable/wear/EmbeddedApp/template-params.xml b/wearable/wear/EmbeddedApp/template-params.xml
index bb9bdc5..9eb6378 100644
--- a/wearable/wear/EmbeddedApp/template-params.xml
+++ b/wearable/wear/EmbeddedApp/template-params.xml
@@ -22,11 +22,11 @@
     <group>Wearable</group>
     <package>com.example.android.wearable.embeddedapp</package>
 
-
-
-    <!-- change minSdk if needed-->
     <minSdk>18</minSdk>
 
+    <wearable>
+        <has_handheld_app>true</has_handheld_app>
+    </wearable>
 
     <strings>
         <intro>
@@ -39,4 +39,54 @@
     <template src="base"/>
     <template src="Wear"/>
 
+    <metadata>
+        <status>PUBLISHED</status>
+        <categories>Wearable</categories>
+        <technologies>Android</technologies>
+        <languages>Java</languages>
+        <solutions>Mobile</solutions>
+        <level>BEGINNER</level>
+        <icon>src/main/res/drawable-xxhdpi/ic_launcher.png</icon>
+        <screenshots>
+            <img>screenshots/embedded_wearable_app.png</img>
+            <img>screenshots/phone_app.png</img>
+        </screenshots>
+        <api_refs>
+            <android>android.app.Activity</android>
+        </api_refs>
+
+        <description>
+<![CDATA[
+This simple app demonstrates how to embed a wearable app into a phone app.
+]]>
+        </description>
+
+        <intro>
+<![CDATA[
+Wearable apps can be installed directly onto Android Wear devices during development, using either a direct ADB
+connection or ADB-over-Bluetooth. However, when releasing your app to end users, you must package your
+wearable APK inside of a traditional APK for dis