Merge "Improve Html.toHtml() documentation" into mnc-dev
diff --git a/api/current.txt b/api/current.txt
index b173638..71a47a9c 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -2716,7 +2716,8 @@
     method public java.lang.String getUserData(android.accounts.Account, java.lang.String);
     method public android.accounts.AccountManagerFuture<java.lang.Boolean> hasFeatures(android.accounts.Account, java.lang.String[], android.accounts.AccountManagerCallback<java.lang.Boolean>, android.os.Handler);
     method public void invalidateAuthToken(java.lang.String, java.lang.String);
-    method public static android.content.Intent newChooseAccountIntent(android.accounts.Account, java.util.ArrayList<android.accounts.Account>, java.lang.String[], boolean, java.lang.String, java.lang.String, java.lang.String[], android.os.Bundle);
+    method public static deprecated android.content.Intent newChooseAccountIntent(android.accounts.Account, java.util.ArrayList<android.accounts.Account>, java.lang.String[], boolean, java.lang.String, java.lang.String, java.lang.String[], android.os.Bundle);
+    method public static android.content.Intent newChooseAccountIntent(android.accounts.Account, java.util.List<android.accounts.Account>, java.lang.String[], java.lang.String, java.lang.String, java.lang.String[], android.os.Bundle);
     method public boolean notifyAccountAuthenticated(android.accounts.Account);
     method public java.lang.String peekAuthToken(android.accounts.Account, java.lang.String);
     method public deprecated android.accounts.AccountManagerFuture<java.lang.Boolean> removeAccount(android.accounts.Account, android.accounts.AccountManagerCallback<java.lang.Boolean>, android.os.Handler);
diff --git a/api/system-current.txt b/api/system-current.txt
index 14fff8a..dc691e8 100644
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -2813,7 +2813,8 @@
     method public java.lang.String getUserData(android.accounts.Account, java.lang.String);
     method public android.accounts.AccountManagerFuture<java.lang.Boolean> hasFeatures(android.accounts.Account, java.lang.String[], android.accounts.AccountManagerCallback<java.lang.Boolean>, android.os.Handler);
     method public void invalidateAuthToken(java.lang.String, java.lang.String);
-    method public static android.content.Intent newChooseAccountIntent(android.accounts.Account, java.util.ArrayList<android.accounts.Account>, java.lang.String[], boolean, java.lang.String, java.lang.String, java.lang.String[], android.os.Bundle);
+    method public static deprecated android.content.Intent newChooseAccountIntent(android.accounts.Account, java.util.ArrayList<android.accounts.Account>, java.lang.String[], boolean, java.lang.String, java.lang.String, java.lang.String[], android.os.Bundle);
+    method public static android.content.Intent newChooseAccountIntent(android.accounts.Account, java.util.List<android.accounts.Account>, java.lang.String[], java.lang.String, java.lang.String, java.lang.String[], android.os.Bundle);
     method public boolean notifyAccountAuthenticated(android.accounts.Account);
     method public java.lang.String peekAuthToken(android.accounts.Account, java.lang.String);
     method public deprecated android.accounts.AccountManagerFuture<java.lang.Boolean> removeAccount(android.accounts.Account, android.accounts.AccountManagerCallback<java.lang.Boolean>, android.os.Handler);
diff --git a/core/java/android/accounts/AccountManager.java b/core/java/android/accounts/AccountManager.java
index aa7692b..7a20929 100644
--- a/core/java/android/accounts/AccountManager.java
+++ b/core/java/android/accounts/AccountManager.java
@@ -43,6 +43,7 @@
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
 import java.util.concurrent.Callable;
 import java.util.concurrent.CancellationException;
@@ -2259,6 +2260,9 @@
     }
 
     /**
+     * Deprecated in favor of {@link #newChooseAccountIntent(Account, List, String[], String,
+     * String, String[], Bundle)}.
+     *
      * Returns an intent to an {@link Activity} that prompts the user to choose from a list of
      * accounts.
      * The caller will then typically start the activity by calling
@@ -2273,14 +2277,13 @@
      * null, null, null);</pre>
      * @param selectedAccount if specified, indicates that the {@link Account} is the currently
      * selected one, according to the caller's definition of selected.
-     * @param allowableAccounts an optional {@link ArrayList} of accounts that are allowed to be
+     * @param allowableAccounts an optional {@link List} of accounts that are allowed to be
      * shown. If not specified then this field will not limit the displayed accounts.
      * @param allowableAccountTypes an optional string array of account types. These are used
      * both to filter the shown accounts and to filter the list of account types that are shown
      * when adding an account. If not specified then this field will not limit the displayed
      * account types when adding an account.
-     * @param alwaysPromptForAccount if set the account chooser screen is always shown, otherwise
-     * it is only shown when there is more than one account from which to choose
+     * @param alwaysPromptForAccount boolean that is ignored.
      * @param descriptionOverrideText if non-null this string is used as the description in the
      * accounts chooser screen rather than the default
      * @param addAccountAuthTokenType this string is passed as the {@link #addAccount}
@@ -2291,7 +2294,9 @@
      * parameter
      * @return an {@link Intent} that can be used to launch the ChooseAccount activity flow.
      */
-    static public Intent newChooseAccountIntent(Account selectedAccount,
+    @Deprecated
+    static public Intent newChooseAccountIntent(
+            Account selectedAccount,
             ArrayList<Account> allowableAccounts,
             String[] allowableAccountTypes,
             boolean alwaysPromptForAccount,
@@ -2299,20 +2304,67 @@
             String addAccountAuthTokenType,
             String[] addAccountRequiredFeatures,
             Bundle addAccountOptions) {
+        return newChooseAccountIntent(
+                selectedAccount,
+                allowableAccounts,
+                allowableAccountTypes,
+                descriptionOverrideText,
+                addAccountAuthTokenType,
+                addAccountRequiredFeatures,
+                addAccountOptions);
+    }
+
+    /**
+     * Returns an intent to an {@link Activity} that prompts the user to choose from a list of
+     * accounts.
+     * The caller will then typically start the activity by calling
+     * <code>startActivityForResult(intent, ...);</code>.
+     * <p>
+     * On success the activity returns a Bundle with the account name and type specified using
+     * keys {@link #KEY_ACCOUNT_NAME} and {@link #KEY_ACCOUNT_TYPE}.
+     * <p>
+     * The most common case is to call this with one account type, e.g.:
+     * <p>
+     * <pre>  newChooseAccountIntent(null, null, new String[]{"com.google"}, null, null, null,
+     * null);</pre>
+     * @param selectedAccount if specified, indicates that the {@link Account} is the currently
+     * selected one, according to the caller's definition of selected.
+     * @param allowableAccounts an optional {@link List} of accounts that are allowed to be
+     * shown. If not specified then this field will not limit the displayed accounts.
+     * @param allowableAccountTypes an optional string array of account types. These are used
+     * both to filter the shown accounts and to filter the list of account types that are shown
+     * when adding an account. If not specified then this field will not limit the displayed
+     * account types when adding an account.
+     * @param descriptionOverrideText if non-null this string is used as the description in the
+     * accounts chooser screen rather than the default
+     * @param addAccountAuthTokenType this string is passed as the {@link #addAccount}
+     * authTokenType parameter
+     * @param addAccountRequiredFeatures this string array is passed as the {@link #addAccount}
+     * requiredFeatures parameter
+     * @param addAccountOptions This {@link Bundle} is passed as the {@link #addAccount} options
+     * parameter
+     * @return an {@link Intent} that can be used to launch the ChooseAccount activity flow.
+     */
+    static public Intent newChooseAccountIntent(
+            Account selectedAccount,
+            List<Account> allowableAccounts,
+            String[] allowableAccountTypes,
+            String descriptionOverrideText,
+            String addAccountAuthTokenType,
+            String[] addAccountRequiredFeatures,
+            Bundle addAccountOptions) {
         Intent intent = new Intent();
         ComponentName componentName = ComponentName.unflattenFromString(
                 Resources.getSystem().getString(R.string.config_chooseTypeAndAccountActivity));
         intent.setClassName(componentName.getPackageName(),
                 componentName.getClassName());
         intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALLOWABLE_ACCOUNTS_ARRAYLIST,
-                allowableAccounts);
+                new ArrayList<Account>(allowableAccounts));
         intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALLOWABLE_ACCOUNT_TYPES_STRING_ARRAY,
                 allowableAccountTypes);
         intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_OPTIONS_BUNDLE,
                 addAccountOptions);
         intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_SELECTED_ACCOUNT, selectedAccount);
-        intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALWAYS_PROMPT_FOR_ACCOUNT,
-                alwaysPromptForAccount);
         intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_DESCRIPTION_TEXT_OVERRIDE,
                 descriptionOverrideText);
         intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_AUTH_TOKEN_TYPE_STRING,
diff --git a/core/java/android/accounts/ChooseTypeAndAccountActivity.java b/core/java/android/accounts/ChooseTypeAndAccountActivity.java
index c06b462..133df2b 100644
--- a/core/java/android/accounts/ChooseTypeAndAccountActivity.java
+++ b/core/java/android/accounts/ChooseTypeAndAccountActivity.java
@@ -88,9 +88,10 @@
     public static final String EXTRA_SELECTED_ACCOUNT = "selectedAccount";
 
     /**
-     * If true then display the account selection list even if there is just
-     * one account to choose from. boolean.
+     * Deprecated. Providing this extra to {@link ChooseTypeAndAccountActivity}
+     * will have no effect.
      */
+    @Deprecated
     public static final String EXTRA_ALWAYS_PROMPT_FOR_ACCOUNT =
             "alwaysPromptForAccount";
 
@@ -117,7 +118,6 @@
     private Set<String> mSetOfRelevantAccountTypes;
     private String mSelectedAccountName = null;
     private boolean mSelectedAddNewAccount = false;
-    private boolean mAlwaysPromptForAccount = false;
     private String mDescriptionOverride;
 
     private ArrayList<Account> mAccounts;
@@ -188,7 +188,6 @@
 
         mSetOfAllowableAccounts = getAllowableAccountSet(intent);
         mSetOfRelevantAccountTypes = getReleventAccountTypes(intent);
-        mAlwaysPromptForAccount = intent.getBooleanExtra(EXTRA_ALWAYS_PROMPT_FOR_ACCOUNT, false);
         mDescriptionOverride = intent.getStringExtra(EXTRA_DESCRIPTION_TEXT_OVERRIDE);
 
         mAccounts = getAcceptableAccountChoices(AccountManager.get(this));
@@ -218,15 +217,6 @@
                 } else {
                     startChooseAccountTypeActivity();
                 }
-                return;
-            }
-
-            // if there is only one allowable account return it
-            if (!mAlwaysPromptForAccount && mAccounts.size() == 1) {
-                Account account = mAccounts.get(0);
-                super.onCreate(savedInstanceState);
-                setResultAndFinish(account.name, account.type);
-                return;
             }
         }
 
diff --git a/core/java/android/net/ConnectivityManager.java b/core/java/android/net/ConnectivityManager.java
index de7ca0c..dc8ff8f 100644
--- a/core/java/android/net/ConnectivityManager.java
+++ b/core/java/android/net/ConnectivityManager.java
@@ -431,7 +431,8 @@
     public static final int TYPE_MOBILE_IA = 14;
 
     /**
-     * Emergency PDN connection for emergency calls
+     * Emergency PDN connection for emergency services.  This
+     * may include IMS and MMS in emergency situations.
      * {@hide}
      */
     public static final int TYPE_MOBILE_EMERGENCY = 15;
diff --git a/core/java/android/net/IConnectivityManager.aidl b/core/java/android/net/IConnectivityManager.aidl
index 78f8b95..46c28a6 100644
--- a/core/java/android/net/IConnectivityManager.aidl
+++ b/core/java/android/net/IConnectivityManager.aidl
@@ -112,7 +112,7 @@
 
     void startLegacyVpn(in VpnProfile profile);
 
-    LegacyVpnInfo getLegacyVpnInfo();
+    LegacyVpnInfo getLegacyVpnInfo(int userId);
 
     VpnInfo[] getAllVpnInfo();
 
diff --git a/core/java/android/net/NetworkCapabilities.java b/core/java/android/net/NetworkCapabilities.java
index 658051c..514d24a 100644
--- a/core/java/android/net/NetworkCapabilities.java
+++ b/core/java/android/net/NetworkCapabilities.java
@@ -133,7 +133,8 @@
 
     /**
      * Indicates this is a network that has the ability to reach a carrier's
-     * Emergency IMS servers, used for network signaling during emergency calls.
+     * Emergency IMS servers or other services, used for network signaling
+     * during emergency calls.
      */
     public static final int NET_CAPABILITY_EIMS           = 10;
 
diff --git a/core/java/android/text/SpannableStringInternal.java b/core/java/android/text/SpannableStringInternal.java
index d114d32..5c5deb4 100644
--- a/core/java/android/text/SpannableStringInternal.java
+++ b/core/java/android/text/SpannableStringInternal.java
@@ -214,10 +214,6 @@
         Object ret1 = null;
 
         for (int i = 0; i < spanCount; i++) {
-            if (kind != null && !kind.isInstance(spans[i])) {
-                continue;
-            }
-
             int spanStart = data[i * COLUMNS + START];
             int spanEnd = data[i * COLUMNS + END];
 
@@ -237,6 +233,11 @@
                 }
             }
 
+            // verify span class as late as possible, since it is expensive
+            if (kind != null && !kind.isInstance(spans[i])) {
+                continue;
+            }
+
             if (count == 0) {
                 ret1 = spans[i];
                 count++;
diff --git a/core/java/android/text/StaticLayout.java b/core/java/android/text/StaticLayout.java
index cdff395..efc9e1a 100644
--- a/core/java/android/text/StaticLayout.java
+++ b/core/java/android/text/StaticLayout.java
@@ -744,7 +744,8 @@
                     && (ellipsize == TextUtils.TruncateAt.END
                         || (mMaximumVisibleLineCount == 1
                                 && ellipsize != TextUtils.TruncateAt.MARQUEE));
-            if (remainingLineCount < breakCount && ellipsisMayBeApplied) {
+            if (remainingLineCount > 0 && remainingLineCount < breakCount &&
+                    ellipsisMayBeApplied) {
                 // Treat the last line and overflowed lines as a single line.
                 breaks[remainingLineCount - 1] = breaks[breakCount - 1];
                 // Calculate width and flag.
diff --git a/core/java/android/widget/Editor.java b/core/java/android/widget/Editor.java
index 96e033a..d897f49 100644
--- a/core/java/android/widget/Editor.java
+++ b/core/java/android/widget/Editor.java
@@ -16,6 +16,12 @@
 
 package android.widget;
 
+import java.text.BreakIterator;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.List;
+
 import android.R;
 import android.annotation.Nullable;
 import android.app.PendingIntent;
@@ -106,12 +112,6 @@
 import com.android.internal.util.Preconditions;
 import com.android.internal.widget.EditableInputConnection;
 
-import java.text.BreakIterator;
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.List;
-
 
 /**
  * Helper class used by TextView to handle editable text views.
@@ -127,6 +127,7 @@
     private static int DRAG_SHADOW_MAX_TEXT_LENGTH = 20;
     private static final float LINE_SLOP_MULTIPLIER_FOR_HANDLEVIEWS = 0.5f;
     private static final int UNSET_X_VALUE = -1;
+    private static final int UNSET_LINE = -1;
     // Tag used when the Editor maintains its own separate UndoManager.
     private static final String UNDO_OWNER_TAG = "Editor";
 
@@ -3510,7 +3511,11 @@
         // Minimum touch target size for handles
         private int mMinSize;
         // Indicates the line of text that the handle is on.
-        protected int mPrevLine = -1;
+        protected int mPrevLine = UNSET_LINE;
+        // Indicates the line of text that the user was touching. This can differ from mPrevLine
+        // when selecting text when the handles jump to the end / start of words which may be on
+        // a different line.
+        protected int mPreviousLineTouched = UNSET_LINE;
 
         public HandleView(Drawable drawableLtr, Drawable drawableRtl) {
             super(mTextView.getContext());
@@ -3801,6 +3806,7 @@
                     mLastParentX = positionListener.getPositionX();
                     mLastParentY = positionListener.getPositionY();
                     mIsDragging = true;
+                    mPreviousLineTouched = UNSET_LINE;
                     break;
                 }
 
@@ -4015,8 +4021,12 @@
             Layout layout = mTextView.getLayout();
             int offset;
             if (layout != null) {
-                int currLine = getCurrentLineAdjustedForSlop(layout, mPrevLine, y);
+                if (mPreviousLineTouched == UNSET_LINE) {
+                    mPreviousLineTouched = mTextView.getLineAtCoordinate(y);
+                }
+                int currLine = getCurrentLineAdjustedForSlop(layout, mPreviousLineTouched, y);
                 offset = mTextView.getOffsetAtCoordinate(currLine, x);
+                mPreviousLineTouched = currLine;
             } else {
                 offset = mTextView.getOffsetForPosition(x, y);
             }
@@ -4092,9 +4102,13 @@
                 return;
             }
 
+            if (mPreviousLineTouched == UNSET_LINE) {
+                mPreviousLineTouched = mTextView.getLineAtCoordinate(y);
+            }
+
             boolean positionCursor = false;
             final int selectionEnd = mTextView.getSelectionEnd();
-            int currLine = getCurrentLineAdjustedForSlop(layout, mPrevLine, y);
+            int currLine = getCurrentLineAdjustedForSlop(layout, mPreviousLineTouched, y);
             int initialOffset = mTextView.getOffsetAtCoordinate(currLine, x);
 
             if (initialOffset >= selectionEnd) {
@@ -4138,9 +4152,9 @@
             } else {
                 final float xDiff = x - mPrevX;
                 if (atRtl) {
-                    isExpanding = xDiff > 0 || currLine > mPrevLine;
+                    isExpanding = xDiff > 0 || currLine > mPreviousLineTouched;
                 } else {
-                    isExpanding = xDiff < 0 || currLine < mPrevLine;
+                    isExpanding = xDiff < 0 || currLine < mPreviousLineTouched;
                 }
             }
 
@@ -4204,6 +4218,7 @@
                     offset = getNextCursorOffset(selectionEnd, false);
                     mTouchWordDelta = 0.0f;
                 }
+                mPreviousLineTouched = currLine;
                 positionAtCursorOffset(offset, false);
             }
             mPrevX = x;
@@ -4218,8 +4233,9 @@
         @Override
         public boolean onTouchEvent(MotionEvent event) {
             boolean superResult = super.onTouchEvent(event);
-            if (event.getActionMasked() == MotionEvent.ACTION_UP) {
-                // Reset the touch word offset when the user has lifted their finger.
+            if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
+                // Reset the touch word offset and x value when the user
+                // re-engages the handle.
                 mTouchWordDelta = 0.0f;
                 mPrevX = UNSET_X_VALUE;
             }
@@ -4280,9 +4296,13 @@
                 return;
             }
 
+            if (mPreviousLineTouched == UNSET_LINE) {
+                mPreviousLineTouched = mTextView.getLineAtCoordinate(y);
+            }
+
             boolean positionCursor = false;
             final int selectionStart = mTextView.getSelectionStart();
-            int currLine = getCurrentLineAdjustedForSlop(layout, mPrevLine, y);
+            int currLine = getCurrentLineAdjustedForSlop(layout, mPreviousLineTouched, y);
             int initialOffset = mTextView.getOffsetAtCoordinate(currLine, x);
 
             if (initialOffset <= selectionStart) {
@@ -4326,9 +4346,9 @@
             } else {
                 final float xDiff = x - mPrevX;
                 if (atRtl) {
-                    isExpanding = xDiff < 0 || currLine < mPrevLine;
+                    isExpanding = xDiff < 0 || currLine < mPreviousLineTouched;
                 } else {
-                    isExpanding = xDiff > 0 || currLine > mPrevLine;
+                    isExpanding = xDiff > 0 || currLine > mPreviousLineTouched;
                 }
             }
 
@@ -4392,6 +4412,7 @@
                     offset = getNextCursorOffset(selectionStart, true);
                     mTouchWordDelta = 0.0f;
                 }
+                mPreviousLineTouched = currLine;
                 positionAtCursorOffset(offset, false);
             }
             mPrevX = x;
@@ -4406,8 +4427,9 @@
         @Override
         public boolean onTouchEvent(MotionEvent event) {
             boolean superResult = super.onTouchEvent(event);
-            if (event.getActionMasked() == MotionEvent.ACTION_UP) {
-                // Reset the touch word offset when the user has lifted their finger.
+            if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
+                // Reset the touch word offset and x value when the user
+                // re-engages the handle.
                 mTouchWordDelta = 0.0f;
                 mPrevX = UNSET_X_VALUE;
             }
@@ -4416,10 +4438,16 @@
     }
 
     private int getCurrentLineAdjustedForSlop(Layout layout, int prevLine, float y) {
+        final int trueLine = mTextView.getLineAtCoordinate(y);
         if (layout == null || prevLine > layout.getLineCount()
                 || layout.getLineCount() <= 0 || prevLine < 0) {
             // Invalid parameters, just return whatever line is at y.
-            return mTextView.getLineAtCoordinate(y);
+            return trueLine;
+        }
+
+        if (Math.abs(trueLine - prevLine) >= 2) {
+            // Only stick to lines if we're within a line of the previous selection.
+            return trueLine;
         }
 
         final float verticalOffset = mTextView.viewportToContentVerticalOffset();
diff --git a/core/jni/android/graphics/Paint.cpp b/core/jni/android/graphics/Paint.cpp
index bff1885..c66cdfe 100644
--- a/core/jni/android/graphics/Paint.cpp
+++ b/core/jni/android/graphics/Paint.cpp
@@ -1065,12 +1065,11 @@
             jint contextEnd, jboolean isRtl, jint offset) {
         const Paint* paint = reinterpret_cast<Paint*>(paintHandle);
         TypefaceImpl* typeface = reinterpret_cast<TypefaceImpl*>(typefaceHandle);
-        // TODO performance: optimize JNI array access
-        jchar* textArray = env->GetCharArrayElements(text, NULL);
+        jchar* textArray = (jchar*) env->GetPrimitiveArrayCritical(text, NULL);
         jfloat result = doRunAdvance(paint, typeface, textArray + contextStart,
                 start - contextStart, end - start, contextEnd - contextStart, isRtl,
                 offset - contextStart);
-        env->ReleaseCharArrayElements(text, textArray, JNI_ABORT);
+        env->ReleasePrimitiveArrayCritical(text, textArray, JNI_ABORT);
         return result;
     }
 
@@ -1086,12 +1085,11 @@
             jint contextEnd, jboolean isRtl, jfloat advance) {
         const Paint* paint = reinterpret_cast<Paint*>(paintHandle);
         TypefaceImpl* typeface = reinterpret_cast<TypefaceImpl*>(typefaceHandle);
-        // TODO performance: optimize JNI array access
-        jchar* textArray = env->GetCharArrayElements(text, NULL);
+        jchar* textArray = (jchar*) env->GetPrimitiveArrayCritical(text, NULL);
         jint result = doOffsetForAdvance(paint, typeface, textArray + contextStart,
                 start - contextStart, end - start, contextEnd - contextStart, isRtl, advance);
         result += contextStart;
-        env->ReleaseCharArrayElements(text, textArray, JNI_ABORT);
+        env->ReleasePrimitiveArrayCritical(text, textArray, JNI_ABORT);
         return result;
     }
 
@@ -1158,9 +1156,9 @@
     {"ascent","!()F", (void*) PaintGlue::ascent},
     {"descent","!()F", (void*) PaintGlue::descent},
 
-    {"getFontMetrics", "(Landroid/graphics/Paint$FontMetrics;)F",
+    {"getFontMetrics", "!(Landroid/graphics/Paint$FontMetrics;)F",
             (void*)PaintGlue::getFontMetrics},
-    {"getFontMetricsInt", "(Landroid/graphics/Paint$FontMetricsInt;)I",
+    {"getFontMetricsInt", "!(Landroid/graphics/Paint$FontMetricsInt;)I",
             (void*)PaintGlue::getFontMetricsInt},
     {"native_measureText","([CIII)F", (void*) PaintGlue::measureText_CIII},
     {"native_measureText","(Ljava/lang/String;I)F", (void*) PaintGlue::measureText_StringI},
diff --git a/docs/html-intl/intl/es/preview/overview.jd b/docs/html-intl/intl/es/preview/overview.jd
index 49cc3d3..2cd2130 100644
--- a/docs/html-intl/intl/es/preview/overview.jd
+++ b/docs/html-intl/intl/es/preview/overview.jd
@@ -5,6 +5,33 @@
 
 @jd:body
 
+<div class="cols" style=
+"background-color:#ffebc3; padding: 5px 0;margin-bottom:1em; text-align:center;">
+<h3>
+    Developer Preview 2 is now available
+  </h3>
+
+ <ul class="dac-section-links">
+    <li class="dac-section-link">
+      <a href="{@docRoot}preview/support.html#preview2-notes">
+      <span class="dac-sprite dac-auto-chevron"></span>
+      Read the Notes</a>
+    </li>
+
+    <li class="dac-section-link">
+      <a href="{@docRoot}preview/support.html#preview2-get">
+      <span class="dac-sprite dac-auto-chevron"></span>
+      Get the Update</a>
+    </li>
+
+    <li class="dac-section-link">
+      <a href="https://code.google.com/p/android-developer-preview/">
+      <span class="dac-sprite dac-auto-chevron"></span>
+      Report Issues</a>
+    </li>
+  </ul>
+</div>
+
 <p>
   Bienvenido a <strong>Android M Developer Preview</strong>, el programa que le brinda todo lo que necesita para probar y optimizar sus aplicaciones para la próxima versión de Android.
 
diff --git a/docs/html-intl/intl/ja/preview/overview.jd b/docs/html-intl/intl/ja/preview/overview.jd
index 4cefdd1..c5390ef 100644
--- a/docs/html-intl/intl/ja/preview/overview.jd
+++ b/docs/html-intl/intl/ja/preview/overview.jd
@@ -5,6 +5,33 @@
 
 @jd:body
 
+<div class="cols" style=
+"background-color:#ffebc3; padding: 5px 0;margin-bottom:1em; text-align:center;">
+<h3>
+    Developer Preview 2 is now available
+  </h3>
+
+ <ul class="dac-section-links">
+    <li class="dac-section-link">
+      <a href="{@docRoot}preview/support.html#preview2-notes">
+      <span class="dac-sprite dac-auto-chevron"></span>
+      Read the Notes</a>
+    </li>
+
+    <li class="dac-section-link">
+      <a href="{@docRoot}preview/support.html#preview2-get">
+      <span class="dac-sprite dac-auto-chevron"></span>
+      Get the Update</a>
+    </li>
+
+    <li class="dac-section-link">
+      <a href="https://code.google.com/p/android-developer-preview/">
+      <span class="dac-sprite dac-auto-chevron"></span>
+      Report Issues</a>
+    </li>
+  </ul>
+</div>
+
 <p>
   <strong>Android M Developer Preview</strong> では、Android の次のバージョンでアプリをテストして最適化するためのすべてを備えています。
 
@@ -323,7 +350,7 @@
 </h2>
 
 <p>
-  アプリのテストをはじめるには: 
+  アプリのテストをはじめるには:
 </p>
 
 <ol>
diff --git a/docs/html-intl/intl/ko/preview/overview.jd b/docs/html-intl/intl/ko/preview/overview.jd
index d325725..04febc7 100644
--- a/docs/html-intl/intl/ko/preview/overview.jd
+++ b/docs/html-intl/intl/ko/preview/overview.jd
@@ -5,6 +5,33 @@
 
 @jd:body
 
+<div class="cols" style=
+"background-color:#ffebc3; padding: 5px 0;margin-bottom:1em; text-align:center;">
+<h3>
+    Developer Preview 2 is now available
+  </h3>
+
+ <ul class="dac-section-links">
+    <li class="dac-section-link">
+      <a href="{@docRoot}preview/support.html#preview2-notes">
+      <span class="dac-sprite dac-auto-chevron"></span>
+      Read the Notes</a>
+    </li>
+
+    <li class="dac-section-link">
+      <a href="{@docRoot}preview/support.html#preview2-get">
+      <span class="dac-sprite dac-auto-chevron"></span>
+      Get the Update</a>
+    </li>
+
+    <li class="dac-section-link">
+      <a href="https://code.google.com/p/android-developer-preview/">
+      <span class="dac-sprite dac-auto-chevron"></span>
+      Report Issues</a>
+    </li>
+  </ul>
+</div>
+
 <p>
   <strong>Android M 개발자 미리 보기</strong>를 시작하신 여러분, 환영합니다. 이 프로그램은 Android의 다음 버전에 대해 앱을 테스트하고 최적화하는 데 필요한 모든 것을 제공해 드립니다.
 
diff --git a/docs/html-intl/intl/pt-br/preview/overview.jd b/docs/html-intl/intl/pt-br/preview/overview.jd
index ce5a596..e81ccd7 100644
--- a/docs/html-intl/intl/pt-br/preview/overview.jd
+++ b/docs/html-intl/intl/pt-br/preview/overview.jd
@@ -5,6 +5,33 @@
 
 @jd:body
 
+<div class="cols" style=
+"background-color:#ffebc3; padding: 5px 0;margin-bottom:1em; text-align:center;">
+<h3>
+    Developer Preview 2 is now available
+  </h3>
+
+ <ul class="dac-section-links">
+    <li class="dac-section-link">
+      <a href="{@docRoot}preview/support.html#preview2-notes">
+      <span class="dac-sprite dac-auto-chevron"></span>
+      Read the Notes</a>
+    </li>
+
+    <li class="dac-section-link">
+      <a href="{@docRoot}preview/support.html#preview2-get">
+      <span class="dac-sprite dac-auto-chevron"></span>
+      Get the Update</a>
+    </li>
+
+    <li class="dac-section-link">
+      <a href="https://code.google.com/p/android-developer-preview/">
+      <span class="dac-sprite dac-auto-chevron"></span>
+      Report Issues</a>
+    </li>
+  </ul>
+</div>
+
 <p>
   Boas-vindas ao <strong>Android M Developer Preview</strong>, um programa que fornece
  tudo que é necessário para testar e otimizar os aplicativos para a próxima versão
diff --git a/docs/html-intl/intl/ru/preview/overview.jd b/docs/html-intl/intl/ru/preview/overview.jd
index 6ed1d20..d1345a25 100644
--- a/docs/html-intl/intl/ru/preview/overview.jd
+++ b/docs/html-intl/intl/ru/preview/overview.jd
@@ -5,6 +5,33 @@
 
 @jd:body
 
+<div class="cols" style=
+"background-color:#ffebc3; padding: 5px 0;margin-bottom:1em; text-align:center;">
+<h3>
+    Developer Preview 2 is now available
+  </h3>
+
+ <ul class="dac-section-links">
+    <li class="dac-section-link">
+      <a href="{@docRoot}preview/support.html#preview2-notes">
+      <span class="dac-sprite dac-auto-chevron"></span>
+      Read the Notes</a>
+    </li>
+
+    <li class="dac-section-link">
+      <a href="{@docRoot}preview/support.html#preview2-get">
+      <span class="dac-sprite dac-auto-chevron"></span>
+      Get the Update</a>
+    </li>
+
+    <li class="dac-section-link">
+      <a href="https://code.google.com/p/android-developer-preview/">
+      <span class="dac-sprite dac-auto-chevron"></span>
+      Report Issues</a>
+    </li>
+  </ul>
+</div>
+
 <p>
   Добро пожаловать в программу <strong>Android M Developer Preview</strong>, участники которой получают всё необходимоедля тестирования и оптимизации своих приложений для следующей версии платформы Android.
 
@@ -114,7 +141,7 @@
 <img src="{@docRoot}preview/images/m-preview-timeline-crop.png" alt="Preview program timeline" id="timeline">
 <p>
   Тестирование версии M Developer Preview запланировано на период с 28 мая до выпуска окончательной версии пакета SDK Android M, который
-состоится незадолго до публикации новой платформы в открытом доступе в 
+состоится незадолго до публикации новой платформы в открытом доступе в
 третьем квартале 2015 г.
 </p>
 
diff --git a/docs/html-intl/intl/zh-cn/preview/overview.jd b/docs/html-intl/intl/zh-cn/preview/overview.jd
index cebbf06..d931db0 100644
--- a/docs/html-intl/intl/zh-cn/preview/overview.jd
+++ b/docs/html-intl/intl/zh-cn/preview/overview.jd
@@ -5,6 +5,33 @@
 
 @jd:body
 
+<div class="cols" style=
+"background-color:#ffebc3; padding: 5px 0;margin-bottom:1em; text-align:center;">
+<h3>
+    Developer Preview 2 is now available
+  </h3>
+
+ <ul class="dac-section-links">
+    <li class="dac-section-link">
+      <a href="{@docRoot}preview/support.html#preview2-notes">
+      <span class="dac-sprite dac-auto-chevron"></span>
+      Read the Notes</a>
+    </li>
+
+    <li class="dac-section-link">
+      <a href="{@docRoot}preview/support.html#preview2-get">
+      <span class="dac-sprite dac-auto-chevron"></span>
+      Get the Update</a>
+    </li>
+
+    <li class="dac-section-link">
+      <a href="https://code.google.com/p/android-developer-preview/">
+      <span class="dac-sprite dac-auto-chevron"></span>
+      Report Issues</a>
+    </li>
+  </ul>
+</div>
+
 <p>
   欢迎使用 <strong>Android M 开发者预览版</strong>计划。此计划将为您提供针对 Android 的下一版本测试和优化应用所需的所有功能。
 
@@ -295,7 +322,7 @@
 </p>
 
 <p>
-  Android M 开发者预览版提供<strong>预览 API</strong> 功能 
+  Android M 开发者预览版提供<strong>预览 API</strong> 功能
 &mdash; 在最终的 SDK 发布之前,这些 API 都不是正式的 API。目前,最终的 SDK 计划于 2015 年第三季度发布。
 这意味着一段时期内,特别是该计划的最初几周内,
 <strong>API 可能会出现细微变化</strong>。
diff --git a/docs/html-intl/intl/zh-tw/preview/overview.jd b/docs/html-intl/intl/zh-tw/preview/overview.jd
index 63cde32..9693eec 100644
--- a/docs/html-intl/intl/zh-tw/preview/overview.jd
+++ b/docs/html-intl/intl/zh-tw/preview/overview.jd
@@ -5,6 +5,33 @@
 
 @jd:body
 
+<div class="cols" style=
+"background-color:#ffebc3; padding: 5px 0;margin-bottom:1em; text-align:center;">
+<h3>
+    Developer Preview 2 is now available
+  </h3>
+
+ <ul class="dac-section-links">
+    <li class="dac-section-link">
+      <a href="{@docRoot}preview/support.html#preview2-notes">
+      <span class="dac-sprite dac-auto-chevron"></span>
+      Read the Notes</a>
+    </li>
+
+    <li class="dac-section-link">
+      <a href="{@docRoot}preview/support.html#preview2-get">
+      <span class="dac-sprite dac-auto-chevron"></span>
+      Get the Update</a>
+    </li>
+
+    <li class="dac-section-link">
+      <a href="https://code.google.com/p/android-developer-preview/">
+      <span class="dac-sprite dac-auto-chevron"></span>
+      Report Issues</a>
+    </li>
+  </ul>
+</div>
+
 <p>
   歡迎使用「Android M 開發人員預覽版」<strong></strong>,本程式提供為新版 Android 測試和最佳化您應用程式所需的一切。
 
diff --git a/docs/html/preview/overview.jd b/docs/html/preview/overview.jd
index a19c926..009e268 100644
--- a/docs/html/preview/overview.jd
+++ b/docs/html/preview/overview.jd
@@ -13,13 +13,13 @@
 
  <ul class="dac-section-links">
     <li class="dac-section-link">
-      <a href="#preview2-notes">
+      <a href="{@docRoot}preview/support.html#preview2-notes">
       <span class="dac-sprite dac-auto-chevron"></span>
       Read the Notes</a>
     </li>
 
     <li class="dac-section-link">
-      <a href="#preview2-get">
+      <a href="{@docRoot}preview/support.html#preview2-get">
       <span class="dac-sprite dac-auto-chevron"></span>
       Get the Update</a>
     </li>
diff --git a/docs/html/preview/support.jd b/docs/html/preview/support.jd
index 8792f778..d908f77 100644
--- a/docs/html/preview/support.jd
+++ b/docs/html/preview/support.jd
@@ -246,9 +246,11 @@
       <strong>Clear data</strong>.</li>
       <li>In YouTube app, it's not possible to share a video. The share window is
       blank.</li>
-      <li>Android For Work Profile setup is not working properly, so you won't be
-      able to create a new Work Profile after you update. As a workaround, make
-      sure to create the Work Profiles you need in Developer Preview 1 before
+      <li>The bundled Google Apps Device Policy app included in Developer Preview 2 is unable to
+      properly set up an Android for Work Profile, so you cannot create a new Work Profile with this
+      app after you update. This issue is specific to the Google Apps Device Policy app, and not the
+      Android for Work platform (or our partner EMM providers). As a workaround for users of the
+      Google Apps Device Policy app, be sure to create a Work Profile in Developer Preview 1 before
       updating to Developer Preview 2.
       </li>
     </ul>
diff --git a/packages/SettingsLib/src/com/android/settingslib/wifi/AccessPoint.java b/packages/SettingsLib/src/com/android/settingslib/wifi/AccessPoint.java
index 9325246..048fb9a 100644
--- a/packages/SettingsLib/src/com/android/settingslib/wifi/AccessPoint.java
+++ b/packages/SettingsLib/src/com/android/settingslib/wifi/AccessPoint.java
@@ -293,7 +293,8 @@
     public String getSecurityString(boolean concise) {
         Context context = mContext;
         if (mConfig != null && mConfig.isPasspoint()) {
-            return context.getString(R.string.wifi_security_passpoint);
+            return concise ? context.getString(R.string.wifi_security_short_eap) :
+                context.getString(R.string.wifi_security_eap);
         }
         switch(security) {
             case SECURITY_EAP:
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
index 7f61fc1..009a0d6 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
@@ -253,6 +253,7 @@
     private KeyguardUpdateMonitor mUpdateMonitor;
 
     private boolean mDeviceInteractive;
+    private boolean mGoingToSleep;
 
     // last known state of the cellular connection
     private String mPhoneState = TelephonyManager.EXTRA_STATE_IDLE;
@@ -639,6 +640,7 @@
         if (DEBUG) Log.d(TAG, "onStartedGoingToSleep(" + why + ")");
         synchronized (this) {
             mDeviceInteractive = false;
+            mGoingToSleep = true;
 
             // Lock immediately based on setting if secure (user has a pin/pattern/password).
             // This also "locks" the device when not secure to provide easy access to the
@@ -678,6 +680,7 @@
         if (DEBUG) Log.d(TAG, "onFinishedGoingToSleep(" + why + ")");
         synchronized (this) {
             mDeviceInteractive = false;
+            mGoingToSleep = false;
 
             resetKeyguardDonePendingLocked();
             mHideAnimationRun = false;
@@ -1239,6 +1242,10 @@
         }
         mUpdateMonitor.clearFingerprintRecognized();
 
+        if (mGoingToSleep) {
+            Log.i(TAG, "Device is going to sleep, aborting keyguardDone");
+            return;
+        }
         if (mExitSecureCallback != null) {
             try {
                 mExitSecureCallback.onKeyguardExitResult(authenticated);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
index bda1374..891cc73 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
@@ -1700,7 +1700,10 @@
                     Log.v(TAG, "DEBUG_MEDIA: Fading out album artwork");
                 }
                 mBackdrop.animate()
-                        .alpha(0f)
+                        // Never let the alpha become zero - otherwise the RenderNode
+                        // won't draw anything and uninitialized memory will show through
+                        // if mScrimSrcModeEnabled. Note that 0.001 is rounded down to 0 in libhwui.
+                        .alpha(0.002f)
                         .setInterpolator(mBackdropInterpolator)
                         .setDuration(300)
                         .setStartDelay(0)
@@ -3030,11 +3033,14 @@
         }
 
         final int N = newlyVisible.size();
-        String[] newlyVisibleKeyAr = new String[N];
-        for (int i = 0; i < N; i++) {
-            newlyVisibleKeyAr[i] = newlyVisibleAr[i].key;
+        if (N > 0) {
+            String[] newlyVisibleKeyAr = new String[N];
+            for (int i = 0; i < N; i++) {
+                newlyVisibleKeyAr[i] = newlyVisibleAr[i].key;
+            }
+
+            setNotificationsShown(newlyVisibleKeyAr);
         }
-        setNotificationsShown(newlyVisibleKeyAr);
     }
 
     // State logging
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/SecurityControllerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/SecurityControllerImpl.java
index b505d9d..6af9854 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/SecurityControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/SecurityControllerImpl.java
@@ -25,7 +25,9 @@
 import android.net.IConnectivityManager;
 import android.net.Network;
 import android.net.NetworkCapabilities;
+import android.net.NetworkInfo;
 import android.net.NetworkRequest;
+import android.os.Process;
 import android.os.RemoteException;
 import android.os.ServiceManager;
 import android.os.UserHandle;
@@ -34,6 +36,7 @@
 import android.util.Log;
 import android.util.SparseArray;
 
+import com.android.internal.net.LegacyVpnInfo;
 import com.android.internal.net.VpnConfig;
 import com.android.internal.net.VpnInfo;
 import com.android.systemui.R;
@@ -210,9 +213,17 @@
         try {
             for (UserInfo user : mUserManager.getUsers()) {
                 VpnConfig cfg = mConnectivityManagerService.getVpnConfig(user.id);
-                if (cfg != null) {
-                    vpns.put(user.id, cfg);
+                if (cfg == null) {
+                    continue;
+                } else if (cfg.legacy) {
+                    // Legacy VPNs should do nothing if the network is disconnected. Third-party
+                    // VPN warnings need to continue as traffic can still go to the app.
+                    LegacyVpnInfo legacyVpn = mConnectivityManagerService.getLegacyVpnInfo(user.id);
+                    if (legacyVpn == null || legacyVpn.state != LegacyVpnInfo.STATE_CONNECTED) {
+                        continue;
+                    }
                 }
+                vpns.put(user.id, cfg);
             }
         } catch (RemoteException rme) {
             // Roll back to previous state
diff --git a/services/core/java/com/android/server/ConnectivityService.java b/services/core/java/com/android/server/ConnectivityService.java
index 2075c07e..39c2891 100644
--- a/services/core/java/com/android/server/ConnectivityService.java
+++ b/services/core/java/com/android/server/ConnectivityService.java
@@ -3031,11 +3031,11 @@
      * are checked in Vpn class.
      */
     @Override
-    public LegacyVpnInfo getLegacyVpnInfo() {
+    public LegacyVpnInfo getLegacyVpnInfo(int userId) {
+        enforceCrossUserPermission(userId);
         throwIfLockdownEnabled();
-        int user = UserHandle.getUserId(Binder.getCallingUid());
         synchronized(mVpns) {
-            return mVpns.get(user).getLegacyVpnInfo();
+            return mVpns.get(userId).getLegacyVpnInfo();
         }
     }
 
diff --git a/services/core/java/com/android/server/am/ActivityStack.java b/services/core/java/com/android/server/am/ActivityStack.java
index 31cdcd5..8c3a950 100644
--- a/services/core/java/com/android/server/am/ActivityStack.java
+++ b/services/core/java/com/android/server/am/ActivityStack.java
@@ -2963,7 +2963,6 @@
         r.state = ActivityState.FINISHING;
 
         if (mode == FINISH_IMMEDIATELY
-                || (mode == FINISH_AFTER_PAUSE && prevState == ActivityState.PAUSED)
                 || prevState == ActivityState.STOPPED
                 || prevState == ActivityState.INITIALIZING) {
             // If this activity is already stopped, we can just finish
diff --git a/services/core/java/com/android/server/hdmi/HdmiCecLocalDevicePlayback.java b/services/core/java/com/android/server/hdmi/HdmiCecLocalDevicePlayback.java
index 493471b..3c35f5e 100644
--- a/services/core/java/com/android/server/hdmi/HdmiCecLocalDevicePlayback.java
+++ b/services/core/java/com/android/server/hdmi/HdmiCecLocalDevicePlayback.java
@@ -33,6 +33,7 @@
 
 import java.io.UnsupportedEncodingException;
 import java.util.List;
+import java.util.Locale;
 
 /**
  * Represent a logical device of type Playback residing in Android system.
@@ -317,6 +318,13 @@
 
         try {
             String iso3Language = new String(message.getParams(), 0, 3, "US-ASCII");
+            Locale currentLocale = mService.getContext().getResources().getConfiguration().locale;
+            if (currentLocale.getISO3Language().equals(iso3Language)) {
+                // Do not switch language if the new language is the same as the current one.
+                // This helps avoid accidental country variant switching from en_US to en_AU
+                // due to the limitation of CEC. See the warning below.
+                return true;
+            }
 
             // Don't use Locale.getAvailableLocales() since it returns a locale
             // which is not available on Settings.
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index 5e37df3..bfb803d 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -3458,8 +3458,12 @@
             mSettings.writeRuntimePermissionsForUserLPr(userId, false);
         }
 
-        if (READ_EXTERNAL_STORAGE.equals(name)
-                || WRITE_EXTERNAL_STORAGE.equals(name)) {
+        // Only need to do this if user is initialized. Otherwise it's a new user
+        // and there are no processes running as the user yet and there's no need
+        // to make an expensive call to remount processes for the changed permissions.
+        if ((READ_EXTERNAL_STORAGE.equals(name)
+                || WRITE_EXTERNAL_STORAGE.equals(name))
+                && sUserManager.isInitialized(userId)) {
             final long token = Binder.clearCallingIdentity();
             try {
                 final StorageManager storage = mContext.getSystemService(StorageManager.class);
@@ -15965,16 +15969,8 @@
         }
     }
 
-    void newUserCreatedLILPw(final int userHandle) {
-        // We cannot grant the default permissions with a lock held as
-        // we query providers from other components for default handlers
-        // such as enabled IMEs, etc.
-        mHandler.post(new Runnable() {
-            @Override
-            public void run() {
-                mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
-            }
-        });
+    void newUserCreated(final int userHandle) {
+        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
     }
 
     @Override
diff --git a/services/core/java/com/android/server/pm/UserManagerService.java b/services/core/java/com/android/server/pm/UserManagerService.java
index 1a79b4e..23cb767 100644
--- a/services/core/java/com/android/server/pm/UserManagerService.java
+++ b/services/core/java/com/android/server/pm/UserManagerService.java
@@ -1220,6 +1220,7 @@
         final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
         final long ident = Binder.clearCallingIdentity();
         UserInfo userInfo = null;
+        final int userId;
         try {
             synchronized (mInstallLock) {
                 synchronized (mPackagesLock) {
@@ -1240,7 +1241,7 @@
                     if (isGuest && findCurrentGuestUserLocked() != null) {
                         return null;
                     }
-                    int userId = getNextAvailableIdLocked();
+                    userId = getNextAvailableIdLocked();
                     userInfo = new UserInfo(userId, name, null, flags);
                     userInfo.serialNumber = mNextSerialNumber++;
                     long now = System.currentTimeMillis();
@@ -1274,9 +1275,9 @@
                     updateUserIdsLocked();
                     Bundle restrictions = new Bundle();
                     mUserRestrictions.append(userId, restrictions);
-                    mPm.newUserCreatedLILPw(userId);
                 }
             }
+            mPm.newUserCreated(userId);
             if (userInfo != null) {
                 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
                 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
@@ -2015,4 +2016,12 @@
             }
         }
     }
+
+    /**
+     * @param userId
+     * @return whether the user has been initialized yet
+     */
+    boolean isInitialized(int userId) {
+        return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
+    }
 }
diff --git a/services/core/java/com/android/server/wm/WindowAnimator.java b/services/core/java/com/android/server/wm/WindowAnimator.java
index 11eb572..7630178 100644
--- a/services/core/java/com/android/server/wm/WindowAnimator.java
+++ b/services/core/java/com/android/server/wm/WindowAnimator.java
@@ -349,6 +349,7 @@
                                 "Now policy hidden: " + win);
                     } else {
                         boolean applyExistingExitAnimation = mPostKeyguardExitAnimation != null
+                                && !mPostKeyguardExitAnimation.hasEnded()
                                 && !winAnimator.mKeyguardGoingAwayAnimation
                                 && win.hasDrawnLw()
                                 && win.mAttachedWindow == null
@@ -499,8 +500,7 @@
                         mPostKeyguardExitAnimation.getStartOffset(),
                         mPostKeyguardExitAnimation.getDuration());
                 mKeyguardGoingAway = false;
-            } else if (mCurrentTime - mPostKeyguardExitAnimation.getStartTime()
-                    > mPostKeyguardExitAnimation.getDuration()) {
+            } else if (mPostKeyguardExitAnimation.hasEnded()) {
                 // Done with the animation, reset.
                 if (DEBUG_KEYGUARD) Slog.v(TAG, "Done with Keyguard exit animations.");
                 mPostKeyguardExitAnimation = null;
diff --git a/telephony/java/android/telephony/TelephonyManager.java b/telephony/java/android/telephony/TelephonyManager.java
index e74344c..89e9d2e 100644
--- a/telephony/java/android/telephony/TelephonyManager.java
+++ b/telephony/java/android/telephony/TelephonyManager.java
@@ -1339,7 +1339,21 @@
      * @return the NETWORK_TYPE_xxxx for current data connection.
      */
     public int getNetworkType() {
-        return getDataNetworkType();
+       try {
+           ITelephony telephony = getITelephony();
+           if (telephony != null) {
+               return telephony.getNetworkType();
+            } else {
+                // This can happen when the ITelephony interface is not up yet.
+                return NETWORK_TYPE_UNKNOWN;
+            }
+        } catch(RemoteException ex) {
+            // This shouldn't happen in the normal case
+            return NETWORK_TYPE_UNKNOWN;
+        } catch (NullPointerException ex) {
+            // This could happen before phone restarts due to crashing
+            return NETWORK_TYPE_UNKNOWN;
+        }
     }
 
     /**
@@ -1365,6 +1379,10 @@
      * @see #NETWORK_TYPE_LTE
      * @see #NETWORK_TYPE_EHRPD
      * @see #NETWORK_TYPE_HSPAP
+     *
+     * <p>
+     * Requires Permission:
+     *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
      */
     /** {@hide} */
    public int getNetworkType(int subId) {
@@ -1407,6 +1425,9 @@
      * @see #NETWORK_TYPE_EHRPD
      * @see #NETWORK_TYPE_HSPAP
      *
+     * <p>
+     * Requires Permission:
+     *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
      * @hide
      */
     public int getDataNetworkType() {
@@ -1419,6 +1440,10 @@
      * @return the network type
      *
      * @param subId for which network type is returned
+     *
+     * <p>
+     * Requires Permission:
+     *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
      */
     /** {@hide} */
     public int getDataNetworkType(int subId) {
@@ -1442,6 +1467,9 @@
     /**
      * Returns the NETWORK_TYPE_xxxx for voice
      *
+     * <p>
+     * Requires Permission:
+     *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
      * @hide
      */
     public int getVoiceNetworkType() {
@@ -1451,13 +1479,16 @@
     /**
      * Returns the NETWORK_TYPE_xxxx for voice for a subId
      *
+     * <p>
+     * Requires Permission:
+     *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
      */
     /** {@hide} */
     public int getVoiceNetworkType(int subId) {
         try{
             ITelephony telephony = getITelephony();
             if (telephony != null) {
-                return telephony.getVoiceNetworkTypeForSubscriber(subId);
+                return telephony.getVoiceNetworkTypeForSubscriber(subId, getOpPackageName());
             } else {
                 // This can happen when the ITelephony interface is not up yet.
                 return NETWORK_TYPE_UNKNOWN;
@@ -1897,6 +1928,10 @@
      * @return {@link PhoneConstants#LTE_ON_CDMA_UNKNOWN}, {@link PhoneConstants#LTE_ON_CDMA_FALSE}
      * or {@link PhoneConstants#LTE_ON_CDMA_TRUE}
      *
+     * <p>
+     * Requires Permission:
+     *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
+     *
      * @hide
      */
     public int getLteOnCdmaMode() {
@@ -1912,6 +1947,9 @@
      * @return {@link PhoneConstants#LTE_ON_CDMA_UNKNOWN}, {@link PhoneConstants#LTE_ON_CDMA_FALSE}
      * or {@link PhoneConstants#LTE_ON_CDMA_TRUE}
      *
+     * <p>
+     * Requires Permission:
+     *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
      */
     /** {@hide} */
     public int getLteOnCdmaMode(int subId) {
@@ -2642,6 +2680,9 @@
     /**
      * Returns the CDMA ERI icon index to display
      *
+     * <p>
+     * Requires Permission:
+     *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
      * @hide
      */
     public int getCdmaEriIconIndex() {
@@ -2650,6 +2691,9 @@
 
     /**
      * Returns the CDMA ERI icon index to display for a subscription
+     * <p>
+     * Requires Permission:
+     *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
      */
     /** {@hide} */
     public int getCdmaEriIconIndex(int subId) {
@@ -2671,6 +2715,9 @@
      * 0 - ON
      * 1 - FLASHING
      *
+     * <p>
+     * Requires Permission:
+     *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
      * @hide
      */
     public int getCdmaEriIconMode() {
@@ -2681,6 +2728,10 @@
      * Returns the CDMA ERI icon mode for a subscription.
      * 0 - ON
      * 1 - FLASHING
+     *
+     * <p>
+     * Requires Permission:
+     *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
      */
     /** {@hide} */
     public int getCdmaEriIconMode(int subId) {
@@ -2700,6 +2751,9 @@
     /**
      * Returns the CDMA ERI text,
      *
+     * <p>
+     * Requires Permission:
+     *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
      * @hide
      */
     public String getCdmaEriText() {
@@ -2709,6 +2763,9 @@
     /**
      * Returns the CDMA ERI text, of a subscription
      *
+     * <p>
+     * Requires Permission:
+     *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
      */
     /** {@hide} */
     public String getCdmaEriText(int subId) {
diff --git a/telephony/java/com/android/internal/telephony/ITelephony.aidl b/telephony/java/com/android/internal/telephony/ITelephony.aidl
index 6db88a7..a93e465 100644
--- a/telephony/java/com/android/internal/telephony/ITelephony.aidl
+++ b/telephony/java/com/android/internal/telephony/ITelephony.aidl
@@ -455,9 +455,9 @@
 
     /**
      * Returns the network type for data transmission
-     * @param callingPackage package making the call.
+     * Legacy call, permission-free
      */
-    int getNetworkType(String callingPackage);
+    int getNetworkType();
 
     /**
      * Returns the network type of a subId.
@@ -480,16 +480,12 @@
     int getDataNetworkTypeForSubscriber(int subId, String callingPackage);
 
     /**
-      * Returns the network type for voice
-      */
-    int getVoiceNetworkType();
-
-    /**
       * Returns the voice network type of a subId
       * @param subId user preferred subId.
+      * @param callingPackage package making the call.
       * Returns the network type
       */
-    int getVoiceNetworkTypeForSubscriber(int subId);
+    int getVoiceNetworkTypeForSubscriber(int subId, String callingPackage);
 
     /**
      * Return true if an ICC card is present
diff --git a/telephony/java/com/android/internal/telephony/PhoneConstants.java b/telephony/java/com/android/internal/telephony/PhoneConstants.java
index 2a4032c..572cc6f 100644
--- a/telephony/java/com/android/internal/telephony/PhoneConstants.java
+++ b/telephony/java/com/android/internal/telephony/PhoneConstants.java
@@ -133,7 +133,8 @@
     public static final String APN_TYPE_CBS = "cbs";
     /** APN type for IA Initial Attach APN */
     public static final String APN_TYPE_IA = "ia";
-    /** APN type for IA Emergency PDN */
+    /** APN type for Emergency PDN. This is not an IA apn, but is used
+     * for access to carrier services in an emergency call situation. */
     public static final String APN_TYPE_EMERGENCY = "emergency";
 
     public static final int RIL_CARD_MAX_APPS    = 8;