Merge "Exorcise notification panel ghosts. Bug: 5105599"
diff --git a/api/current.txt b/api/current.txt
index 8151243..8f3b38f 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -190,6 +190,8 @@
     field public static final int accountPreferences = 16843423; // 0x101029f
     field public static final int accountType = 16843407; // 0x101028f
     field public static final int action = 16842797; // 0x101002d
+    field public static final int actionBarDivider = 16843685; // 0x10103a5
+    field public static final int actionBarItemBackground = 16843686; // 0x10103a6
     field public static final int actionBarSize = 16843499; // 0x10102eb
     field public static final int actionBarSplitStyle = 16843666; // 0x1010392
     field public static final int actionBarStyle = 16843470; // 0x10102ce
diff --git a/core/java/android/text/TextLine.java b/core/java/android/text/TextLine.java
index 3e5f32e..376e4f5 100644
--- a/core/java/android/text/TextLine.java
+++ b/core/java/android/text/TextLine.java
@@ -16,8 +16,6 @@
 
 package android.text;
 
-import com.android.internal.util.ArrayUtils;
-
 import android.graphics.Bitmap;
 import android.graphics.Canvas;
 import android.graphics.Paint;
@@ -30,6 +28,8 @@
 import android.text.style.ReplacementSpan;
 import android.util.Log;
 
+import com.android.internal.util.ArrayUtils;
+
 /**
  * Represents a line of styled text, for measuring in visual order and
  * for rendering.
@@ -720,7 +720,7 @@
         float ret = 0;
 
         int contextLen = contextEnd - contextStart;
-        if (needWidth || (c != null && (wp.bgColor != 0 || runIsRtl))) {
+        if (needWidth || (c != null && (wp.bgColor != 0 || wp.underlineColor !=0 || runIsRtl))) {
             int flags = runIsRtl ? Paint.DIRECTION_RTL : Paint.DIRECTION_LTR;
             if (mCharsValid) {
                 ret = wp.getTextRunAdvances(mChars, start, runLen,
@@ -739,15 +739,32 @@
             }
 
             if (wp.bgColor != 0) {
-                int color = wp.getColor();
-                Paint.Style s = wp.getStyle();
+                int previousColor = wp.getColor();
+                Paint.Style previousStyle = wp.getStyle();
+
                 wp.setColor(wp.bgColor);
                 wp.setStyle(Paint.Style.FILL);
-
                 c.drawRect(x, top, x + ret, bottom, wp);
 
-                wp.setStyle(s);
-                wp.setColor(color);
+                wp.setStyle(previousStyle);
+                wp.setColor(previousColor);
+            }
+
+            if (wp.underlineColor != 0) {
+                // kStdUnderline_Offset = 1/9, defined in SkTextFormatParams.h
+                float middle = y + wp.baselineShift + (1.0f / 9.0f) * wp.getTextSize();
+                // kStdUnderline_Thickness = 1/18, defined in SkTextFormatParams.h
+                float halfHeight = wp.underlineThickness * (1.0f / 18.0f / 2.0f) * wp.getTextSize();
+
+                int previousColor = wp.getColor();
+                Paint.Style previousStyle = wp.getStyle();
+
+                wp.setColor(wp.underlineColor);
+                wp.setStyle(Paint.Style.FILL);
+                c.drawRect(x, middle - halfHeight, x + ret, middle + halfHeight, wp);
+
+                wp.setStyle(previousStyle);
+                wp.setColor(previousColor);
             }
 
             drawTextRun(c, wp, start, end, contextStart, contextEnd, runIsRtl,
diff --git a/core/java/android/text/TextPaint.java b/core/java/android/text/TextPaint.java
index f9e7cac..de57dfa 100644
--- a/core/java/android/text/TextPaint.java
+++ b/core/java/android/text/TextPaint.java
@@ -23,11 +23,22 @@
  * data used during text measuring and drawing.
  */
 public class TextPaint extends Paint {
+    // Special value 0 means no background paint
     public int bgColor;
     public int baselineShift;
     public int linkColor;
     public int[] drawableState;
     public float density = 1.0f;
+    /**
+     * Special value 0 means no custom underline
+     * @hide
+     */
+    public int underlineColor;
+    /**
+     * Defined as a multiplier of the default underline thickness. Use 1.0f for default thickness.
+     * @hide
+     */
+    public float underlineThickness;
 
     public TextPaint() {
         super();
@@ -53,5 +64,24 @@
         linkColor = tp.linkColor;
         drawableState = tp.drawableState;
         density = tp.density;
+        underlineColor = tp.underlineColor;
+        underlineThickness = tp.underlineThickness;
+    }
+
+    /**
+     * Defines a custom underline for this Paint.
+     * @param color underline solid color
+     * @param thickness underline thickness, defined as a multiplier of the default underline
+     * thickness.
+     * @hide
+     */
+    public void setUnderlineText(boolean isUnderlined, int color, float thickness) {
+        setUnderlineText(false);
+        if (isUnderlined) {
+            underlineColor = color;
+            underlineThickness = thickness;
+        } else {
+            underlineColor = 0;
+        }
     }
 }
diff --git a/core/java/com/android/internal/app/ActionBarImpl.java b/core/java/com/android/internal/app/ActionBarImpl.java
index 0df7bcc..31360e1 100644
--- a/core/java/com/android/internal/app/ActionBarImpl.java
+++ b/core/java/com/android/internal/app/ActionBarImpl.java
@@ -253,7 +253,7 @@
 
     @Override
     public void setCustomView(int resId) {
-        setCustomView(LayoutInflater.from(mContext).inflate(resId, mActionView, false));
+        setCustomView(LayoutInflater.from(getThemedContext()).inflate(resId, mActionView, false));
     }
 
     @Override
@@ -630,14 +630,14 @@
         
         public ActionModeImpl(ActionMode.Callback callback) {
             mCallback = callback;
-            mMenu = new MenuBuilder(mActionView.getContext())
+            mMenu = new MenuBuilder(getThemedContext())
                     .setDefaultShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
             mMenu.setCallback(this);
         }
 
         @Override
         public MenuInflater getMenuInflater() {
-            return new MenuInflater(mContext);
+            return new MenuInflater(getThemedContext());
         }
 
         @Override
@@ -755,7 +755,7 @@
                 return true;
             }
 
-            new MenuPopupHelper(mContext, subMenu).show();
+            new MenuPopupHelper(getThemedContext(), subMenu).show();
             return true;
         }
 
@@ -819,7 +819,8 @@
 
         @Override
         public Tab setCustomView(int layoutResId) {
-            return setCustomView(LayoutInflater.from(mContext).inflate(layoutResId, null));
+            return setCustomView(LayoutInflater.from(getThemedContext())
+                    .inflate(layoutResId, null));
         }
 
         @Override
diff --git a/core/res/res/layout/action_bar_home.xml b/core/res/res/layout/action_bar_home.xml
index 9612710..96467d0 100644
--- a/core/res/res/layout/action_bar_home.xml
+++ b/core/res/res/layout/action_bar_home.xml
@@ -18,7 +18,7 @@
       class="com.android.internal.widget.ActionBarView$HomeView"
       android:layout_width="wrap_content"
       android:layout_height="match_parent"
-      android:background="?android:attr/selectableItemBackground" >
+      android:background="?android:attr/actionBarItemBackground" >
     <ImageView android:id="@android:id/up"
                android:src="?android:attr/homeAsUpIndicator"
                android:layout_gravity="center_vertical|left"
diff --git a/core/res/res/layout/search_bar.xml b/core/res/res/layout/search_bar.xml
index f6b5b53..673c96c 100644
--- a/core/res/res/layout/search_bar.xml
+++ b/core/res/res/layout/search_bar.xml
@@ -75,5 +75,5 @@
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:scaleType="fitXY"
-        android:src="@drawable/title_bar_shadow"/>
+        android:src="@drawable/ab_solid_shadow_holo"/>
 </view>
diff --git a/core/res/res/values/attrs.xml b/core/res/res/values/attrs.xml
index f4c0240..140a8c9 100755
--- a/core/res/res/values/attrs.xml
+++ b/core/res/res/values/attrs.xml
@@ -633,6 +633,10 @@
         <attr name="actionBarSize" format="dimension" >
             <enum name="wrap_content" value="0" />
         </attr>
+        <!-- Custom divider drawable to use for elements in the action bar. -->
+        <attr name="actionBarDivider" format="reference" />
+        <!-- Custom item state list drawable background for action bar items. -->
+        <attr name="actionBarItemBackground" format="reference" />
         <!-- TextAppearance style that will be applied to text that
              appears within action menu items. -->
         <attr name="actionMenuTextAppearance" format="reference" />
diff --git a/core/res/res/values/public.xml b/core/res/res/values/public.xml
index 1ba54cf..44995c8 100644
--- a/core/res/res/values/public.xml
+++ b/core/res/res/values/public.xml
@@ -1788,6 +1788,9 @@
   <public type="attr" name="subtypeLocale" />
   <public type="attr" name="subtypeExtraValue" />
 
+  <public type="attr" name="actionBarDivider" />
+  <public type="attr" name="actionBarItemBackground" />
+
   <public type="style" name="TextAppearance.SuggestionHighlight" />
 
   <public type="style" name="Theme.Holo.Light.DarkActionBar" />
diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml
index 583310d..71e302f 100755
--- a/core/res/res/values/strings.xml
+++ b/core/res/res/values/strings.xml
@@ -916,18 +916,19 @@
         applications can use this to erase or modify your contact data.</string>
 
     <!-- Title of the read profile permission, listed so the user can decide whether to allow the application to read the user's personal profile data. [CHAR LIMIT=30] -->
-    <string name="permlab_readProfile">read profile data</string>
+    <string name="permlab_readProfile">read your profile data</string>
     <!-- Description of the read profile permission, listed so the user can decide whether to allow the application to read the user's personal profile data. [CHAR LIMIT=NONE] -->
-    <string name="permdesc_readProfile" product="default">Allows an application to read all
-        of your personal profile information. Malicious applications can use this to identify
-        you and send your personal information to other people.</string>
+    <string name="permdesc_readProfile" product="default">Allows the application to read personal
+        profile information stored on your device, such as your name and contact information. This
+        means the application can identify you and send your profile information to others.</string>
 
     <!-- Title of the write profile permission, listed so the user can decide whether to allow the application to write to the user's personal profile data. [CHAR LIMIT=30] -->
-    <string name="permlab_writeProfile">write profile data</string>
+    <string name="permlab_writeProfile">write to your profile data</string>
     <!-- Description of the write profile permission, listed so the user can decide whether to allow the application to write to the user's personal profile data. [CHAR LIMIT=NONE] -->
-    <string name="permdesc_writeProfile" product="default">Allows an application to modify
-        your personal profile information. Malicious applications can use this to erase or
-        modify your profile data.</string>
+    <string name="permdesc_writeProfile" product="default">Allows the application to change or add
+        to personal profile information stored on your device, such as your name and contact
+        information.  This means other applications can identify you and send your profile
+        information to others.</string>
 
     <!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
     <string name="permlab_readCalendar">read calendar events plus confidential information</string>
diff --git a/core/res/res/values/styles.xml b/core/res/res/values/styles.xml
index 0c6e20f..1f6b50a 100644
--- a/core/res/res/values/styles.xml
+++ b/core/res/res/values/styles.xml
@@ -1113,7 +1113,7 @@
     </style>
 
     <style name="Widget.ActionButton">
-        <item name="android:background">?android:attr/selectableItemBackground</item>
+        <item name="android:background">?android:attr/actionBarItemBackground</item>
         <item name="android:paddingLeft">12dip</item>
         <item name="android:paddingRight">12dip</item>
         <item name="android:minWidth">56dip</item>
@@ -1847,9 +1847,9 @@
     </style>
 
     <style name="Widget.Holo.ActionBar.TabBar" parent="Widget.ActionBar.TabBar">
-        <item name="android:divider">?android:attr/dividerVertical</item>
+        <item name="android:divider">?android:attr/actionBarDivider</item>
         <item name="android:showDividers">middle</item>
-        <item name="android:dividerPadding">8dip</item>
+        <item name="android:dividerPadding">12dip</item>
     </style>
 
     <style name="Widget.Holo.ActionBar.TabText" parent="Widget.ActionBar.TabText">
diff --git a/core/res/res/values/themes.xml b/core/res/res/values/themes.xml
index 82299b8..add7dc8 100644
--- a/core/res/res/values/themes.xml
+++ b/core/res/res/values/themes.xml
@@ -308,6 +308,8 @@
         <item name="actionMenuTextAppearance">@android:style/TextAppearance.Holo.Widget.ActionBar.Menu</item>
         <item name="actionMenuTextColor">?android:attr/textColorPrimary</item>
         <item name="actionBarWidgetTheme">@null</item>
+        <item name="actionBarDivider">?android:attr/dividerVertical</item>
+        <item name="actionBarItemBackground">?android:attr/selectableItemBackground</item>
 
         <item name="dividerVertical">@drawable/divider_vertical_dark</item>
         <item name="dividerHorizontal">@drawable/divider_vertical_dark</item>
@@ -1429,7 +1431,7 @@
          with an inverse color profile. The dark action bar sharply stands out against
          the light content. -->
     <style name="Theme.Holo.Light.DarkActionBar">
-        <item name="android:windowContentOverlay">@android:drawable/title_bar_shadow</item>
+        <item name="android:windowContentOverlay">@android:drawable/ab_solid_shadow_holo</item>
         <item name="android:actionBarStyle">@android:style/Widget.Holo.Light.ActionBar.Solid.Inverse</item>
         <item name="actionBarWidgetTheme">@android:style/Theme.Holo</item>
 
@@ -1442,6 +1444,8 @@
         <item name="actionBarTabStyle">@style/Widget.Holo.Light.ActionBar.TabView.Inverse</item>
         <item name="actionBarTabBarStyle">@style/Widget.Holo.Light.ActionBar.TabBar.Inverse</item>
         <item name="actionBarTabTextStyle">@style/Widget.Holo.Light.ActionBar.TabText.Inverse</item>
+        <item name="actionBarDivider">@android:drawable/list_divider_holo_dark</item>
+        <item name="actionBarItemBackground">@android:drawable/item_background_holo_dark</item>
         <item name="actionMenuTextColor">?android:attr/textColorPrimaryInverse</item>
         <item name="actionModeStyle">@style/Widget.Holo.Light.ActionMode.Inverse</item>
         <item name="actionModeCloseButtonStyle">@style/Widget.Holo.ActionButton.CloseMode</item>
diff --git a/docs/html/guide/practices/design/jni.jd b/docs/html/guide/practices/design/jni.jd
index 1d0e26e..6e984b0 100644
--- a/docs/html/guide/practices/design/jni.jd
+++ b/docs/html/guide/practices/design/jni.jd
@@ -18,9 +18,9 @@
   <li><a href="#native_libraries">Native Libraries</a></li>
   <li><a href="#64_bit">64-bit Considerations</a></li>
   <li><a href="#unsupported">Unsupported Features</a></li>
-  <li><a href="#faq_ULE">FAQ: UnsatisfiedLinkError</a></li>
-  <li><a href="#faq_FindClass">FAQ: FindClass didn't find my class</a></li>
-  <li><a href="#faq_sharing">FAQ: Sharing raw data with native code</a></li>
+  <li><a href="#faq_ULE">FAQ: Why do I get <code>UnsatisfiedLinkError</code></a></li>
+  <li><a href="#faq_FindClass">FAQ: Why didn't <code>FindClass</code> find my class?</a></li>
+  <li><a href="#faq_sharing">FAQ: How do I share raw data with native code?</a></li>
 </ol>
 
 </div>
@@ -28,7 +28,7 @@
 
 <p>JNI is the Java Native Interface.  It defines a way for code written in the
 Java programming language to interact with native
-code, e.g. functions written in C/C++.  It's VM-neutral, has support for loading code from
+code: functions written in C/C++.  It's VM-neutral, has support for loading code from
 dynamic shared libraries, and while cumbersome at times is reasonably efficient.</p>
 
 <p>You really should read through the
@@ -36,8 +36,7 @@
 to get a sense for how JNI works and what features are available.  Some
 aspects of the interface aren't immediately obvious on
 first reading, so you may find the next few sections handy.
-The more detailed <i>JNI Programmer's Guide and Specification</i> can be found
-<a href="http://java.sun.com/docs/books/jni/html/jniTOC.html">here</a>.</p>
+There's a more detailed <a href="http://java.sun.com/docs/books/jni/html/jniTOC.html">JNI Programmer's Guide and Specification</a>.</p>
 
 
 <a name="JavaVM_and_JNIEnv" id="JavaVM_and_JNIEnv"></a>
@@ -55,20 +54,20 @@
 
 <p>On some VMs, the JNIEnv is used for thread-local storage.  For this reason, <strong>you cannot share a JNIEnv between threads</strong>.
 If a piece of code has no other way to get its JNIEnv, you should share
-the JavaVM, and use JavaVM-&gt;GetEnv to discover the thread's JNIEnv. (Assuming it has one; see <code>AttachCurrentThread</code> below.)</p>
+the JavaVM, and use <code>GetEnv</code> to discover the thread's JNIEnv. (Assuming it has one; see <code>AttachCurrentThread</code> below.)</p>
 
 <p>The C declarations of JNIEnv and JavaVM are different from the C++
-declarations.  "jni.h" provides different typedefs
-depending on whether it's included into ".c" or ".cpp".  For this reason it's a bad idea to
+declarations.  The <code>"jni.h"</code> include file provides different typedefs
+depending on whether it's included into C or C++.  For this reason it's a bad idea to
 include JNIEnv arguments in header files included by both languages.  (Put another way: if your
-header file requires "#ifdef __cplusplus", you may have to do some extra work if anything in
+header file requires <code>#ifdef __cplusplus</code>, you may have to do some extra work if anything in
 that header refers to JNIEnv.)</p>
 
 <a name="threads" id="threads"></a>
 <h2>Threads</h2>
 
 <p>All VM threads are Linux threads, scheduled by the kernel.  They're usually
-started using Java language features (notably <code>Thread.start()</code>),
+started using Java language features (notably <code>Thread.start</code>),
 but they can also be created elsewhere and then attached to the VM.  For
 example, a thread started with <code>pthread_create</code> can be attached
 with the JNI <code>AttachCurrentThread</code> or
@@ -87,7 +86,7 @@
 
 <p>Threads attached through JNI <strong>must call
 <code>DetachCurrentThread</code> before they exit</strong>.
-If coding this directly is awkward, in Android &gt;= 2.0 ("Eclair") you
+If coding this directly is awkward, in Android 2.0 (Eclair) and higher you
 can use <code>pthread_key_create</code> to define a destructor
 function that will be called before the thread exits, and
 call <code>DetachCurrentThread</code> from there.  (Use that
@@ -104,7 +103,7 @@
 <ul>
 <li> Get the class object reference for the class with <code>FindClass</code></li>
 <li> Get the field ID for the field with <code>GetFieldID</code></li>
-<li> Get the contents of the field with something appropriate, e.g.
+<li> Get the contents of the field with something appropriate, such as
 <code>GetIntField</code></li>
 </ul>
 
@@ -114,12 +113,12 @@
 is very quick.</p>
 
 <p>If performance is important, it's useful to look the values up once and cache the results
-in your native code.  Because we are limiting ourselves to one VM per process, it's reasonable
+in your native code.  Because there is a limit of one VM per process, it's reasonable
 to store this data in a static local structure.</p>
 
 <p>The class references, field IDs, and method IDs are guaranteed valid until the class is unloaded.  Classes
 are only unloaded if all classes associated with a ClassLoader can be garbage collected,
-which is rare but will not be impossible in our system.  Note however that
+which is rare but will not be impossible in Android.  Note however that
 the <code>jclass</code>
 is a class reference and <strong>must be protected</strong> with a call
 to <code>NewGlobalRef</code> (see the next section).</p>
@@ -130,27 +129,18 @@
 
 <pre>    /*
      * We use a class initializer to allow the native code to cache some
-     * field offsets.
+     * field offsets. This native function looks up and caches interesting
+     * class/field/method IDs. Throws on failure.
      */
+    private static native void nativeInit();
 
-    /*
-     * A native function that looks up and caches interesting
-     * class/field/method IDs for this class.  Returns false on failure.
-     */
-    native private static boolean nativeClassInit();
-
-    /*
-     * Invoke the native initializer when the class is loaded.
-     */
     static {
-        if (!nativeClassInit())
-            throw new RuntimeException("native init failed");
+        nativeInit();
     }</pre>
 
-<p>Create a nativeClassInit method in your C/C++ code that performs the ID lookups.  The code
+<p>Create a <code>nativeClassInit</code> method in your C/C++ code that performs the ID lookups.  The code
 will be executed once, when the class is initialized.  If the class is ever unloaded and
-then reloaded, it will be executed again.  (See the implementation of java.io.FileDescriptor
-for an example in our source tree.)</p>
+then reloaded, it will be executed again.</p>
 
 <a name="local_and_global_references" id="local_and_global_references"></a>
 <h2>Local and Global References</h2>
@@ -175,12 +165,12 @@
 jclass globalClass = reinterpret_cast&lt;jclass&gt;(env-&gt;NewGlobalRef(localClass));</pre>
 
 <p>All JNI methods accept both local and global references as arguments.
-It's possible for references to the same object to have different values;
-for example, the return values from consecutive calls to
+It's possible for references to the same object to have different values.
+For example, the return values from consecutive calls to
 <code>NewGlobalRef</code> on the same object may be different.
 <strong>To see if two references refer to the same object,
 you must use the <code>IsSameObject</code> function.</strong>  Never compare
-references with "==" in native code.</p>
+references with <code>==</code> in native code.</p>
 
 <p>One consequence of this is that you
 <strong>must not assume object references are constant or unique</strong>
@@ -197,13 +187,13 @@
 16 local references, so if you need more than that you should either delete as you go or use
 <code>EnsureLocalCapacity</code> to reserve more.</p>
 
-<p>Note: method and field IDs are just 32-bit identifiers, not object
+<p>Note that <code>jfieldID</code>s and <code>jmethodID</code>s are just integers, not object
 references, and should not be passed to <code>NewGlobalRef</code>.  The raw data
 pointers returned by functions like <code>GetStringUTFChars</code>
 and <code>GetByteArrayElements</code> are also not objects.</p>
 
 <p>One unusual case deserves separate mention.  If you attach a native
-thread to the VM with AttachCurrentThread, the code you are running will
+thread to the VM with <code>AttachCurrentThread</code>, the code you are running will
 never "return" to the VM until the thread detaches from the VM.  Any local
 references you create will have to be deleted manually unless you're going
 to detach the thread soon.</p>
@@ -217,17 +207,17 @@
 suitable for use with standard libc string functions.  The down side is that you cannot pass
 arbitrary UTF-8 data into the VM and expect it to work correctly.</p>
 
-<p>It's usually best to operate with UTF-16 strings.  With our current VMs, the
+<p>It's usually best to operate with UTF-16 strings.  With Android's current VMs, the
 <code>GetStringChars</code> method
 does not require a copy, whereas <code>GetStringUTFChars</code> requires a malloc and a UTF conversion.  Note that
 <strong>UTF-16 strings are not zero-terminated</strong>, and \u0000 is allowed,
 so you need to hang on to the string length as well as
 the string pointer.</p>
 
-<p><strong>Don't forget to Release the strings you Get</strong>.  The
+<p><strong>Don't forget to <code>Release</code> the strings you <code>Get</code></strong>.  The
 string functions return <code>jchar*</code> or <code>jbyte*</code>, which
 are C-style pointers to primitive data rather than local references.  They
-are guaranteed valid until Release is called, which means they are not
+are guaranteed valid until <code>Release</code> is called, which means they are not
 released when the native method returns.</p>
 
 <p><strong>Data passed to NewStringUTF must be in Modified UTF-8 format</strong>.  A
@@ -254,8 +244,8 @@
 is guaranteed to be valid until the corresponding <code>Release</code> call
 is issued (which implies that, if the data wasn't copied, the array object
 will be pinned down and can't be relocated as part of compacting the heap).
-<strong>You must Release every array you Get.</strong>  Also, if the Get
-call fails, you must ensure that your code doesn't try to Release a NULL
+<strong>You must <code>Release</code> every array you <code>Get</code>.</strong>  Also, if the <code>Get</code>
+call fails, you must ensure that your code doesn't try to <code>Release</code> a NULL
 pointer later.</p>
 
 <p>You can determine whether or not the data was copied by passing in a
@@ -298,12 +288,12 @@
 you, there's no need to create another "editable" copy.  If JNI is passing
 you the original, then you do need to make your own copy.</p>
 
-<p>Some have asserted that you can skip the <code>Release</code> call if
+<p>It is a common mistake (repeated in example code) to assume that you can skip the <code>Release</code> call if
 <code>*isCopy</code> is false.  This is not the case.  If no copy buffer was
 allocated, then the original memory must be pinned down and can't be moved by
 the garbage collector.</p>
 
-<p>Also note that the <code>JNI_COMMIT</code> flag does NOT release the array,
+<p>Also note that the <code>JNI_COMMIT</code> flag does <strong>not</strong> release the array,
 and you will need to call <code>Release</code> again with a different flag
 eventually.</p>
 
@@ -315,8 +305,7 @@
 and <code>GetStringChars</code> that may be very helpful when all you want
 to do is copy data in or out.  Consider the following:</p>
 
-<pre>
-    jbyte* data = env-&gt;GetByteArrayElements(array, NULL);
+<pre>    jbyte* data = env-&gt;GetByteArrayElements(array, NULL);
     if (data != NULL) {
         memcpy(buffer, data, len);
         env-&gt;ReleaseByteArrayElements(array, data, JNI_ABORT);
@@ -325,12 +314,11 @@
 <p>This grabs the array, copies the first <code>len</code> byte
 elements out of it, and then releases the array.  Depending upon the VM
 policies the <code>Get</code> call will either pin or copy the array contents.
-We copy the data (for perhaps a second time), then call Release; in this case
-we use <code>JNI_ABORT</code> so there's no chance of a third copy.</p>
+The code copies the data (for perhaps a second time), then calls <code>Release</code>; in this case
+<code>JNI_ABORT</code> ensures there's no chance of a third copy.</p>
 
-<p>We can accomplish the same thing with this:</p>
-<pre>
-    env-&gt;GetByteArrayRegion(array, 0, len, buffer);</pre>
+<p>One can accomplish the same thing more simply:</p>
+<pre>    env-&gt;GetByteArrayRegion(array, 0, len, buffer);</pre>
 
 <p>This has several advantages:</p>
 <ul>
@@ -349,29 +337,29 @@
 <a name="exceptions" id="exceptions"></a>
 <h2>Exception</h2>
 
-<p><strong>You may not call most JNI functions while an exception is pending.</strong>
+<p><strong>You must not call most JNI functions while an exception is pending.</strong>
 Your code is expected to notice the exception (via the function's return value,
-<code>ExceptionCheck()</code>, or <code>ExceptionOccurred()</code>) and return,
+<code>ExceptionCheck</code>, or <code>ExceptionOccurred</code>) and return,
 or clear the exception and handle it.</p>
 
 <p>The only JNI functions that you are allowed to call while an exception is
 pending are:</p>
 <ul>
-    <li>DeleteGlobalRef
-    <li>DeleteLocalRef
-    <li>DeleteWeakGlobalRef
-    <li>ExceptionCheck
-    <li>ExceptionClear
-    <li>ExceptionDescribe
-    <li>ExceptionOccurred
-    <li>MonitorExit
-    <li>PopLocalFrame
-    <li>PushLocalFrame
-    <li>Release&lt;PrimitiveType&gt;ArrayElements
-    <li>ReleasePrimitiveArrayCritical
-    <li>ReleaseStringChars
-    <li>ReleaseStringCritical
-    <li>ReleaseStringUTFChars
+    <li><code>DeleteGlobalRef</code>
+    <li><code>DeleteLocalRef</code>
+    <li><code>DeleteWeakGlobalRef</code>
+    <li><code>ExceptionCheck</code>
+    <li><code>ExceptionClear</code>
+    <li><code>ExceptionDescribe</code>
+    <li><code>ExceptionOccurred</code>
+    <li><code>MonitorExit</code>
+    <li><code>PopLocalFrame</code>
+    <li><code>PushLocalFrame</code>
+    <li><code>Release&lt;PrimitiveType&gt;ArrayElements</code>
+    <li><code>ReleasePrimitiveArrayCritical</code>
+    <li><code>ReleaseStringChars</code>
+    <li><code>ReleaseStringCritical</code>
+    <li><code>ReleaseStringUTFChars</code>
 </ul>
 
 <p>Many JNI calls can throw an exception, but often provide a simpler way
@@ -392,86 +380,80 @@
 <code>ExceptionClear</code>.  As usual,
 discarding exceptions without handling them can lead to problems.</p>
 
-<p>There are no built-in functions for manipulating the Throwable object
+<p>There are no built-in functions for manipulating the <code>Throwable</code> object
 itself, so if you want to (say) get the exception string you will need to
-find the Throwable class, look up the method ID for
+find the <code>Throwable</code> class, look up the method ID for
 <code>getMessage "()Ljava/lang/String;"</code>, invoke it, and if the result
 is non-NULL use <code>GetStringUTFChars</code> to get something you can
-hand to printf or a LOG macro.</p>
+hand to <code>printf(3)</code> or equivalent.</p>
 
 
 <a name="extended_checking" id="extended_checking"></a>
 <h2>Extended Checking</h2>
 
-<p>JNI does very little error checking.  Calling <code>SetIntField</code>
-on an Object field will succeed, even if the field is marked
-<code>private</code> and <code>final</code>.  The
-goal is to minimize the overhead on the assumption that, if you've written it in native code,
-you probably did it for performance reasons.</p>
+<p>JNI does very little error checking. Errors usually result in a crash. Android also offers a mode called CheckJNI, where the JavaVM and JNIEnv function table pointers are switched to tables of functions that perform an extended series of checks before calling the standard implementation.</p>
 
-<p>In Dalvik, you can enable additional checks by setting the
-"<code>-Xcheck:jni</code>" flag.  If the flag is set, the VM directs
-the JavaVM and JNIEnv pointers to a different table of functions.
-These functions perform an extended series of checks before calling the
-standard implementation.</p>
-
-<p>The additional tests include:</p>
+<p>The additional checks include:</p>
 
 <ul>
-<li> Check for null pointers where not allowed.</li>
-<li> Verify argument type correctness (jclass is a class object,
-jfieldID points to field data, jstring is a java.lang.String).</li>
-<li> Field type correctness, e.g. don't store a HashMap in a String field.</li>
-<li> Ensure jmethodID is appropriate when making a static or virtual
-method call.</li>
-<li> Check to see if an exception is pending on calls where pending exceptions are not legal.</li>
-<li> Check for calls to inappropriate functions between Critical get/release calls.</li>
-<li> Check that JNIEnv structs aren't being shared between threads.</li>
-<li> Make sure local references aren't used outside their allowed lifespan.</li>
-<li> UTF-8 strings contain only valid <a href="http://en.wikipedia.org/wiki/UTF-8#Modified_UTF-8">Modified UTF-8</a> data.</li>
+<li>Arrays: attempting to allocate a negative-sized array.</li>
+<li>Bad pointers: passing a bad jarray/jclass/jobject/jstring to a JNI call, or passing a NULL pointer to a JNI call with a non-nullable argument.</li>
+<li>Class names: passing anything but the “java/lang/String” style of class name to a JNI call.</li>
+<li>Critical calls: making a JNI call between a “critical” get and its corresponding release.</li>
+<li>Direct ByteBuffers: passing bad arguments to <code>NewDirectByteBuffer</code>.</li>
+<li>Exceptions: making a JNI call while there’s an exception pending.</li>
+<li>JNIEnv*s: using a JNIEnv* from the wrong thread.</li>
+<li>jfieldIDs: using a NULL jfieldID, or using a jfieldID to set a field to a value of the wrong type (trying to assign a StringBuilder to a String field, say), or using a jfieldID for a static field to set an instance field or vice versa, or using a jfieldID from one class with instances of another class.</li>
+<li>jmethodIDs: using the wrong kind of jmethodID when making a <code>Call*Method</code> JNI call: incorrect return type, static/non-static mismatch, wrong type for ‘this’ (for non-static calls) or wrong class (for static calls).</li>
+<li>References: using <code>DeleteGlobalRef</code>/<code>DeleteLocalRef</code> on the wrong kind of reference.</li>
+<li>Release modes: passing a bad release mode to a release call (something other than <code>0</code>, <code>JNI_ABORT</code>, or <code>JNI_COMMIT</code>).</li>
+<li>Type safety: returning an incompatible type from your native method (returning a StringBuilder from a method declared to return a String, say).</li>
+<li>UTF-8: passing an invalid <a href="http://en.wikipedia.org/wiki/UTF-8#Modified_UTF-8">Modified UTF-8</a> byte sequence to a JNI call.</li>
 </ul>
 
-<p>Accessibility of methods and fields (i.e. public vs. private) is not
-checked.</p>
+<p>(Accessibility of methods and fields is still not checked: access restrictions don't apply to native code.)</p>
 
-<p>For a description of how to enable CheckJNI for Android apps, see
-<a href="embedded-vm-control.html">Controlling the Embedded VM</a>.
-It's currently enabled by default in the Android emulator and on
-"engineering" device builds.</p>
+<p>There are several ways to enable CheckJNI.</p>
 
-<p>JNI checks can be modified with the <code>-Xjniopts</code> command-line
-flag.  Currently supported values include:</p>
+<p>If you’re using the emulator, CheckJNI is on by default.</p>
 
-<dl>
-<dt>forcecopy
-<dd>When set, any function that can return a copy of the original data
-(array of primitive values, UTF-16 chars) will always do so.  The buffers
-are over-allocated and surrounded with a guard pattern to help identify
-code writing outside the buffer, and the contents are erased before the
-storage is freed to trip up code that uses the data after calling Release.
-This will have a noticeable performance impact on some applications.
-<dt>warnonly
-<dd>By default, JNI "warnings" cause the VM to abort.  With this flag
-it continues on.
-</dl>
+<p>If you have a rooted device, you can use the following sequence of commands to restart the runtime with CheckJNI enabled:</p>
+
+<pre>adb shell stop
+adb shell setprop dalvik.vm.checkjni true
+adb shell start</pre>
+
+<p>In either of these cases, you’ll see something like this in your logcat output when the runtime starts:</p>
+
+<pre>D AndroidRuntime: CheckJNI is ON</pre>
+
+<p>If you have a regular device, you can use the following command:</p>
+
+<pre>adb shell setprop debug.checkjni 1</pre>
+
+<p>This won’t affect already-running apps, but any app launched from that point on will have CheckJNI enabled. (Change the property to any other value or simply rebooting will disable CheckJNI again.) In this case, you’ll see something like this in your logcat output the next time an app starts:</p>
+
+<pre>D Late-enabling CheckJNI</pre>
+
+
 
 
 <a name="native_libraries" id="native_libraries"></a>
 <h2>Native Libraries</h2>
 
 <p>You can load native code from shared libraries with the standard
-<code>System.loadLibrary()</code> call.  The
+<code>System.loadLibrary</code> call.  The
 preferred way to get at your native code is:</p>
 
 <ul>
-<li> Call <code>System.loadLibrary()</code> from a static class
+<li> Call <code>System.loadLibrary</code> from a static class
 initializer.  (See the earlier example, where one is used to call
-<code>nativeClassInit()</code>.)  The argument is the "undecorated"
-library name, e.g. to load "libfubar.so" you would pass in "fubar".</li>
+<code>nativeClassInit</code>.)  The argument is the "undecorated"
+library name, so to load "libfubar.so" you would pass in "fubar".</li>
 <li> Provide a native function: <code><strong>jint JNI_OnLoad(JavaVM* vm, void* reserved)</strong></code></li>
 <li>In <code>JNI_OnLoad</code>, register all of your native methods.  You
 should declare
-the functions <code>static</code> so the names don't take up space in the symbol table
+the methods "static" so the names don't take up space in the symbol table
 on the device.</li>
 </ul>
 
@@ -490,7 +472,7 @@
     return JNI_VERSION_1_6;
 }</pre>
 
-<p>You can also call <code>System.load()</code> with the full path name of the
+<p>You can also call <code>System.load</code> with the full path name of the
 shared library.  For Android apps, you may find it useful to get the full
 path to the application's private data storage area from the context object.</p>
 
@@ -549,28 +531,28 @@
 
 <p>For backward compatibility, you may need to be aware of:</p>
 <ul>
-    <li>Until Android 2.0 ("Eclair"), the '$' character was not properly
+    <li>Until Android 2.0 (Eclair), the '$' character was not properly
     converted to "_00024" during searches for method names.  Working
     around this requires using explicit registration or moving the
     native methods out of inner classes.
-    <li>Until Android 2.0 ("Eclair"), it was not possible to use a <code>pthread_key_create</code>
+    <li>Until Android 2.0 (Eclair), it was not possible to use a <code>pthread_key_create</code>
     destructor function to avoid the VM's "thread must be detached before
     exit" check.  (The VM also uses a pthread key destructor function,
     so it'd be a race to see which gets called first.)
-    <li>"Weak global" references were not implemented until Android 2.2 ("Froyo").
+    <li>Until Android 2.2 (Froyo), weak global references were not implemented.
     Older VMs will vigorously reject attempts to use them.  You can use
     the Android platform version constants to test for support.
 </ul>
 
 
 <a name="faq_ULE" id="faq_ULE"></a>
-<h2>FAQ: UnsatisfiedLinkError</h2>
+<h2>FAQ: Why do I get <code>UnsatisfiedLinkError</code>?</h2>
 
 <p>When working on native code it's not uncommon to see a failure like this:</p>
 <pre>java.lang.UnsatisfiedLinkError: Library foo not found</pre>
 
 <p>In some cases it means what it says &mdash; the library wasn't found.  In
-other cases the library exists but couldn't be opened by dlopen(), and
+other cases the library exists but couldn't be opened by <code>dlopen(3)</code>, and
 the details of the failure can be found in the exception's detail message.</p>
 
 <p>Common reasons why you might encounter "library not found" exceptions:</p>
@@ -601,7 +583,7 @@
         <li>For lazy method lookup, failing to declare C++ functions
         with <code>extern "C"</code>.  You can use <code>arm-eabi-nm</code>
         to see the symbols as they appear in the library; if they look
-        mangled (e.g. <code>_Z15Java_Foo_myfuncP7_JNIEnvP7_jclass</code>
+        mangled (something like <code>_Z15Java_Foo_myfuncP7_JNIEnvP7_jclass</code>
         rather than <code>Java_Foo_myfunc</code>) then you need to
         adjust the declaration.
         <li>For explicit registration, minor errors when entering the
@@ -610,8 +592,7 @@
         Remember that 'B' is <code>byte</code> and 'Z' is <code>boolean</code>.
         Class name components in signatures start with 'L', end with ';',
         use '/' to separate package/class names, and use '$' to separate
-        inner-class names
-        (e.g. <code>Ljava/util/Map$Entry;</code>).
+        inner-class names (<code>Ljava/util/Map$Entry;</code>, say).
     </ul>
 </ul>
 
@@ -620,11 +601,11 @@
 
 
 <a name="faq_FindClass" id="faq_FindClass"></a>
-<h2>FAQ: FindClass didn't find my class</h2>
+<h2>FAQ: Why didn't <code>FindClass</code> find my class?</h2>
 
 <p>Make sure that the class name string has the correct format.  JNI class
 names start with the package name and are separated with slashes,
-e.g. <code>java/lang/String</code>.  If you're looking up an array class,
+such as <code>java/lang/String</code>.  If you're looking up an array class,
 you need to start with the appropriate number of square brackets and
 must also wrap the class with 'L' and ';', so a one-dimensional array of
 <code>String</code> would be <code>[Ljava/lang/String;</code>.</p>
@@ -663,8 +644,8 @@
     If your app code is loading the library, <code>FindClass</code>
     will use the correct class loader.
     <li>Pass an instance of the class into the functions that need
-    it, e.g. declare your native method to take a Class argument and
-    then pass <code>Foo.class</code> in.
+    it, by declaring your native method to take a Class argument and
+    then passing <code>Foo.class</code> in.
     <li>Cache a reference to the <code>ClassLoader</code> object somewhere
     handy, and issue <code>loadClass</code> calls directly.  This requires
     some effort.
@@ -672,7 +653,7 @@
 
 
 <a name="faq_sharing" id="faq_sharing"></a>
-<h2>FAQ: Sharing raw data with native code</h2>
+<h2>FAQ: How do I share raw data with native code?</h2>
 
 <p>You may find yourself in a situation where you need to access a large
 buffer of raw data from code written in Java and C/C++.  Common examples
diff --git a/media/java/android/media/MediaScanner.java b/media/java/android/media/MediaScanner.java
index 1ba4c4f..2d1761f 100644
--- a/media/java/android/media/MediaScanner.java
+++ b/media/java/android/media/MediaScanner.java
@@ -327,6 +327,8 @@
     // used when scanning the image database so we know whether we have to prune
     // old thumbnail files
     private int mOriginalCount;
+    /** Whether the database had any entries in it before the scan started */
+    private boolean mWasEmptyPriorToScan = false;
     /** Whether the scanner has set a default sound for the ringer ringtone. */
     private boolean mDefaultRingtoneSet;
     /** Whether the scanner has set a default sound for the notification ringtone. */
@@ -547,6 +549,7 @@
             return entry;
         }
 
+        @Override
         public void scanFile(String path, long lastModified, long fileSize,
                 boolean isDirectory, boolean noMedia) {
             // This is the callback funtion from native codes.
@@ -901,19 +904,19 @@
                 mMediaProvider.update(result, values, null, null);
             }
 
-            if (notifications && !mDefaultNotificationSet) {
+            if (notifications && mWasEmptyPriorToScan && !mDefaultNotificationSet) {
                 if (TextUtils.isEmpty(mDefaultNotificationFilename) ||
                         doesPathHaveFilename(entry.mPath, mDefaultNotificationFilename)) {
                     setSettingIfNotSet(Settings.System.NOTIFICATION_SOUND, tableUri, rowId);
                     mDefaultNotificationSet = true;
                 }
-            } else if (ringtones && !mDefaultRingtoneSet) {
+            } else if (ringtones && mWasEmptyPriorToScan && !mDefaultRingtoneSet) {
                 if (TextUtils.isEmpty(mDefaultRingtoneFilename) ||
                         doesPathHaveFilename(entry.mPath, mDefaultRingtoneFilename)) {
                     setSettingIfNotSet(Settings.System.RINGTONE, tableUri, rowId);
                     mDefaultRingtoneSet = true;
                 }
-            } else if (alarms && !mDefaultAlarmSet) {
+            } else if (alarms && mWasEmptyPriorToScan && !mDefaultAlarmSet) {
                 if (TextUtils.isEmpty(mDefaultAlarmAlertFilename) ||
                         doesPathHaveFilename(entry.mPath, mDefaultAlarmAlertFilename)) {
                     setSettingIfNotSet(Settings.System.ALARM_ALERT, tableUri, rowId);
@@ -997,6 +1000,7 @@
                         where, selectionArgs, null);
 
                 if (c != null) {
+                    mWasEmptyPriorToScan = c.getCount() == 0;
                     while (c.moveToNext()) {
                         long rowId = c.getLong(FILES_PRESCAN_ID_COLUMN_INDEX);
                         String path = c.getString(FILES_PRESCAN_PATH_COLUMN_INDEX);
diff --git a/services/java/com/android/server/BackupManagerService.java b/services/java/com/android/server/BackupManagerService.java
index 8b7d3a8..1c06636 100644
--- a/services/java/com/android/server/BackupManagerService.java
+++ b/services/java/com/android/server/BackupManagerService.java
@@ -2105,10 +2105,13 @@
                     backupOnePackage(pkg, out);
                 }
 
-                // Finally, shared storage if requested
+                // Shared storage if requested
                 if (mIncludeShared) {
                     backupSharedStorage();
                 }
+
+                // Done!
+                finalizeBackup(out);
             } catch (RemoteException e) {
                 Slog.e(TAG, "App died during full backup");
             } finally {
@@ -2326,6 +2329,16 @@
             }
         }
 
+        private void finalizeBackup(OutputStream out) {
+            try {
+                // A standard 'tar' EOF sequence: two 512-byte blocks of all zeroes.
+                byte[] eof = new byte[512 * 2]; // newly allocated == zero filled
+                out.write(eof);
+            } catch (IOException e) {
+                Slog.w(TAG, "Error attempting to finalize backup stream");
+            }
+        }
+
         private void writeAppManifest(PackageInfo pkg, File manifestFile, boolean withApk)
                 throws IOException {
             // Manifest format. All data are strings ending in LF:
@@ -3186,9 +3199,11 @@
         void skipTarPadding(long size, InputStream instream) throws IOException {
             long partial = (size + 512) % 512;
             if (partial > 0) {
-                byte[] buffer = new byte[512];
-                int nRead = instream.read(buffer, 0, 512 - (int)partial);
-                if (nRead >= 0) mBytes += nRead;
+                final int needed = 512 - (int)partial;
+                byte[] buffer = new byte[needed];
+                if (readExactly(instream, buffer, 0, needed) == needed) {
+                    mBytes += needed;
+                } else throw new IOException("Unexpected EOF in padding");
             }
         }
 
@@ -3199,12 +3214,11 @@
             if (info.size > 64 * 1024) {
                 throw new IOException("Restore manifest too big; corrupt? size=" + info.size);
             }
+
             byte[] buffer = new byte[(int) info.size];
-            int nRead = 0;
-            while (nRead < info.size) {
-                nRead += instream.read(buffer, nRead, (int)info.size - nRead);
-            }
-            if (nRead >= 0) mBytes += nRead;
+            if (readExactly(instream, buffer, 0, (int)info.size) == info.size) {
+                mBytes += info.size;
+            } else throw new IOException("Unexpected EOF in manifest");
 
             RestorePolicy policy = RestorePolicy.IGNORE;
             String[] str = new String[1];
@@ -3453,7 +3467,7 @@
                     }
                 } catch (IOException e) {
                     if (DEBUG) {
-                        Slog.e(TAG, "Parse error in header.  Hexdump:");
+                        Slog.e(TAG, "Parse error in header: " + e.getMessage());
                         HEXLOG(block);
                     }
                     throw e;
@@ -3479,22 +3493,31 @@
             }
         }
 
-        boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
-            int totalRead = 0;
-            while (totalRead < 512) {
-                int nRead = instream.read(block, totalRead, 512 - totalRead);
-                if (nRead >= 0) {
-                    mBytes += nRead;
-                    totalRead += nRead;
-                } else {
-                    if (totalRead == 0) {
-                        // EOF instead of a new header; we're done
-                        break;
-                    }
-                    throw new IOException("Unable to read full block header, t=" + totalRead);
+        // Read exactly the given number of bytes into a buffer at the stated offset.
+        // Returns false if EOF is encountered before the requested number of bytes
+        // could be read.
+        int readExactly(InputStream in, byte[] buffer, int offset, int size)
+                throws IOException {
+            if (size <= 0) throw new IllegalArgumentException("size must be > 0");
+
+            int soFar = 0;
+            while (soFar < size) {
+                int nRead = in.read(buffer, offset + soFar, size - soFar);
+                if (nRead <= 0) {
+                    if (MORE_DEBUG) Slog.w(TAG, "- wanted exactly " + size + " but got only " + soFar);
+                    break;
                 }
+                soFar += nRead;
             }
-            return (totalRead == 512);
+            return soFar;
+        }
+
+        boolean readTarHeader(InputStream instream, byte[] block) throws IOException {
+            final int got = readExactly(instream, block, 0, 512);
+            if (got == 0) return false;     // Clean EOF
+            if (got < 512) throw new IOException("Unable to read full block header");
+            mBytes += 512;
+            return true;
         }
 
         // overwrites 'info' fields based on the pax extended header
@@ -3510,11 +3533,10 @@
             // read whole blocks, not just the content size
             int numBlocks = (int)((info.size + 511) >> 9);
             byte[] data = new byte[numBlocks * 512];
-            int nRead = instream.read(data);
-            if (nRead >= 0) mBytes += nRead;
-            if (nRead != data.length) {
-                return false;
+            if (readExactly(instream, data, 0, data.length) < data.length) {
+                throw new IOException("Unable to read full pax header");
             }
+            mBytes += data.length;
 
             final int contentSize = (int) info.size;
             int offset = 0;