Merge "Persist nickname and flags for volumes."
diff --git a/api/current.txt b/api/current.txt
index 5f4336d..5346895 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -14780,6 +14780,7 @@
     method public int getChannelConfiguration();
     method public int getChannelCount();
     method public static int getMinBufferSize(int, int, int);
+    method public int getNativeFrameCount() throws java.lang.IllegalStateException;
     method public int getNotificationMarkerPosition();
     method public int getPositionNotificationPeriod();
     method public int getRecordingState();
@@ -15156,7 +15157,6 @@
     field public static final java.lang.String PARAMETER_KEY_REQUEST_SYNC_FRAME = "request-sync";
     field public static final java.lang.String PARAMETER_KEY_SUSPEND = "drop-input-frames";
     field public static final java.lang.String PARAMETER_KEY_VIDEO_BITRATE = "video-bitrate";
-    field public static final int REASON_RECLAIMED = 1; // 0x1
     field public static final int VIDEO_SCALING_MODE_SCALE_TO_FIT = 1; // 0x1
     field public static final int VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING = 2; // 0x2
   }
@@ -15172,7 +15172,6 @@
 
   public static abstract class MediaCodec.Callback {
     ctor public MediaCodec.Callback();
-    method public void onCodecReleased(android.media.MediaCodec, int);
     method public abstract void onError(android.media.MediaCodec, android.media.MediaCodec.CodecException);
     method public abstract void onInputBufferAvailable(android.media.MediaCodec, int);
     method public abstract void onOutputBufferAvailable(android.media.MediaCodec, int, android.media.MediaCodec.BufferInfo);
@@ -15181,8 +15180,11 @@
 
   public static final class MediaCodec.CodecException extends java.lang.IllegalStateException {
     method public java.lang.String getDiagnosticInfo();
+    method public int getReason();
     method public boolean isRecoverable();
     method public boolean isTransient();
+    field public static final int REASON_HARDWARE = 0; // 0x0
+    field public static final int REASON_RECLAIMED = 1; // 0x1
   }
 
   public static final class MediaCodec.CryptoException extends java.lang.RuntimeException {
diff --git a/api/system-current.txt b/api/system-current.txt
index 684ef80..c7db72b 100644
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -15990,6 +15990,7 @@
     method public int getChannelConfiguration();
     method public int getChannelCount();
     method public static int getMinBufferSize(int, int, int);
+    method public int getNativeFrameCount() throws java.lang.IllegalStateException;
     method public int getNotificationMarkerPosition();
     method public int getPositionNotificationPeriod();
     method public int getRecordingState();
@@ -16368,7 +16369,6 @@
     field public static final java.lang.String PARAMETER_KEY_REQUEST_SYNC_FRAME = "request-sync";
     field public static final java.lang.String PARAMETER_KEY_SUSPEND = "drop-input-frames";
     field public static final java.lang.String PARAMETER_KEY_VIDEO_BITRATE = "video-bitrate";
-    field public static final int REASON_RECLAIMED = 1; // 0x1
     field public static final int VIDEO_SCALING_MODE_SCALE_TO_FIT = 1; // 0x1
     field public static final int VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING = 2; // 0x2
   }
@@ -16384,7 +16384,6 @@
 
   public static abstract class MediaCodec.Callback {
     ctor public MediaCodec.Callback();
-    method public void onCodecReleased(android.media.MediaCodec, int);
     method public abstract void onError(android.media.MediaCodec, android.media.MediaCodec.CodecException);
     method public abstract void onInputBufferAvailable(android.media.MediaCodec, int);
     method public abstract void onOutputBufferAvailable(android.media.MediaCodec, int, android.media.MediaCodec.BufferInfo);
@@ -16393,8 +16392,11 @@
 
   public static final class MediaCodec.CodecException extends java.lang.IllegalStateException {
     method public java.lang.String getDiagnosticInfo();
+    method public int getReason();
     method public boolean isRecoverable();
     method public boolean isTransient();
+    field public static final int REASON_HARDWARE = 0; // 0x0
+    field public static final int REASON_RECLAIMED = 1; // 0x1
   }
 
   public static final class MediaCodec.CryptoException extends java.lang.RuntimeException {
@@ -18053,6 +18055,10 @@
 package android.media.audiopolicy {
 
   public class AudioMix {
+    method public int getMixState();
+    field public static final int MIX_STATE_DISABLED = -1; // 0xffffffff
+    field public static final int MIX_STATE_IDLE = 0; // 0x0
+    field public static final int MIX_STATE_MIXING = 1; // 0x1
     field public static final int ROUTE_FLAG_LOOP_BACK = 2; // 0x2
     field public static final int ROUTE_FLAG_RENDER = 1; // 0x1
   }
diff --git a/core/java/android/hardware/location/GeofenceHardwareImpl.java b/core/java/android/hardware/location/GeofenceHardwareImpl.java
index b34c9fb..ee2d43c 100644
--- a/core/java/android/hardware/location/GeofenceHardwareImpl.java
+++ b/core/java/android/hardware/location/GeofenceHardwareImpl.java
@@ -239,7 +239,12 @@
                     case GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE:
                         return CAPABILITY_GNSS;
                     case GeofenceHardware.MONITORING_TYPE_FUSED_HARDWARE:
-                        return mCapabilities;
+                        if (mVersion >= FIRST_VERSION_WITH_CAPABILITIES) {
+                            return mCapabilities;
+                        }
+                        // This was the implied capability on old FLP HAL versions that didn't
+                        // have the capability callback.
+                        return CAPABILITY_GNSS;
                 }
                 break;
         }
diff --git a/core/java/android/os/Debug.java b/core/java/android/os/Debug.java
index 360e5c68..75b1101 100644
--- a/core/java/android/os/Debug.java
+++ b/core/java/android/os/Debug.java
@@ -1181,7 +1181,7 @@
 
     /**
      * Returns a map of the names/values of the runtime statistics
-     * that {@link #getRuntimeStat()} supports.
+     * that {@link #getRuntimeStat(String)} supports.
      *
      * @return a map of the names/values of the supported runtime statistics.
      * @hide
diff --git a/core/java/android/text/StaticLayout.java b/core/java/android/text/StaticLayout.java
index 2bcb352..7828851 100644
--- a/core/java/android/text/StaticLayout.java
+++ b/core/java/android/text/StaticLayout.java
@@ -811,7 +811,7 @@
                 float sum = 0;
                 int i;
 
-                for (i = len; i >= 0; i--) {
+                for (i = len; i > 0; i--) {
                     float w = widths[i - 1 + lineStart - widthStart];
 
                     if (w + sum + ellipsisWidth > avail) {
diff --git a/core/jni/android_media_AudioRecord.cpp b/core/jni/android_media_AudioRecord.cpp
index ec2b590..c9b0e76 100644
--- a/core/jni/android_media_AudioRecord.cpp
+++ b/core/jni/android_media_AudioRecord.cpp
@@ -524,6 +524,17 @@
 
 
 // ----------------------------------------------------------------------------
+static jint android_media_AudioRecord_get_native_frame_count(JNIEnv *env,  jobject thiz) {
+    sp<AudioRecord> lpRecorder = getAudioRecord(env, thiz);
+    if (lpRecorder == NULL) {
+        jniThrowException(env, "java/lang/IllegalStateException",
+            "Unable to retrieve AudioRecord pointer for getNativeFrameCount()");
+        return (jint)AUDIO_JAVA_ERROR;
+    }
+    return lpRecorder->frameCount();
+}
+
+// ----------------------------------------------------------------------------
 static jint android_media_AudioRecord_set_marker_pos(JNIEnv *env,  jobject thiz,
         jint markerPos) {
 
@@ -629,6 +640,8 @@
                              "([FIIZ)I", (void *)android_media_AudioRecord_readInFloatArray},
     {"native_read_in_direct_buffer","(Ljava/lang/Object;I)I",
                                        (void *)android_media_AudioRecord_readInDirectBuffer},
+    {"native_get_native_frame_count",
+                             "()I",    (void *)android_media_AudioRecord_get_native_frame_count},
     {"native_set_marker_pos","(I)I",   (void *)android_media_AudioRecord_set_marker_pos},
     {"native_get_marker_pos","()I",    (void *)android_media_AudioRecord_get_marker_pos},
     {"native_set_pos_update_period",
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index 6b44cd4..13877fb 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -1636,6 +1636,14 @@
         android:protectionLevel="signature" />
     <uses-permission android:name="android.permission.BIND_JOB_SERVICE"/>
 
+    <!-- Allows an application to initiate configuration updates
+         <p>An application requesting this permission is responsible for
+         verifying the source and integrity of any update before passing
+         it off to the various individual installer components
+         @hide -->
+    <permission android:name="android.permission.UPDATE_CONFIG"
+        android:protectionLevel="signature|system" />
+
     <!-- ========================================= -->
     <!-- Permissions for special development tools -->
     <!-- ========================================= -->
@@ -2556,42 +2564,48 @@
             </intent-filter>
         </receiver>
 
-        <receiver android:name="com.android.server.updates.CertPinInstallReceiver" >
+        <receiver android:name="com.android.server.updates.CertPinInstallReceiver"
+                android:permission="android.permission.UPDATE_CONFIG">
             <intent-filter>
                 <action android:name="android.intent.action.UPDATE_PINS" />
                 <data android:scheme="content" android:host="*" android:mimeType="*/*" />
             </intent-filter>
         </receiver>
 
-        <receiver android:name="com.android.server.updates.IntentFirewallInstallReceiver" >
+        <receiver android:name="com.android.server.updates.IntentFirewallInstallReceiver"
+                android:permission="android.permission.UPDATE_CONFIG">
             <intent-filter>
                 <action android:name="android.intent.action.UPDATE_INTENT_FIREWALL" />
                 <data android:scheme="content" android:host="*" android:mimeType="*/*" />
             </intent-filter>
         </receiver>
 
-        <receiver android:name="com.android.server.updates.SmsShortCodesInstallReceiver" >
+        <receiver android:name="com.android.server.updates.SmsShortCodesInstallReceiver"
+                android:permission="android.permission.UPDATE_CONFIG">
             <intent-filter>
                 <action android:name="android.intent.action.UPDATE_SMS_SHORT_CODES" />
                 <data android:scheme="content" android:host="*" android:mimeType="*/*" />
             </intent-filter>
         </receiver>
 
-        <receiver android:name="com.android.server.updates.CarrierProvisioningUrlsInstallReceiver" >
+        <receiver android:name="com.android.server.updates.CarrierProvisioningUrlsInstallReceiver"
+                android:permission="android.permission.UPDATE_CONFIG">
             <intent-filter>
                 <action android:name="android.intent.action.UPDATE_CARRIER_PROVISIONING_URLS" />
                 <data android:scheme="content" android:host="*" android:mimeType="*/*" />
             </intent-filter>
         </receiver>
 
-        <receiver android:name="com.android.server.updates.TzDataInstallReceiver" >
+        <receiver android:name="com.android.server.updates.TzDataInstallReceiver"
+                android:permission="android.permission.UPDATE_CONFIG">
             <intent-filter>
                 <action android:name="android.intent.action.UPDATE_TZDATA" />
                 <data android:scheme="content" android:host="*" android:mimeType="*/*" />
             </intent-filter>
         </receiver>
 
-        <receiver android:name="com.android.server.updates.SELinuxPolicyInstallReceiver" >
+        <receiver android:name="com.android.server.updates.SELinuxPolicyInstallReceiver"
+                android:permission="android.permission.UPDATE_CONFIG">
             <intent-filter>
                 <action android:name="android.intent.action.UPDATE_SEPOLICY" />
                 <data android:scheme="content" android:host="*" android:mimeType="*/*" />
diff --git a/docs/html/design/building-blocks/buttons.jd b/docs/html/design/building-blocks/buttons.jd
index 3a34601..e698f38 100644
--- a/docs/html/design/building-blocks/buttons.jd
+++ b/docs/html/design/building-blocks/buttons.jd
@@ -2,6 +2,14 @@
 page.tags=button,input
 @jd:body
 
+<a class="notice-designers-material"
+  href="http://www.google.com/design/spec/components/buttons.html">
+  <div>
+    <h3>Material Design</h3>
+    <p>Buttons<p>
+  </div>
+</a>
+
 <a class="notice-developers" href="{@docRoot}guide/topics/ui/controls/button.html">
   <div>
     <h3>Developer Docs</h3>
diff --git a/docs/html/design/building-blocks/dialogs.jd b/docs/html/design/building-blocks/dialogs.jd
index 53d99b8..9c91abf 100644
--- a/docs/html/design/building-blocks/dialogs.jd
+++ b/docs/html/design/building-blocks/dialogs.jd
@@ -2,6 +2,14 @@
 page.tags=dialog,alert,popup,toast
 @jd:body
 
+<a class="notice-designers-material"
+  href="http://www.google.com/design/spec/components/dialogs.html">
+  <div>
+    <h3>Material Design</h3>
+    <p>Dialogs<p>
+  </div>
+</a>
+
 <a class="notice-developers" href="{@docRoot}guide/topics/ui/dialogs.html">
   <div>
     <h3>Developer Docs</h3>
@@ -35,7 +43,7 @@
   <h4>Action buttons</h4>
   <p>Action buttons are typically Cancel and/or OK, with OK indicating the preferred or most likely action. However, if the options consist of specific actions such as Close or Wait rather than a confirmation or cancellation of the action described in the content, then all the buttons should be active verbs. Order actions following these rules:</p>
     <ul>
-    
+
     <li>The dismissive action of a dialog is always on the left. Dismissive actions return to the user to the previous state.</li>
     <li>The affirmative actions are on the right. Affirmative actions continue progress toward the user goal that triggered the dialog.</li>
     </ul>
@@ -152,6 +160,15 @@
 away from an email before you send it triggers a "Draft saved" toast to let you know that you can
 continue editing later. Toasts automatically disappear after a timeout.</p>
 
+<a class="notice-designers-material left"
+  href="http://www.google.com/design/spec/components/snackbars-toasts.html">
+  <div>
+    <h3>Material Design</h3>
+    <p>Toasts<p>
+  </div>
+</a>
+
+
 <a class="notice-developers left" href="{@docRoot}guide/topics/ui/notifiers/toasts.html">
   <div>
     <h3>Developer Docs</h3>
diff --git a/docs/html/design/building-blocks/grid-lists.jd b/docs/html/design/building-blocks/grid-lists.jd
index d98637cc..ac3a3ebf 100644
--- a/docs/html/design/building-blocks/grid-lists.jd
+++ b/docs/html/design/building-blocks/grid-lists.jd
@@ -4,6 +4,15 @@
 
 <img src="{@docRoot}design/media/gridview_overview.png">
 
+
+<a class="notice-designers-material"
+  href="http://www.google.com/design/spec/components/grid-lists.html">
+  <div>
+    <h3>Material Design</h3>
+    <p>Grid lists<p>
+  </div>
+</a>
+
 <a class="notice-developers" href="{@docRoot}guide/topics/ui/layout/gridview.html">
   <div>
     <h3>Developer Docs</h3>
diff --git a/docs/html/design/building-blocks/lists.jd b/docs/html/design/building-blocks/lists.jd
index 4949d00..6f69feb 100644
--- a/docs/html/design/building-blocks/lists.jd
+++ b/docs/html/design/building-blocks/lists.jd
@@ -2,10 +2,11 @@
 page.tags=listview,layout
 @jd:body
 
-<a class="notice-developers" href="{@docRoot}guide/topics/ui/layout/listview.html">
+<a class="notice-designers-material"
+  href="http://www.google.com/design/spec/components/lists.html">
   <div>
-    <h3>Developer Docs</h3>
-    <p>List View</p>
+    <h3>Material Design</h3>
+    <p>Lists<p>
   </div>
 </a>
 
@@ -22,7 +23,7 @@
   </div>
   <div class="layout-content-col span-4 with-callouts">
 
-<ol>
+<ol style="margin-bottom: 60px;">
 <li>
 <h4>Section Divider</h4>
 <p>Use section dividers to organize the content of your list into groups and facilitate scanning.</p>
@@ -35,5 +36,21 @@
 </li>
 </ol>
 
+<a class="notice-developers" href="{@docRoot}guide/topics/ui/layout/listview.html">
+  <div>
+    <h3>Developer Docs</h3>
+    <p>List View</p>
+  </div>
+</a>
+
+<a class="notice-designers-material"
+  href="http://www.google.com/design/spec/components/lists-controls.html">
+  <div>
+    <h3>Material Design</h3>
+    <p>Lists: Controls<p>
+  </div>
+</a>
+
+
   </div>
 </div>
diff --git a/docs/html/design/building-blocks/progress.jd b/docs/html/design/building-blocks/progress.jd
index 6946a75..2de75dc 100644
--- a/docs/html/design/building-blocks/progress.jd
+++ b/docs/html/design/building-blocks/progress.jd
@@ -2,6 +2,14 @@
 page.tags=progressbar,download,network
 @jd:body
 
+<a class="notice-designers-material"
+  href="http://www.google.com/design/spec/components/progress-activity.html">
+  <div>
+    <h3>Material Design</h3>
+    <p>Progress and Activity<p>
+  </div>
+</a>
+
 <p>Progress bars and activity indicators signal to users that something is happening that will take a moment.</p>
 <h2 id="progress">Progress bars</h2>
 
diff --git a/docs/html/design/building-blocks/scrolling.jd b/docs/html/design/building-blocks/scrolling.jd
index 41e7cec..04b1e4a 100644
--- a/docs/html/design/building-blocks/scrolling.jd
+++ b/docs/html/design/building-blocks/scrolling.jd
@@ -2,6 +2,7 @@
 page.tags=scrollview,listview
 @jd:body
 
+
 <p>Scrolling allows the user to navigate to content in the overflow using a swipe gesture. The
 scrolling speed is proportional to the speed of the gesture.</p>
 <h2 id="indicator">Scroll Indicator</h2>
diff --git a/docs/html/design/building-blocks/seek-bars.jd b/docs/html/design/building-blocks/seek-bars.jd
index 1465688..5c42102 100644
--- a/docs/html/design/building-blocks/seek-bars.jd
+++ b/docs/html/design/building-blocks/seek-bars.jd
@@ -2,6 +2,14 @@
 page.tags=seekbar,progressbar
 @jd:body
 
+<a class="notice-designers-material"
+  href="http://www.google.com/design/spec/components/sliders.html">
+  <div>
+    <h3>Material Design</h3>
+    <p>Sliders<p>
+  </div>
+</a>
+
 <p>Interactive sliders make it possible to select a value from a continuous or discrete range of values
 by moving the slider thumb. The smallest value is to the left, the largest to the right. The
 interactive nature of the slider makes it a great choice for settings that reflect intensity levels,
diff --git a/docs/html/design/building-blocks/spinners.jd b/docs/html/design/building-blocks/spinners.jd
index f7d80e7..3a74ccf 100644
--- a/docs/html/design/building-blocks/spinners.jd
+++ b/docs/html/design/building-blocks/spinners.jd
@@ -2,6 +2,14 @@
 page.tags=spinner,dropdown
 @jd:body
 
+<a class="notice-designers-material"
+  href="http://www.google.com/design/spec/components/menus.html">
+  <div>
+    <h3>Material Design</h3>
+    <p>Menus<p>
+  </div>
+</a>
+
 <a class="notice-developers" href="{@docRoot}guide/topics/ui/controls/spinner.html">
   <div>
     <h3>Developer Docs</h3>
diff --git a/docs/html/design/building-blocks/switches.jd b/docs/html/design/building-blocks/switches.jd
index d435657..9dd09ca 100644
--- a/docs/html/design/building-blocks/switches.jd
+++ b/docs/html/design/building-blocks/switches.jd
@@ -2,6 +2,14 @@
 page.tags=switch,checkbox,radiobutton,button
 @jd:body
 
+<a class="notice-designers-material"
+  href="http://www.google.com/design/spec/components/selection-controls.html">
+  <div>
+    <h3>Material Design</h3>
+    <p>Selection Controls<p>
+  </div>
+</a>
+
 <p>Switches allow the user to select options. There are three kinds of switches: checkboxes, radio
 buttons, and on/off switches.</p>
 
diff --git a/docs/html/design/building-blocks/tabs.jd b/docs/html/design/building-blocks/tabs.jd
index 93818c3..078de92 100644
--- a/docs/html/design/building-blocks/tabs.jd
+++ b/docs/html/design/building-blocks/tabs.jd
@@ -4,10 +4,18 @@
 
 <img src="{@docRoot}design/media/tabs_overview.png">
 
+<a class="notice-designers-material"
+  href="http://www.google.com/design/spec/components/tabs.html">
+  <div>
+    <h3>Material Design</h3>
+    <p>Tabs<p>
+  </div>
+</a>
+
 <a class="notice-developers" href="{@docRoot}training/implementing-navigation/lateral.html">
   <div>
     <h3>Developer Docs</h3>
-    <p>Creating Swipe Views with Tabs</p>
+    <p>Creating Swipe Views<br>with Tabs</p>
   </div>
 </a>
 
diff --git a/docs/html/design/building-blocks/text-fields.jd b/docs/html/design/building-blocks/text-fields.jd
index e109d5f..19c22f9 100644
--- a/docs/html/design/building-blocks/text-fields.jd
+++ b/docs/html/design/building-blocks/text-fields.jd
@@ -2,6 +2,15 @@
 page.tags=text,edittext,input
 @jd:body
 
+
+<a class="notice-designers-material"
+  href="http://www.google.com/design/spec/components/text-fields.html">
+  <div>
+    <h3>Material Design</h3>
+    <p>Text Fields<p>
+  </div>
+</a>
+
 <a class="notice-developers" href="{@docRoot}guide/topics/ui/controls/text.html">
   <div>
     <h3>Developer Docs</h3>
diff --git a/docs/html/design/downloads/index.jd b/docs/html/design/downloads/index.jd
index 16d61e7..4111bca 100644
--- a/docs/html/design/downloads/index.jd
+++ b/docs/html/design/downloads/index.jd
@@ -12,6 +12,7 @@
 <div class="layout-content-row">
   <div class="layout-content-col span-5">
 
+
 <p>Drag and drop your way to beautifully designed Android apps. The stencils feature the
 rich typography, colors, interactive controls, and icons found throughout Android, along with
 phone and tablet outlines to frame your creations. Source files for icons and controls are also
@@ -23,15 +24,31 @@
     <img src="{@docRoot}design/media/downloads_stencils.png">
 
   </div>
-  <div class="layout-content-col span-4">
 
+  <div class="layout-content-col span-4">
+    <a class="notice-designers-material"
+      style="width:218px;"
+      href="http://www.google.com/design/spec/resources/layout-templates.html">
+      <div>
+        <h3>Material Design</h3>
+        <p>Layout Templates<p>
+      </div>
+    </a>
+  </div>
+
+  <div class="layout-content-col span-4">
+    <a class="notice-designers-material"
+      style="width:218px;"
+      href="http://www.google.com/design/spec/resources/sticker-sheets-icons.html">
+      <div>
+        <h3>Material Design</h3>
+        <p>Sticker Sheets<p>
+      </div>
+    </a>
+  </div>
+
+  <div class="layout-content-col span-4">
 <p>
-  <!--<a class="download-button"  onClick="ga('send', 'event', 'Design', 'Download', 'Fireworks Stencil');"
-    href="{@docRoot}downloads/design/Android_Design_Fireworks_Stencil_20120814.png">Adobe&reg; Fireworks&reg; PNG Stencil</a>
-  <a class="download-button"  onClick="ga('send', 'event', 'Design', 'Download', 'Illustrator Stencil');"
-    href="{@docRoot}downloads/design/Android_Design_Illustrator_Vectors_20120814.ai">Adobe&reg; Illustrator&reg; Stencil</a>
-  <a class="download-button"  onClick="ga('send', 'event', 'Design', 'Download', 'OmniGraffle Stencil');"
-    href="{@docRoot}downloads/design/Android_Design_OmniGraffle_Stencil_20120814.graffle">Omni&reg; OmniGraffle&reg; Stencil</a>-->
   <a class="download-button"  onClick="ga('send', 'event', 'Design', 'Download', 'Photoshop Sources');"
     href="{@docRoot}downloads/design/Android_Design_Stencils_Sources_20131106.zip">Adobe&reg; Photoshop&reg; Stencils and Sources</a>
 </p>
@@ -61,6 +78,18 @@
     <img src="{@docRoot}design/media/iconography_actionbar_style.png">
 
   </div>
+
+  <div class="layout-content-col span-4">
+    <a class="notice-designers-material"
+      style="width:218px;"
+      href="http://www.google.com/design/spec/resources/sticker-sheets-icons.html">
+      <div>
+        <h3>Material Design</h3>
+        <p>Sticker Sheets<p>
+      </div>
+    </a>
+  </div>
+
   <div class="layout-content-col span-4">
 
 <p>
@@ -238,6 +267,18 @@
     <img src="{@docRoot}design/media/downloads_roboto_specimen_preview.png">
 
   </div>
+
+  <div class="layout-content-col span-4">
+    <a class="notice-designers-material"
+      style="width:218px;"
+      href="http://www.google.com/design/spec/resources/roboto-noto-fonts.html">
+      <div>
+        <h3>Material Design</h3>
+        <p>Roboto Font<p>
+      </div>
+    </a>
+  </div>
+
   <div class="layout-content-col span-4">
 
 <p>
@@ -264,6 +305,18 @@
     <img src="{@docRoot}design/media/downloads_color_swatches.png">
 
   </div>
+
+  <div class="layout-content-col span-4">
+    <a class="notice-designers-material"
+      style="width:218px;"
+      href="http://www.google.com/design/spec/resources/color-palettes.html">
+      <div>
+        <h3>Material Design</h3>
+        <p>Color Palettes<p>
+      </div>
+    </a>
+  </div>
+
   <div class="layout-content-col span-4">
 
 <p>
diff --git a/docs/html/design/patterns/accessibility.jd b/docs/html/design/patterns/accessibility.jd
index aaa6f16..b968237 100644
--- a/docs/html/design/patterns/accessibility.jd
+++ b/docs/html/design/patterns/accessibility.jd
@@ -3,6 +3,14 @@
 page.metaDescription=Design an app that's universally accessible to people with visual impairment, color deficiency, hearing loss, and limited dexterity.
 @jd:body
 
+<a class="notice-designers-material"
+  href="http://www.google.com/design/spec/usability/accessibility.html">
+  <div>
+    <h3>Material Design</h3>
+    <p>Accessibility<p>
+  </div>
+</a>
+
 <a class="notice-developers" href="{@docRoot}training/accessibility/index.html">
   <div>
     <h3>Developer Docs</h3>
diff --git a/docs/html/design/patterns/actionbar.jd b/docs/html/design/patterns/actionbar.jd
index f28df01..5467722 100644
--- a/docs/html/design/patterns/actionbar.jd
+++ b/docs/html/design/patterns/actionbar.jd
@@ -5,6 +5,14 @@
 
 <img src="{@docRoot}design/media/action_bar_pattern_overview.png">
 
+
+<a class="notice-designers-material" href="http://www.google.com/design/spec/layout/structure.html#structure-app-bar">
+  <div>
+    <h3>Material Design</h3>
+    <p>App Bar<p>
+  </div>
+</a>
+
 <a class="notice-developers" href="{@docRoot}guide/topics/ui/actionbar.html">
   <div>
     <h3>Developer Docs</h3>
@@ -12,7 +20,6 @@
   </div>
 </a>
 
-
 <p>The <em>action bar</em> is a dedicated piece of real estate at the top of each screen that is generally persistent throughout the app.</p>
 <p><strong>It provides several key functions</strong>:</p>
 <ul>
diff --git a/docs/html/design/patterns/app-structure.jd b/docs/html/design/patterns/app-structure.jd
index e0a11ed..404dd4d 100644
--- a/docs/html/design/patterns/app-structure.jd
+++ b/docs/html/design/patterns/app-structure.jd
@@ -2,6 +2,15 @@
 page.tags=navigation,layout,tablet
 @jd:body
 
+
+<a class="notice-designers-material"
+  href="http://www.google.com/design/spec/patterns/app-structure.html">
+  <div>
+    <h3>Material Design</h3>
+    <p>App Structure<p>
+  </div>
+</a>
+
     <p>Apps come in many varieties that address very different needs. For example:</p>
 <ul>
 <li>Apps such as Calculator or Camera that are built around a single focused activity handled from a
@@ -63,7 +72,7 @@
     <div class="figure-caption">
       Play Music allows navigation among artists, albums, and playlists through rich content display.
       It is also enriched with tailored recommendations and promotions that surface content of interest
-      to the user. Search is readily available from the action bar. 
+      to the user. Search is readily available from the action bar.
     </div>
 
   </div>
@@ -92,7 +101,7 @@
     <img src="{@docRoot}design/media/app_structure_gmail.png">
     <div class="figure-caption">
       A calendar is about productivity, so an efficient, easy-to-skim view with higher data density works
-      well. Navigation supports switching views of day, week, month, and agenda views. 
+      well. Navigation supports switching views of day, week, month, and agenda views.
     </div>
 
   </div>
diff --git a/docs/html/design/patterns/gestures.jd b/docs/html/design/patterns/gestures.jd
index 1ec7094..ada0735 100644
--- a/docs/html/design/patterns/gestures.jd
+++ b/docs/html/design/patterns/gestures.jd
@@ -2,6 +2,14 @@
 page.tags=gesture,input,touch
 @jd:body
 
+<a class="notice-designers-material"
+   href="http://www.google.com/design/spec/patterns/gestures.html">
+  <div>
+    <h3>Material Design</h3>
+    <p>Gestures<p>
+  </div>
+</a>
+
 <p>Gestures allow users to interact with your app by manipulating the screen objects you provide. The
 following table shows the core gesture set that is supported in Android.</p>
 
@@ -92,7 +100,7 @@
       </li>
     </ul>
   </div>
-  
+
 </div>
 
 
diff --git a/docs/html/design/patterns/multi-pane-layouts.jd b/docs/html/design/patterns/multi-pane-layouts.jd
index 4e99462..dbe7d01 100644
--- a/docs/html/design/patterns/multi-pane-layouts.jd
+++ b/docs/html/design/patterns/multi-pane-layouts.jd
@@ -5,6 +5,14 @@
 @jd:body
 
 
+<a class="notice-designers-material"
+  href="http://www.google.com/design/spec/layout/structure.html#structure-ui-regions">
+  <div>
+    <h3>Material Design</h3>
+    <p>UI Regions and Guidance<p>
+  </div>
+</a>
+
 <a class="notice-developers" href="{@docRoot}training/basics/fragments/index.html">
   <div>
     <h3>Developer Docs</h3>
@@ -47,7 +55,7 @@
   <div class="layout-content-col span-8">
 
     <img src="{@docRoot}design/media/multipane_stretch.png">
-    
+
   </div>
   <div class="layout-content-col span-5">
 
@@ -61,7 +69,7 @@
   <div class="layout-content-col span-8">
 
     <img src="{@docRoot}design/media/multipane_stack.png">
-    
+
   </div>
   <div class="layout-content-col span-5">
 
@@ -75,7 +83,7 @@
   <div class="layout-content-col span-8">
 
     <img src="{@docRoot}design/media/multipane_expand.png">
-    
+
   </div>
   <div class="layout-content-col span-5">
 
@@ -89,7 +97,7 @@
   <div class="layout-content-col span-8">
 
     <img src="{@docRoot}design/media/multipane_show.png">
-    
+
   </div>
   <div class="layout-content-col span-5">
 
diff --git a/docs/html/design/patterns/navigation-drawer.jd b/docs/html/design/patterns/navigation-drawer.jd
index 7e63ba6c..dbac459 100644
--- a/docs/html/design/patterns/navigation-drawer.jd
+++ b/docs/html/design/patterns/navigation-drawer.jd
@@ -3,6 +3,14 @@
 @jd:body
 
 
+<a class="notice-designers-material"
+  href="http://www.google.com/design/spec/layout/structure.html#structure-side-nav">
+  <div>
+    <h3>Material Design</h3>
+    <p>Side Nav<p>
+  </div>
+</a>
+
 <a class="notice-developers" href="{@docRoot}training/implementing-navigation/nav-drawer.html">
   <div>
     <h3>Developer Docs</h3>
@@ -12,7 +20,7 @@
 
 
 <p>The navigation drawer is a panel that transitions in from the left edge of the screen and
-displays the app’s main navigation options.</p> 
+displays the app’s main navigation options.</p>
 
 
 <h4>Displaying the navigation drawer</h4>
@@ -92,7 +100,7 @@
 
 <p>The navigation drawer is a reflection of your app’s structure and displays its major
 navigation hubs. Think of navigation hubs as those places in your app that a user will want
-to visit frequently or use as a jumping-off point to other parts of the app. 
+to visit frequently or use as a jumping-off point to other parts of the app.
 At a minimum, the navigation hubs are the top-level views, since they correspond to your app’s
 major functional areas.</p>
 <p> If your app’s structure is deep, you can add screens from lower levels that your users will
@@ -125,8 +133,8 @@
 <h2 id="Content">Content of the Navigation Drawer</h2>
 
 <p> Keep the content of the navigation drawer focused on app navigation. Expose the navigation
-hubs of your app as list items inside the navigation drawer - one item per row. 
-    
+hubs of your app as list items inside the navigation drawer - one item per row.
+
 <div class="layout-content-row">
   <div class="layout-content-col span-8">
   <h4>Titles, icons, and counters</h4>
@@ -139,7 +147,7 @@
   <div class="layout-content-col span-5">
   <img src="{@docRoot}design/media/navigation_drawer_titles_icons.png">
   <div class="figure-caption">
-    Use titles and icons to organize your drawer. 
+    Use titles and icons to organize your drawer.
   </div>
   </div>
 </div>
@@ -149,13 +157,13 @@
   <img src="{@docRoot}design/media/navigation_drawer_collapse.png">
   <div class="figure-caption">
     Collapsible navigation items are split. Use the left side for navigation and the right
-    to collapse and expand items. 
+    to collapse and expand items.
     </div>
   </div>
   <div class="layout-content-col span-5">
   <h4>Collapsible navigation items</h4>
   <p>If you have many views with some subordinate to others, consider collapsing them into one
-  expandable item to conserve space. 
+  expandable item to conserve space.
   The parent in the navigation drawer then turns into a split item. The left side allows
   navigation to the parent item’s view, and the right side collapses or expands the list of
   child items. </p>
@@ -189,7 +197,7 @@
 <img src="{@docRoot}design/media/navigation_drawer_open_overflow.png">
 <div class="figure-caption">
   Clean up the action bar when the drawer is fully expanded. Remove actions that are not needed
-  and display your app's name in the title area. 
+  and display your app's name in the title area.
 </div>
 
 <h4>Actions</h4>
@@ -232,7 +240,7 @@
 
 <img src="{@docRoot}design/media/navigation_drawer_CAB.png">
 <div class="figure-caption">
-  Hide contextual action bars while the drawer is visible. 
+  Hide contextual action bars while the drawer is visible.
 </div>
 
 <p>If the user navigates away from a view with selected content, deselect the content before
diff --git a/docs/html/design/patterns/selection.jd b/docs/html/design/patterns/selection.jd
index be31677..7ed6dcc 100644
--- a/docs/html/design/patterns/selection.jd
+++ b/docs/html/design/patterns/selection.jd
@@ -2,6 +2,14 @@
 page.tags=actionmode,navigation,contextual
 @jd:body
 
+<a class="notice-designers-material"
+  href="http://www.google.com/design/spec/patterns/selection.html">
+  <div>
+    <h3>Material Design</h3>
+    <p>Selection<p>
+  </div>
+</a>
+
 <a class="notice-developers" href="{@docRoot}guide/topics/ui/menus.html#context-menu">
   <div>
     <h3>Developer Docs</h3>
@@ -9,6 +17,7 @@
   </div>
 </a>
 
+
 <p>Android 3.0 changed the <em>long press</em> gesture&mdash;that is, a touch that's held in the same position for a moment&mdash;to be the global gesture to select data.. This affects the way you should
 handle multi-select and contextual actions in your apps.</p>
 
diff --git a/docs/html/design/patterns/settings.jd b/docs/html/design/patterns/settings.jd
index e3a3f05..a24d6c0 100644
--- a/docs/html/design/patterns/settings.jd
+++ b/docs/html/design/patterns/settings.jd
@@ -2,6 +2,14 @@
 page.tags=preferences,sharedpreferences
 @jd:body
 
+<a class="notice-designers-material"
+  href="http://www.google.com/design/spec/patterns/settings.html">
+  <div>
+    <h3>Material Design</h3>
+    <p>Settings<p>
+  </div>
+</a>
+
 <a class="notice-developers" href="{@docRoot}guide/topics/ui/settings.html">
   <div>
     <h3>Developer Docs</h3>
@@ -9,6 +17,7 @@
   </div>
 </a>
 
+
 <p itemprop="description">Settings is a place in your app where users indicate their preferences for how your app should
 behave. This benefits users because:</p>
 
diff --git a/docs/html/design/style/branding.jd b/docs/html/design/style/branding.jd
index 2353a93..b5bb77c 100644
--- a/docs/html/design/style/branding.jd
+++ b/docs/html/design/style/branding.jd
@@ -7,6 +7,14 @@
 
 <h2 id="color">Color</h2>
 
+<a class="notice-designers-material"
+  href="http://www.google.com/design/spec/style/color.html#color-ui-color-application">
+  <div>
+    <h3>Material Design</h3>
+    <p>UI Color Application<p>
+  </div>
+</a>
+
 <p>Use your brand color for accent by overriding the Android framework's default blue in UI elements like checkboxes, progress bars, radio buttons, sliders, tabs, and scroll indicators.</p>
 
 <p>Look for opportunities to use high-contrast color for emphasis, for example, as the background color of the action bar or a primary button. But don't go overboard: not all actions are equal, so use it only for the one or two most important things.</p>
@@ -62,17 +70,32 @@
       Example of a the logo in the action bar. This works well in cases where the brand's logo matches the name of the app.
     </div>
   </div>
-</div> 
+</div>
 
 <h2 id="logo">Icons</h2>
 
+<a class="notice-designers-material" href="http://www.google.com/design/spec/style/icons.html">
+  <div>
+    <h3>Material Design</h3>
+    <p>Icons<p>
+  </div>
+</a>
+
+<p>If you have icons that you're already using for your app on other platforms
+and they have a distinctive look intended to fit your brand, use them on your
+Android app as well. <strong>If you take this approach, make sure your brand styling is
+applied to every single icon in your app.</strong></p>
+
 
 <div class="layout-content-row">
   <div class="layout-content-col span-6">
-    <p>If you have icons that you're already using for your app on other platforms
-    and they have a distinctive look intended to fit your brand, use them on your
-    Android app as well. <strong>If you take this approach, make sure your brand styling is
-    applied to every single icon in your app</strong>.</p>
+    <p>One exception: For any icon in your existing set where the symbol is different from
+    Android's, use Android's symbol but give it your brand's styling. That way, users will
+    understand what the purpose of the icon is based on what they've learned in other
+    Android apps (Design principle:
+    <a href="{@docRoot}design/get-started/principles.html#give-me-tricks">Give me tricks that
+    work everywhere</a>). But the icon will still look like it belongs with all of
+    your other icons as a part of your brand.</p>
 
   </div>
 
@@ -81,13 +104,6 @@
     </div>
   </div>
 </div>
-  <p>One exception: For any icon in your existing set where the symbol is different from
-  Android's, use Android's symbol but give it your brand's styling. That way, users will
-  understand what the purpose of the icon is based on what they've learned in other
-  Android apps (Design principle:
-  <a href="{@docRoot}design/get-started/principles.html#give-me-tricks">Give me tricks that
-  work everywhere</a>). But the icon will still look like it belongs with all of
-  your other icons as a part of your brand.</p>
 
 <div class="layout-content-row">
   <div class="layout-content-col span-6">
diff --git a/docs/html/design/style/color.jd b/docs/html/design/style/color.jd
index e00f6bc..4c5f5ab 100644
--- a/docs/html/design/style/color.jd
+++ b/docs/html/design/style/color.jd
@@ -88,6 +88,13 @@
   }
 </style>
 
+<a class="notice-designers-material" href="http://www.google.com/design/spec/style/color.html">
+  <div>
+    <h3>Material Design</h3>
+    <p>Color<p>
+  </div>
+</a>
+
 <p>Use color primarily for emphasis. Choose colors that fit with your brand and provide good contrast
 between visual components. Note that red and green may be indistinguishable to color-blind users.</p>
 
@@ -129,6 +136,6 @@
           .css('color', color)
           .text(color.toUpperCase());
     });
-    
+
   });
 </script>
diff --git a/docs/html/design/style/devices-displays.jd b/docs/html/design/style/devices-displays.jd
index 6a7234b..1590363 100644
--- a/docs/html/design/style/devices-displays.jd
+++ b/docs/html/design/style/devices-displays.jd
@@ -3,6 +3,14 @@
 
 @jd:body
 
+<a class="notice-designers-material"
+  href="http://www.google.com/design/spec/layout/principles.html">
+  <div>
+    <h3>Material Design</h3>
+    <p>Layout Principles<p>
+  </div>
+</a>
+
 <p>Android powers hundreds of millions of phones, tablets, and other devices in a wide variety of screen sizes and
 form factors. By taking advantage of Android's flexible layout system, you can create apps that
 gracefully scale from large tablets to smaller phones.</p>
@@ -15,12 +23,14 @@
   <div class="layout-content-col span-4">
 
 <h4>Be flexible</h4>
+
 <p>Stretch and compress your layouts to accommodate various heights and widths.</p>
 
   </div>
   <div class="layout-content-col span-5">
 
 <h4>Optimize layouts</h4>
+
 <p>On larger devices, take advantage of extra screen real estate. Create compound views that combine
 multiple views to reveal more content and ease navigation.</p>
 
@@ -37,6 +47,15 @@
   <img src="{@docRoot}design/media/devices_displays_density@2x.png" alt="" height="160" />
 
 <h4>Strategies</h4>
+
+<a class="notice-designers-material"
+  href="http://www.google.com/design/spec/layout/structure.html">
+  <div>
+    <h3>Material Design</h3>
+    <p>Layout Structure<p>
+  </div>
+</a>
+
 <p>So where do you begin when designing for multiple screens? One approach is to work in the base
 standard (normal size and <acronym title="Medium density (160 dpi)">MDPI</acronym>) and scale it up or
 down for the other buckets. Another approach is to start with the device with the largest screen
diff --git a/docs/html/design/style/iconography.jd b/docs/html/design/style/iconography.jd
index 75f541a..e2cdf3f 100644
--- a/docs/html/design/style/iconography.jd
+++ b/docs/html/design/style/iconography.jd
@@ -41,6 +41,14 @@
 
 <h2 id="launcher">Launcher</h2>
 
+<a class="notice-designers-material"
+  href="http://www.google.com/design/spec/style/icons.html#icons-product-icons">
+  <div>
+    <h3>Material Design</h3>
+    <p>Product Icons<p>
+  </div>
+</a>
+
 <p>The launcher icon is the visual representation of your app on the Home or All Apps screen. Since the
 user can change the Home screen's wallpaper, make sure that your launcher icon is clearly visible on
 any type of background.</p>
@@ -123,6 +131,14 @@
 
 <h2 id="action-bar">Action Bar</h2>
 
+<a class="notice-designers-material"
+  href="http://www.google.com/design/spec/style/icons.html#icons-system-icons">
+  <div>
+    <h3>Material Design</h3>
+    <p>System Icons<p>
+  </div>
+</a>
+
 <p>
 
 Action bar icons are graphic buttons that represent the most important actions people can take
@@ -220,6 +236,14 @@
 
 <h2 id="small-contextual">Small / Contextual Icons</h2>
 
+<a class="notice-designers-material"
+  href="http://www.google.com/design/spec/style/icons.html#icons-system-icons">
+  <div>
+    <h3>Material Design</h3>
+    <p>System Icons<p>
+  </div>
+</a>
+
 <p>Within the body of your app, use small icons to surface actions and/or provide status for specific
 items. For example, in the Gmail app, each message has a star icon that marks the message as
 important.</p>
@@ -300,6 +324,15 @@
 
 <h2 id="notification">Notification Icons</h2>
 
+<a class="notice-designers-material"
+  href="http://www.google.com/design/spec/style/icons.html#icons-system-icons">
+  <div>
+    <h3>Material Design</h3>
+    <p>System Icons<p>
+  </div>
+</a>
+
+
 <p>If your app generates notifications, provide an icon that the system can display in the status bar
 whenever a new notification is available.</p>
 
diff --git a/docs/html/design/style/metrics-grids.jd b/docs/html/design/style/metrics-grids.jd
index e92d57e..d7b5f78 100644
--- a/docs/html/design/style/metrics-grids.jd
+++ b/docs/html/design/style/metrics-grids.jd
@@ -5,6 +5,16 @@
 page.image=/design/media/metrics_closeup.png
 @jd:body
 
+
+<a class="notice-designers-material"
+  href="http://www.google.com/design/spec/layout/metrics-keylines.html">
+  <div>
+    <h3>Material Design</h3>
+    <p>Metrics and Keylines<p>
+  </div>
+</a>
+
+
 <p>Devices vary not only in physical size, but also in screen density (<acronym title="Dots per
 inch">DPI</acronym>). To simplify the way you design for multiple screens, think of each device as
 falling into a particular size bucket and density bucket:</p>
diff --git a/docs/html/design/style/themes.jd b/docs/html/design/style/themes.jd
index 2dc8ead..3313a2b 100644
--- a/docs/html/design/style/themes.jd
+++ b/docs/html/design/style/themes.jd
@@ -17,6 +17,16 @@
   </div>
   <div class="layout-content-col span-7">
 
+
+<a class="notice-designers-material"
+  href="http://www.google.com/design/spec/style/color.html#color-themes">
+  <div>
+    <h3>Material Design</h3>
+    <p>Color Themes<p>
+  </div>
+</a>
+
+
 <p>Themes are Android's mechanism for applying a consistent style to an app or activity.
 The style specifies the visual properties of the elements that make up your user interface,
 such as color, height, padding and font size. To promote greater cohesion between all apps
@@ -34,7 +44,7 @@
 
 <div class="note develop">
 <p><strong>Developer Guide</strong></p>
-  <p>For information about how to apply themes such as Holo Light and Dark, and 
+  <p>For information about how to apply themes such as Holo Light and Dark, and
   how to build your own themes, see the
   <a href="{@docRoot}guide/topics/ui/themes.html">Styles and Themes</a> API guide.</p>
 </div>
diff --git a/docs/html/design/style/touch-feedback.jd b/docs/html/design/style/touch-feedback.jd
index 9f36fed..b6d6407 100644
--- a/docs/html/design/style/touch-feedback.jd
+++ b/docs/html/design/style/touch-feedback.jd
@@ -2,8 +2,17 @@
 page.tags=input,button
 @jd:body
 
-    <div class="layout-content-row" style="margin-bottom: -100px">
-  <div class="layout-content-col span-7">
+<div class="layout-content-row" style="margin-bottom: -100px">
+<div class="layout-content-col span-7">
+
+<a class="notice-designers-material"
+  href="http://www.google.com/design/spec/animation/responsive-interaction.html">
+  <div>
+    <h3>Material Design</h3>
+    <p>Responsive Interaction<p>
+  </div>
+</a>
+
 
 <p>Use illumination and dimming to respond to touches, reinforce the resulting behaviors
 of gestures, and indicate what actions are enabled and disabled.</p>
diff --git a/docs/html/design/style/typography.jd b/docs/html/design/style/typography.jd
index a665097..2f8e91b 100644
--- a/docs/html/design/style/typography.jd
+++ b/docs/html/design/style/typography.jd
@@ -9,7 +9,17 @@
     <img src="{@docRoot}design/media/typography_main.png">
 
   </div>
-  <div class="layout-content-col span-5">
+
+<a class="notice-designers-material"
+  style="width: 278px;"
+  href="http://www.google.com/design/spec/style/typography.html">
+  <div>
+    <h3>Material Design</h3>
+    <p>Typography<p>
+  </div>
+</a>
+
+<div class="layout-content-col span-5">
 
 <p>
   <a class="download-button"  onClick="ga('send', 'event', 'Design', 'Download', 'Roboto ZIP');"
diff --git a/include/androidfw/ResourceTypes.h b/include/androidfw/ResourceTypes.h
index da70e9b..df278c8 100644
--- a/include/androidfw/ResourceTypes.h
+++ b/include/androidfw/ResourceTypes.h
@@ -372,7 +372,8 @@
     };
 
     // The data for this item, as interpreted according to dataType.
-    uint32_t data;
+    typedef uint32_t data_type;
+    data_type data;
 
     void copyFrom_dtoh(const Res_value& src);
 };
@@ -1512,6 +1513,8 @@
     KeyedVector<String16, uint8_t>  mEntries;
 };
 
+bool U16StringToInt(const char16_t* s, size_t len, Res_value* outValue);
+
 /**
  * Convenience class for accessing data in a ResTable resource.
  */
diff --git a/libs/androidfw/ResourceTypes.cpp b/libs/androidfw/ResourceTypes.cpp
index e247150..04ebe70 100644
--- a/libs/androidfw/ResourceTypes.cpp
+++ b/libs/androidfw/ResourceTypes.cpp
@@ -17,6 +17,16 @@
 #define LOG_TAG "ResourceType"
 //#define LOG_NDEBUG 0
 
+#include <ctype.h>
+#include <memory.h>
+#include <stddef.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <limits>
+#include <type_traits>
+
 #include <androidfw/ByteBucketArray.h>
 #include <androidfw/ResourceTypes.h>
 #include <androidfw/TypeWrappers.h>
@@ -27,17 +37,10 @@
 #include <utils/String16.h>
 #include <utils/String8.h>
 
-#ifdef HAVE_ANDROID_OS
+#ifdef __ANDROID__
 #include <binder/TextOutput.h>
 #endif
 
-#include <stdlib.h>
-#include <string.h>
-#include <memory.h>
-#include <ctype.h>
-#include <stdint.h>
-#include <stddef.h>
-
 #ifndef INT32_MAX
 #define INT32_MAX ((int32_t)(2147483647))
 #endif
@@ -4615,8 +4618,7 @@
     return false;
 }
 
-
-bool ResTable::stringToInt(const char16_t* s, size_t len, Res_value* outValue)
+bool U16StringToInt(const char16_t* s, size_t len, Res_value* outValue)
 {
     while (len > 0 && isspace16(*s)) {
         s++;
@@ -4628,7 +4630,7 @@
     }
 
     size_t i = 0;
-    int32_t val = 0;
+    int64_t val = 0;
     bool neg = false;
 
     if (*s == '-') {
@@ -4640,28 +4642,50 @@
         return false;
     }
 
+    static_assert(std::is_same<uint32_t, Res_value::data_type>::value,
+                  "Res_value::data_type has changed. The range checks in this "
+                  "function are no longer correct.");
+
     // Decimal or hex?
-    if (s[i] == '0' && s[i+1] == 'x') {
-        if (outValue)
-            outValue->dataType = outValue->TYPE_INT_HEX;
+    bool isHex;
+    if (len > 1 && s[i] == '0' && s[i+1] == 'x') {
+        isHex = true;
         i += 2;
+
+        if (neg) {
+            return false;
+        }
+
+        if (i == len) {
+            // Just u"0x"
+            return false;
+        }
+
         bool error = false;
         while (i < len && !error) {
             val = (val*16) + get_hex(s[i], &error);
             i++;
+
+            if (val > std::numeric_limits<uint32_t>::max()) {
+                return false;
+            }
         }
         if (error) {
             return false;
         }
     } else {
-        if (outValue)
-            outValue->dataType = outValue->TYPE_INT_DEC;
+        isHex = false;
         while (i < len) {
             if (s[i] < '0' || s[i] > '9') {
                 return false;
             }
             val = (val*10) + s[i]-'0';
             i++;
+
+            if ((neg && -val < std::numeric_limits<int32_t>::min()) ||
+                (!neg && val > std::numeric_limits<int32_t>::max())) {
+                return false;
+            }
         }
     }
 
@@ -4671,13 +4695,21 @@
         i++;
     }
 
-    if (i == len) {
-        if (outValue)
-            outValue->data = val;
-        return true;
+    if (i != len) {
+        return false;
     }
 
-    return false;
+    if (outValue) {
+        outValue->dataType =
+            isHex ? outValue->TYPE_INT_HEX : outValue->TYPE_INT_DEC;
+        outValue->data = static_cast<Res_value::data_type>(val);
+    }
+    return true;
+}
+
+bool ResTable::stringToInt(const char16_t* s, size_t len, Res_value* outValue)
+{
+    return U16StringToInt(s, len, outValue);
 }
 
 bool ResTable::stringToFloat(const char16_t* s, size_t len, Res_value* outValue)
diff --git a/libs/androidfw/tests/Android.mk b/libs/androidfw/tests/Android.mk
index 58b78b5..a353575 100644
--- a/libs/androidfw/tests/Android.mk
+++ b/libs/androidfw/tests/Android.mk
@@ -19,6 +19,7 @@
 # targets here.
 # ==========================================================
 LOCAL_PATH:= $(call my-dir)
+
 testFiles := \
     AttributeFinder_test.cpp \
     ByteBucketArray_test.cpp \
@@ -32,27 +33,33 @@
     TypeWrappers_test.cpp \
     ZipUtils_test.cpp
 
+androidfw_test_cflags := \
+    -Wall \
+    -Werror \
+    -Wunused \
+    -Wunreachable-code \
+    -Wno-missing-field-initializers \
+
+# gtest is broken.
+androidfw_test_cflags += -Wno-unnamed-type-template-args
+
 # ==========================================================
 # Build the host tests: libandroidfw_tests
 # ==========================================================
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := libandroidfw_tests
-
-LOCAL_CFLAGS += -Wall -Werror -Wunused -Wunreachable-code
-# gtest is broken.
-LOCAL_CFLAGS += -Wno-unnamed-type-template-args
-
+LOCAL_CFLAGS := $(androidfw_test_cflags)
 LOCAL_SRC_FILES := $(testFiles)
 LOCAL_STATIC_LIBRARIES := \
     libandroidfw \
     libutils \
     libcutils \
-    liblog
+    liblog \
+    libz \
 
 include $(BUILD_HOST_NATIVE_TEST)
 
-
 # ==========================================================
 # Build the device tests: libandroidfw_tests
 # ==========================================================
@@ -60,14 +67,11 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := libandroidfw_tests
-
-LOCAL_CFLAGS += -Wall -Werror -Wunused -Wunreachable-code
-# gtest is broken.
-LOCAL_CFLAGS += -Wno-unnamed-type-template-args
-
+LOCAL_CFLAGS := $(androidfw_test_cflags)
 LOCAL_SRC_FILES := $(testFiles) \
     BackupData_test.cpp \
-    ObbFile_test.cpp
+    ObbFile_test.cpp \
+
 LOCAL_SHARED_LIBRARIES := \
     libandroidfw \
     libcutils \
diff --git a/libs/androidfw/tests/ResTable_test.cpp b/libs/androidfw/tests/ResTable_test.cpp
index 6a9314e..dcfe91e 100644
--- a/libs/androidfw/tests/ResTable_test.cpp
+++ b/libs/androidfw/tests/ResTable_test.cpp
@@ -16,6 +16,10 @@
 
 #include <androidfw/ResourceTypes.h>
 
+#include <codecvt>
+#include <locale>
+#include <string>
+
 #include <utils/String8.h>
 #include <utils/String16.h>
 #include "TestHelpers.h"
@@ -201,4 +205,81 @@
     ASSERT_LT(table.getResource(base::R::integer::number1, &val, MAY_NOT_BE_BAG), 0);
 }
 
+void testU16StringToInt(const char16_t* str, uint32_t expectedValue,
+                        bool expectSuccess, bool expectHex) {
+    size_t len = std::char_traits<char16_t>::length(str);
+
+    // Gtest can't print UTF-16 strings, so we have to convert to UTF-8 :(
+    std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert;
+    std::string s = convert.to_bytes(std::u16string(str, len));
+
+    Res_value out = {};
+    ASSERT_EQ(expectSuccess, U16StringToInt(str, len, &out))
+        << "Failed with " << s;
+
+    if (!expectSuccess) {
+        ASSERT_EQ(out.TYPE_NULL, out.dataType) << "Failed with " << s;
+        return;
+    }
+
+    if (expectHex) {
+        ASSERT_EQ(out.TYPE_INT_HEX, out.dataType) << "Failed with " << s;
+    } else {
+        ASSERT_EQ(out.TYPE_INT_DEC, out.dataType) << "Failed with " << s;
+    }
+
+    ASSERT_EQ(expectedValue, out.data) << "Failed with " << s;
+}
+
+TEST(ResTableTest, U16StringToInt) {
+    testU16StringToInt(u"", 0U, false, false);
+    testU16StringToInt(u"    ", 0U, false, false);
+    testU16StringToInt(u"\t\n", 0U, false, false);
+
+    testU16StringToInt(u"abcd", 0U, false, false);
+    testU16StringToInt(u"10abcd", 0U, false, false);
+    testU16StringToInt(u"42 42", 0U, false, false);
+    testU16StringToInt(u"- 42", 0U, false, false);
+    testU16StringToInt(u"-", 0U, false, false);
+
+    testU16StringToInt(u"0x", 0U, false, true);
+    testU16StringToInt(u"0xnope", 0U, false, true);
+    testU16StringToInt(u"0X42", 0U, false, true);
+    testU16StringToInt(u"0x42 0x42", 0U, false, true);
+    testU16StringToInt(u"-0x0", 0U, false, true);
+    testU16StringToInt(u"-0x42", 0U, false, true);
+    testU16StringToInt(u"- 0x42", 0U, false, true);
+
+    // Note that u" 42" would pass. This preserves the old behavior, but it may
+    // not be desired.
+    testU16StringToInt(u"42 ", 0U, false, false);
+    testU16StringToInt(u"0x42 ", 0U, false, true);
+
+    // Decimal cases.
+    testU16StringToInt(u"0", 0U, true, false);
+    testU16StringToInt(u"-0", 0U, true, false);
+    testU16StringToInt(u"42", 42U, true, false);
+    testU16StringToInt(u" 42", 42U, true, false);
+    testU16StringToInt(u"-42", static_cast<uint32_t>(-42), true, false);
+    testU16StringToInt(u" -42", static_cast<uint32_t>(-42), true, false);
+    testU16StringToInt(u"042", 42U, true, false);
+    testU16StringToInt(u"-042", static_cast<uint32_t>(-42), true, false);
+
+    // Hex cases.
+    testU16StringToInt(u"0x0", 0x0, true, true);
+    testU16StringToInt(u"0x42", 0x42, true, true);
+    testU16StringToInt(u" 0x42", 0x42, true, true);
+
+    // Just before overflow cases:
+    testU16StringToInt(u"2147483647", INT_MAX, true, false);
+    testU16StringToInt(u"-2147483648", static_cast<uint32_t>(INT_MIN), true,
+                       false);
+    testU16StringToInt(u"0xffffffff", UINT_MAX, true, true);
+
+    // Overflow cases:
+    testU16StringToInt(u"2147483648", 0U, false, false);
+    testU16StringToInt(u"-2147483649", 0U, false, false);
+    testU16StringToInt(u"0x1ffffffff", 0U, false, true);
+}
+
 }
diff --git a/media/java/android/media/AudioRecord.java b/media/java/android/media/AudioRecord.java
index fc0189c..9e1e055 100644
--- a/media/java/android/media/AudioRecord.java
+++ b/media/java/android/media/AudioRecord.java
@@ -398,8 +398,8 @@
      * default output sample rate of the device (see
      * {@link AudioManager#PROPERTY_OUTPUT_SAMPLE_RATE}), its channel configuration will be
      * {@link AudioFormat#CHANNEL_IN_DEFAULT}.
-     * <br>Failing to set an adequate buffer size with {@link #setBufferSizeInBytes(int)} will
-     * prevent the successful creation of an <code>AudioRecord</code> instance.
+     * <br>If the buffer size is not specified with {@link #setBufferSizeInBytes(int)},
+     * the minimum buffer size for the source is used.
      */
     public static class Builder {
         private AudioAttributes mAttributes;
@@ -473,7 +473,9 @@
          * during the recording. New audio data can be read from this buffer in smaller chunks
          * than this size. See {@link #getMinBufferSize(int, int, int)} to determine the minimum
          * required buffer size for the successful creation of an AudioRecord instance.
-         * Using values smaller than getMinBufferSize() will result in an initialization failure.
+         * Since bufferSizeInBytes may be internally increased to accommodate the source
+         * requirements, use {@link #getNativeFrameCount()} to determine the actual buffer size
+         * in frames.
          * @param bufferSizeInBytes a value strictly greater than 0
          * @return the same Builder instance.
          * @throws IllegalArgumentException
@@ -520,6 +522,13 @@
                         .build();
             }
             try {
+                // If the buffer size is not specified,
+                // use a single frame for the buffer size and let the
+                // native code figure out the minimum buffer size.
+                if (mBufferSizeInBytes == 0) {
+                    mBufferSizeInBytes = mFormat.getChannelCount()
+                            * mFormat.getBytesPerSample(mFormat.getEncoding());
+                }
                 return new AudioRecord(mAttributes, mFormat, mBufferSizeInBytes, mSessionId);
             } catch (IllegalArgumentException e) {
                 throw new UnsupportedOperationException(e.getMessage());
@@ -711,6 +720,20 @@
     }
 
     /**
+     *  Returns the "native frame count" of the <code>AudioRecord</code> buffer.
+     *  This is greater than or equal to the bufferSizeInBytes converted to frame units
+     *  specified in the <code>AudioRecord</code> constructor or Builder.
+     *  The native frame count may be enlarged to accommodate the requirements of the
+     *  source on creation or if the <code>AudioRecord</code>
+     *  is subsequently rerouted.
+     *  @return current size in frames of the <code>AudioRecord</code> buffer.
+     *  @throws IllegalStateException
+     */
+    public int getNativeFrameCount() throws IllegalStateException {
+        return native_get_native_frame_count();
+    }
+
+    /**
      * Returns the notification marker position expressed in frames.
      */
     public int getNotificationMarkerPosition() {
@@ -1173,6 +1196,8 @@
 
     private native final int native_read_in_direct_buffer(Object jBuffer, int sizeInBytes);
 
+    private native final int native_get_native_frame_count();
+
     private native final int native_set_marker_pos(int marker);
     private native final int native_get_marker_pos();
 
diff --git a/media/java/android/media/MediaCodec.java b/media/java/android/media/MediaCodec.java
index e028e3f..59fccda 100644
--- a/media/java/android/media/MediaCodec.java
+++ b/media/java/android/media/MediaCodec.java
@@ -325,13 +325,6 @@
      */
     public static final int BUFFER_FLAG_END_OF_STREAM = 4;
 
-    /**
-     * This indicates that the codec is released because the media resources used by the codec
-     * have been reclaimed, for example by the resource manager.
-     * This is used by the {@link Callback#onCodecReleased} callback.
-     */
-    public static final int REASON_RECLAIMED = 1;
-
     private EventHandler mEventHandler;
     private Callback mCallback;
 
@@ -342,7 +335,6 @@
     private static final int CB_OUTPUT_AVAILABLE = 2;
     private static final int CB_ERROR = 3;
     private static final int CB_OUTPUT_FORMAT_CHANGE = 4;
-    private static final int CB_CODEC_RELEASED = 5;
 
     private class EventHandler extends Handler {
         private MediaCodec mCodec;
@@ -413,13 +405,6 @@
                     break;
                 }
 
-                case CB_CODEC_RELEASED:
-                {
-                    int reason = msg.arg2;
-                    mCallback.onCodecReleased(mCodec, reason);
-                    break;
-                }
-
                 default:
                 {
                     break;
@@ -687,6 +672,7 @@
         CodecException(int errorCode, int actionCode, String detailMessage) {
             super(detailMessage);
             mErrorCode = errorCode;
+            mReason = REASON_HARDWARE;
             mActionCode = actionCode;
 
             // TODO get this from codec
@@ -714,6 +700,15 @@
         }
 
         /**
+         * Retrieve the reason associated with a CodecException.
+         * The reason could be one of {@link #REASON_HARDWARE} or {@link #REASON_RECLAIMED}.
+         *
+         */
+        public int getReason() {
+            return mReason;
+        }
+
+        /**
          * Retrieve the error code associated with a CodecException.
          * This is opaque diagnostic information and may depend on
          * hardware or API level.
@@ -734,13 +729,26 @@
             return mDiagnosticInfo;
         }
 
+        /**
+         * This indicates the exception is caused by the hardware.
+         */
+        public static final int REASON_HARDWARE = 0;
+
+        /**
+         * This indicates the exception is because the resource manager reclaimed
+         * the media resource used by the codec.
+         * <p>
+         * With this exception, the codec must be released, as it has moved to terminal state.
+         */
+        public static final int REASON_RECLAIMED = 1;
+
         /* Must be in sync with android_media_MediaCodec.cpp */
-        private final static int ACTION_FATAL = 0;
         private final static int ACTION_TRANSIENT = 1;
         private final static int ACTION_RECOVERABLE = 2;
 
         private final String mDiagnosticInfo;
         private final int mErrorCode;
+        private final int mReason;
         private final int mActionCode;
     }
 
@@ -1670,22 +1678,6 @@
          * @param format The new output format.
          */
         public abstract void onOutputFormatChanged(MediaCodec codec, MediaFormat format);
-
-        /**
-         * Called when the underlying codec component has been released.
-         * <p>
-         * At this point the MediaCodec must be released, as it has moved to terminal
-         * Uninitialized state.
-         *
-         * @param codec The MediaCodec object.
-         * @param reason The reason of the release.
-         */
-        public void onCodecReleased(MediaCodec codec, int reason) {
-            int errorCode = -1;
-            String detailMessage = "resources reclaimed";
-            onError(codec,
-                    new CodecException(errorCode, CodecException.ACTION_FATAL, detailMessage));
-        }
     }
 
     private void postEventFromNative(
diff --git a/media/java/android/media/audiopolicy/AudioMix.java b/media/java/android/media/audiopolicy/AudioMix.java
index 1806662..6aa4d8a 100644
--- a/media/java/android/media/audiopolicy/AudioMix.java
+++ b/media/java/android/media/audiopolicy/AudioMix.java
@@ -36,6 +36,7 @@
     private int mRouteFlags;
     private String mRegistrationId;
     private int mMixType = MIX_TYPE_INVALID;
+    private int mMixState = MIX_STATE_DISABLED;
 
     /**
      * All parameters are guaranteed valid through the Builder.
@@ -48,6 +49,7 @@
         mMixType = rule.getTargetMixType();
     }
 
+    // ROUTE_FLAG_* values to keep in sync with frameworks/av/include/media/AudioPolicy.h
     /**
      * An audio mix behavior where the output of the mix is sent to the original destination of
      * the audio signal, i.e. an output device for an output mix, or a recording for an input mix.
@@ -62,6 +64,7 @@
     @SystemApi
     public static final int ROUTE_FLAG_LOOP_BACK = 0x1 << 1;
 
+    // MIX_TYPE_* values to keep in sync with frameworks/av/include/media/AudioPolicy.h
     /**
      * @hide
      * Invalid mix type, default value.
@@ -78,6 +81,39 @@
      */
     public static final int MIX_TYPE_RECORDERS = 1;
 
+
+    // MIX_STATE_* values to keep in sync with frameworks/av/include/media/AudioPolicy.h
+    /**
+     * @hide
+     * State of a mix before its policy is enabled.
+     */
+    @SystemApi
+    public static final int MIX_STATE_DISABLED = -1;
+    /**
+     * @hide
+     * State of a mix when there is no audio to mix.
+     */
+    @SystemApi
+    public static final int MIX_STATE_IDLE = 0;
+    /**
+     * @hide
+     * State of a mix that is actively mixing audio.
+     */
+    @SystemApi
+    public static final int MIX_STATE_MIXING = 1;
+
+    /**
+     * @hide
+     * The current mixing state.
+     * @return one of {@link #MIX_STATE_DISABLED}, {@link #MIX_STATE_IDLE},
+     *          {@link #MIX_STATE_MIXING}.
+     */
+    @SystemApi
+    public int getMixState() {
+        return mMixState;
+    }
+
+
     int getRouteFlags() {
         return mRouteFlags;
     }
diff --git a/media/jni/android_media_MediaCodec.cpp b/media/jni/android_media_MediaCodec.cpp
index 71457b7..16758d0 100644
--- a/media/jni/android_media_MediaCodec.cpp
+++ b/media/jni/android_media_MediaCodec.cpp
@@ -669,14 +669,6 @@
             break;
         }
 
-        case MediaCodec::CB_CODEC_RELEASED:
-        {
-            if (!msg->findInt32("reason", &arg2)) {
-                arg2 = MediaCodec::REASON_UNKNOWN;
-            }
-            break;
-        }
-
         default:
             TRESPASS();
     }
diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/mediarecorder/MediaRecorderTest.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/mediarecorder/MediaRecorderTest.java
index d7069cac..e730329 100644
--- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/mediarecorder/MediaRecorderTest.java
+++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/mediarecorder/MediaRecorderTest.java
@@ -27,6 +27,7 @@
 import android.graphics.Paint;
 import android.graphics.Typeface;
 import android.hardware.Camera;
+import android.media.MediaMetadataRetriever;
 import android.media.MediaPlayer;
 import android.media.MediaRecorder;
 import android.media.EncoderCapabilities;
@@ -426,6 +427,29 @@
         return validVideo;
     }
 
+    private boolean validateMetadata(String filePath, int captureRate) {
+        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
+
+        retriever.setDataSource(filePath);
+
+        // verify capture rate meta key is present and correct
+        String captureFps = retriever.extractMetadata(
+                MediaMetadataRetriever.METADATA_KEY_CAPTURE_FRAMERATE);
+
+        if (captureFps == null) {
+            Log.d(TAG, "METADATA_KEY_CAPTURE_FRAMERATE is missing");
+            return false;
+        }
+
+        if (Math.abs(Float.parseFloat(captureFps) - captureRate) > 0.001) {
+            Log.d(TAG, "METADATA_KEY_CAPTURE_FRAMERATE is incorrect: "
+                    + captureFps + "vs. " + captureRate);
+            return false;
+        }
+
+        // verify other meta keys here if necessary
+        return true;
+    }
     @LargeTest
     /*
      * This test case set the camera in portrait mode.
@@ -555,13 +579,16 @@
 
                 // always set videoOnly=false, MediaRecorder should disable
                 // audio automatically with time lapse/slow motion
-                success = recordVideoFromSurface(frameRate,
-                        k==0 ? MIN_VIDEO_FPS : HIGH_SPEED_FPS,
-                        352, 288, codec,
+                int captureRate = k==0 ? MIN_VIDEO_FPS : HIGH_SPEED_FPS;
+                success = recordVideoFromSurface(
+                        frameRate, captureRate, 352, 288, codec,
                         MediaRecorder.OutputFormat.THREE_GPP,
                         filename, false /* videoOnly */);
                 if (success) {
                     success = validateVideo(filename, 352, 288);
+                    if (success) {
+                        success = validateMetadata(filename, captureRate);
+                    }
                 }
                 if (!success) {
                     noOfFailure++;
@@ -569,6 +596,7 @@
             }
         } catch (Exception e) {
             Log.v(TAG, e.toString());
+            noOfFailure++;
         }
         assertTrue("testSurfaceRecordingTimeLapse", noOfFailure == 0);
     }
diff --git a/packages/DocumentsUI/res/layout/fragment_pick.xml b/packages/DocumentsUI/res/layout/fragment_pick.xml
index 5735871..87dc4f8 100644
--- a/packages/DocumentsUI/res/layout/fragment_pick.xml
+++ b/packages/DocumentsUI/res/layout/fragment_pick.xml
@@ -21,12 +21,19 @@
     android:baselineAligned="false"
     android:gravity="center_vertical"
     android:minHeight="?android:attr/listPreferredItemHeightSmall">
-
+    <Button
+        android:id="@android:id/button2"
+        android:layout_width="wrap_content"
+        android:layout_height="match_parent"
+        android:layout_weight="1"
+        android:text="@android:string/cancel"
+        android:visibility="gone"
+        style="?android:attr/buttonBarNegativeButtonStyle" />
     <Button
         android:id="@android:id/button1"
-        android:layout_width="match_parent"
+        android:layout_width="wrap_content"
         android:layout_height="match_parent"
+        android:layout_weight="1"
         android:textAllCaps="false"
         style="?android:attr/buttonBarPositiveButtonStyle" />
-
 </LinearLayout>
diff --git a/packages/DocumentsUI/res/values/strings.xml b/packages/DocumentsUI/res/values/strings.xml
index 3ca239a..062d433 100644
--- a/packages/DocumentsUI/res/values/strings.xml
+++ b/packages/DocumentsUI/res/values/strings.xml
@@ -65,6 +65,9 @@
     <!-- Menu item that hides the sizes of displayed files [CHAR LIMIT=24] -->
     <string name="menu_file_size_hide">Hide file size</string>
 
+    <!-- Button label that copies files to the current directory [CHAR LIMIT=48] -->
+    <string name="button_copy">Copy</string>
+
     <!-- Action mode title summarizing the number of documents selected [CHAR LIMIT=32] -->
     <string name="mode_selected_count"><xliff:g id="count" example="3">%1$d</xliff:g> selected</string>
 
@@ -112,8 +115,6 @@
     <!-- Title of dialog when prompting user to select an app to share documents with [CHAR LIMIT=32] -->
     <string name="share_via">Share via</string>
 
-    <!-- Title of the cancel button [CHAR LIMIT=24] -->
-    <string name="cancel">Cancel</string>
     <!-- Title of the copy notification [CHAR LIMIT=24] -->
     <string name="copy_notification_title">Copying files</string>
     <!-- Text shown on the copy notification to indicate remaining time, in minutes [CHAR LIMIT=24] -->
@@ -125,5 +126,17 @@
     </plurals>
     <!-- Text shown on the copy notification while DocumentsUI performs setup in preparation for copying files [CHAR LIMIT=32] -->
     <string name="copy_preparing">Preparing for copy\u2026</string>
-
+    <!-- Title of the copy error notification [CHAR LIMIT=48] -->
+    <plurals name="copy_error_notification_title">
+      <item quantity="one">Error copying <xliff:g id="count" example="1">%1$d</xliff:g> file.</item>
+      <item quantity="other">Error copying <xliff:g id="count" example="1">%1$d</xliff:g> files.</item>
+    </plurals>
+    <!-- Second line for notifications saying that more information will be shown after touching [CHAR LIMIT=48] -->
+    <string name="notification_touch_for_details">Touch to view details</string>
+    <!-- Label of a dialog button for retrying a failed operation [CHAR LIMIT=24] -->
+    <string name="retry">Retry</string>
+    <!-- Title of the copying failure alert dialog. [CHAR LIMIT=48] -->
+    <string name="copy_failure_alert_title">Error copying files</string>
+    <!-- Contents of the copying failure alert dialog. [CHAR LIMIT=48] -->
+    <string name="copy_failure_alert_content">Following files are not copied: <xliff:g id="list">%1$s</xliff:g></string>
 </resources>
diff --git a/packages/DocumentsUI/src/com/android/documentsui/BaseActivity.java b/packages/DocumentsUI/src/com/android/documentsui/BaseActivity.java
index bd17401..66792da 100644
--- a/packages/DocumentsUI/src/com/android/documentsui/BaseActivity.java
+++ b/packages/DocumentsUI/src/com/android/documentsui/BaseActivity.java
@@ -33,10 +33,6 @@
 import com.google.common.collect.Maps;
 
 abstract class BaseActivity extends Activity {
-    /** Intent action name to open copy destination. */
-    public static String ACTION_OPEN_COPY_DESTINATION_STRING =
-        "com.android.documentsui.OPEN_COPY_DESTINATION";
-
     public abstract State getDisplayState();
     public abstract RootInfo getCurrentRoot();
     public abstract void onStateChanged();
@@ -56,6 +52,18 @@
         return (BaseActivity) fragment.getActivity();
     }
 
+    public static abstract class DocumentsIntent {
+        /** Intent action name to open copy destination. */
+        public static String ACTION_OPEN_COPY_DESTINATION =
+                "com.android.documentsui.OPEN_COPY_DESTINATION";
+
+        /**
+         * Extra boolean flag for ACTION_OPEN_COPY_DESTINATION_STRING, which
+         * specifies if the destination directory needs to create new directory or not.
+         */
+        public static String EXTRA_DIRECTORY_COPY = "com.android.documentsui.DIRECTORY_COPY";
+    }
+
     public static class State implements android.os.Parcelable {
         public int action;
         public String[] acceptMimes;
@@ -77,6 +85,7 @@
         public boolean showAdvanced = false;
         public boolean stackTouched = false;
         public boolean restored = false;
+        public boolean directoryCopy = false;
 
         /** Current user navigation stack; empty implies recents. */
         public DocumentStack stack = new DocumentStack();
diff --git a/packages/DocumentsUI/src/com/android/documentsui/CopyService.java b/packages/DocumentsUI/src/com/android/documentsui/CopyService.java
index e140f33..337b862 100644
--- a/packages/DocumentsUI/src/com/android/documentsui/CopyService.java
+++ b/packages/DocumentsUI/src/com/android/documentsui/CopyService.java
@@ -57,6 +57,10 @@
     private static final String EXTRA_CANCEL = "com.android.documentsui.CANCEL";
     public static final String EXTRA_SRC_LIST = "com.android.documentsui.SRC_LIST";
     public static final String EXTRA_STACK = "com.android.documentsui.STACK";
+    public static final String EXTRA_FAILURE = "com.android.documentsui.FAILURE";
+
+    // TODO: Move it to a shared file when more operations are implemented.
+    public static final int FAILURE_COPY = 1;
 
     private NotificationManager mNotificationManager;
     private Notification.Builder mProgressBuilder;
@@ -66,7 +70,7 @@
     private volatile boolean mIsCancelled;
     // Parameters of the copy job. Requests to an IntentService are serialized so this code only
     // needs to deal with one job at a time.
-    private final List<Uri> mFailedFiles;
+    private final ArrayList<Uri> mFailedFiles;
     private long mBatchSize;
     private long mBytesCopied;
     private long mStartTime;
@@ -128,7 +132,23 @@
             mNotificationManager.cancel(mJobId, 0);
 
             if (mFailedFiles.size() > 0) {
-                // TODO: Display a notification when an error has occurred.
+                final Context context = getApplicationContext();
+                final Intent navigateIntent = new Intent(context, StandaloneActivity.class);
+                navigateIntent.putExtra(EXTRA_STACK, (Parcelable) stack);
+                navigateIntent.putExtra(EXTRA_FAILURE, FAILURE_COPY);
+                navigateIntent.putParcelableArrayListExtra(EXTRA_SRC_LIST, mFailedFiles);
+
+                final Notification.Builder errorBuilder = new Notification.Builder(this)
+                        .setContentTitle(context.getResources().
+                                getQuantityString(R.plurals.copy_error_notification_title,
+                                        mFailedFiles.size(), mFailedFiles.size()))
+                        .setContentText(getString(R.string.notification_touch_for_details))
+                        .setContentIntent(PendingIntent.getActivity(context, 0, navigateIntent,
+                                PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT))
+                        .setCategory(Notification.CATEGORY_ERROR)
+                        .setSmallIcon(R.drawable.ic_menu_copy)
+                        .setAutoCancel(true);
+                mNotificationManager.notify(mJobId, 0, errorBuilder.build());
             }
 
             // TODO: Display a toast if the copy was cancelled.
@@ -158,13 +178,14 @@
 
         final Context context = getApplicationContext();
         final Intent navigateIntent = new Intent(context, StandaloneActivity.class);
-        navigateIntent.putExtra(EXTRA_STACK, (Parcelable)stack);
+        navigateIntent.putExtra(EXTRA_STACK, (Parcelable) stack);
 
         mProgressBuilder = new Notification.Builder(this)
                 .setContentTitle(getString(R.string.copy_notification_title))
                 .setContentIntent(PendingIntent.getActivity(context, 0, navigateIntent, 0))
                 .setCategory(Notification.CATEGORY_PROGRESS)
-                .setSmallIcon(R.drawable.ic_menu_copy).setOngoing(true);
+                .setSmallIcon(R.drawable.ic_menu_copy)
+                .setOngoing(true);
 
         final Intent cancelIntent = new Intent(this, CopyService.class);
         cancelIntent.putExtra(EXTRA_CANCEL, mJobId);
diff --git a/packages/DocumentsUI/src/com/android/documentsui/DirectoryFragment.java b/packages/DocumentsUI/src/com/android/documentsui/DirectoryFragment.java
index 61fcad2..e2e9807 100644
--- a/packages/DocumentsUI/src/com/android/documentsui/DirectoryFragment.java
+++ b/packages/DocumentsUI/src/com/android/documentsui/DirectoryFragment.java
@@ -683,10 +683,18 @@
         // Pop up a dialog to pick a destination.  This is inadequate but works for now.
         // TODO: Implement a picker that is to spec.
         final Intent intent = new Intent(
-                BaseActivity.ACTION_OPEN_COPY_DESTINATION_STRING,
+                BaseActivity.DocumentsIntent.ACTION_OPEN_COPY_DESTINATION,
                 Uri.EMPTY,
                 getActivity(),
                 DocumentsActivity.class);
+        boolean directoryCopy = false;
+        for (DocumentInfo info : docs) {
+            if (Document.MIME_TYPE_DIR.equals(info.mimeType)) {
+                directoryCopy = true;
+                break;
+            }
+        }
+        intent.putExtra(BaseActivity.DocumentsIntent.EXTRA_DIRECTORY_COPY, directoryCopy);
         startActivityForResult(intent, REQUEST_COPY_DESTINATION);
     }
 
diff --git a/packages/DocumentsUI/src/com/android/documentsui/DocumentsActivity.java b/packages/DocumentsUI/src/com/android/documentsui/DocumentsActivity.java
index 1e798eb..a2a789f 100644
--- a/packages/DocumentsUI/src/com/android/documentsui/DocumentsActivity.java
+++ b/packages/DocumentsUI/src/com/android/documentsui/DocumentsActivity.java
@@ -237,7 +237,7 @@
             mState.action = ACTION_MANAGE;
         } else if (DocumentsContract.ACTION_BROWSE_DOCUMENT_ROOT.equals(action)) {
             mState.action = ACTION_BROWSE;
-        } else if (ACTION_OPEN_COPY_DESTINATION_STRING.equals(action)) {
+        } else if (DocumentsIntent.ACTION_OPEN_COPY_DESTINATION.equals(action)) {
             mState.action = ACTION_OPEN_COPY_DESTINATION;
         }
 
@@ -265,6 +265,10 @@
         } else {
             mState.showSize = LocalPreferences.getDisplayFileSize(this);
         }
+        if (mState.action == ACTION_OPEN_COPY_DESTINATION) {
+            mState.directoryCopy = intent.getBooleanExtra(
+                    BaseActivity.DocumentsIntent.EXTRA_DIRECTORY_COPY, false);
+        }
     }
 
     private class RestoreRootTask extends AsyncTask<Void, Void, RootInfo> {
@@ -906,7 +910,7 @@
             if (pick != null) {
                 final CharSequence displayName = (mState.stack.size() <= 1) ? root.title
                         : cwd.displayName;
-                pick.setPickTarget(cwd, displayName);
+                pick.setPickTarget(mState.action, cwd, displayName);
             }
         }
 
diff --git a/packages/DocumentsUI/src/com/android/documentsui/FailureDialogFragment.java b/packages/DocumentsUI/src/com/android/documentsui/FailureDialogFragment.java
new file mode 100644
index 0000000..1748c9c
--- /dev/null
+++ b/packages/DocumentsUI/src/com/android/documentsui/FailureDialogFragment.java
@@ -0,0 +1,99 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.documentsui;
+
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.app.Dialog;
+import android.app.DialogFragment;
+import android.app.FragmentManager;
+import android.app.FragmentTransaction;
+import android.content.DialogInterface;
+import android.net.Uri;
+import android.os.Bundle;
+import android.text.Html;
+
+import com.android.documentsui.model.DocumentInfo;
+
+import java.io.FileNotFoundException;
+import java.util.ArrayList;
+
+/**
+ * Alert dialog for failed operations.
+ */
+public class FailureDialogFragment extends DialogFragment
+        implements DialogInterface.OnClickListener {
+    private static final String TAG = "FailureDialogFragment";
+
+    private int mFailure;
+    private ArrayList<Uri> mFailedSrcList;
+
+    public static void show(FragmentManager fm, int failure, ArrayList<Uri> failedSrcList) {
+        // TODO: Add support for other failures than copy.
+        if (failure != CopyService.FAILURE_COPY) {
+            return;
+        }
+
+        final Bundle args = new Bundle();
+        args.putInt(CopyService.EXTRA_FAILURE, failure);
+        args.putParcelableArrayList(CopyService.EXTRA_SRC_LIST, failedSrcList);
+
+        final FragmentTransaction ft = fm.beginTransaction();
+        final FailureDialogFragment fragment = new FailureDialogFragment();
+        fragment.setArguments(args);
+
+        ft.add(fragment, TAG);
+        ft.commitAllowingStateLoss();
+    }
+
+    @Override
+    public void onClick(DialogInterface dialog, int whichButton) {
+      // TODO: Pass mFailure and mFailedSrcList to the parent fragment.
+    }
+
+    @Override
+    public Dialog onCreateDialog(Bundle inState) {
+        super.onCreate(inState);
+
+        mFailure = getArguments().getInt(CopyService.EXTRA_FAILURE);
+        mFailedSrcList = getArguments().getParcelableArrayList(CopyService.EXTRA_SRC_LIST);
+
+        final StringBuilder list = new StringBuilder("<p>");
+        for (Uri documentUri : mFailedSrcList) {
+            try {
+                final DocumentInfo documentInfo = DocumentInfo.fromUri(
+                    getActivity().getContentResolver(), documentUri);
+                list.append(String.format("&#8226; %s<br>", documentInfo.displayName));
+            }
+            catch (FileNotFoundException ignore) {
+                // Source file most probably gone.
+            }
+        }
+        list.append("</p>");
+        final String message = String.format(getString(R.string.copy_failure_alert_content),
+                list.toString());
+
+        return new AlertDialog.Builder(getActivity())
+            .setTitle(getString(R.string.copy_failure_alert_title))
+            .setMessage(Html.fromHtml(message))
+            // TODO: Implement retrying the copy operation.
+            .setPositiveButton(R.string.retry, this)
+            .setNegativeButton(android.R.string.cancel, this)
+            .setIcon(android.R.drawable.ic_dialog_alert)
+            .create();
+    }
+}
diff --git a/packages/DocumentsUI/src/com/android/documentsui/PickFragment.java b/packages/DocumentsUI/src/com/android/documentsui/PickFragment.java
index 4b008ca..5e565bf 100644
--- a/packages/DocumentsUI/src/com/android/documentsui/PickFragment.java
+++ b/packages/DocumentsUI/src/com/android/documentsui/PickFragment.java
@@ -16,6 +16,8 @@
 
 package com.android.documentsui;
 
+import android.R.string;
+import android.app.Activity;
 import android.app.Fragment;
 import android.app.FragmentManager;
 import android.app.FragmentTransaction;
@@ -40,6 +42,7 @@
 
     private View mContainer;
     private Button mPick;
+    private Button mCancel;
 
     public static void show(FragmentManager fm) {
         final PickFragment fragment = new PickFragment();
@@ -61,7 +64,10 @@
         mPick = (Button) mContainer.findViewById(android.R.id.button1);
         mPick.setOnClickListener(mPickListener);
 
-        setPickTarget(null, null);
+        mCancel = (Button) mContainer.findViewById(android.R.id.button2);
+        mCancel.setOnClickListener(mCancelListener);
+
+        setPickTarget(0, null, null);
 
         return mContainer;
     }
@@ -74,18 +80,43 @@
         }
     };
 
-    public void setPickTarget(DocumentInfo pickTarget, CharSequence displayName) {
-        mPickTarget = pickTarget;
+    private View.OnClickListener mCancelListener = new View.OnClickListener() {
+        @Override
+        public void onClick(View v) {
+            final BaseActivity activity = BaseActivity.get(PickFragment.this);
+            activity.setResult(Activity.RESULT_CANCELED);
+            activity.finish();
+        }
+    };
 
+    /**
+     * @param action Which action defined in BaseActivity.State is the picker shown for.
+     */
+    public void setPickTarget(int action,
+                              DocumentInfo pickTarget,
+                              CharSequence displayName) {
         if (mContainer != null) {
-            if (mPickTarget != null) {
+            if (pickTarget != null) {
                 mContainer.setVisibility(View.VISIBLE);
                 final Locale locale = getResources().getConfiguration().locale;
-                final String raw = getString(R.string.menu_select).toUpperCase(locale);
-                mPick.setText(TextUtils.expandTemplate(raw, displayName));
+                switch (action) {
+                    case BaseActivity.State.ACTION_OPEN_TREE:
+                        final String raw = getString(R.string.menu_select).toUpperCase(locale);
+                        mPick.setText(TextUtils.expandTemplate(raw, displayName));
+                        mCancel.setVisibility(View.GONE);
+                        break;
+                    case BaseActivity.State.ACTION_OPEN_COPY_DESTINATION:
+                        mPick.setText(getString(R.string.button_copy).toUpperCase(locale));
+                        mCancel.setVisibility(View.VISIBLE);
+                        break;
+                    default:
+                        throw new IllegalArgumentException("Illegal action for PickFragment.");
+                }
+
             } else {
                 mContainer.setVisibility(View.GONE);
             }
         }
+        mPickTarget = pickTarget;
     }
 }
diff --git a/packages/DocumentsUI/src/com/android/documentsui/RootsCache.java b/packages/DocumentsUI/src/com/android/documentsui/RootsCache.java
index d2267b1..27e8f20 100644
--- a/packages/DocumentsUI/src/com/android/documentsui/RootsCache.java
+++ b/packages/DocumentsUI/src/com/android/documentsui/RootsCache.java
@@ -367,6 +367,9 @@
             if (!state.showAdvanced && advanced) continue;
             // Exclude non-local devices when local only
             if (state.localOnly && !localOnly) continue;
+            // Exclude downloads roots that don't support directory creation
+            // TODO: Add flag to check the root supports directory creation or not.
+            if (state.directoryCopy && root.isDownloads()) continue;
             // Only show empty roots when creating
             if ((state.action != State.ACTION_CREATE ||
                  state.action != State.ACTION_OPEN_TREE ||
diff --git a/packages/DocumentsUI/src/com/android/documentsui/StandaloneActivity.java b/packages/DocumentsUI/src/com/android/documentsui/StandaloneActivity.java
index f542838..976f21d 100644
--- a/packages/DocumentsUI/src/com/android/documentsui/StandaloneActivity.java
+++ b/packages/DocumentsUI/src/com/android/documentsui/StandaloneActivity.java
@@ -63,6 +63,7 @@
 import android.widget.Toast;
 import android.widget.Toolbar;
 
+import com.android.documentsui.FailureDialogFragment;
 import com.android.documentsui.RecentsProvider.ResumeColumns;
 import com.android.documentsui.model.DocumentInfo;
 import com.android.documentsui.model.DocumentStack;
@@ -73,6 +74,7 @@
 
 import java.io.FileNotFoundException;
 import java.io.IOException;
+import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.List;
@@ -153,6 +155,13 @@
         RootsFragment.show(getFragmentManager(), null);
         if (!mState.restored) {
             new RestoreStackTask().execute();
+            final Intent intent = getIntent();
+            final int failure = intent.getIntExtra(CopyService.EXTRA_FAILURE, 0);
+            if (failure != 0) {
+                final ArrayList<Uri> failedSrcList = intent.getParcelableArrayListExtra(
+                        CopyService.EXTRA_SRC_LIST);
+                FailureDialogFragment.show(getFragmentManager(), failure, failedSrcList);
+            }
         } else {
             onCurrentDirectoryChanged(ANIM_NONE);
         }
diff --git a/services/core/java/com/android/server/updates/ConfigUpdateInstallReceiver.java b/services/core/java/com/android/server/updates/ConfigUpdateInstallReceiver.java
index 1135dfe..8fc979c 100644
--- a/services/core/java/com/android/server/updates/ConfigUpdateInstallReceiver.java
+++ b/services/core/java/com/android/server/updates/ConfigUpdateInstallReceiver.java
@@ -16,29 +16,21 @@
 
 package com.android.server.updates;
 
+import com.android.server.EventLogTags;
+
 import android.content.BroadcastReceiver;
-import android.content.ContentResolver;
 import android.content.Context;
 import android.content.Intent;
 import android.net.Uri;
-import android.provider.Settings;
-import android.util.Base64;
 import android.util.EventLog;
 import android.util.Slog;
 
-import com.android.server.EventLogTags;
-
-import java.io.ByteArrayInputStream;
 import java.io.File;
 import java.io.FileOutputStream;
-import java.io.InputStream;
 import java.io.IOException;
-import java.security.cert.CertificateException;
-import java.security.cert.CertificateFactory;
-import java.security.cert.X509Certificate;
+import java.io.InputStream;
 import java.security.MessageDigest;
 import java.security.NoSuchAlgorithmException;
-import java.security.Signature;
 
 import libcore.io.IoUtils;
 import libcore.io.Streams;
@@ -48,11 +40,8 @@
     private static final String TAG = "ConfigUpdateInstallReceiver";
 
     private static final String EXTRA_REQUIRED_HASH = "REQUIRED_HASH";
-    private static final String EXTRA_SIGNATURE = "SIGNATURE";
     private static final String EXTRA_VERSION_NUMBER = "VERSION";
 
-    private static final String UPDATE_CERTIFICATE_KEY = "config_update_certificate";
-
     protected final File updateDir;
     protected final File updateContent;
     protected final File updateVersion;
@@ -71,16 +60,12 @@
             @Override
             public void run() {
                 try {
-                    // get the certificate from Settings.Secure
-                    X509Certificate cert = getCert(context.getContentResolver());
                     // get the content path from the extras
                     byte[] altContent = getAltContent(context, intent);
                     // get the version from the extras
                     int altVersion = getVersionFromIntent(intent);
                     // get the previous value from the extras
                     String altRequiredHash = getRequiredHashFromIntent(intent);
-                    // get the signature from the extras
-                    String altSig = getSignatureFromIntent(intent);
                     // get the version currently being used
                     int currentVersion = getCurrentVersion();
                     // get the hash of the currently used value
@@ -90,10 +75,6 @@
                     } else if (!verifyPreviousHash(currentHash, altRequiredHash)) {
                         EventLog.writeEvent(EventLogTags.CONFIG_INSTALL_FAILED,
                                             "Current hash did not match required value");
-                    } else if (!verifySignature(altContent, altVersion, altRequiredHash, altSig,
-                               cert)) {
-                        EventLog.writeEvent(EventLogTags.CONFIG_INSTALL_FAILED,
-                                            "Signature did not verify");
                     } else {
                         // install the new content
                         Slog.i(TAG, "Found new update, installing...");
@@ -114,20 +95,6 @@
         }.start();
     }
 
-    private X509Certificate getCert(ContentResolver cr) {
-        // get the cert from settings
-        String cert = Settings.Secure.getString(cr, UPDATE_CERTIFICATE_KEY);
-        // convert it into a real certificate
-        try {
-            byte[] derCert = Base64.decode(cert.getBytes(), Base64.DEFAULT);
-            InputStream istream = new ByteArrayInputStream(derCert);
-            CertificateFactory cf = CertificateFactory.getInstance("X.509");
-            return (X509Certificate) cf.generateCertificate(istream);
-        } catch (CertificateException e) {
-            throw new IllegalStateException("Got malformed certificate from settings, ignoring");
-        }
-    }
-
     private Uri getContentFromIntent(Intent i) {
         Uri data = i.getData();
         if (data == null) {
@@ -152,14 +119,6 @@
         return extraValue.trim();
     }
 
-    private String getSignatureFromIntent(Intent i) {
-        String extraValue = i.getStringExtra(EXTRA_SIGNATURE);
-        if (extraValue == null) {
-            throw new IllegalStateException("Missing required signature, ignoring.");
-        }
-        return extraValue.trim();
-    }
-
     private int getCurrentVersion() throws NumberFormatException {
         try {
             String strVersion = IoUtils.readFileAsString(updateVersion.getCanonicalPath()).trim();
@@ -215,16 +174,6 @@
         return current.equals(required);
     }
 
-    private boolean verifySignature(byte[] content, int version, String requiredPrevious,
-                                   String signature, X509Certificate cert) throws Exception {
-        Signature signer = Signature.getInstance("SHA512withRSA");
-        signer.initVerify(cert);
-        signer.update(content);
-        signer.update(Long.toString(version).getBytes());
-        signer.update(requiredPrevious.getBytes());
-        return signer.verify(Base64.decode(signature.getBytes(), Base64.DEFAULT));
-    }
-
     protected void writeUpdate(File dir, File file, byte[] content) throws IOException {
         FileOutputStream out = null;
         File tmp = null;
diff --git a/services/core/jni/Android.mk b/services/core/jni/Android.mk
index 6448de2..19ca2b4 100644
--- a/services/core/jni/Android.mk
+++ b/services/core/jni/Android.mk
@@ -37,6 +37,7 @@
     frameworks/native/services \
     libcore/include \
     libcore/include/libsuspend \
+    system/security/keystore/include \
     $(call include-path-for, libhardware)/hardware \
     $(call include-path-for, libhardware_legacy)/hardware_legacy \
 
@@ -48,6 +49,7 @@
     liblog \
     libhardware \
     libhardware_legacy \
+    libkeystore_binder \
     libnativehelper \
     libutils \
     libui \
diff --git a/services/core/jni/com_android_server_fingerprint_FingerprintService.cpp b/services/core/jni/com_android_server_fingerprint_FingerprintService.cpp
index bd09bdf..a6cdbc4 100644
--- a/services/core/jni/com_android_server_fingerprint_FingerprintService.cpp
+++ b/services/core/jni/com_android_server_fingerprint_FingerprintService.cpp
@@ -22,13 +22,19 @@
 #include <android_runtime/AndroidRuntime.h>
 #include <android_runtime/Log.h>
 #include <android_os_MessageQueue.h>
+#include <binder/IServiceManager.h>
+#include <utils/String16.h>
+#include <utils/Looper.h>
+#include <keystore/IKeystoreService.h>
+
 #include <hardware/hardware.h>
 #include <hardware/fingerprint.h>
 #include <hardware/hw_auth_token.h>
+
 #include <utils/Log.h>
-#include <utils/Looper.h>
 #include "core_jni_helpers.h"
 
+
 namespace android {
 
 static const uint16_t kVersion = HARDWARE_MODULE_API_VERSION(2, 0);
@@ -61,6 +67,22 @@
     }
 };
 
+static void notifyKeystore(uint8_t *auth_token, size_t auth_token_length) {
+    if (auth_token != NULL && auth_token_length > 0) {
+        // TODO: cache service?
+        sp<IServiceManager> sm = defaultServiceManager();
+        sp<IBinder> binder = sm->getService(String16("android.security.keystore"));
+        sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder);
+        if (service != NULL) {
+            if (service->addAuthToken(auth_token, auth_token_length) != NO_ERROR) {
+                ALOGE("Falure sending auth token to KeyStore");
+            }
+        } else {
+            ALOGE("Unable to communicate with KeyStore");
+        }
+    }
+}
+
 // Called by the HAL to notify us of fingerprint events
 static void hal_notify_callback(fingerprint_msg_t msg) {
     uint32_t arg1 = 0;
@@ -76,7 +98,10 @@
         case FINGERPRINT_AUTHENTICATED:
             arg1 = msg.data.authenticated.finger.fid;
             arg2 = msg.data.authenticated.finger.gid;
-            // Jim, arg3 would be the hw_auth_token_t, please pass it the way you like.
+            if (arg1 != 0) {
+                notifyKeystore(reinterpret_cast<uint8_t *>(&msg.data.authenticated.hat),
+                        sizeof(msg.data.authenticated.hat));
+            }
             break;
         case FINGERPRINT_TEMPLATE_ENROLLING:
             arg1 = msg.data.enroll.finger.fid;
@@ -198,6 +223,7 @@
 
 // ----------------------------------------------------------------------------
 
+
 // TODO: clean up void methods
 static const JNINativeMethod g_methods[] = {
     { "nativeAuthenticate", "(JI)I", (void*)nativeAuthenticate },