Merge "Eliminating “-1” user serial numbers."
diff --git a/Android.mk b/Android.mk
index b1ca0bc..769a555 100644
--- a/Android.mk
+++ b/Android.mk
@@ -752,6 +752,7 @@
     -since $(SRC_API_DIR)/20.txt 20 \
     -since $(SRC_API_DIR)/21.txt 21 \
     -since $(SRC_API_DIR)/22.txt 22 \
+    -since $(SRC_API_DIR)/23.txt 23 \
 		-werror -hide 111 -hide 113 \
 		-overview $(LOCAL_PATH)/core/java/overview.html
 
@@ -790,7 +791,7 @@
 
 ## SDK version identifiers used in the published docs
   # major[.minor] version for current SDK. (full releases only)
-framework_docs_SDK_VERSION:=5.1
+framework_docs_SDK_VERSION:=6.0
   # release version (ie "Release x")  (full releases only)
 framework_docs_SDK_REL_ID:=1
 
diff --git a/api/current.txt b/api/current.txt
index b034c86..0394d56 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -11276,6 +11276,7 @@
     method public static int blue(int);
     method public static void colorToHSV(int, float[]);
     method public static int green(int);
+    method public static float luminance(int);
     method public static int parseColor(java.lang.String);
     method public static int red(int);
     method public static int rgb(int, int, int);
@@ -12398,9 +12399,17 @@
     ctor public GradientDrawable();
     ctor public GradientDrawable(android.graphics.drawable.GradientDrawable.Orientation, int[]);
     method public void draw(android.graphics.Canvas);
+    method public android.content.res.ColorStateList getColor();
+    method public int[] getColors();
+    method public float[] getCornerRadii();
+    method public float getCornerRadius();
+    method public float getGradientCenterX();
+    method public float getGradientCenterY();
     method public float getGradientRadius();
+    method public int getGradientType();
     method public int getOpacity();
     method public android.graphics.drawable.GradientDrawable.Orientation getOrientation();
+    method public boolean isUseLevel();
     method public void setAlpha(int);
     method public void setColor(int);
     method public void setColor(android.content.res.ColorStateList);
@@ -12534,10 +12543,12 @@
     ctor public deprecated NinePatchDrawable(android.graphics.NinePatch);
     ctor public NinePatchDrawable(android.content.res.Resources, android.graphics.NinePatch);
     method public void draw(android.graphics.Canvas);
+    method public android.graphics.NinePatch getNinePatch();
     method public int getOpacity();
     method public android.graphics.Paint getPaint();
     method public void setAlpha(int);
     method public void setColorFilter(android.graphics.ColorFilter);
+    method public void setNinePatch(android.graphics.NinePatch);
     method public void setTargetDensity(android.graphics.Canvas);
     method public void setTargetDensity(android.util.DisplayMetrics);
     method public void setTargetDensity(int);
@@ -22694,12 +22705,14 @@
 
   public static class Build.VERSION {
     ctor public Build.VERSION();
+    field public static final java.lang.String BASE_OS;
     field public static final java.lang.String CODENAME;
     field public static final java.lang.String INCREMENTAL;
     field public static final int PREVIEW_SDK_INT;
     field public static final java.lang.String RELEASE;
     field public static final deprecated java.lang.String SDK;
     field public static final int SDK_INT;
+    field public static final java.lang.String SECURITY_PATCH;
   }
 
   public static class Build.VERSION_CODES {
@@ -23885,6 +23898,7 @@
     method protected void onClick();
     method protected android.view.View onCreateView(android.view.ViewGroup);
     method public void onDependencyChanged(android.preference.Preference, boolean);
+    method protected void onDetachedFromActivity();
     method protected java.lang.Object onGetDefaultValue(android.content.res.TypedArray, int);
     method public void onParentChanged(android.preference.Preference, boolean);
     method protected void onPrepareForRemoval();
@@ -32483,7 +32497,7 @@
     method public static boolean isDigitsOnly(java.lang.CharSequence);
     method public static boolean isEmpty(java.lang.CharSequence);
     method public static boolean isGraphic(java.lang.CharSequence);
-    method public static boolean isGraphic(char);
+    method public static deprecated boolean isGraphic(char);
     method public static java.lang.String join(java.lang.CharSequence, java.lang.Object[]);
     method public static java.lang.String join(java.lang.CharSequence, java.lang.Iterable);
     method public static int lastIndexOf(java.lang.CharSequence, char);
@@ -33984,6 +33998,7 @@
     field public static final int DENSITY_280 = 280; // 0x118
     field public static final int DENSITY_360 = 360; // 0x168
     field public static final int DENSITY_400 = 400; // 0x190
+    field public static final int DENSITY_420 = 420; // 0x1a4
     field public static final int DENSITY_560 = 560; // 0x230
     field public static final int DENSITY_DEFAULT = 160; // 0xa0
     field public static final int DENSITY_HIGH = 240; // 0xf0
@@ -35172,6 +35187,10 @@
     field public static final int KEYCODE_MEDIA_PREVIOUS = 88; // 0x58
     field public static final int KEYCODE_MEDIA_RECORD = 130; // 0x82
     field public static final int KEYCODE_MEDIA_REWIND = 89; // 0x59
+    field public static final int KEYCODE_MEDIA_SKIP_BACKWARD = 273; // 0x111
+    field public static final int KEYCODE_MEDIA_SKIP_FORWARD = 272; // 0x110
+    field public static final int KEYCODE_MEDIA_STEP_BACKWARD = 275; // 0x113
+    field public static final int KEYCODE_MEDIA_STEP_FORWARD = 274; // 0x112
     field public static final int KEYCODE_MEDIA_STOP = 86; // 0x56
     field public static final int KEYCODE_MEDIA_TOP_MENU = 226; // 0xe2
     field public static final int KEYCODE_MENU = 82; // 0x52
@@ -39711,6 +39730,7 @@
     ctor public AutoCompleteTextView(android.content.Context, android.util.AttributeSet);
     ctor public AutoCompleteTextView(android.content.Context, android.util.AttributeSet, int);
     ctor public AutoCompleteTextView(android.content.Context, android.util.AttributeSet, int, int);
+    ctor public AutoCompleteTextView(android.content.Context, android.util.AttributeSet, int, int, android.content.res.Resources.Theme);
     method public void clearListSelection();
     method protected java.lang.CharSequence convertSelectionToString(java.lang.Object);
     method public void dismissDropDown();
@@ -41432,6 +41452,8 @@
     method public void dispatchDraw(android.graphics.Canvas);
     method public void focusCurrentTab(int);
     method public android.view.View getChildTabViewAt(int);
+    method public android.graphics.drawable.Drawable getLeftStripDrawable();
+    method public android.graphics.drawable.Drawable getRightStripDrawable();
     method public int getTabCount();
     method public boolean isStripEnabled();
     method public void onFocusChange(android.view.View, boolean);
diff --git a/api/system-current.txt b/api/system-current.txt
index c5a4af4..a1aa042 100644
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -11613,6 +11613,7 @@
     method public static int blue(int);
     method public static void colorToHSV(int, float[]);
     method public static int green(int);
+    method public static float luminance(int);
     method public static int parseColor(java.lang.String);
     method public static int red(int);
     method public static int rgb(int, int, int);
@@ -12735,9 +12736,17 @@
     ctor public GradientDrawable();
     ctor public GradientDrawable(android.graphics.drawable.GradientDrawable.Orientation, int[]);
     method public void draw(android.graphics.Canvas);
+    method public android.content.res.ColorStateList getColor();
+    method public int[] getColors();
+    method public float[] getCornerRadii();
+    method public float getCornerRadius();
+    method public float getGradientCenterX();
+    method public float getGradientCenterY();
     method public float getGradientRadius();
+    method public int getGradientType();
     method public int getOpacity();
     method public android.graphics.drawable.GradientDrawable.Orientation getOrientation();
+    method public boolean isUseLevel();
     method public void setAlpha(int);
     method public void setColor(int);
     method public void setColor(android.content.res.ColorStateList);
@@ -12871,10 +12880,12 @@
     ctor public deprecated NinePatchDrawable(android.graphics.NinePatch);
     ctor public NinePatchDrawable(android.content.res.Resources, android.graphics.NinePatch);
     method public void draw(android.graphics.Canvas);
+    method public android.graphics.NinePatch getNinePatch();
     method public int getOpacity();
     method public android.graphics.Paint getPaint();
     method public void setAlpha(int);
     method public void setColorFilter(android.graphics.ColorFilter);
+    method public void setNinePatch(android.graphics.NinePatch);
     method public void setTargetDensity(android.graphics.Canvas);
     method public void setTargetDensity(android.util.DisplayMetrics);
     method public void setTargetDensity(int);
@@ -24638,12 +24649,14 @@
 
   public static class Build.VERSION {
     ctor public Build.VERSION();
+    field public static final java.lang.String BASE_OS;
     field public static final java.lang.String CODENAME;
     field public static final java.lang.String INCREMENTAL;
     field public static final int PREVIEW_SDK_INT;
     field public static final java.lang.String RELEASE;
     field public static final deprecated java.lang.String SDK;
     field public static final int SDK_INT;
+    field public static final java.lang.String SECURITY_PATCH;
   }
 
   public static class Build.VERSION_CODES {
@@ -25841,6 +25854,7 @@
     method protected void onClick();
     method protected android.view.View onCreateView(android.view.ViewGroup);
     method public void onDependencyChanged(android.preference.Preference, boolean);
+    method protected void onDetachedFromActivity();
     method protected java.lang.Object onGetDefaultValue(android.content.res.TypedArray, int);
     method public void onParentChanged(android.preference.Preference, boolean);
     method protected void onPrepareForRemoval();
@@ -33484,6 +33498,7 @@
     field public static final java.lang.String ACTION_CONFIGURE_VOICEMAIL = "android.telephony.action.CONFIGURE_VOICEMAIL";
     field public static final java.lang.String ACTION_PHONE_STATE_CHANGED = "android.intent.action.PHONE_STATE";
     field public static final java.lang.String ACTION_RESPOND_VIA_MESSAGE = "android.intent.action.RESPOND_VIA_MESSAGE";
+    field public static final java.lang.String ACTION_SHOW_VOICEMAIL_NOTIFICATION = "android.telephony.action.SHOW_VOICEMAIL_NOTIFICATION";
     field public static final int CALL_STATE_IDLE = 0; // 0x0
     field public static final int CALL_STATE_OFFHOOK = 2; // 0x2
     field public static final int CALL_STATE_RINGING = 1; // 0x1
@@ -33500,11 +33515,15 @@
     field public static final int DATA_CONNECTING = 1; // 0x1
     field public static final int DATA_DISCONNECTED = 0; // 0x0
     field public static final int DATA_SUSPENDED = 3; // 0x3
+    field public static final java.lang.String EXTRA_CALL_VOICEMAIL_INTENT = "android.telephony.extra.CALL_VOICEMAIL_INTENT";
     field public static final java.lang.String EXTRA_INCOMING_NUMBER = "incoming_number";
+    field public static final java.lang.String EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT = "android.telephony.extra.LAUNCH_VOICEMAIL_SETTINGS_INTENT";
+    field public static final java.lang.String EXTRA_NOTIFICATION_COUNT = "android.telephony.extra.NOTIFICATION_COUNT";
     field public static final java.lang.String EXTRA_STATE = "state";
     field public static final java.lang.String EXTRA_STATE_IDLE;
     field public static final java.lang.String EXTRA_STATE_OFFHOOK;
     field public static final java.lang.String EXTRA_STATE_RINGING;
+    field public static final java.lang.String EXTRA_VOICEMAIL_NUMBER = "android.telephony.extra.VOICEMAIL_NUMBER";
     field public static final int NETWORK_TYPE_1xRTT = 7; // 0x7
     field public static final int NETWORK_TYPE_CDMA = 4; // 0x4
     field public static final int NETWORK_TYPE_EDGE = 2; // 0x2
@@ -34810,7 +34829,7 @@
     method public static boolean isDigitsOnly(java.lang.CharSequence);
     method public static boolean isEmpty(java.lang.CharSequence);
     method public static boolean isGraphic(java.lang.CharSequence);
-    method public static boolean isGraphic(char);
+    method public static deprecated boolean isGraphic(char);
     method public static java.lang.String join(java.lang.CharSequence, java.lang.Object[]);
     method public static java.lang.String join(java.lang.CharSequence, java.lang.Iterable);
     method public static int lastIndexOf(java.lang.CharSequence, char);
@@ -36311,6 +36330,7 @@
     field public static final int DENSITY_280 = 280; // 0x118
     field public static final int DENSITY_360 = 360; // 0x168
     field public static final int DENSITY_400 = 400; // 0x190
+    field public static final int DENSITY_420 = 420; // 0x1a4
     field public static final int DENSITY_560 = 560; // 0x230
     field public static final int DENSITY_DEFAULT = 160; // 0xa0
     field public static final int DENSITY_HIGH = 240; // 0xf0
@@ -37499,6 +37519,10 @@
     field public static final int KEYCODE_MEDIA_PREVIOUS = 88; // 0x58
     field public static final int KEYCODE_MEDIA_RECORD = 130; // 0x82
     field public static final int KEYCODE_MEDIA_REWIND = 89; // 0x59
+    field public static final int KEYCODE_MEDIA_SKIP_BACKWARD = 273; // 0x111
+    field public static final int KEYCODE_MEDIA_SKIP_FORWARD = 272; // 0x110
+    field public static final int KEYCODE_MEDIA_STEP_BACKWARD = 275; // 0x113
+    field public static final int KEYCODE_MEDIA_STEP_FORWARD = 274; // 0x112
     field public static final int KEYCODE_MEDIA_STOP = 86; // 0x56
     field public static final int KEYCODE_MEDIA_TOP_MENU = 226; // 0xe2
     field public static final int KEYCODE_MENU = 82; // 0x52
@@ -42352,6 +42376,7 @@
     ctor public AutoCompleteTextView(android.content.Context, android.util.AttributeSet);
     ctor public AutoCompleteTextView(android.content.Context, android.util.AttributeSet, int);
     ctor public AutoCompleteTextView(android.content.Context, android.util.AttributeSet, int, int);
+    ctor public AutoCompleteTextView(android.content.Context, android.util.AttributeSet, int, int, android.content.res.Resources.Theme);
     method public void clearListSelection();
     method protected java.lang.CharSequence convertSelectionToString(java.lang.Object);
     method public void dismissDropDown();
@@ -44073,6 +44098,8 @@
     method public void dispatchDraw(android.graphics.Canvas);
     method public void focusCurrentTab(int);
     method public android.view.View getChildTabViewAt(int);
+    method public android.graphics.drawable.Drawable getLeftStripDrawable();
+    method public android.graphics.drawable.Drawable getRightStripDrawable();
     method public int getTabCount();
     method public boolean isStripEnabled();
     method public void onFocusChange(android.view.View, boolean);
diff --git a/cmds/pm/src/com/android/commands/pm/Pm.java b/cmds/pm/src/com/android/commands/pm/Pm.java
index 964b776..f66a4c7 100644
--- a/cmds/pm/src/com/android/commands/pm/Pm.java
+++ b/cmds/pm/src/com/android/commands/pm/Pm.java
@@ -19,6 +19,7 @@
 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
+import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
 
 import android.app.ActivityManager;
@@ -844,7 +845,7 @@
         return Integer.toString(result);
     }
 
-    // pm set-app-link [--user USER_ID] PACKAGE {always|ask|never|undefined}
+    // pm set-app-link [--user USER_ID] PACKAGE {always|ask|always-ask|never|undefined}
     private int runSetAppLink() {
         int userId = UserHandle.USER_SYSTEM;
 
@@ -893,6 +894,10 @@
                 newMode = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
                 break;
 
+            case "always-ask":
+                newMode = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
+                break;
+
             case "never":
                 newMode = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
                 break;
diff --git a/core/java/android/animation/AnimatorSet.java b/core/java/android/animation/AnimatorSet.java
index ff7705b..5b88c8e 100644
--- a/core/java/android/animation/AnimatorSet.java
+++ b/core/java/android/animation/AnimatorSet.java
@@ -415,7 +415,8 @@
     public boolean isRunning() {
         int size = mNodes.size();
         for (int i = 0; i < size; i++) {
-            if (mNodes.get(i).mAnimation.isRunning()) {
+            Node node = mNodes.get(i);
+            if (node != mRootNode && node.mAnimation.isRunning()) {
                 return true;
             }
         }
@@ -512,7 +513,9 @@
         int size = mNodes.size();
         for (int i = 0; i < size; i++) {
             Node node = mNodes.get(i);
-            node.mAnimation.setupStartValues();
+            if (node != mRootNode) {
+                node.mAnimation.setupStartValues();
+            }
         }
     }
 
@@ -521,7 +524,9 @@
         int size = mNodes.size();
         for (int i = 0; i < size; i++) {
             Node node = mNodes.get(i);
-            node.mAnimation.setupEndValues();
+            if (node != mRootNode) {
+                node.mAnimation.setupEndValues();
+            }
         }
     }
 
@@ -536,7 +541,9 @@
                 int size = mNodes.size();
                 for (int i = 0; i < size; i++) {
                     Node node = mNodes.get(i);
-                    node.mAnimation.pause();
+                    if (node != mRootNode) {
+                        node.mAnimation.pause();
+                    }
                 }
             }
         }
@@ -553,7 +560,9 @@
                 int size = mNodes.size();
                 for (int i = 0; i < size; i++) {
                     Node node = mNodes.get(i);
-                    node.mAnimation.resume();
+                    if (node != mRootNode) {
+                        node.mAnimation.resume();
+                    }
                 }
             }
         }
diff --git a/core/java/android/app/Activity.java b/core/java/android/app/Activity.java
index 84892a3..07fa52c 100644
--- a/core/java/android/app/Activity.java
+++ b/core/java/android/app/Activity.java
@@ -31,7 +31,7 @@
 import android.transition.TransitionManager;
 import android.util.ArrayMap;
 import android.util.SuperNotCalledException;
-import android.view.Window.WindowStackCallback;
+import android.view.Window.WindowControllerCallback;
 import android.widget.Toolbar;
 
 import com.android.internal.app.IVoiceInteractor;
@@ -60,6 +60,7 @@
 import android.graphics.Bitmap;
 import android.graphics.Canvas;
 import android.graphics.drawable.Drawable;
+import android.graphics.Rect;
 import android.media.AudioManager;
 import android.media.session.MediaController;
 import android.net.Uri;
@@ -673,7 +674,7 @@
         implements LayoutInflater.Factory2,
         Window.Callback, KeyEvent.Callback,
         OnCreateContextMenuListener, ComponentCallbacks2,
-        Window.OnWindowDismissedCallback, WindowStackCallback {
+        Window.OnWindowDismissedCallback, WindowControllerCallback {
     private static final String TAG = "Activity";
     private static final boolean DEBUG_LIFECYCLE = false;
 
@@ -2712,7 +2713,8 @@
     }
 
 
-    /** Called to move the window and its activity/task to a different stack container.
+    /**
+     * Called to move the window and its activity/task to a different stack container.
      * For example, a window can move between
      * {@link android.app.ActivityManager#FULLSCREEN_WORKSPACE_STACK_ID} stack and
      * {@link android.app.ActivityManager#FREEFORM_WORKSPACE_STACK_ID} stack.
@@ -2734,6 +2736,31 @@
     }
 
     /**
+     * Returns the bounds of the task that contains this activity.
+     *
+     * @return Rect The bounds that contains the activity.
+     * @hide
+     */
+    @Override
+    public Rect getActivityBounds() throws RemoteException {
+        return ActivityManagerNative.getDefault().getActivityBounds(mToken);
+    }
+
+    /**
+     * Sets the bounds (size and position) of the task or stack that contains this
+     * activity.
+     * NOTE: The requested bounds might not the fully honored by the system depending
+     * on the window placement policy.
+     *
+     * @param newBounds The new target bounds of the activity in task or stack.
+     * @hide
+     */
+    @Override
+    public void setActivityBounds(Rect newBounds) throws RemoteException {
+        ActivityManagerNative.getDefault().setActivityBounds(mToken, newBounds);
+    }
+
+    /**
      * Called to process key events.  You can override this to intercept all
      * key events before they are dispatched to the window.  Be sure to call
      * this implementation for key events that should be handled normally.
@@ -6211,7 +6238,7 @@
         mFragments.attachHost(null /*parent*/);
 
         mWindow = new PhoneWindow(this);
-        mWindow.setWindowStackCallback(this);
+        mWindow.setWindowControllerCallback(this);
         mWindow.setCallback(this);
         mWindow.setOnWindowDismissedCallback(this);
         mWindow.getLayoutInflater().setPrivateFactory(this);
diff --git a/core/java/android/app/ActivityManagerNative.java b/core/java/android/app/ActivityManagerNative.java
index 10c122a..5f33344 100644
--- a/core/java/android/app/ActivityManagerNative.java
+++ b/core/java/android/app/ActivityManagerNative.java
@@ -752,6 +752,24 @@
             return true;
         }
 
+        case GET_ACTIVITY_BOUNDS_TRANSACTION: {
+            data.enforceInterface(IActivityManager.descriptor);
+            IBinder token = data.readStrongBinder();
+            Rect r = getActivityBounds(token);
+            reply.writeNoException();
+            r.writeToParcel(reply, 0);
+            return true;
+        }
+
+        case SET_ACTIVITY_BOUNDS_TRANSACTION: {
+            data.enforceInterface(IActivityManager.descriptor);
+            IBinder token = data.readStrongBinder();
+            Rect r = Rect.CREATOR.createFromParcel(data);
+            setActivityBounds(token, r);
+            reply.writeNoException();
+            return true;
+        }
+
         case POSITION_TASK_IN_STACK_TRANSACTION: {
             data.enforceInterface(IActivityManager.descriptor);
             int taskId = data.readInt();
@@ -5903,6 +5921,35 @@
     }
 
     @Override
+    public void setActivityBounds(IBinder token, Rect r) throws RemoteException
+    {
+        Parcel data = Parcel.obtain();
+        Parcel reply = Parcel.obtain();
+        data.writeInterfaceToken(IActivityManager.descriptor);
+        data.writeStrongBinder(token);
+        r.writeToParcel(data, 0);
+        mRemote.transact(SET_ACTIVITY_BOUNDS_TRANSACTION, data, reply, 0);
+        reply.readException();
+        data.recycle();
+        reply.recycle();
+    }
+
+    @Override
+    public Rect getActivityBounds(IBinder token) throws RemoteException
+    {
+        Parcel data = Parcel.obtain();
+        Parcel reply = Parcel.obtain();
+        data.writeInterfaceToken(IActivityManager.descriptor);
+        data.writeStrongBinder(token);
+        mRemote.transact(GET_ACTIVITY_BOUNDS_TRANSACTION, data, reply, 0);
+        reply.readException();
+        Rect rect = Rect.CREATOR.createFromParcel(reply);
+        data.recycle();
+        reply.recycle();
+        return rect;
+    }
+
+    @Override
     public Bitmap getTaskDescriptionIcon(String filename) throws RemoteException {
         Parcel data = Parcel.obtain();
         Parcel reply = Parcel.obtain();
diff --git a/core/java/android/app/AlertDialog.java b/core/java/android/app/AlertDialog.java
index abe12dc..7824072 100644
--- a/core/java/android/app/AlertDialog.java
+++ b/core/java/android/app/AlertDialog.java
@@ -1082,7 +1082,8 @@
          * create and display the dialog.
          */
         public AlertDialog create() {
-            final AlertDialog dialog = new AlertDialog(P.mContext);
+            // Context has already been wrapped with the appropriate theme.
+            final AlertDialog dialog = new AlertDialog(P.mContext, 0, false);
             P.apply(dialog.mAlert);
             dialog.setCancelable(P.mCancelable);
             if (P.mCancelable) {
diff --git a/core/java/android/app/ApplicationPackageManager.java b/core/java/android/app/ApplicationPackageManager.java
index 0adce5d..0cd02dd 100644
--- a/core/java/android/app/ApplicationPackageManager.java
+++ b/core/java/android/app/ApplicationPackageManager.java
@@ -74,6 +74,7 @@
 import android.os.UserManager;
 import android.os.storage.StorageManager;
 import android.os.storage.VolumeInfo;
+import android.provider.Settings;
 import android.util.ArrayMap;
 import android.util.Log;
 import android.view.Display;
@@ -1603,14 +1604,17 @@
         final List<VolumeInfo> vols = storage.getVolumes();
         final List<VolumeInfo> candidates = new ArrayList<>();
         for (VolumeInfo vol : vols) {
-            if (Objects.equals(vol, currentVol) || isPackageCandidateVolume(app, vol)) {
+            if (Objects.equals(vol, currentVol) || isPackageCandidateVolume(mContext, app, vol)) {
                 candidates.add(vol);
             }
         }
         return candidates;
     }
 
-    private static boolean isPackageCandidateVolume(ApplicationInfo app, VolumeInfo vol) {
+    private static boolean isPackageCandidateVolume(
+            ContextImpl context, ApplicationInfo app, VolumeInfo vol) {
+        final boolean forceAllowOnExternal = Settings.Global.getInt(
+                context.getContentResolver(), Settings.Global.FORCE_ALLOW_ON_EXTERNAL, 0) != 0;
         // Private internal is always an option
         if (VolumeInfo.ID_PRIVATE_INTERNAL.equals(vol.getId())) {
             return true;
@@ -1618,8 +1622,11 @@
 
         // System apps and apps demanding internal storage can't be moved
         // anywhere else
-        if (app.isSystemApp()
-                || app.installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
+        if (app.isSystemApp()) {
+            return false;
+        }
+        if (!forceAllowOnExternal
+                && app.installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
             return false;
         }
 
diff --git a/core/java/android/app/DialogFragment.java b/core/java/android/app/DialogFragment.java
index 2fb8cc2..9caf752 100644
--- a/core/java/android/app/DialogFragment.java
+++ b/core/java/android/app/DialogFragment.java
@@ -230,6 +230,15 @@
         ft.commit();
     }
 
+    /** {@hide} */
+    public void showAllowingStateLoss(FragmentManager manager, String tag) {
+        mDismissed = false;
+        mShownByMe = true;
+        FragmentTransaction ft = manager.beginTransaction();
+        ft.add(this, tag);
+        ft.commitAllowingStateLoss();
+    }
+
     /**
      * Display the dialog, adding the fragment using an existing transaction
      * and then committing the transaction.
diff --git a/core/java/android/app/IActivityManager.java b/core/java/android/app/IActivityManager.java
index ff1d595..d355219 100644
--- a/core/java/android/app/IActivityManager.java
+++ b/core/java/android/app/IActivityManager.java
@@ -490,6 +490,9 @@
             throws RemoteException;
     public void setTaskResizeable(int taskId, boolean resizeable) throws RemoteException;
     public void resizeTask(int taskId, Rect bounds) throws RemoteException;
+    public void setActivityBounds(IBinder token, Rect bounds) throws RemoteException;
+    public Rect getActivityBounds(IBinder token) throws RemoteException;
+
     public Rect getTaskBounds(int taskId) throws RemoteException;
     public Bitmap getTaskDescriptionIcon(String filename) throws RemoteException;
 
@@ -887,4 +890,6 @@
     int GET_ACTIVITY_STACK_ID_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 343;
     int MOVE_ACTIVITY_TO_STACK_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 344;
     int REPORT_SIZE_CONFIGURATIONS = IBinder.FIRST_CALL_TRANSACTION + 345;
+    int GET_ACTIVITY_BOUNDS_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 346;
+    int SET_ACTIVITY_BOUNDS_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 347;
 }
diff --git a/core/java/android/app/IUiAutomationConnection.aidl b/core/java/android/app/IUiAutomationConnection.aidl
index 474154b..2caec369 100644
--- a/core/java/android/app/IUiAutomationConnection.aidl
+++ b/core/java/android/app/IUiAutomationConnection.aidl
@@ -43,6 +43,8 @@
     void clearWindowAnimationFrameStats();
     WindowAnimationFrameStats getWindowAnimationFrameStats();
     void executeShellCommand(String command, in ParcelFileDescriptor fd);
+    void grantRuntimePermission(String packageName, String permission, int userId);
+    void revokeRuntimePermission(String packageName, String permission, int userId);
 
     // Called from the system process.
     oneway void shutdown();
diff --git a/core/java/android/app/Instrumentation.java b/core/java/android/app/Instrumentation.java
index 69b8b95..dee8d21 100644
--- a/core/java/android/app/Instrumentation.java
+++ b/core/java/android/app/Instrumentation.java
@@ -1809,21 +1809,12 @@
             case ActivityManager.START_NOT_VOICE_COMPATIBLE:
                 throw new SecurityException(
                         "Starting under voice control not allowed for: " + intent);
-            case ActivityManager.START_NOT_CURRENT_USER_ACTIVITY:
-                // Fail silently for this case so we don't break current apps.
-                // TODO(b/22929608): Instead of failing silently or throwing an exception,
-                // we should properly position the activity in the stack (i.e. behind all current
-                // user activity/task) and not change the positioning of stacks.
-                Log.e(TAG,
-                        "Not allowed to start background user activity that shouldn't be displayed"
-                        + " for all users. Failing silently...");
-                break;
             default:
                 throw new AndroidRuntimeException("Unknown error code "
                         + res + " when starting " + intent);
         }
     }
-    
+
     private final void validateNotAppThread() {
         if (Looper.myLooper() == Looper.getMainLooper()) {
             throw new RuntimeException(
diff --git a/core/java/android/app/UiAutomation.java b/core/java/android/app/UiAutomation.java
index a8494fb..efed2e0 100644
--- a/core/java/android/app/UiAutomation.java
+++ b/core/java/android/app/UiAutomation.java
@@ -30,6 +30,7 @@
 import android.os.ParcelFileDescriptor;
 import android.os.RemoteException;
 import android.os.SystemClock;
+import android.os.UserHandle;
 import android.util.Log;
 import android.view.Display;
 import android.view.InputEvent;
@@ -846,6 +847,62 @@
     }
 
     /**
+     * Grants a runtime permission to a package for a user.
+     * @param packageName The package to which to grant.
+     * @param permission The permission to grant.
+     * @return Whether granting succeeded.
+     *
+     * @hide
+     */
+    public boolean grantRuntimePermission(String packageName, String permission,
+            UserHandle userHandle) {
+        synchronized (mLock) {
+            throwIfNotConnectedLocked();
+        }
+        try {
+            if (DEBUG) {
+                Log.i(LOG_TAG, "Granting runtime permission");
+            }
+            // Calling out without a lock held.
+            mUiAutomationConnection.grantRuntimePermission(packageName,
+                    permission, userHandle.getIdentifier());
+            // TODO: The package manager API should return boolean.
+            return true;
+        } catch (RemoteException re) {
+            Log.e(LOG_TAG, "Error granting runtime permission", re);
+        }
+        return false;
+    }
+
+    /**
+     * Revokes a runtime permission from a package for a user.
+     * @param packageName The package from which to revoke.
+     * @param permission The permission to revoke.
+     * @return Whether revoking succeeded.
+     *
+     * @hide
+     */
+    public boolean revokeRuntimePermission(String packageName, String permission,
+            UserHandle userHandle) {
+        synchronized (mLock) {
+            throwIfNotConnectedLocked();
+        }
+        try {
+            if (DEBUG) {
+                Log.i(LOG_TAG, "Revoking runtime permission");
+            }
+            // Calling out without a lock held.
+            mUiAutomationConnection.revokeRuntimePermission(packageName,
+                    permission, userHandle.getIdentifier());
+            // TODO: The package manager API should return boolean.
+            return true;
+        } catch (RemoteException re) {
+            Log.e(LOG_TAG, "Error revoking runtime permission", re);
+        }
+        return false;
+    }
+
+    /**
      * Executes a shell command. This method returs a file descriptor that points
      * to the standard output stream. The command execution is similar to running
      * "adb shell <command>" from a host connected to the device.
diff --git a/core/java/android/app/UiAutomationConnection.java b/core/java/android/app/UiAutomationConnection.java
index 39cd3bc..13e27e2 100644
--- a/core/java/android/app/UiAutomationConnection.java
+++ b/core/java/android/app/UiAutomationConnection.java
@@ -19,6 +19,7 @@
 import android.accessibilityservice.AccessibilityServiceInfo;
 import android.accessibilityservice.IAccessibilityServiceClient;
 import android.content.Context;
+import android.content.pm.IPackageManager;
 import android.graphics.Bitmap;
 import android.hardware.input.InputManager;
 import android.os.Binder;
@@ -60,6 +61,9 @@
     private final IAccessibilityManager mAccessibilityManager = IAccessibilityManager.Stub
             .asInterface(ServiceManager.getService(Service.ACCESSIBILITY_SERVICE));
 
+    private final IPackageManager mPackageManager = IPackageManager.Stub
+            .asInterface(ServiceManager.getService("package"));
+
     private final Object mLock = new Object();
 
     private final Binder mToken = new Binder();
@@ -227,6 +231,38 @@
     }
 
     @Override
+    public void grantRuntimePermission(String packageName, String permission, int userId)
+            throws RemoteException {
+        synchronized (mLock) {
+            throwIfCalledByNotTrustedUidLocked();
+            throwIfShutdownLocked();
+            throwIfNotConnectedLocked();
+        }
+        final long identity = Binder.clearCallingIdentity();
+        try {
+            mPackageManager.grantRuntimePermission(packageName, permission, userId);
+        } finally {
+            Binder.restoreCallingIdentity(identity);
+        }
+    }
+
+    @Override
+    public void revokeRuntimePermission(String packageName, String permission, int userId)
+            throws RemoteException {
+        synchronized (mLock) {
+            throwIfCalledByNotTrustedUidLocked();
+            throwIfShutdownLocked();
+            throwIfNotConnectedLocked();
+        }
+        final long identity = Binder.clearCallingIdentity();
+        try {
+            mPackageManager.revokeRuntimePermission(packageName, permission, userId);
+        } finally {
+            Binder.restoreCallingIdentity(identity);
+        }
+    }
+
+    @Override
     public void executeShellCommand(final String command, final ParcelFileDescriptor sink)
             throws RemoteException {
         synchronized (mLock) {
diff --git a/core/java/android/content/pm/IntentFilterVerificationInfo.java b/core/java/android/content/pm/IntentFilterVerificationInfo.java
index 4dbac05..953b051 100644
--- a/core/java/android/content/pm/IntentFilterVerificationInfo.java
+++ b/core/java/android/content/pm/IntentFilterVerificationInfo.java
@@ -19,6 +19,7 @@
 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
+import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
 
 import android.os.Parcel;
@@ -199,6 +200,10 @@
                 sb.append("never");
                 break;
 
+            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK:
+                sb.append("always-ask");
+                break;
+
             case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
             default:
                 sb.append("undefined");
diff --git a/core/java/android/content/pm/PackageManager.java b/core/java/android/content/pm/PackageManager.java
index 0f936fd..c8e9402 100644
--- a/core/java/android/content/pm/PackageManager.java
+++ b/core/java/android/content/pm/PackageManager.java
@@ -1073,6 +1073,18 @@
     public static final int INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER = 3;
 
     /**
+     * Used as the {@code status} argument for {@link PackageManager#updateIntentVerificationStatus}
+     * to indicate that this app should always be considered as an ambiguous candidate for
+     * handling the matching Intent even if there are other candidate apps in the "always"
+     * state.  Put another way: if there are any 'always ask' apps in a set of more than
+     * one candidate app, then a disambiguation is *always* presented even if there is
+     * another candidate app with the 'always' state.
+     *
+     * @hide
+     */
+    public static final int INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK = 4;
+
+    /**
      * Can be used as the {@code millisecondsToDelay} argument for
      * {@link PackageManager#extendVerificationTimeout}. This is the
      * maximum time {@code PackageManager} waits for the verification
diff --git a/core/java/android/content/res/Resources.java b/core/java/android/content/res/Resources.java
index 5abc645e3..ae92108 100644
--- a/core/java/android/content/res/Resources.java
+++ b/core/java/android/content/res/Resources.java
@@ -1426,10 +1426,12 @@
          *              if not already defined in the theme.
          */
         public void applyStyle(int resId, boolean force) {
-            AssetManager.applyThemeStyle(mTheme, resId, force);
+            synchronized (mKey) {
+                AssetManager.applyThemeStyle(mTheme, resId, force);
 
-            mThemeResId = resId;
-            mKey.append(resId, force);
+                mThemeResId = resId;
+                mKey.append(resId, force);
+            }
         }
 
         /**
@@ -1442,10 +1444,14 @@
          * @param other The existing Theme to copy from.
          */
         public void setTo(Theme other) {
-            AssetManager.copyTheme(mTheme, other.mTheme);
+            synchronized (mKey) {
+                synchronized (other.mKey) {
+                    AssetManager.copyTheme(mTheme, other.mTheme);
 
-            mThemeResId = other.mThemeResId;
-            mKey.setTo(other.getKey());
+                    mThemeResId = other.mThemeResId;
+                    mKey.setTo(other.getKey());
+                }
+            }
         }
 
         /**
@@ -1468,11 +1474,13 @@
          * @see #obtainStyledAttributes(AttributeSet, int[], int, int)
          */
         public TypedArray obtainStyledAttributes(@StyleableRes int[] attrs) {
-            final int len = attrs.length;
-            final TypedArray array = TypedArray.obtain(Resources.this, len);
-            array.mTheme = this;
-            AssetManager.applyStyle(mTheme, 0, 0, 0, attrs, array.mData, array.mIndices);
-            return array;
+            synchronized (mKey) {
+                final int len = attrs.length;
+                final TypedArray array = TypedArray.obtain(Resources.this, len);
+                array.mTheme = this;
+                AssetManager.applyStyle(mTheme, 0, 0, 0, attrs, array.mData, array.mIndices);
+                return array;
+            }
         }
 
         /**
@@ -1482,7 +1490,7 @@
          * <p>Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} when you are done
          * with the array.
          * 
-         * @param resid The desired style resource.
+         * @param resId The desired style resource.
          * @param attrs The desired attributes in the style.
          * 
          * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
@@ -1495,39 +1503,15 @@
          * @see #obtainStyledAttributes(int[])
          * @see #obtainStyledAttributes(AttributeSet, int[], int, int)
          */
-        public TypedArray obtainStyledAttributes(@StyleRes int resid, @StyleableRes int[] attrs)
+        public TypedArray obtainStyledAttributes(@StyleRes int resId, @StyleableRes int[] attrs)
                 throws NotFoundException {
-            final int len = attrs.length;
-            final TypedArray array = TypedArray.obtain(Resources.this, len);
-            array.mTheme = this;
-            if (false) {
-                int[] data = array.mData;
-                
-                System.out.println("**********************************************************");
-                System.out.println("**********************************************************");
-                System.out.println("**********************************************************");
-                System.out.println("Attributes:");
-                String s = "  Attrs:";
-                int i;
-                for (i=0; i<attrs.length; i++) {
-                    s = s + " 0x" + Integer.toHexString(attrs[i]);
-                }
-                System.out.println(s);
-                s = "  Found:";
-                TypedValue value = new TypedValue();
-                for (i=0; i<attrs.length; i++) {
-                    int d = i*AssetManager.STYLE_NUM_ENTRIES;
-                    value.type = data[d+AssetManager.STYLE_TYPE];
-                    value.data = data[d+AssetManager.STYLE_DATA];
-                    value.assetCookie = data[d+AssetManager.STYLE_ASSET_COOKIE];
-                    value.resourceId = data[d+AssetManager.STYLE_RESOURCE_ID];
-                    s = s + " 0x" + Integer.toHexString(attrs[i])
-                        + "=" + value;
-                }
-                System.out.println(s);
+            synchronized (mKey) {
+                final int len = attrs.length;
+                final TypedArray array = TypedArray.obtain(Resources.this, len);
+                array.mTheme = this;
+                AssetManager.applyStyle(mTheme, 0, resId, 0, attrs, array.mData, array.mIndices);
+                return array;
             }
-            AssetManager.applyStyle(mTheme, 0, resid, 0, attrs, array.mData, array.mIndices);
-            return array;
         }
 
         /**
@@ -1580,50 +1564,23 @@
          */
         public TypedArray obtainStyledAttributes(AttributeSet set,
                 @StyleableRes int[] attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) {
-            final int len = attrs.length;
-            final TypedArray array = TypedArray.obtain(Resources.this, len);
+            synchronized (mKey) {
+                final int len = attrs.length;
+                final TypedArray array = TypedArray.obtain(Resources.this, len);
 
-            // XXX note that for now we only work with compiled XML files.
-            // To support generic XML files we will need to manually parse
-            // out the attributes from the XML file (applying type information
-            // contained in the resources and such).
-            final XmlBlock.Parser parser = (XmlBlock.Parser)set;
-            AssetManager.applyStyle(mTheme, defStyleAttr, defStyleRes,
-                    parser != null ? parser.mParseState : 0, attrs, array.mData, array.mIndices);
+                // XXX note that for now we only work with compiled XML files.
+                // To support generic XML files we will need to manually parse
+                // out the attributes from the XML file (applying type information
+                // contained in the resources and such).
+                final XmlBlock.Parser parser = (XmlBlock.Parser) set;
+                AssetManager.applyStyle(mTheme, defStyleAttr, defStyleRes,
+                        parser != null ? parser.mParseState : 0,
+                        attrs, array.mData, array.mIndices);
+                array.mTheme = this;
+                array.mXml = parser;
 
-            array.mTheme = this;
-            array.mXml = parser;
-
-            if (false) {
-                int[] data = array.mData;
-                
-                System.out.println("Attributes:");
-                String s = "  Attrs:";
-                int i;
-                for (i=0; i<set.getAttributeCount(); i++) {
-                    s = s + " " + set.getAttributeName(i);
-                    int id = set.getAttributeNameResource(i);
-                    if (id != 0) {
-                        s = s + "(0x" + Integer.toHexString(id) + ")";
-                    }
-                    s = s + "=" + set.getAttributeValue(i);
-                }
-                System.out.println(s);
-                s = "  Found:";
-                TypedValue value = new TypedValue();
-                for (i=0; i<attrs.length; i++) {
-                    int d = i*AssetManager.STYLE_NUM_ENTRIES;
-                    value.type = data[d+AssetManager.STYLE_TYPE];
-                    value.data = data[d+AssetManager.STYLE_DATA];
-                    value.assetCookie = data[d+AssetManager.STYLE_ASSET_COOKIE];
-                    value.resourceId = data[d+AssetManager.STYLE_RESOURCE_ID];
-                    s = s + " 0x" + Integer.toHexString(attrs[i])
-                        + "=" + value;
-                }
-                System.out.println(s);
+                return array;
             }
-
-            return array;
         }
 
         /**
@@ -1642,18 +1599,20 @@
          */
         @NonNull
         public TypedArray resolveAttributes(@NonNull int[] values, @NonNull int[] attrs) {
-            final int len = attrs.length;
-            if (values == null || len != values.length) {
-                throw new IllegalArgumentException(
-                        "Base attribute values must the same length as attrs");
+            synchronized (mKey) {
+                final int len = attrs.length;
+                if (values == null || len != values.length) {
+                    throw new IllegalArgumentException(
+                            "Base attribute values must the same length as attrs");
+                }
+
+                final TypedArray array = TypedArray.obtain(Resources.this, len);
+                AssetManager.resolveAttrs(mTheme, 0, 0, values, attrs, array.mData, array.mIndices);
+                array.mTheme = this;
+                array.mXml = null;
+
+                return array;
             }
-
-            final TypedArray array = TypedArray.obtain(Resources.this, len);
-            AssetManager.resolveAttrs(mTheme, 0, 0, values, attrs, array.mData, array.mIndices);
-            array.mTheme = this;
-            array.mXml = null;
-
-            return array;
         }
 
         /**
@@ -1674,14 +1633,9 @@
          *         <var>outValue</var> is valid, else false.
          */
         public boolean resolveAttribute(int resid, TypedValue outValue, boolean resolveRefs) {
-            boolean got = mAssets.getThemeValue(mTheme, resid, outValue, resolveRefs);
-            if (false) {
-                System.out.println(
-                    "resolveAttribute #" + Integer.toHexString(resid)
-                    + " got=" + got + ", type=0x" + Integer.toHexString(outValue.type)
-                    + ", data=0x" + Integer.toHexString(outValue.data));
+            synchronized (mKey) {
+                return mAssets.getThemeValue(mTheme, resid, outValue, resolveRefs);
             }
-            return got;
         }
 
         /**
@@ -1727,8 +1681,11 @@
          * @see ActivityInfo
          */
         public int getChangingConfigurations() {
-            final int nativeChangingConfig = AssetManager.getThemeChangingConfigurations(mTheme);
-            return ActivityInfo.activityInfoConfigNativeToJava(nativeChangingConfig);
+            synchronized (mKey) {
+                final int nativeChangingConfig =
+                        AssetManager.getThemeChangingConfigurations(mTheme);
+                return ActivityInfo.activityInfoConfigNativeToJava(nativeChangingConfig);
+            }
         }
 
         /**
@@ -1739,7 +1696,9 @@
          * @param prefix Text to prefix each line printed.
          */
         public void dump(int priority, String tag, String prefix) {
-            AssetManager.dumpTheme(mTheme, priority, tag, prefix);
+            synchronized (mKey) {
+                AssetManager.dumpTheme(mTheme, priority, tag, prefix);
+            }
         }
 
         @Override
@@ -1789,19 +1748,21 @@
          */
         @ViewDebug.ExportedProperty(category = "theme", hasAdjacentMapping = true)
         public String[] getTheme() {
-            final int N = mKey.mCount;
-            final String[] themes = new String[N * 2];
-            for (int i = 0, j = N - 1; i < themes.length; i += 2, --j) {
-                final int resId = mKey.mResId[j];
-                final boolean forced = mKey.mForce[j];
-                try {
-                    themes[i] = getResourceName(resId);
-                } catch (NotFoundException e) {
-                    themes[i] = Integer.toHexString(i);
+            synchronized (mKey) {
+                final int N = mKey.mCount;
+                final String[] themes = new String[N * 2];
+                for (int i = 0, j = N - 1; i < themes.length; i += 2, --j) {
+                    final int resId = mKey.mResId[j];
+                    final boolean forced = mKey.mForce[j];
+                    try {
+                        themes[i] = getResourceName(resId);
+                    } catch (NotFoundException e) {
+                        themes[i] = Integer.toHexString(i);
+                    }
+                    themes[i + 1] = forced ? "forced" : "not forced";
                 }
-                themes[i + 1] = forced ? "forced" : "not forced";
+                return themes;
             }
-            return themes;
         }
 
         /** @hide */
@@ -1822,13 +1783,15 @@
          * @hide
          */
         public void rebase() {
-            AssetManager.clearTheme(mTheme);
+            synchronized (mKey) {
+                AssetManager.clearTheme(mTheme);
 
-            // Reapply the same styles in the same order.
-            for (int i = 0; i < mKey.mCount; i++) {
-                final int resId = mKey.mResId[i];
-                final boolean force = mKey.mForce[i];
-                AssetManager.applyThemeStyle(mTheme, resId, force);
+                // Reapply the same styles in the same order.
+                for (int i = 0; i < mKey.mCount; i++) {
+                    final int resId = mKey.mResId[i];
+                    final boolean force = mKey.mForce[i];
+                    AssetManager.applyThemeStyle(mTheme, resId, force);
+                }
             }
         }
     }
diff --git a/core/java/android/content/res/TypedArray.java b/core/java/android/content/res/TypedArray.java
index 8bcd5d1..cc65e1e 100644
--- a/core/java/android/content/res/TypedArray.java
+++ b/core/java/android/content/res/TypedArray.java
@@ -19,6 +19,7 @@
 import android.annotation.AnyRes;
 import android.annotation.ColorInt;
 import android.annotation.Nullable;
+import android.annotation.StyleableRes;
 import android.graphics.drawable.Drawable;
 import android.os.StrictMode;
 import android.util.AttributeSet;
@@ -144,7 +145,7 @@
      *         coerced to a string.
      * @throws RuntimeException if the TypedArray has already been recycled.
      */
-    public CharSequence getText(int index) {
+    public CharSequence getText(@StyleableRes int index) {
         if (mRecycled) {
             throw new RuntimeException("Cannot make calls to a recycled instance!");
         }
@@ -181,7 +182,7 @@
      * @throws RuntimeException if the TypedArray has already been recycled.
      */
     @Nullable
-    public String getString(int index) {
+    public String getString(@StyleableRes int index) {
         if (mRecycled) {
             throw new RuntimeException("Cannot make calls to a recycled instance!");
         }
@@ -220,7 +221,7 @@
      *         an immediate string value.
      * @throws RuntimeException if the TypedArray has already been recycled.
      */
-    public String getNonResourceString(int index) {
+    public String getNonResourceString(@StyleableRes int index) {
         if (mRecycled) {
             throw new RuntimeException("Cannot make calls to a recycled instance!");
         }
@@ -251,7 +252,7 @@
      * @throws RuntimeException if the TypedArray has already been recycled.
      * @hide
      */
-    public String getNonConfigurationString(int index, int allowedChangingConfigs) {
+    public String getNonConfigurationString(@StyleableRes int index, int allowedChangingConfigs) {
         if (mRecycled) {
             throw new RuntimeException("Cannot make calls to a recycled instance!");
         }
@@ -295,7 +296,7 @@
      *         not defined or could not be coerced to an integer.
      * @throws RuntimeException if the TypedArray has already been recycled.
      */
-    public boolean getBoolean(int index, boolean defValue) {
+    public boolean getBoolean(@StyleableRes int index, boolean defValue) {
         if (mRecycled) {
             throw new RuntimeException("Cannot make calls to a recycled instance!");
         }
@@ -334,7 +335,7 @@
      *         not defined or could not be coerced to an integer.
      * @throws RuntimeException if the TypedArray has already been recycled.
      */
-    public int getInt(int index, int defValue) {
+    public int getInt(@StyleableRes int index, int defValue) {
         if (mRecycled) {
             throw new RuntimeException("Cannot make calls to a recycled instance!");
         }
@@ -371,7 +372,7 @@
      *         not defined or could not be coerced to a float.
      * @throws RuntimeException if the TypedArray has already been recycled.
      */
-    public float getFloat(int index, float defValue) {
+    public float getFloat(@StyleableRes int index, float defValue) {
         if (mRecycled) {
             throw new RuntimeException("Cannot make calls to a recycled instance!");
         }
@@ -420,7 +421,7 @@
      *         not an integer color or color state list.
      */
     @ColorInt
-    public int getColor(int index, @ColorInt int defValue) {
+    public int getColor(@StyleableRes int index, @ColorInt int defValue) {
         if (mRecycled) {
             throw new RuntimeException("Cannot make calls to a recycled instance!");
         }
@@ -471,7 +472,7 @@
      *         not an integer color or color state list.
      */
     @Nullable
-    public ColorStateList getColorStateList(int index) {
+    public ColorStateList getColorStateList(@StyleableRes int index) {
         if (mRecycled) {
             throw new RuntimeException("Cannot make calls to a recycled instance!");
         }
@@ -502,7 +503,7 @@
      * @throws UnsupportedOperationException if the attribute is defined but is
      *         not an integer.
      */
-    public int getInteger(int index, int defValue) {
+    public int getInteger(@StyleableRes int index, int defValue) {
         if (mRecycled) {
             throw new RuntimeException("Cannot make calls to a recycled instance!");
         }
@@ -548,7 +549,7 @@
      * @see #getDimensionPixelOffset
      * @see #getDimensionPixelSize
      */
-    public float getDimension(int index, float defValue) {
+    public float getDimension(@StyleableRes int index, float defValue) {
         if (mRecycled) {
             throw new RuntimeException("Cannot make calls to a recycled instance!");
         }
@@ -595,7 +596,7 @@
      * @see #getDimension
      * @see #getDimensionPixelSize
      */
-    public int getDimensionPixelOffset(int index, int defValue) {
+    public int getDimensionPixelOffset(@StyleableRes int index, int defValue) {
         if (mRecycled) {
             throw new RuntimeException("Cannot make calls to a recycled instance!");
         }
@@ -643,7 +644,7 @@
      * @see #getDimension
      * @see #getDimensionPixelOffset
      */
-    public int getDimensionPixelSize(int index, int defValue) {
+    public int getDimensionPixelSize(@StyleableRes int index, int defValue) {
         if (mRecycled) {
             throw new RuntimeException("Cannot make calls to a recycled instance!");
         }
@@ -685,7 +686,7 @@
      * @throws UnsupportedOperationException if the attribute is defined but is
      *         not a dimension or integer (enum).
      */
-    public int getLayoutDimension(int index, String name) {
+    public int getLayoutDimension(@StyleableRes int index, String name) {
         if (mRecycled) {
             throw new RuntimeException("Cannot make calls to a recycled instance!");
         }
@@ -724,7 +725,7 @@
      *         metric and truncated to integer pixels.
      * @throws RuntimeException if the TypedArray has already been recycled.
      */
-    public int getLayoutDimension(int index, int defValue) {
+    public int getLayoutDimension(@StyleableRes int index, int defValue) {
         if (mRecycled) {
             throw new RuntimeException("Cannot make calls to a recycled instance!");
         }
@@ -761,7 +762,7 @@
      * @throws UnsupportedOperationException if the attribute is defined but is
      *         not a fraction.
      */
-    public float getFraction(int index, int base, int pbase, float defValue) {
+    public float getFraction(@StyleableRes int index, int base, int pbase, float defValue) {
         if (mRecycled) {
             throw new RuntimeException("Cannot make calls to a recycled instance!");
         }
@@ -801,7 +802,7 @@
      * @throws RuntimeException if the TypedArray has already been recycled.
      */
     @AnyRes
-    public int getResourceId(int index, int defValue) {
+    public int getResourceId(@StyleableRes int index, int defValue) {
         if (mRecycled) {
             throw new RuntimeException("Cannot make calls to a recycled instance!");
         }
@@ -829,7 +830,7 @@
      * @throws RuntimeException if the TypedArray has already been recycled.
      * @hide
      */
-    public int getThemeAttributeId(int index, int defValue) {
+    public int getThemeAttributeId(@StyleableRes int index, int defValue) {
         if (mRecycled) {
             throw new RuntimeException("Cannot make calls to a recycled instance!");
         }
@@ -856,7 +857,7 @@
      *         not a color or drawable resource.
      */
     @Nullable
-    public Drawable getDrawable(int index) {
+    public Drawable getDrawable(@StyleableRes int index) {
         if (mRecycled) {
             throw new RuntimeException("Cannot make calls to a recycled instance!");
         }
@@ -887,7 +888,7 @@
      *         defined.
      * @throws RuntimeException if the TypedArray has already been recycled.
      */
-    public CharSequence[] getTextArray(int index) {
+    public CharSequence[] getTextArray(@StyleableRes int index) {
         if (mRecycled) {
             throw new RuntimeException("Cannot make calls to a recycled instance!");
         }
@@ -909,7 +910,7 @@
      * @return {@code true} if the value was retrieved, false otherwise.
      * @throws RuntimeException if the TypedArray has already been recycled.
      */
-    public boolean getValue(int index, TypedValue outValue) {
+    public boolean getValue(@StyleableRes int index, TypedValue outValue) {
         if (mRecycled) {
             throw new RuntimeException("Cannot make calls to a recycled instance!");
         }
@@ -925,7 +926,7 @@
      * @return Attribute type.
      * @throws RuntimeException if the TypedArray has already been recycled.
      */
-    public int getType(int index) {
+    public int getType(@StyleableRes int index) {
         if (mRecycled) {
             throw new RuntimeException("Cannot make calls to a recycled instance!");
         }
@@ -945,7 +946,7 @@
      * @return True if the attribute has a value, false otherwise.
      * @throws RuntimeException if the TypedArray has already been recycled.
      */
-    public boolean hasValue(int index) {
+    public boolean hasValue(@StyleableRes int index) {
         if (mRecycled) {
             throw new RuntimeException("Cannot make calls to a recycled instance!");
         }
@@ -966,7 +967,7 @@
      * @return True if the attribute has a value or is empty, false otherwise.
      * @throws RuntimeException if the TypedArray has already been recycled.
      */
-    public boolean hasValueOrEmpty(int index) {
+    public boolean hasValueOrEmpty(@StyleableRes int index) {
         if (mRecycled) {
             throw new RuntimeException("Cannot make calls to a recycled instance!");
         }
@@ -990,7 +991,7 @@
      *         receive a TypedValue whose type is TYPE_NULL.)
      * @throws RuntimeException if the TypedArray has already been recycled.
      */
-    public TypedValue peekValue(int index) {
+    public TypedValue peekValue(@StyleableRes int index) {
         if (mRecycled) {
             throw new RuntimeException("Cannot make calls to a recycled instance!");
         }
diff --git a/core/java/android/hardware/camera2/params/StreamConfigurationMap.java b/core/java/android/hardware/camera2/params/StreamConfigurationMap.java
index 8e0eab2..e71e49f 100644
--- a/core/java/android/hardware/camera2/params/StreamConfigurationMap.java
+++ b/core/java/android/hardware/camera2/params/StreamConfigurationMap.java
@@ -98,9 +98,19 @@
             HighSpeedVideoConfiguration[] highSpeedVideoConfigurations,
             ReprocessFormatsMap inputOutputFormatsMap,
             boolean listHighResolution) {
-        mConfigurations = checkArrayElementsNotNull(configurations, "configurations");
-        mMinFrameDurations = checkArrayElementsNotNull(minFrameDurations, "minFrameDurations");
-        mStallDurations = checkArrayElementsNotNull(stallDurations, "stallDurations");
+
+        if (configurations == null) {
+            // If no color configurations exist, ensure depth ones do
+            checkArrayElementsNotNull(depthConfigurations, "depthConfigurations");
+            mConfigurations = new StreamConfiguration[0];
+            mMinFrameDurations = new StreamConfigurationDuration[0];
+            mStallDurations = new StreamConfigurationDuration[0];
+        } else {
+            mConfigurations = checkArrayElementsNotNull(configurations, "configurations");
+            mMinFrameDurations = checkArrayElementsNotNull(minFrameDurations, "minFrameDurations");
+            mStallDurations = checkArrayElementsNotNull(stallDurations, "stallDurations");
+        }
+
         mListHighResolution = listHighResolution;
 
         if (depthConfigurations == null) {
@@ -124,7 +134,7 @@
         }
 
         // For each format, track how many sizes there are available to configure
-        for (StreamConfiguration config : configurations) {
+        for (StreamConfiguration config : mConfigurations) {
             int fmt = config.getFormat();
             SparseIntArray map = null;
             if (config.isOutput()) {
@@ -159,7 +169,8 @@
                     mDepthOutputFormats.get(config.getFormat()) + 1);
         }
 
-        if (mOutputFormats.indexOfKey(HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) < 0) {
+        if (configurations != null &&
+                mOutputFormats.indexOfKey(HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) < 0) {
             throw new AssertionError(
                     "At least one stream configuration for IMPLEMENTATION_DEFINED must exist");
         }
diff --git a/core/java/android/os/Build.java b/core/java/android/os/Build.java
index a0162f7..2374899 100644
--- a/core/java/android/os/Build.java
+++ b/core/java/android/os/Build.java
@@ -157,6 +157,17 @@
         public static final String RELEASE = getString("ro.build.version.release");
 
         /**
+         * The base OS build the product is based on.
+         */
+        public static final String BASE_OS = SystemProperties.get("ro.build.version.base_os", "");
+
+        /**
+         * The user-visible security patch level.
+         */
+        public static final String SECURITY_PATCH = SystemProperties.get(
+                "ro.build.version.security_patch", "");
+
+        /**
          * The user-visible SDK version of the framework in its raw String
          * representation; use {@link #SDK_INT} instead.
          *
diff --git a/core/java/android/os/UserHandle.java b/core/java/android/os/UserHandle.java
index dadec51..48ede4f 100644
--- a/core/java/android/os/UserHandle.java
+++ b/core/java/android/os/UserHandle.java
@@ -193,16 +193,16 @@
     }
 
     /**
-     * Returns the app id for a given shared app gid.
+     * Returns the app id for a given shared app gid. Returns -1 if the ID is invalid.
      * @hide
      */
     public static final int getAppIdFromSharedAppGid(int gid) {
-        final int noUserGid = getAppId(gid);
-        if (noUserGid < Process.FIRST_SHARED_APPLICATION_GID ||
-                noUserGid > Process.LAST_SHARED_APPLICATION_GID) {
-            throw new IllegalArgumentException(Integer.toString(gid) + " is not a shared app gid");
+        final int appId = getAppId(gid) + Process.FIRST_APPLICATION_UID
+                - Process.FIRST_SHARED_APPLICATION_GID;
+        if (appId < 0 || appId >= Process.FIRST_SHARED_APPLICATION_GID) {
+            return -1;
         }
-        return (noUserGid + Process.FIRST_APPLICATION_UID) - Process.FIRST_SHARED_APPLICATION_GID;
+        return appId;
     }
 
     /**
diff --git a/core/java/android/preference/Preference.java b/core/java/android/preference/Preference.java
index 3b482eb..5d64af5 100644
--- a/core/java/android/preference/Preference.java
+++ b/core/java/android/preference/Preference.java
@@ -1184,9 +1184,10 @@
     
     /**
      * Called when the Preference hierarchy has been attached to the
-     * {@link PreferenceActivity}. This can also be called when this
-     * Preference has been attached to a group that was already attached
-     * to the {@link PreferenceActivity}.
+     * {@link PreferenceActivity} or {@link PreferenceFragment}. This can
+     * also be called when this Preference has been attached to a group
+     * that was already attached to the {@link PreferenceActivity} or
+     * {@link PreferenceFragment}.
      */
     protected void onAttachedToActivity() {
         // At this point, the hierarchy that this preference is in is connected
@@ -1194,6 +1195,16 @@
         registerDependency();
     }
 
+    /**
+     * Called when the Preference hierarchy has been detached from the
+     * {@link PreferenceActivity} or {@link PreferenceFragment}. This can
+     * also be called when this Preference has been removed from a group
+     * that was already attached to the {@link PreferenceActivity} or
+     * {@link PreferenceFragment}.
+     */
+    protected void onDetachedFromActivity() {
+    }
+
     private void registerDependency() {
         
         if (TextUtils.isEmpty(mDependencyKey)) return;
diff --git a/core/java/android/preference/PreferenceGroup.java b/core/java/android/preference/PreferenceGroup.java
index 5e84086..d6e9e61f 100644
--- a/core/java/android/preference/PreferenceGroup.java
+++ b/core/java/android/preference/PreferenceGroup.java
@@ -187,7 +187,11 @@
     private boolean removePreferenceInt(Preference preference) {
         synchronized(this) {
             preference.onPrepareForRemoval();
-            return mPreferenceList.remove(preference);
+            boolean success = mPreferenceList.remove(preference);
+            if (mAttachedToActivity) {
+                preference.onDetachedFromActivity();
+            }
+            return success;
         }
     }
     
@@ -263,7 +267,7 @@
     protected boolean isOnSameScreenAsChildren() {
         return true;
     }
-    
+
     @Override
     protected void onAttachedToActivity() {
         super.onAttachedToActivity();
@@ -280,11 +284,17 @@
     }
 
     @Override
-    protected void onPrepareForRemoval() {
-        super.onPrepareForRemoval();
-        
+    protected void onDetachedFromActivity() {
+        super.onDetachedFromActivity();
+
         // We won't be attached to the activity anymore
         mAttachedToActivity = false;
+
+        // Dispatch to all contained preferences
+        final int preferenceCount = getPreferenceCount();
+        for (int i = 0; i < preferenceCount; i++) {
+            getPreference(i).onDetachedFromActivity();
+        }
     }
 
     @Override
diff --git a/core/java/android/preference/PreferenceManager.java b/core/java/android/preference/PreferenceManager.java
index 55ee77a..4e4b1c9 100644
--- a/core/java/android/preference/PreferenceManager.java
+++ b/core/java/android/preference/PreferenceManager.java
@@ -396,6 +396,9 @@
      */
     boolean setPreferences(PreferenceScreen preferenceScreen) {
         if (preferenceScreen != mPreferenceScreen) {
+            if (mPreferenceScreen != null) {
+                mPreferenceScreen.onDetachedFromActivity();
+            }
             mPreferenceScreen = preferenceScreen;
             return true;
         }
@@ -704,7 +707,11 @@
      */
     void dispatchActivityDestroy() {
         List<OnActivityDestroyListener> list = null;
-        
+
+        if (mPreferenceScreen != null) {
+            mPreferenceScreen.onDetachedFromActivity();
+            mPreferenceScreen = null;
+        }
         synchronized (this) {
             if (mActivityDestroyListeners != null) {
                 list = new ArrayList<OnActivityDestroyListener>(mActivityDestroyListeners);
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index 9b860515e..d1744b4 100644
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -6260,6 +6260,14 @@
        public static final String MDC_INITIAL_MAX_RETRY = "mdc_initial_max_retry";
 
        /**
+        * Whether any package can be on external storage. When this is true, any
+        * package, regardless of manifest values, is a candidate for installing
+        * or moving onto external storage. (0 = false, 1 = true)
+        * @hide
+        */
+       public static final String FORCE_ALLOW_ON_EXTERNAL = "force_allow_on_external";
+
+       /**
         * Whether user has enabled development settings.
         */
        public static final String DEVELOPMENT_SETTINGS_ENABLED = "development_settings_enabled";
@@ -8101,6 +8109,13 @@
          * @hide
          */
         public static final String CONTACT_METADATA_SYNC = "contact_metadata_sync";
+
+        /**
+         * Whether to enable cellular on boot.
+         * The value 1 - enable, 0 - disable
+         * @hide
+         */
+        public static final String ENABLE_CELLULAR_ON_BOOT = "enable_cellular_on_boot";
     }
 
     /**
diff --git a/core/java/android/text/Html.java b/core/java/android/text/Html.java
index dc1d6f6..3d8ab1e 100644
--- a/core/java/android/text/Html.java
+++ b/core/java/android/text/Html.java
@@ -514,6 +514,12 @@
             startA(mSpannableStringBuilder, attributes);
         } else if (tag.equalsIgnoreCase("u")) {
             start(mSpannableStringBuilder, new Underline());
+        } else if (tag.equalsIgnoreCase("del")) {
+            start(mSpannableStringBuilder, new Strikethrough());
+        } else if (tag.equalsIgnoreCase("s")) {
+            start(mSpannableStringBuilder, new Strikethrough());
+        } else if (tag.equalsIgnoreCase("strike")) {
+            start(mSpannableStringBuilder, new Strikethrough());
         } else if (tag.equalsIgnoreCase("sup")) {
             start(mSpannableStringBuilder, new Super());
         } else if (tag.equalsIgnoreCase("sub")) {
@@ -565,6 +571,12 @@
             endA(mSpannableStringBuilder);
         } else if (tag.equalsIgnoreCase("u")) {
             end(mSpannableStringBuilder, Underline.class, new UnderlineSpan());
+        } else if (tag.equalsIgnoreCase("del")) {
+            end(mSpannableStringBuilder, Strikethrough.class, new StrikethroughSpan());
+        } else if (tag.equalsIgnoreCase("s")) {
+            end(mSpannableStringBuilder, Strikethrough.class, new StrikethroughSpan());
+        } else if (tag.equalsIgnoreCase("strike")) {
+            end(mSpannableStringBuilder, Strikethrough.class, new StrikethroughSpan());
         } else if (tag.equalsIgnoreCase("sup")) {
             end(mSpannableStringBuilder, Super.class, new SuperscriptSpan());
         } else if (tag.equalsIgnoreCase("sub")) {
@@ -822,6 +834,7 @@
     private static class Bold { }
     private static class Italic { }
     private static class Underline { }
+    private static class Strikethrough { }
     private static class Big { }
     private static class Small { }
     private static class Monospace { }
diff --git a/core/java/android/text/SpannableStringBuilder.java b/core/java/android/text/SpannableStringBuilder.java
index 992dc4d..40315ad 100644
--- a/core/java/android/text/SpannableStringBuilder.java
+++ b/core/java/android/text/SpannableStringBuilder.java
@@ -16,6 +16,7 @@
 
 package android.text;
 
+import android.annotation.Nullable;
 import android.graphics.Canvas;
 import android.graphics.Paint;
 import android.util.Log;
@@ -814,8 +815,9 @@
      * a list of all the spans regardless of type.
      */
     @SuppressWarnings("unchecked")
-    public <T> T[] getSpans(int queryStart, int queryEnd, Class<T> kind) {
-        if (kind == null || mSpanCount == 0) return ArrayUtils.emptyArray(kind);
+    public <T> T[] getSpans(int queryStart, int queryEnd, @Nullable Class<T> kind) {
+        if (kind == null) return (T[]) ArrayUtils.emptyArray(Object.class);
+        if (mSpanCount == 0) return ArrayUtils.emptyArray(kind);
         int count = countSpans(queryStart, queryEnd, kind, treeRoot());
         if (count == 0) {
             return ArrayUtils.emptyArray(kind);
diff --git a/core/java/android/text/TextUtils.java b/core/java/android/text/TextUtils.java
index ae2c0c7..4d8a7d0 100644
--- a/core/java/android/text/TextUtils.java
+++ b/core/java/android/text/TextUtils.java
@@ -1430,8 +1430,9 @@
      */
     public static boolean isGraphic(CharSequence str) {
         final int len = str.length();
-        for (int i=0; i<len; i++) {
-            int gc = Character.getType(str.charAt(i));
+        for (int cp, i=0; i<len; i+=Character.charCount(cp)) {
+            cp = Character.codePointAt(str, i);
+            int gc = Character.getType(cp);
             if (gc != Character.CONTROL
                     && gc != Character.FORMAT
                     && gc != Character.SURROGATE
@@ -1447,7 +1448,12 @@
 
     /**
      * Returns whether this character is a printable character.
+     *
+     * This does not support non-BMP characters and should not be used.
+     *
+     * @deprecated Use {@link #isGraphic(CharSequence)} instead.
      */
+    @Deprecated
     public static boolean isGraphic(char c) {
         int gc = Character.getType(c);
         return     gc != Character.CONTROL
diff --git a/core/java/android/text/format/Formatter.java b/core/java/android/text/format/Formatter.java
index b5068b2..a53da09 100644
--- a/core/java/android/text/format/Formatter.java
+++ b/core/java/android/text/format/Formatter.java
@@ -131,7 +131,10 @@
         // floating point errors.
         final int roundFactor;
         final String roundFormat;
-        if (result < 1) {
+        if (mult == 1 || result >= 100) {
+            roundFactor = 1;
+            roundFormat = "%.0f";
+        } else if (result < 1) {
             roundFactor = 100;
             roundFormat = "%.2f";
         } else if (result < 10) {
@@ -142,7 +145,7 @@
                 roundFactor = 100;
                 roundFormat = "%.2f";
             }
-        } else if (result < 100) {
+        } else { // 10 <= result < 100
             if ((flags & FLAG_SHORTER) != 0) {
                 roundFactor = 1;
                 roundFormat = "%.0f";
@@ -150,9 +153,6 @@
                 roundFactor = 100;
                 roundFormat = "%.2f";
             }
-        } else {
-            roundFactor = 1;
-            roundFormat = "%.0f";
         }
         final String roundedString = String.format(roundFormat, result);
 
diff --git a/core/java/android/util/DisplayMetrics.java b/core/java/android/util/DisplayMetrics.java
index a36e66c..9a69600 100644
--- a/core/java/android/util/DisplayMetrics.java
+++ b/core/java/android/util/DisplayMetrics.java
@@ -90,6 +90,14 @@
     public static final int DENSITY_400 = 400;
 
     /**
+     * Intermediate density for screens that sit somewhere between
+     * {@link #DENSITY_XHIGH} (320 dpi) and {@link #DENSITY_XXHIGH} (480 dpi).
+     * This is not a density that applications should target, instead relying
+     * on the system to scale their {@link #DENSITY_XXHIGH} assets for them.
+     */
+    public static final int DENSITY_420 = 420;
+
+    /**
      * Standard quantized DPI for extra-extra-high-density screens.
      */
     public static final int DENSITY_XXHIGH = 480;
diff --git a/core/java/android/view/KeyEvent.java b/core/java/android/view/KeyEvent.java
index e77daa6..6d89824 100644
--- a/core/java/android/view/KeyEvent.java
+++ b/core/java/android/view/KeyEvent.java
@@ -747,18 +747,18 @@
     public static final int KEYCODE_TV_TIMER_PROGRAMMING = 258;
     /** Key code constant: Help key. */
     public static final int KEYCODE_HELP = 259;
-    /** Key code constant: Navigate to previous key. 
+    /** Key code constant: Navigate to previous key.
      * Goes backward by one item in an ordered collection of items. */
     public static final int KEYCODE_NAVIGATE_PREVIOUS = 260;
-    /** Key code constant: Navigate to next key. 
+    /** Key code constant: Navigate to next key.
      * Advances to the next item in an ordered collection of items. */
     public static final int KEYCODE_NAVIGATE_NEXT   = 261;
     /** Key code constant: Navigate in key.
-     * Activates the item that currently has focus or expands to the next level of a navigation 
+     * Activates the item that currently has focus or expands to the next level of a navigation
      * hierarchy. */
     public static final int KEYCODE_NAVIGATE_IN     = 262;
     /** Key code constant: Navigate out key.
-     * Backs out one level of a navigation hierarchy or collapses the item that currently has 
+     * Backs out one level of a navigation hierarchy or collapses the item that currently has
      * focus. */
     public static final int KEYCODE_NAVIGATE_OUT    = 263;
     /** Key code constant: Primary stem key for Wear
@@ -778,8 +778,18 @@
     public static final int KEYCODE_DPAD_UP_RIGHT   = 270;
     /** Key code constant: Directional Pad Down-Right */
     public static final int KEYCODE_DPAD_DOWN_RIGHT = 271;
+    /** Key code constant: Skip forward media key. */
+    public static final int KEYCODE_MEDIA_SKIP_FORWARD = 272;
+    /** Key code constant: Skip backward media key. */
+    public static final int KEYCODE_MEDIA_SKIP_BACKWARD = 273;
+    /** Key code constant: Step forward media key.
+     * Steps media forward, one frame at a time. */
+    public static final int KEYCODE_MEDIA_STEP_FORWARD = 274;
+    /** Key code constant: Step backward media key.
+     * Steps media backward, one frame at a time. */
+    public static final int KEYCODE_MEDIA_STEP_BACKWARD = 275;
 
-    private static final int LAST_KEYCODE = KEYCODE_DPAD_DOWN_RIGHT;
+    private static final int LAST_KEYCODE = KEYCODE_MEDIA_STEP_BACKWARD;
 
     // NOTE: If you add a new keycode here you must also add it to:
     //  isSystem()
diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java
index 17a9741..a492518 100644
--- a/core/java/android/view/View.java
+++ b/core/java/android/view/View.java
@@ -4437,7 +4437,8 @@
         private final View mHostView;
         private final String mMethodName;
 
-        private Method mMethod;
+        private Method mResolvedMethod;
+        private Context mResolvedContext;
 
         public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) {
             mHostView = hostView;
@@ -4446,12 +4447,12 @@
 
         @Override
         public void onClick(@NonNull View v) {
-            if (mMethod == null) {
-                mMethod = resolveMethod(mHostView.getContext(), mMethodName);
+            if (mResolvedMethod == null) {
+                resolveMethod(mHostView.getContext(), mMethodName);
             }
 
             try {
-                mMethod.invoke(mHostView.getContext(), v);
+                mResolvedMethod.invoke(mResolvedContext, v);
             } catch (IllegalAccessException e) {
                 throw new IllegalStateException(
                         "Could not execute non-public method for android:onClick", e);
@@ -4462,11 +4463,16 @@
         }
 
         @NonNull
-        private Method resolveMethod(@Nullable Context context, @NonNull String name) {
+        private void resolveMethod(@Nullable Context context, @NonNull String name) {
             while (context != null) {
                 try {
                     if (!context.isRestricted()) {
-                        return context.getClass().getMethod(mMethodName, View.class);
+                        final Method method = context.getClass().getMethod(mMethodName, View.class);
+                        if (method != null) {
+                            mResolvedMethod = method;
+                            mResolvedContext = context;
+                            return;
+                        }
                     }
                 } catch (NoSuchMethodException e) {
                     // Failed to find method, keep searching up the hierarchy.
diff --git a/core/java/android/view/Window.java b/core/java/android/view/Window.java
index eecda89..1a9fb34 100644
--- a/core/java/android/view/Window.java
+++ b/core/java/android/view/Window.java
@@ -28,8 +28,9 @@
 import android.content.res.Configuration;
 import android.content.res.Resources;
 import android.content.res.TypedArray;
-import android.graphics.PixelFormat;
 import android.graphics.drawable.Drawable;
+import android.graphics.PixelFormat;
+import android.graphics.Rect;
 import android.media.session.MediaController;
 import android.net.Uri;
 import android.os.Bundle;
@@ -183,7 +184,7 @@
     private TypedArray mWindowStyle;
     private Callback mCallback;
     private OnWindowDismissedCallback mOnWindowDismissedCallback;
-    private WindowStackCallback mWindowStackCallback;
+    private WindowControllerCallback mWindowControllerCallback;
     private WindowManager mWindowManager;
     private IBinder mAppToken;
     private String mAppName;
@@ -479,8 +480,9 @@
     }
 
     /** @hide */
-    public interface WindowStackCallback {
-        /** Called to move the window and its activity/task to a different stack container.
+    public interface WindowControllerCallback {
+        /**
+         * Called to move the window and its activity/task to a different stack container.
          * For example, a window can move between
          * {@link android.app.ActivityManager#FULLSCREEN_WORKSPACE_STACK_ID} stack and
          * {@link android.app.ActivityManager#FREEFORM_WORKSPACE_STACK_ID} stack.
@@ -491,6 +493,23 @@
 
         /** Returns the current stack Id for the window. */
         int getWindowStackId() throws RemoteException;
+
+        /**
+         * Returns the bounds of the task that contains this activity.
+         *
+         * @return Rect The bounds that contains the activity.
+         */
+        Rect getActivityBounds() throws RemoteException;
+
+        /**
+         * Sets the bounds (size and position) of the task or stack that contains this
+         * activity.
+         * NOTE: The requested bounds might not the fully honored by the system depending
+         * on the window placement policy.
+         *
+         * @param newBounds The new target bounds of the activity in task or stack.
+         */
+        void setActivityBounds(Rect newBounds) throws RemoteException;
     }
 
     public Window(Context context) {
@@ -682,13 +701,13 @@
     }
 
     /** @hide */
-    public final void setWindowStackCallback(WindowStackCallback wscb) {
-        mWindowStackCallback = wscb;
+    public final void setWindowControllerCallback(WindowControllerCallback wccb) {
+        mWindowControllerCallback = wccb;
     }
 
     /** @hide */
-    public final WindowStackCallback getWindowStackCallback() {
-        return mWindowStackCallback;
+    public final WindowControllerCallback getWindowControllerCallback() {
+        return mWindowControllerCallback;
     }
 
     /**
diff --git a/core/java/android/view/inputmethod/InputMethodManager.java b/core/java/android/view/inputmethod/InputMethodManager.java
index 1c8a79b..ee06806 100644
--- a/core/java/android/view/inputmethod/InputMethodManager.java
+++ b/core/java/android/view/inputmethod/InputMethodManager.java
@@ -26,7 +26,6 @@
 
 import android.annotation.RequiresPermission;
 import android.content.Context;
-import android.graphics.Matrix;
 import android.graphics.Rect;
 import android.os.Bundle;
 import android.os.Handler;
@@ -377,8 +376,8 @@
      */
     private int mRequestUpdateCursorAnchorInfoMonitorMode = REQUEST_UPDATE_CURSOR_ANCHOR_INFO_NONE;
 
-    final Pool<PendingEvent> mPendingEventPool = new SimplePool<PendingEvent>(20);
-    final SparseArray<PendingEvent> mPendingEvents = new SparseArray<PendingEvent>(20);
+    final Pool<PendingEvent> mPendingEventPool = new SimplePool<>(20);
+    final SparseArray<PendingEvent> mPendingEvents = new SparseArray<>(20);
 
     // -----------------------------------------------------------
     
@@ -2033,8 +2032,7 @@
      */
     public Map<InputMethodInfo, List<InputMethodSubtype>> getShortcutInputMethodsAndSubtypes() {
         synchronized (mH) {
-            HashMap<InputMethodInfo, List<InputMethodSubtype>> ret =
-                    new HashMap<InputMethodInfo, List<InputMethodSubtype>>();
+            HashMap<InputMethodInfo, List<InputMethodSubtype>> ret = new HashMap<>();
             try {
                 // TODO: We should change the return type from List<Object> to List<Parcelable>
                 List<Object> info = mService.getShortcutInputMethodsAndSubtypes();
@@ -2049,7 +2047,7 @@
                                 Log.e(TAG, "IMI list already contains the same InputMethod.");
                                 break;
                             }
-                            subtypes = new ArrayList<InputMethodSubtype>();
+                            subtypes = new ArrayList<>();
                             ret.put((InputMethodInfo)o, subtypes);
                         } else if (subtypes != null && o instanceof InputMethodSubtype) {
                             subtypes.add((InputMethodSubtype)o);
diff --git a/core/java/android/widget/AutoCompleteTextView.java b/core/java/android/widget/AutoCompleteTextView.java
index 01767d5..7d57cb8 100644
--- a/core/java/android/widget/AutoCompleteTextView.java
+++ b/core/java/android/widget/AutoCompleteTextView.java
@@ -18,6 +18,7 @@
 
 import android.annotation.DrawableRes;
 import android.content.Context;
+import android.content.res.Resources.Theme;
 import android.content.res.TypedArray;
 import android.database.DataSetObserver;
 import android.graphics.Rect;
@@ -28,10 +29,12 @@
 import android.text.TextWatcher;
 import android.util.AttributeSet;
 import android.util.Log;
+import android.view.ContextThemeWrapper;
 import android.view.KeyEvent;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
+import android.view.ViewGroup.LayoutParams;
 import android.view.WindowManager;
 import android.view.inputmethod.CompletionInfo;
 import android.view.inputmethod.EditorInfo;
@@ -94,6 +97,12 @@
 
     static final int EXPAND_MAX = 3;
 
+    /** Context used to inflate the popup window or dialog. */
+    private final Context mPopupContext;
+
+    private final ListPopupWindow mPopup;
+    private final PassThroughClickListener mPassThroughClickListener;
+
     private CharSequence mHintText;
     private TextView mHintView;
     private int mHintResource;
@@ -102,7 +111,6 @@
     private Filter mFilter;
     private int mThreshold;
 
-    private ListPopupWindow mPopup;
     private int mDropDownAnchorId;
 
     private AdapterView.OnItemClickListener mItemClickListener;
@@ -122,71 +130,172 @@
     // Set to false when the list is hidden to prevent asynchronous updates to popup the list again.
     private boolean mPopupCanBeUpdated = true;
 
-    private PassThroughClickListener mPassThroughClickListener;
     private PopupDataSetObserver mObserver;
 
+    /**
+     * Constructs a new auto-complete text view with the given context's theme.
+     *
+     * @param context The Context the view is running in, through which it can
+     *                access the current theme, resources, etc.
+     */
     public AutoCompleteTextView(Context context) {
         this(context, null);
     }
 
+    /**
+     * Constructs a new auto-complete text view with the given context's theme
+     * and the supplied attribute set.
+     *
+     * @param context The Context the view is running in, through which it can
+     *                access the current theme, resources, etc.
+     * @param attrs The attributes of the XML tag that is inflating the view.
+     */
     public AutoCompleteTextView(Context context, AttributeSet attrs) {
         this(context, attrs, R.attr.autoCompleteTextViewStyle);
     }
 
+    /**
+     * Constructs a new auto-complete text view with the given context's theme,
+     * the supplied attribute set, and default style attribute.
+     *
+     * @param context The Context the view is running in, through which it can
+     *                access the current theme, resources, etc.
+     * @param attrs The attributes of the XML tag that is inflating the view.
+     * @param defStyleAttr An attribute in the current theme that contains a
+     *                     reference to a style resource that supplies default
+     *                     values for the view. Can be 0 to not look for
+     *                     defaults.
+     */
     public AutoCompleteTextView(Context context, AttributeSet attrs, int defStyleAttr) {
         this(context, attrs, defStyleAttr, 0);
     }
 
+    /**
+     * Constructs a new auto-complete text view with the given context's theme,
+     * the supplied attribute set, and default styles.
+     *
+     * @param context The Context the view is running in, through which it can
+     *                access the current theme, resources, etc.
+     * @param attrs The attributes of the XML tag that is inflating the view.
+     * @param defStyleAttr An attribute in the current theme that contains a
+     *                     reference to a style resource that supplies default
+     *                     values for the view. Can be 0 to not look for
+     *                     defaults.
+     * @param defStyleRes A resource identifier of a style resource that
+     *                    supplies default values for the view, used only if
+     *                    defStyleAttr is 0 or can not be found in the theme.
+     *                    Can be 0 to not look for defaults.
+     */
     public AutoCompleteTextView(
             Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
-        super(context, attrs, defStyleAttr, defStyleRes);
+        this(context, attrs, defStyleAttr, defStyleRes, null);
+    }
 
-        mPopup = new ListPopupWindow(context, attrs, defStyleAttr, defStyleRes);
-        mPopup.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
-        mPopup.setPromptPosition(ListPopupWindow.POSITION_PROMPT_BELOW);
+    /**
+     * Constructs a new auto-complete text view with the given context, the
+     * supplied attribute set, default styles, and the theme against which the
+     * completion popup should be inflated.
+     *
+     * @param context The context against which the view is inflated, which
+     *                provides access to the current theme, resources, etc.
+     * @param attrs The attributes of the XML tag that is inflating the view.
+     * @param defStyleAttr An attribute in the current theme that contains a
+     *                     reference to a style resource that supplies default
+     *                     values for the view. Can be 0 to not look for
+     *                     defaults.
+     * @param defStyleRes A resource identifier of a style resource that
+     *                    supplies default values for the view, used only if
+     *                    defStyleAttr is 0 or can not be found in the theme.
+     *                    Can be 0 to not look for defaults.
+     * @param popupTheme The theme against which the completion popup window
+     *                   should be inflated. May be {@code null} to use the
+     *                   view theme. If set, this will override any value
+     *                   specified by
+     *                   {@link android.R.styleable#AutoCompleteTextView_popupTheme}.
+     */
+    public AutoCompleteTextView(Context context, AttributeSet attrs, int defStyleAttr,
+            int defStyleRes, Theme popupTheme) {
+        super(context, attrs, defStyleAttr, defStyleRes);
 
         final TypedArray a = context.obtainStyledAttributes(
                 attrs, R.styleable.AutoCompleteTextView, defStyleAttr, defStyleRes);
 
+        if (popupTheme != null) {
+            mPopupContext = new ContextThemeWrapper(context, popupTheme);
+        } else {
+            final int popupThemeResId = a.getResourceId(
+                    R.styleable.AutoCompleteTextView_popupTheme, 0);
+            if (popupThemeResId != 0) {
+                mPopupContext = new ContextThemeWrapper(context, popupThemeResId);
+            } else {
+                mPopupContext = context;
+            }
+        }
+
+        // Load attributes used within the popup against the popup context.
+        final TypedArray pa;
+        if (mPopupContext != context) {
+            pa = mPopupContext.obtainStyledAttributes(
+                    attrs, R.styleable.AutoCompleteTextView, defStyleAttr, defStyleRes);
+        } else {
+            pa = a;
+        }
+
+        final Drawable popupListSelector = pa.getDrawable(
+                R.styleable.AutoCompleteTextView_dropDownSelector);
+        final int popupWidth = pa.getLayoutDimension(
+                R.styleable.AutoCompleteTextView_dropDownWidth, LayoutParams.WRAP_CONTENT);
+        final int popupHeight = pa.getLayoutDimension(
+                R.styleable.AutoCompleteTextView_dropDownHeight, LayoutParams.WRAP_CONTENT);
+        final int popupHintLayoutResId = pa.getResourceId(
+                R.styleable.AutoCompleteTextView_completionHintView, R.layout.simple_dropdown_hint);
+        final CharSequence popupHintText = pa.getText(
+                R.styleable.AutoCompleteTextView_completionHint);
+
+        if (pa != a) {
+            pa.recycle();
+        }
+
+        mPopup = new ListPopupWindow(mPopupContext, attrs, defStyleAttr, defStyleRes);
+        mPopup.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
+        mPopup.setPromptPosition(ListPopupWindow.POSITION_PROMPT_BELOW);
+        mPopup.setListSelector(popupListSelector);
+        mPopup.setOnItemClickListener(new DropDownItemClickListener());
+
+        // For dropdown width, the developer can specify a specific width, or
+        // MATCH_PARENT (for full screen width), or WRAP_CONTENT (to match the
+        // width of the anchored view).
+        mPopup.setWidth(popupWidth);
+        mPopup.setHeight(popupHeight);
+
+        // Completion hint must be set after specifying hint layout.
+        mHintResource = popupHintLayoutResId;
+        setCompletionHint(popupHintText);
+
+        // Get the anchor's id now, but the view won't be ready, so wait to
+        // actually get the view and store it in mDropDownAnchorView lazily in
+        // getDropDownAnchorView later. Defaults to NO_ID, in which case the
+        // getDropDownAnchorView method will simply return this TextView, as a
+        // default anchoring point.
+        mDropDownAnchorId = a.getResourceId(
+                R.styleable.AutoCompleteTextView_dropDownAnchor, View.NO_ID);
+
         mThreshold = a.getInt(R.styleable.AutoCompleteTextView_completionThreshold, 2);
 
-        mPopup.setListSelector(a.getDrawable(R.styleable.AutoCompleteTextView_dropDownSelector));
-
-        // Get the anchor's id now, but the view won't be ready, so wait to actually get the
-        // view and store it in mDropDownAnchorView lazily in getDropDownAnchorView later.
-        // Defaults to NO_ID, in which case the getDropDownAnchorView method will simply return
-        // this TextView, as a default anchoring point.
-        mDropDownAnchorId = a.getResourceId(R.styleable.AutoCompleteTextView_dropDownAnchor,
-                View.NO_ID);
-        
-        // For dropdown width, the developer can specify a specific width, or MATCH_PARENT
-        // (for full screen width) or WRAP_CONTENT (to match the width of the anchored view).
-        mPopup.setWidth(a.getLayoutDimension(R.styleable.AutoCompleteTextView_dropDownWidth,
-                ViewGroup.LayoutParams.WRAP_CONTENT));
-        mPopup.setHeight(a.getLayoutDimension(R.styleable.AutoCompleteTextView_dropDownHeight,
-                ViewGroup.LayoutParams.WRAP_CONTENT));
-
-        mHintResource = a.getResourceId(R.styleable.AutoCompleteTextView_completionHintView,
-                R.layout.simple_dropdown_hint);
-        
-        mPopup.setOnItemClickListener(new DropDownItemClickListener());
-        setCompletionHint(a.getText(R.styleable.AutoCompleteTextView_completionHint));
+        a.recycle();
 
         // Always turn on the auto complete input type flag, since it
         // makes no sense to use this widget without it.
         int inputType = getInputType();
-        if ((inputType&EditorInfo.TYPE_MASK_CLASS)
-                == EditorInfo.TYPE_CLASS_TEXT) {
+        if ((inputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) {
             inputType |= EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE;
             setRawInputType(inputType);
         }
 
-        a.recycle();
-
         setFocusable(true);
 
         addTextChangedListener(new MyWatcher());
-        
+
         mPassThroughClickListener = new PassThroughClickListener();
         super.setOnClickListener(mPassThroughClickListener);
     }
@@ -222,8 +331,8 @@
         mHintText = hint;
         if (hint != null) {
             if (mHintView == null) {
-                final TextView hintView = (TextView) LayoutInflater.from(getContext()).inflate(
-                        mHintResource, null).findViewById(com.android.internal.R.id.text1);
+                final TextView hintView = (TextView) LayoutInflater.from(mPopupContext).inflate(
+                        mHintResource, null).findViewById(R.id.text1);
                 hintView.setText(mHintText);
                 mHintView = hintView;
                 mPopup.setPromptView(hintView);
diff --git a/core/java/android/widget/CheckedTextView.java b/core/java/android/widget/CheckedTextView.java
index 6b4b2c7..c1d2756 100644
--- a/core/java/android/widget/CheckedTextView.java
+++ b/core/java/android/widget/CheckedTextView.java
@@ -152,13 +152,8 @@
             return;
         }
 
-        mCheckMarkResource = resId;
-
-        Drawable d = null;
-        if (mCheckMarkResource != 0) {
-            d = getContext().getDrawable(mCheckMarkResource);
-        }
-        setCheckMarkDrawable(d);
+        final Drawable d = resId != 0 ? getContext().getDrawable(resId) : null;
+        setCheckMarkDrawableInternal(d, resId);
     }
 
     /**
@@ -172,12 +167,18 @@
      * @see #setCheckMarkDrawable(int)
      * @see #getCheckMarkDrawable()
      */
-    public void setCheckMarkDrawable(Drawable d) {
+    public void setCheckMarkDrawable(@Nullable Drawable d) {
+        setCheckMarkDrawableInternal(d, 0);
+    }
+
+    private void setCheckMarkDrawableInternal(@Nullable Drawable d, @DrawableRes int resId) {
         if (mCheckMarkDrawable != null) {
             mCheckMarkDrawable.setCallback(null);
             unscheduleDrawable(mCheckMarkDrawable);
         }
+
         mNeedRequestlayout = (d != mCheckMarkDrawable);
+
         if (d != null) {
             d.setCallback(this);
             d.setVisible(getVisibility() == VISIBLE, false);
@@ -190,7 +191,9 @@
         } else {
             mCheckMarkWidth = 0;
         }
+
         mCheckMarkDrawable = d;
+        mCheckMarkResource = resId;
 
         // Do padding resolution. This will call internalSetPadding() and do a
         // requestLayout() if needed.
diff --git a/core/java/android/widget/Editor.java b/core/java/android/widget/Editor.java
index 15353bb..a822a1d 100644
--- a/core/java/android/widget/Editor.java
+++ b/core/java/android/widget/Editor.java
@@ -3308,7 +3308,7 @@
                 mSelectionBounds.set(
                         primaryHorizontal,
                         layout.getLineTop(line),
-                        primaryHorizontal + 1,
+                        primaryHorizontal,
                         layout.getLineTop(line + 1) + mHandleHeight);
             }
             // Take TextView's padding and scroll into account.
diff --git a/core/java/android/widget/Spinner.java b/core/java/android/widget/Spinner.java
index 6abd1293..f3cf61c 100644
--- a/core/java/android/widget/Spinner.java
+++ b/core/java/android/widget/Spinner.java
@@ -85,8 +85,10 @@
      */
     private static final int MODE_THEME = -1;
 
+    private final Rect mTempRect = new Rect();
+
     /** Context used to inflate the popup window or dialog. */
-    private Context mPopupContext;
+    private final Context mPopupContext;
 
     /** Forwarding listener used to implement drag-to-open. */
     private ForwardingListener mForwardingListener;
@@ -100,26 +102,25 @@
     private int mGravity;
     private boolean mDisableChildrenWhenDisabled;
 
-    private Rect mTempRect = new Rect();
-
     /**
-     * Construct a new spinner with the given context's theme.
+     * Constructs a new spinner with the given context's theme.
      *
      * @param context The Context the view is running in, through which it can
-     *        access the current theme, resources, etc.
+     *                access the current theme, resources, etc.
      */
     public Spinner(Context context) {
         this(context, null);
     }
 
     /**
-     * Construct a new spinner with the given context's theme and the supplied
+     * Constructs a new spinner with the given context's theme and the supplied
      * mode of displaying choices. <code>mode</code> may be one of
      * {@link #MODE_DIALOG} or {@link #MODE_DROPDOWN}.
      *
      * @param context The Context the view is running in, through which it can
-     *        access the current theme, resources, etc.
-     * @param mode Constant describing how the user will select choices from the spinner.
+     *                access the current theme, resources, etc.
+     * @param mode Constant describing how the user will select choices from
+     *             the spinner.
      * 
      * @see #MODE_DIALOG
      * @see #MODE_DROPDOWN
@@ -129,10 +130,11 @@
     }
 
     /**
-     * Construct a new spinner with the given context's theme and the supplied attribute set.
+     * Constructs a new spinner with the given context's theme and the supplied
+     * attribute set.
      *
      * @param context The Context the view is running in, through which it can
-     *        access the current theme, resources, etc.
+     *                access the current theme, resources, etc.
      * @param attrs The attributes of the XML tag that is inflating the view.
      */
     public Spinner(Context context, AttributeSet attrs) {
@@ -140,32 +142,35 @@
     }
 
     /**
-     * Construct a new spinner with the given context's theme, the supplied attribute set,
-     * and default style attribute.
+     * Constructs a new spinner with the given context's theme, the supplied
+     * attribute set, and default style attribute.
      *
      * @param context The Context the view is running in, through which it can
-     *        access the current theme, resources, etc.
+     *                access the current theme, resources, etc.
      * @param attrs The attributes of the XML tag that is inflating the view.
      * @param defStyleAttr An attribute in the current theme that contains a
-     *        reference to a style resource that supplies default values for
-     *        the view. Can be 0 to not look for defaults.
+     *                     reference to a style resource that supplies default
+     *                     values for the view. Can be 0 to not look for
+     *                     defaults.
      */
     public Spinner(Context context, AttributeSet attrs, int defStyleAttr) {
         this(context, attrs, defStyleAttr, 0, MODE_THEME);
     }
 
     /**
-     * Construct a new spinner with the given context's theme, the supplied attribute set,
-     * and default style. <code>mode</code> may be one of {@link #MODE_DIALOG} or
-     * {@link #MODE_DROPDOWN} and determines how the user will select choices from the spinner.
+     * Constructs a new spinner with the given context's theme, the supplied
+     * attribute set, and default style attribute. <code>mode</code> may be one
+     * of {@link #MODE_DIALOG} or {@link #MODE_DROPDOWN} and determines how the
+     * user will select choices from the spinner.
      *
      * @param context The Context the view is running in, through which it can
-     *        access the current theme, resources, etc.
+     *                access the current theme, resources, etc.
      * @param attrs The attributes of the XML tag that is inflating the view.
      * @param defStyleAttr An attribute in the current theme that contains a
-     *        reference to a style resource that supplies default values for
-     *        the view. Can be 0 to not look for defaults.
-     * @param mode Constant describing how the user will select choices from the spinner.
+     *                     reference to a style resource that supplies default
+     *                     values for the view. Can be 0 to not look for defaults.
+     * @param mode Constant describing how the user will select choices from the
+     *             spinner.
      *
      * @see #MODE_DIALOG
      * @see #MODE_DROPDOWN
@@ -175,21 +180,24 @@
     }
 
     /**
-     * Construct a new spinner with the given context's theme, the supplied attribute set,
-     * and default style. <code>mode</code> may be one of {@link #MODE_DIALOG} or
-     * {@link #MODE_DROPDOWN} and determines how the user will select choices from the spinner.
+     * Constructs a new spinner with the given context's theme, the supplied
+     * attribute set, and default styles. <code>mode</code> may be one of
+     * {@link #MODE_DIALOG} or {@link #MODE_DROPDOWN} and determines how the
+     * user will select choices from the spinner.
      *
      * @param context The Context the view is running in, through which it can
-     *        access the current theme, resources, etc.
+     *                access the current theme, resources, etc.
      * @param attrs The attributes of the XML tag that is inflating the view.
      * @param defStyleAttr An attribute in the current theme that contains a
-     *        reference to a style resource that supplies default values for
-     *        the view. Can be 0 to not look for defaults.
+     *                     reference to a style resource that supplies default
+     *                     values for the view. Can be 0 to not look for
+     *                     defaults.
      * @param defStyleRes A resource identifier of a style resource that
-     *        supplies default values for the view, used only if
-     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
-     *        to not look for defaults.
-     * @param mode Constant describing how the user will select choices from the spinner.
+     *                    supplies default values for the view, used only if
+     *                    defStyleAttr is 0 or can not be found in the theme.
+     *                    Can be 0 to not look for defaults.
+     * @param mode Constant describing how the user will select choices from
+     *             the spinner.
      *
      * @see #MODE_DIALOG
      * @see #MODE_DROPDOWN
@@ -200,10 +208,10 @@
     }
 
     /**
-     * Constructs a new spinner with the given context's theme, the supplied
-     * attribute set, default styles, popup mode (one of {@link #MODE_DIALOG}
-     * or {@link #MODE_DROPDOWN}), and the context against which the popup
-     * should be inflated.
+     * Constructs a new spinner with the given context, the supplied attribute
+     * set, default styles, popup mode (one of {@link #MODE_DIALOG} or
+     * {@link #MODE_DROPDOWN}), and the theme against which the popup should be
+     * inflated.
      *
      * @param context The context against which the view is inflated, which
      *                provides access to the current theme, resources, etc.
diff --git a/core/java/android/widget/TabWidget.java b/core/java/android/widget/TabWidget.java
index d9cff4e..0cc630a 100644
--- a/core/java/android/widget/TabWidget.java
+++ b/core/java/android/widget/TabWidget.java
@@ -16,8 +16,10 @@
 
 package android.widget;
 
-import android.R;
+import com.android.internal.R;
+
 import android.annotation.DrawableRes;
+import android.annotation.Nullable;
 import android.content.Context;
 import android.content.res.TypedArray;
 import android.graphics.Canvas;
@@ -33,21 +35,25 @@
 /**
  *
  * Displays a list of tab labels representing each page in the parent's tab
- * collection. The container object for this widget is
- * {@link android.widget.TabHost TabHost}. When the user selects a tab, this
- * object sends a message to the parent container, TabHost, to tell it to switch
- * the displayed page. You typically won't use many methods directly on this
- * object. The container TabHost is used to add labels, add the callback
- * handler, and manage callbacks. You might call this object to iterate the list
- * of tabs, or to tweak the layout of the tab list, but most methods should be
- * called on the containing TabHost object.
- * 
+ * collection.
+ * <p>
+ * The container object for this widget is {@link android.widget.TabHost TabHost}.
+ * When the user selects a tab, this object sends a message to the parent
+ * container, TabHost, to tell it to switch the displayed page. You typically
+ * won't use many methods directly on this object. The container TabHost is
+ * used to add labels, add the callback handler, and manage callbacks. You
+ * might call this object to iterate the list of tabs, or to tweak the layout
+ * of the tab list, but most methods should be called on the containing TabHost
+ * object.
+ *
  * @attr ref android.R.styleable#TabWidget_divider
  * @attr ref android.R.styleable#TabWidget_tabStripEnabled
  * @attr ref android.R.styleable#TabWidget_tabStripLeft
  * @attr ref android.R.styleable#TabWidget_tabStripRight
  */
 public class TabWidget extends LinearLayout implements OnFocusChangeListener {
+    private final Rect mBounds = new Rect();
+
     private OnTabSelectionChanged mSelectionChangedListener;
 
     // This value will be set to 0 as soon as the first tab is added to TabHost.
@@ -59,9 +65,8 @@
     private boolean mDrawBottomStrips = true;
     private boolean mStripMoved;
 
-    private final Rect mBounds = new Rect();
-
-    // When positive, the widths and heights of tabs will be imposed so that they fit in parent
+    // When positive, the widths and heights of tabs will be imposed so that
+    // they fit in parent.
     private int mImposedTabsHeight = -1;
     private int[] mImposedTabWidths;
 
@@ -81,20 +86,48 @@
         super(context, attrs, defStyleAttr, defStyleRes);
 
         final TypedArray a = context.obtainStyledAttributes(
-                attrs, com.android.internal.R.styleable.TabWidget, defStyleAttr, defStyleRes);
+                attrs, R.styleable.TabWidget, defStyleAttr, defStyleRes);
 
-        setStripEnabled(a.getBoolean(R.styleable.TabWidget_tabStripEnabled, true));
-        setLeftStripDrawable(a.getDrawable(R.styleable.TabWidget_tabStripLeft));
-        setRightStripDrawable(a.getDrawable(R.styleable.TabWidget_tabStripRight));
+        mDrawBottomStrips = a.getBoolean(R.styleable.TabWidget_tabStripEnabled, mDrawBottomStrips);
+
+        // Tests the target SDK version, as set in the Manifest. Could not be
+        // set using styles.xml in a values-v? directory which targets the
+        // current platform SDK version instead.
+        final boolean isTargetSdkDonutOrLower =
+                context.getApplicationInfo().targetSdkVersion <= Build.VERSION_CODES.DONUT;
+
+        final boolean hasExplicitLeft = a.hasValueOrEmpty(R.styleable.TabWidget_tabStripLeft);
+        if (hasExplicitLeft) {
+            mLeftStrip = a.getDrawable(R.styleable.TabWidget_tabStripLeft);
+        } else if (isTargetSdkDonutOrLower) {
+            mLeftStrip = context.getDrawable(R.drawable.tab_bottom_left_v4);
+        } else {
+            mLeftStrip = context.getDrawable(R.drawable.tab_bottom_left);
+        }
+
+        final boolean hasExplicitRight = a.hasValueOrEmpty(R.styleable.TabWidget_tabStripRight);
+        if (hasExplicitRight) {
+            mRightStrip = a.getDrawable(R.styleable.TabWidget_tabStripRight);
+        } else if (isTargetSdkDonutOrLower) {
+            mRightStrip = context.getDrawable(R.drawable.tab_bottom_right_v4);
+        } else {
+            mRightStrip = context.getDrawable(R.drawable.tab_bottom_right);
+        }
 
         a.recycle();
 
-        initTabWidget();
+        setChildrenDrawingOrderEnabled(true);
+
+        // Deal with focus, as we don't want the focus to go by default
+        // to a tab other than the current tab
+        setFocusable(true);
+        setOnFocusChangeListener(this);
     }
 
     @Override
     protected void onSizeChanged(int w, int h, int oldw, int oldh) {
         mStripMoved = true;
+
         super.onSizeChanged(w, h, oldw, oldh);
     }
 
@@ -115,44 +148,8 @@
         }
     }
 
-    private void initTabWidget() {
-        setChildrenDrawingOrderEnabled(true);
-
-        final Context context = mContext;
-
-        // Tests the target Sdk version, as set in the Manifest. Could not be set using styles.xml
-        // in a values-v? directory which targets the current platform Sdk version instead.
-        if (context.getApplicationInfo().targetSdkVersion <= Build.VERSION_CODES.DONUT) {
-            // Donut apps get old color scheme
-            if (mLeftStrip == null) {
-                mLeftStrip = context.getDrawable(
-                        com.android.internal.R.drawable.tab_bottom_left_v4);
-            }
-            if (mRightStrip == null) {
-                mRightStrip = context.getDrawable(
-                        com.android.internal.R.drawable.tab_bottom_right_v4);
-            }
-        } else {
-            // Use modern color scheme for Eclair and beyond
-            if (mLeftStrip == null) {
-                mLeftStrip = context.getDrawable(
-                        com.android.internal.R.drawable.tab_bottom_left);
-            }
-            if (mRightStrip == null) {
-                mRightStrip = context.getDrawable(
-                        com.android.internal.R.drawable.tab_bottom_right);
-            }
-        }
-
-        // Deal with focus, as we don't want the focus to go by default
-        // to a tab other than the current tab
-        setFocusable(true);
-        setOnFocusChangeListener(this);
-    }
-
     @Override
-    void measureChildBeforeLayout(View child, int childIndex,
-            int widthMeasureSpec, int totalWidth,
+    void measureChildBeforeLayout(View child, int childIndex, int widthMeasureSpec, int totalWidth,
             int heightMeasureSpec, int totalHeight) {
         if (!isMeasureWithLargestChildEnabled() && mImposedTabsHeight >= 0) {
             widthMeasureSpec = MeasureSpec.makeMeasureSpec(
@@ -209,7 +206,8 @@
             }
         }
 
-        // Measure again, this time with imposed tab widths and respecting initial spec request
+        // Measure again, this time with imposed tab widths and respecting
+        // initial spec request.
         super.measureHorizontal(widthMeasureSpec, heightMeasureSpec);
     }
 
@@ -225,7 +223,8 @@
 
     /**
      * Returns the number of tab indicator views.
-     * @return the number of tab indicator views.
+     *
+     * @return the number of tab indicator views
      */
     public int getTabCount() {
         return getChildCount();
@@ -233,65 +232,104 @@
 
     /**
      * Sets the drawable to use as a divider between the tab indicators.
+     *
      * @param drawable the divider drawable
+     * @attr ref android.R.styleable#TabWidget_divider
      */
     @Override
-    public void setDividerDrawable(Drawable drawable) {
+    public void setDividerDrawable(@Nullable Drawable drawable) {
         super.setDividerDrawable(drawable);
     }
 
     /**
      * Sets the drawable to use as a divider between the tab indicators.
-     * @param resId the resource identifier of the drawable to use as a
-     * divider.
+     *
+     * @param resId the resource identifier of the drawable to use as a divider
+     * @attr ref android.R.styleable#TabWidget_divider
      */
     public void setDividerDrawable(@DrawableRes int resId) {
         setDividerDrawable(mContext.getDrawable(resId));
     }
-    
+
     /**
-     * Sets the drawable to use as the left part of the strip below the
-     * tab indicators.
+     * Sets the drawable to use as the left part of the strip below the tab
+     * indicators.
+     *
      * @param drawable the left strip drawable
+     * @see #getLeftStripDrawable()
+     * @attr ref android.R.styleable#TabWidget_tabStripLeft
      */
-    public void setLeftStripDrawable(Drawable drawable) {
+    public void setLeftStripDrawable(@Nullable Drawable drawable) {
         mLeftStrip = drawable;
         requestLayout();
         invalidate();
     }
 
     /**
-     * Sets the drawable to use as the left part of the strip below the
-     * tab indicators.
-     * @param resId the resource identifier of the drawable to use as the
-     * left strip drawable
+     * Sets the drawable to use as the left part of the strip below the tab
+     * indicators.
+     *
+     * @param resId the resource identifier of the drawable to use as the left
+     *              strip drawable
+     * @see #getLeftStripDrawable()
+     * @attr ref android.R.styleable#TabWidget_tabStripLeft
      */
     public void setLeftStripDrawable(@DrawableRes int resId) {
         setLeftStripDrawable(mContext.getDrawable(resId));
     }
 
     /**
-     * Sets the drawable to use as the right part of the strip below the
-     * tab indicators.
-     * @param drawable the right strip drawable
+     * @return the drawable used as the left part of the strip below the tab
+     *         indicators, may be {@code null}
+     * @see #setLeftStripDrawable(int)
+     * @see #setLeftStripDrawable(Drawable)
+     * @attr ref android.R.styleable#TabWidget_tabStripLeft
      */
-    public void setRightStripDrawable(Drawable drawable) {
+    @Nullable
+    public Drawable getLeftStripDrawable() {
+        return mLeftStrip;
+    }
+
+    /**
+     * Sets the drawable to use as the right part of the strip below the tab
+     * indicators.
+     *
+     * @param drawable the right strip drawable
+     * @see #getRightStripDrawable()
+     * @attr ref android.R.styleable#TabWidget_tabStripRight
+     */
+    public void setRightStripDrawable(@Nullable Drawable drawable) {
         mRightStrip = drawable;
         requestLayout();
         invalidate();
     }
 
     /**
-     * Sets the drawable to use as the right part of the strip below the
-     * tab indicators.
-     * @param resId the resource identifier of the drawable to use as the
-     * right strip drawable
+     * Sets the drawable to use as the right part of the strip below the tab
+     * indicators.
+     *
+     * @param resId the resource identifier of the drawable to use as the right
+     *              strip drawable
+     * @see #getRightStripDrawable()
+     * @attr ref android.R.styleable#TabWidget_tabStripRight
      */
     public void setRightStripDrawable(@DrawableRes int resId) {
         setRightStripDrawable(mContext.getDrawable(resId));
     }
 
     /**
+     * @return the drawable used as the right part of the strip below the tab
+     *         indicators, may be {@code null}
+     * @see #setRightStripDrawable(int)
+     * @see #setRightStripDrawable(Drawable)
+     * @attr ref android.R.styleable#TabWidget_tabStripRight
+     */
+    @Nullable
+    public Drawable getRightStripDrawable() {
+        return mRightStrip;
+    }
+
+    /**
      * Controls whether the bottom strips on the tab indicators are drawn or
      * not.  The default is to draw them.  If the user specifies a custom
      * view for the tab indicators, then the TabHost class calls this method
@@ -360,13 +398,14 @@
 
     /**
      * Sets the current tab.
+     * <p>
      * This method is used to bring a tab to the front of the Widget,
      * and is used to post to the rest of the UI that a different tab
      * has been brought to the foreground.
-     *
+     * <p>
      * Note, this is separate from the traditional "focus" that is
      * employed from the view logic.
-     *
+     * <p>
      * For instance, if we have a list in a tabbed view, a user may be
      * navigating up and down the list, moving the UI focus (orange
      * highlighting) through the list items.  The cursor movement does
@@ -374,16 +413,15 @@
      * scrolled through is all on the same tab.  The selected tab only
      * changes when we navigate between tabs (moving from the list view
      * to the next tabbed view, in this example).
-     *
+     * <p>
      * To move both the focus AND the selected tab at once, please use
      * {@link #setCurrentTab}. Normally, the view logic takes care of
      * adjusting the focus, so unless you're circumventing the UI,
      * you'll probably just focus your interest here.
      *
-     *  @param index The tab that you want to indicate as the selected
-     *  tab (tab brought to the front of the widget)
-     *
-     *  @see #focusCurrentTab
+     * @param index the index of the tab that you want to indicate as the
+     *              selected tab (tab brought to the front of the widget)
+     * @see #focusCurrentTab
      */
     public void setCurrentTab(int index) {
         if (index < 0 || index >= getTabCount() || index == mSelectedTab) {
@@ -473,7 +511,7 @@
 
         final int count = getTabCount();
         for (int i = 0; i < count; i++) {
-            View child = getChildTabViewAt(i);
+            final View child = getChildTabViewAt(i);
             child.setEnabled(enabled);
         }
     }
@@ -482,8 +520,7 @@
     public void addView(View child) {
         if (child.getLayoutParams() == null) {
             final LinearLayout.LayoutParams lp = new LayoutParams(
-                    0,
-                    ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
+                    0, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
             lp.setMargins(0, 0, 0, 0);
             child.setLayoutParams(lp);
         }
@@ -507,13 +544,13 @@
     }
 
     /**
-     * Provides a way for {@link TabHost} to be notified that the user clicked on a tab indicator.
+     * Provides a way for {@link TabHost} to be notified that the user clicked
+     * on a tab indicator.
      */
     void setTabSelectionListener(OnTabSelectionChanged listener) {
         mSelectionChangedListener = listener;
     }
 
-    /** {@inheritDoc} */
     public void onFocusChange(View v, boolean hasFocus) {
         if (v == this && hasFocus && getTabCount() > 0) {
             getChildTabViewAt(mSelectedTab).requestFocus();
@@ -540,7 +577,6 @@
 
     // registered with each tab indicator so we can notify tab host
     private class TabClickListener implements OnClickListener {
-
         private final int mTabIndex;
 
         private TabClickListener(int tabIndex) {
@@ -553,17 +589,18 @@
     }
 
     /**
-     * Let {@link TabHost} know that the user clicked on a tab indicator.
+     * Lets {@link TabHost} know that the user clicked on a tab indicator.
      */
-    static interface OnTabSelectionChanged {
+    interface OnTabSelectionChanged {
         /**
          * Informs the TabHost which tab was selected. It also indicates
          * if the tab was clicked/pressed or just focused into.
          *
          * @param tabIndex index of the tab that was selected
-         * @param clicked whether the selection changed due to a touch/click
-         * or due to focus entering the tab through navigation. Pass true
-         * if it was due to a press/click and false otherwise.
+         * @param clicked whether the selection changed due to a touch/click or
+         *                due to focus entering the tab through navigation.
+         *                {@code true} if it was due to a press/click and
+         *                {@code false} otherwise.
          */
         void onTabSelectionChanged(int tabIndex, boolean clicked);
     }
diff --git a/core/java/com/android/internal/content/PackageHelper.java b/core/java/com/android/internal/content/PackageHelper.java
index b04ddf4..de29a96 100644
--- a/core/java/com/android/internal/content/PackageHelper.java
+++ b/core/java/com/android/internal/content/PackageHelper.java
@@ -34,8 +34,10 @@
 import android.os.storage.StorageResultCode;
 import android.os.storage.StorageVolume;
 import android.os.storage.VolumeInfo;
+import android.provider.Settings;
 import android.util.ArraySet;
 import android.util.Log;
+import android.util.Slog;
 
 import libcore.io.IoUtils;
 
@@ -345,6 +347,8 @@
      */
     public static String resolveInstallVolume(Context context, String packageName,
             int installLocation, long sizeBytes) throws IOException {
+        final boolean forceAllowOnExternal = Settings.Global.getInt(
+                context.getContentResolver(), Settings.Global.FORCE_ALLOW_ON_EXTERNAL, 0) != 0;
         // TODO: handle existing apps installed in ASEC; currently assumes
         // they'll end up back on internal storage
         ApplicationInfo existingInfo = null;
@@ -379,7 +383,8 @@
         }
 
         // If app expresses strong desire for internal space, honor it
-        if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
+        if (!forceAllowOnExternal
+                && installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
             if (fitsOnInternal) {
                 return null;
             } else {
diff --git a/core/java/com/android/internal/inputmethod/InputMethodUtils.java b/core/java/com/android/internal/inputmethod/InputMethodUtils.java
index 742173b..d53efa0 100644
--- a/core/java/com/android/internal/inputmethod/InputMethodUtils.java
+++ b/core/java/com/android/internal/inputmethod/InputMethodUtils.java
@@ -428,7 +428,7 @@
     }
 
     public static ArrayList<InputMethodSubtype> getSubtypes(InputMethodInfo imi) {
-        ArrayList<InputMethodSubtype> subtypes = new ArrayList<InputMethodSubtype>();
+        ArrayList<InputMethodSubtype> subtypes = new ArrayList<>();
         final int subtypeCount = imi.getSubtypeCount();
         for (int i = 0; i < subtypeCount; ++i) {
             subtypes.add(imi.getSubtypeAt(i));
@@ -438,7 +438,7 @@
 
     public static ArrayList<InputMethodSubtype> getOverridingImplicitlyEnabledSubtypes(
             InputMethodInfo imi, String mode) {
-        ArrayList<InputMethodSubtype> subtypes = new ArrayList<InputMethodSubtype>();
+        ArrayList<InputMethodSubtype> subtypes = new ArrayList<>();
         final int subtypeCount = imi.getSubtypeCount();
         for (int i = 0; i < subtypeCount; ++i) {
             final InputMethodSubtype subtype = imi.getSubtypeAt(i);
@@ -496,10 +496,9 @@
             Resources res, InputMethodInfo imi) {
         final List<InputMethodSubtype> subtypes = InputMethodUtils.getSubtypes(imi);
         final String systemLocale = res.getConfiguration().locale.toString();
-        if (TextUtils.isEmpty(systemLocale)) return new ArrayList<InputMethodSubtype>();
+        if (TextUtils.isEmpty(systemLocale)) return new ArrayList<>();
         final String systemLanguage = res.getConfiguration().locale.getLanguage();
-        final HashMap<String, InputMethodSubtype> applicableModeAndSubtypesMap =
-                new HashMap<String, InputMethodSubtype>();
+        final HashMap<String, InputMethodSubtype> applicableModeAndSubtypesMap = new HashMap<>();
         final int N = subtypes.size();
         for (int i = 0; i < N; ++i) {
             // scan overriding implicitly enabled subtypes.
@@ -512,7 +511,7 @@
             }
         }
         if (applicableModeAndSubtypesMap.size() > 0) {
-            return new ArrayList<InputMethodSubtype>(applicableModeAndSubtypesMap.values());
+            return new ArrayList<>(applicableModeAndSubtypesMap.values());
         }
         for (int i = 0; i < N; ++i) {
             final InputMethodSubtype subtype = subtypes.get(i);
@@ -545,7 +544,7 @@
         }
         final InputMethodSubtype keyboardSubtype
                 = applicableModeAndSubtypesMap.get(SUBTYPE_MODE_KEYBOARD);
-        final ArrayList<InputMethodSubtype> applicableSubtypes = new ArrayList<InputMethodSubtype>(
+        final ArrayList<InputMethodSubtype> applicableSubtypes = new ArrayList<>(
                 applicableModeAndSubtypesMap.values());
         if (keyboardSubtype != null && !keyboardSubtype.containsExtraValueKey(TAG_ASCII_CAPABLE)) {
             for (int i = 0; i < N; ++i) {
@@ -818,8 +817,7 @@
                 String enabledInputMethodsStr,
                 TextUtils.SimpleStringSplitter inputMethodSplitter,
                 TextUtils.SimpleStringSplitter subtypeSplitter) {
-            ArrayList<Pair<String, ArrayList<String>>> imsList =
-                    new ArrayList<Pair<String, ArrayList<String>>>();
+            ArrayList<Pair<String, ArrayList<String>>> imsList = new ArrayList<>();
             if (TextUtils.isEmpty(enabledInputMethodsStr)) {
                 return imsList;
             }
@@ -828,13 +826,13 @@
                 String nextImsStr = inputMethodSplitter.next();
                 subtypeSplitter.setString(nextImsStr);
                 if (subtypeSplitter.hasNext()) {
-                    ArrayList<String> subtypeHashes = new ArrayList<String>();
+                    ArrayList<String> subtypeHashes = new ArrayList<>();
                     // The first element is ime id.
                     String imeId = subtypeSplitter.next();
                     while (subtypeSplitter.hasNext()) {
                         subtypeHashes.add(subtypeSplitter.next());
                     }
-                    imsList.add(new Pair<String, ArrayList<String>>(imeId, subtypeHashes));
+                    imsList.add(new Pair<>(imeId, subtypeHashes));
                 }
             }
             return imsList;
@@ -880,12 +878,6 @@
                     getEnabledInputMethodsAndSubtypeListLocked());
         }
 
-        public List<Pair<InputMethodInfo, ArrayList<String>>>
-                getEnabledInputMethodAndSubtypeHashCodeListLocked() {
-            return createEnabledInputMethodAndSubtypeHashCodeListLocked(
-                    getEnabledInputMethodsAndSubtypeListLocked());
-        }
-
         public List<InputMethodSubtype> getEnabledInputMethodSubtypeListLocked(
                 Context context, InputMethodInfo imi, boolean allowsImplicitlySelectedSubtypes) {
             List<InputMethodSubtype> enabledSubtypes =
@@ -901,8 +893,7 @@
                 InputMethodInfo imi) {
             List<Pair<String, ArrayList<String>>> imsList =
                     getEnabledInputMethodsAndSubtypeListLocked();
-            ArrayList<InputMethodSubtype> enabledSubtypes =
-                    new ArrayList<InputMethodSubtype>();
+            ArrayList<InputMethodSubtype> enabledSubtypes = new ArrayList<>();
             if (imi != null) {
                 for (Pair<String, ArrayList<String>> imsPair : imsList) {
                     InputMethodInfo info = mMethodMap.get(imsPair.first);
@@ -991,7 +982,7 @@
 
         private List<InputMethodInfo> createEnabledInputMethodListLocked(
                 List<Pair<String, ArrayList<String>>> imsList) {
-            final ArrayList<InputMethodInfo> res = new ArrayList<InputMethodInfo>();
+            final ArrayList<InputMethodInfo> res = new ArrayList<>();
             for (Pair<String, ArrayList<String>> ims: imsList) {
                 InputMethodInfo info = mMethodMap.get(ims.first);
                 if (info != null) {
@@ -1001,20 +992,6 @@
             return res;
         }
 
-        private List<Pair<InputMethodInfo, ArrayList<String>>>
-                createEnabledInputMethodAndSubtypeHashCodeListLocked(
-                        List<Pair<String, ArrayList<String>>> imsList) {
-            final ArrayList<Pair<InputMethodInfo, ArrayList<String>>> res
-                    = new ArrayList<Pair<InputMethodInfo, ArrayList<String>>>();
-            for (Pair<String, ArrayList<String>> ims : imsList) {
-                InputMethodInfo info = mMethodMap.get(ims.first);
-                if (info != null) {
-                    res.add(new Pair<InputMethodInfo, ArrayList<String>>(info, ims.second));
-                }
-            }
-            return res;
-        }
-
         private void putEnabledInputMethodsStr(String str) {
             Settings.Secure.putStringForUser(
                     mResolver, Settings.Secure.ENABLED_INPUT_METHODS, str, mCurrentUserId);
@@ -1118,7 +1095,7 @@
                         if (DEBUG) {
                             Slog.d(TAG, "Enabled subtype found in the history: " + subtypeHashCode);
                         }
-                        return new Pair<String, String>(imeInTheHistory, subtypeHashCode);
+                        return new Pair<>(imeInTheHistory, subtypeHashCode);
                     }
                 }
             }
@@ -1179,7 +1156,7 @@
         }
 
         private List<Pair<String, String>> loadInputMethodAndSubtypeHistoryLocked() {
-            ArrayList<Pair<String, String>> imsList = new ArrayList<Pair<String, String>>();
+            ArrayList<Pair<String, String>> imsList = new ArrayList<>();
             final String subtypeHistoryStr = getSubtypeHistoryStr();
             if (TextUtils.isEmpty(subtypeHistoryStr)) {
                 return imsList;
@@ -1196,7 +1173,7 @@
                         subtypeId = mSubtypeSplitter.next();
                         break;
                     }
-                    imsList.add(new Pair<String, String>(imeId, subtypeId));
+                    imsList.add(new Pair<>(imeId, subtypeId));
                 }
             }
             return imsList;
@@ -1229,11 +1206,6 @@
                     subtypeId, mCurrentUserId);
         }
 
-        public String getDisabledSystemInputMethods() {
-            return Settings.Secure.getStringForUser(
-                    mResolver, Settings.Secure.DISABLED_SYSTEM_INPUT_METHODS, mCurrentUserId);
-        }
-
         public String getSelectedInputMethod() {
             if (DEBUG) {
                 Slog.d(TAG, "getSelectedInputMethodStr: " + Settings.Secure.getStringForUser(
@@ -1294,7 +1266,7 @@
         public HashMap<InputMethodInfo, List<InputMethodSubtype>>
                 getExplicitlyOrImplicitlyEnabledInputMethodsAndSubtypeListLocked(Context context) {
             HashMap<InputMethodInfo, List<InputMethodSubtype>> enabledInputMethodAndSubtypes =
-                    new HashMap<InputMethodInfo, List<InputMethodSubtype>>();
+                    new HashMap<>();
             for (InputMethodInfo imi: getEnabledInputMethodListLocked()) {
                 enabledInputMethodAndSubtypes.put(
                         imi, getEnabledInputMethodSubtypeListLocked(context, imi, true));
diff --git a/core/java/com/android/internal/policy/PhoneWindow.java b/core/java/com/android/internal/policy/PhoneWindow.java
index eccf5fa..508cb01 100644
--- a/core/java/com/android/internal/policy/PhoneWindow.java
+++ b/core/java/com/android/internal/policy/PhoneWindow.java
@@ -16,8 +16,10 @@
 
 package com.android.internal.policy;
 
-import static android.app.ActivityManager.FULLSCREEN_WORKSPACE_STACK_ID;
+import static android.app.ActivityManager.FIRST_DYNAMIC_STACK_ID;
 import static android.app.ActivityManager.FREEFORM_WORKSPACE_STACK_ID;
+import static android.app.ActivityManager.FULLSCREEN_WORKSPACE_STACK_ID;
+import static android.app.ActivityManager.HOME_STACK_ID;
 import static android.view.View.MeasureSpec.AT_MOST;
 import static android.view.View.MeasureSpec.EXACTLY;
 import static android.view.View.MeasureSpec.getMode;
@@ -2923,13 +2925,18 @@
                     mLastHasRightStableInset = hasRightStableInset;
                 }
 
-                updateColorViewInt(mStatusColorViewState, sysUiVisibility, mStatusBarColor,
-                        mLastTopInset, false /* matchVertical */, animate && !disallowAnimate);
-
                 boolean navBarToRightEdge = mLastBottomInset == 0 && mLastRightInset > 0;
                 int navBarSize = navBarToRightEdge ? mLastRightInset : mLastBottomInset;
                 updateColorViewInt(mNavigationColorViewState, sysUiVisibility, mNavigationBarColor,
-                        navBarSize, navBarToRightEdge, animate && !disallowAnimate);
+                        navBarSize, navBarToRightEdge, 0 /* rightInset */,
+                        animate && !disallowAnimate);
+
+                boolean statusBarNeedsRightInset = navBarToRightEdge
+                        && mNavigationColorViewState.present;
+                int statusBarRightInset = statusBarNeedsRightInset ? mLastRightInset : 0;
+                updateColorViewInt(mStatusColorViewState, sysUiVisibility, mStatusBarColor,
+                        mLastTopInset, false /* matchVertical */, statusBarRightInset,
+                        animate && !disallowAnimate);
             }
 
             // When we expand the window with FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS, we still need
@@ -2982,15 +2989,17 @@
          * @param size the current size in the non-parent-matching dimension.
          * @param verticalBar if true the view is attached to a vertical edge, otherwise to a
          *                    horizontal edge,
+         * @param rightMargin rightMargin for the color view.
          * @param animate if true, the change will be animated.
          */
         private void updateColorViewInt(final ColorViewState state, int sysUiVis, int color,
-                int size, boolean verticalBar, boolean animate) {
-            boolean show = size > 0 && (sysUiVis & state.systemUiHideFlag) == 0
+                int size, boolean verticalBar, int rightMargin, boolean animate) {
+            state.present = size > 0 && (sysUiVis & state.systemUiHideFlag) == 0
                     && (getAttributes().flags & state.hideWindowFlag) == 0
-                    && (getAttributes().flags & state.translucentFlag) == 0
-                    && (color & Color.BLACK) != 0
                     && (getAttributes().flags & FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) != 0;
+            boolean show = state.present
+                    && (color & Color.BLACK) != 0
+                    && (getAttributes().flags & state.translucentFlag) == 0;
 
             boolean visibilityChanged = false;
             View view = state.view;
@@ -3009,7 +3018,10 @@
                     view.setVisibility(INVISIBLE);
                     state.targetVisibility = VISIBLE;
 
-                    addView(view, new LayoutParams(resolvedWidth, resolvedHeight, resolvedGravity));
+                    LayoutParams lp = new LayoutParams(resolvedWidth, resolvedHeight,
+                            resolvedGravity);
+                    lp.rightMargin = rightMargin;
+                    addView(view, lp);
                     updateColorViewTranslations();
                 }
             } else {
@@ -3019,10 +3031,11 @@
                 if (show) {
                     LayoutParams lp = (LayoutParams) view.getLayoutParams();
                     if (lp.height != resolvedHeight || lp.width != resolvedWidth
-                            || lp.gravity != resolvedGravity) {
+                            || lp.gravity != resolvedGravity || lp.rightMargin != rightMargin) {
                         lp.height = resolvedHeight;
                         lp.width = resolvedWidth;
                         lp.gravity = resolvedGravity;
+                        lp.rightMargin = rightMargin;
                         view.setLayoutParams(lp);
                     }
                     view.setBackgroundColor(color);
@@ -4011,13 +4024,15 @@
         boolean isApplication = attrs.type == TYPE_BASE_APPLICATION ||
                 attrs.type == TYPE_APPLICATION;
         mWorkspaceId = getWorkspaceId();
-        // Only a non floating application window can get a non client decor.
-        if (!isFloating() && isApplication) {
+        // Only a non floating application window on one of the allowed worksapces can get a non
+        // client decor.
+        if (!isFloating() && isApplication && mWorkspaceId != HOME_STACK_ID &&
+                mWorkspaceId < FIRST_DYNAMIC_STACK_ID) {
             // Dependent on the brightness of the used title we either use the
             // dark or the light button frame.
             TypedValue value = new TypedValue();
             getContext().getTheme().resolveAttribute(R.attr.colorPrimary, value, true);
-            if (Color.brightness(value.data) < 0.5) {
+            if (Color.luminance(value.data) < 0.5) {
                 nonClientDecorView = (NonClientDecorView) mLayoutInflater.inflate(
                         R.layout.non_client_decor_dark, null);
             } else {
@@ -5104,6 +5119,7 @@
     private static class ColorViewState {
         View view = null;
         int targetVisibility = View.INVISIBLE;
+        boolean present = false;
 
         final int id;
         final int systemUiHideFlag;
@@ -5183,7 +5199,7 @@
      **/
     private int getWorkspaceId() {
         int workspaceId = FULLSCREEN_WORKSPACE_STACK_ID;
-        WindowStackCallback callback = getWindowStackCallback();
+        WindowControllerCallback callback = getWindowControllerCallback();
         if (callback != null) {
             try {
                 workspaceId = callback.getWindowStackId();
diff --git a/core/java/com/android/internal/util/ArrayUtils.java b/core/java/com/android/internal/util/ArrayUtils.java
index 9d0636a..f190d8c 100644
--- a/core/java/com/android/internal/util/ArrayUtils.java
+++ b/core/java/com/android/internal/util/ArrayUtils.java
@@ -294,6 +294,29 @@
     }
 
     /**
+     * Removes value from given array if present, providing set-like behavior.
+     */
+    public static @Nullable String[] removeString(@Nullable String[] cur, String val) {
+        if (cur == null) {
+            return null;
+        }
+        final int N = cur.length;
+        for (int i = 0; i < N; i++) {
+            if (Objects.equals(cur[i], val)) {
+                String[] ret = new String[N - 1];
+                if (i > 0) {
+                    System.arraycopy(cur, 0, ret, 0, i);
+                }
+                if (i < (N - 1)) {
+                    System.arraycopy(cur, i + 1, ret, i, N - i - 1);
+                }
+                return ret;
+            }
+        }
+        return cur;
+    }
+
+    /**
      * Adds value to given array if not already present, providing set-like
      * behavior.
      */
diff --git a/core/java/com/android/internal/view/FloatingActionMode.java b/core/java/com/android/internal/view/FloatingActionMode.java
index 41628d0..9761661 100644
--- a/core/java/com/android/internal/view/FloatingActionMode.java
+++ b/core/java/com/android/internal/view/FloatingActionMode.java
@@ -194,8 +194,16 @@
             mContext.getResources().getDisplayMetrics().widthPixels,
             mContext.getResources().getDisplayMetrics().heightPixels);
 
-        return Rect.intersects(mContentRectOnScreen, mScreenRect)
-            && Rect.intersects(mContentRectOnScreen, mViewRectOnScreen);
+        return intersectsClosed(mContentRectOnScreen, mScreenRect)
+            && intersectsClosed(mContentRectOnScreen, mViewRectOnScreen);
+    }
+
+    /*
+     * Same as Rect.intersects, but includes cases where the rectangles touch.
+    */
+    private static boolean intersectsClosed(Rect a, Rect b) {
+         return a.left <= b.right && b.left <= a.right
+                 && a.top <= b.bottom && b.top <= a.bottom;
     }
 
     @Override
diff --git a/core/java/com/android/internal/widget/ExploreByTouchHelper.java b/core/java/com/android/internal/widget/ExploreByTouchHelper.java
index bdf17fc..f5637dd 100644
--- a/core/java/com/android/internal/widget/ExploreByTouchHelper.java
+++ b/core/java/com/android/internal/widget/ExploreByTouchHelper.java
@@ -20,7 +20,6 @@
 import android.graphics.Rect;
 import android.os.Bundle;
 import android.util.IntArray;
-import android.view.accessibility.*;
 import android.view.MotionEvent;
 import android.view.View;
 import android.view.ViewParent;
@@ -50,6 +49,9 @@
     /** Virtual node identifier value for invalid nodes. */
     public static final int INVALID_ID = Integer.MIN_VALUE;
 
+    /** Virtual node identifier value for the host view's node. */
+    public static final int HOST_ID = View.NO_ID;
+
     /** Default class name used for virtual views. */
     private static final String DEFAULT_CLASS_NAME = View.class.getName();
 
@@ -195,7 +197,7 @@
      * parent view.
      */
     public void invalidateRoot() {
-        invalidateVirtualView(View.NO_ID);
+        invalidateVirtualView(HOST_ID, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
     }
 
     /**
@@ -205,10 +207,43 @@
      * You <b>must</b> call this method after changing any of the properties set
      * in {@link #onPopulateNodeForVirtualView}.
      *
-     * @param virtualViewId The virtual view id to invalidate.
+     * @param virtualViewId The virtual view id to invalidate, or
+     *                      {@link #HOST_ID} to invalidate the root view.
+     * @see #invalidateVirtualView(int, int)
      */
     public void invalidateVirtualView(int virtualViewId) {
-        sendEventForVirtualView(virtualViewId, AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
+        invalidateVirtualView(virtualViewId,
+                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
+    }
+
+    /**
+     * Notifies the accessibility framework that the properties of a particular
+     * item have changed.
+     * <p>
+     * You <b>must</b> call this method after changing any of the properties set
+     * in {@link #onPopulateNodeForVirtualView}.
+     *
+     * @param virtualViewId The virtual view id to invalidate, or
+     *                      {@link #HOST_ID} to invalidate the root view.
+     * @param changeTypes The bit mask of change types. May be {@code 0} for the
+     *                    default (undefined) change type or one or more of:
+     *         <ul>
+     *         <li>{@link AccessibilityEvent#CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION}
+     *         <li>{@link AccessibilityEvent#CONTENT_CHANGE_TYPE_SUBTREE}
+     *         <li>{@link AccessibilityEvent#CONTENT_CHANGE_TYPE_TEXT}
+     *         <li>{@link AccessibilityEvent#CONTENT_CHANGE_TYPE_UNDEFINED}
+     *         </ul>
+     */
+    public void invalidateVirtualView(int virtualViewId, int changeTypes) {
+        if (virtualViewId != INVALID_ID && mManager.isEnabled()) {
+            final ViewParent parent = mView.getParent();
+            if (parent != null) {
+                final AccessibilityEvent event = createEvent(virtualViewId,
+                        AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
+                event.setContentChangeTypes(changeTypes);
+                parent.requestSendAccessibilityEvent(mView, event);
+            }
+        }
     }
 
     /**
@@ -245,7 +280,7 @@
 
     /**
      * Constructs and returns an {@link AccessibilityEvent} for the specified
-     * virtual view id, which includes the host view ({@link View#NO_ID}).
+     * virtual view id, which includes the host view ({@link #HOST_ID}).
      *
      * @param virtualViewId The virtual view id for the item for which to
      *            construct an event.
@@ -255,7 +290,7 @@
      */
     private AccessibilityEvent createEvent(int virtualViewId, int eventType) {
         switch (virtualViewId) {
-            case View.NO_ID:
+            case HOST_ID:
                 return createEventForHost(eventType);
             default:
                 return createEventForChild(virtualViewId, eventType);
@@ -271,7 +306,7 @@
      */
     private AccessibilityEvent createEventForHost(int eventType) {
         final AccessibilityEvent event = AccessibilityEvent.obtain(eventType);
-        onInitializeAccessibilityEvent(mView, event);
+        mView.onInitializeAccessibilityEvent(event);
         return event;
     }
 
@@ -309,7 +344,7 @@
     /**
      * Constructs and returns an {@link android.view.accessibility.AccessibilityNodeInfo} for the
      * specified virtual view id, which includes the host view
-     * ({@link View#NO_ID}).
+     * ({@link #HOST_ID}).
      *
      * @param virtualViewId The virtual view id for the item for which to
      *            construct a node.
@@ -318,7 +353,7 @@
      */
     private AccessibilityNodeInfo createNode(int virtualViewId) {
         switch (virtualViewId) {
-            case View.NO_ID:
+            case HOST_ID:
                 return createNodeForHost();
             default:
                 return createNodeForChild(virtualViewId);
@@ -333,7 +368,7 @@
      */
     private AccessibilityNodeInfo createNodeForHost() {
         final AccessibilityNodeInfo node = AccessibilityNodeInfo.obtain(mView);
-        onInitializeAccessibilityNodeInfo(mView, node);
+        mView.onInitializeAccessibilityNodeInfo(node);
 
         // Add the virtual descendants.
         if (mTempArray == null) {
@@ -457,7 +492,7 @@
 
     private boolean performAction(int virtualViewId, int action, Bundle arguments) {
         switch (virtualViewId) {
-            case View.NO_ID:
+            case HOST_ID:
                 return performActionForHost(action, arguments);
             default:
                 return performActionForChild(virtualViewId, action, arguments);
@@ -465,7 +500,7 @@
     }
 
     private boolean performActionForHost(int action, Bundle arguments) {
-        return performAccessibilityAction(mView, action, arguments);
+        return mView.performAccessibilityAction(action, arguments);
     }
 
     private boolean performActionForChild(int virtualViewId, int action, Bundle arguments) {
@@ -646,7 +681,7 @@
      * <li>package name, set to the package of the host view's
      * {@link Context}, see {@link AccessibilityEvent#setPackageName}
      * <li>event source, set to the host view and virtual view identifier,
-     * see {@link AccessibilityRecord#setSource(View, int)}
+     * see {@link android.view.accessibility.AccessibilityRecord#setSource(View, int)}
      * </ul>
      *
      * @param virtualViewId The virtual view id for the item for which to
diff --git a/core/java/com/android/internal/widget/NonClientDecorView.java b/core/java/com/android/internal/widget/NonClientDecorView.java
index d8626cd..05711b5 100644
--- a/core/java/com/android/internal/widget/NonClientDecorView.java
+++ b/core/java/com/android/internal/widget/NonClientDecorView.java
@@ -17,9 +17,11 @@
 package com.android.internal.widget;
 
 import android.content.Context;
+import android.graphics.Rect;
 import android.os.RemoteException;
 import android.util.AttributeSet;
 import android.view.View;
+import android.widget.LinearLayout;
 import android.view.ViewGroup;
 import android.view.ViewOutlineProvider;
 import android.view.Window;
@@ -55,7 +57,7 @@
  * </ul>
  * This will be mitigated once b/22527834 will be addressed.
  */
-public class NonClientDecorView extends ViewGroup implements View.OnClickListener {
+public class NonClientDecorView extends LinearLayout implements View.OnClickListener {
     private final static String TAG = "NonClientDecorView";
     // The height of a window which has focus in DIP.
     private final int DECOR_SHADOW_FOCUSED_HEIGHT_IN_DIP = 20;
@@ -90,6 +92,7 @@
         mOwner = owner;
         mWindowHasShadow = windowHasShadow;
         mShowDecor = showDecor;
+        updateCaptionVisibility();
         if (mWindowHasShadow) {
             initializeElevation();
         }
@@ -107,6 +110,7 @@
      **/
     public void phoneWindowUpdated(boolean showDecor, boolean windowHasShadow) {
         mShowDecor = showDecor;
+        updateCaptionVisibility();
         if (windowHasShadow != mWindowHasShadow) {
             mWindowHasShadow = windowHasShadow;
             initializeElevation();
@@ -130,48 +134,17 @@
     }
 
     @Override
-    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
-        measureChildren(widthMeasureSpec, heightMeasureSpec);
-        final int width = MeasureSpec.getSize(widthMeasureSpec);
-        final int height = MeasureSpec.getSize(heightMeasureSpec);
-        setMeasuredDimension(width, height);
-    }
-
-    @Override
     protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
-        // The system inset needs only to be applied to the caption. The client area of
-        // the window will automatically be adjusted by the the DecorView.
-        WindowInsets insets = getRootWindowInsets();
-        int systemMargin = insets.getSystemWindowInsetTop();
-
-        final int leftPos = getPaddingLeft();
-        final int rightPos = right - left - getPaddingRight();
-        final int topPos = getPaddingTop();
-        final int bottomPos = bottom - top - getPaddingBottom();
-
-        // On top we have the caption which has to fill left to right with a fixed height.
-        final int width = rightPos - leftPos;
-        final View caption = getChildAt(0);
-
         // If the application changed its SystemUI metrics, we might also have to adapt
         // our shadow elevation.
         updateElevation();
         mAllowUpdateElevation = true;
 
-        // Don't show the decor if the window has e.g. entered full screen.
-        final int captionHeight =
-                (isFillingScreen() || !mShowDecor) ? 0 : caption.getMeasuredHeight();
-        caption.layout(leftPos, topPos + systemMargin, leftPos + width,
-                topPos + systemMargin + captionHeight);
-
-        // Note: We should never have more then 1 additional item in here.
-        if (getChildCount() > 1) {
-            getChildAt(1).layout(leftPos, topPos + captionHeight, leftPos + width, bottomPos);
-        }
+        super.onLayout(changed, left, top, right, bottom);
     }
 
     @Override
-    public void addView(View child, int index, LayoutParams params) {
+    public void addView(View child, int index, ViewGroup.LayoutParams params) {
         // Make sure that we never get more then one client area in our view.
         if (index >= 2 || getChildCount() >= 2) {
             throw new IllegalStateException("NonClientDecorView can only handle 1 client view");
@@ -190,6 +163,16 @@
     }
 
     /**
+     * Updates the visibility of the caption.
+     **/
+    private void updateCaptionVisibility() {
+        // Don't show the decor if the window has e.g. entered full screen.
+        boolean invisible = isFillingScreen() || !mShowDecor;
+        View caption = getChildAt(0);
+        caption.setVisibility(invisible ? GONE : VISIBLE);
+    }
+
+    /**
      * The elevation gets set for the first time and the framework needs to be informed that
      * the surface layer gets created with the shadow size in mind.
      **/
@@ -243,7 +226,7 @@
      * Maximize the window by moving it to the maximized workspace stack.
      **/
     private void maximizeWindow() {
-        Window.WindowStackCallback callback = mOwner.getWindowStackCallback();
+        Window.WindowControllerCallback callback = mOwner.getWindowControllerCallback();
         if (callback != null) {
             try {
                 callback.changeWindowStack(
@@ -253,4 +236,40 @@
             }
         }
     }
+
+    /**
+     * Returns the bounds of this activity.
+     * @return Returns bounds of the activity. It will return null if either the window is
+     *     fullscreen or the bounds could not be retrieved.
+     */
+    private Rect getActivityBounds() {
+        Window.WindowControllerCallback callback = mOwner.getWindowControllerCallback();
+        if (callback != null) {
+            try {
+                return callback.getActivityBounds();
+            } catch (RemoteException ex) {
+                Log.e(TAG, "Failed to get the activity bounds.");
+            }
+        }
+        return null;
+    }
+
+    /**
+     * Sets the bounds of this Activity on the stack.
+     * @param newBounds The bounds of the activity. Passing null is not allowed.
+     */
+    private void setActivityBounds(Rect newBounds) {
+        if (newBounds == null) {
+            Log.e(TAG, "Failed to set null bounds to the activity.");
+            return;
+        }
+        Window.WindowControllerCallback callback = mOwner.getWindowControllerCallback();
+        if (callback != null) {
+            try {
+                callback.setActivityBounds(newBounds);
+            } catch (RemoteException ex) {
+                Log.e(TAG, "Failed to set the activity bounds.");
+            }
+        }
+    }
 }
diff --git a/core/jni/AndroidRuntime.cpp b/core/jni/AndroidRuntime.cpp
index 467e03c..991ea25 100644
--- a/core/jni/AndroidRuntime.cpp
+++ b/core/jni/AndroidRuntime.cpp
@@ -43,6 +43,9 @@
 #include <dirent.h>
 #include <assert.h>
 
+#include <string>
+#include <vector>
+
 
 using namespace android;
 
@@ -356,38 +359,66 @@
     return false;
 }
 
+// Convenience wrapper over the property API that returns an
+// std::string.
+std::string getProperty(const char* key, const char* defaultValue) {
+    std::vector<char> temp(PROPERTY_VALUE_MAX);
+    const int len = property_get(key, &temp[0], defaultValue);
+    if (len < 0) {
+        return "";
+    }
+    return std::string(&temp[0], len);
+}
+
 /*
- * Read the persistent locale. Attempts to read to persist.sys.locale
- * and falls back to the default locale (ro.product.locale) if
- * persist.sys.locale is empty.
+ * Read the persistent locale. Inspects the following system properties
+ * (in order) and returns the first non-empty property in the list :
+ *
+ * (1) persist.sys.locale
+ * (2) persist.sys.language/country/localevar (country and localevar are
+ * inspected iff. language is non-empty.
+ * (3) ro.product.locale
+ * (4) ro.product.locale.language/region
+ *
+ * Note that we need to inspect persist.sys.language/country/localevar to
+ * preserve language settings for devices that are upgrading from Lollipop
+ * to M. The same goes for ro.product.locale.language/region as well.
  */
-static void readLocale(char* locale)
+const std::string readLocale()
 {
-    // Allocate 4 extra bytes because we might read a property into
-    // this array at offset 4.
-    char propLocale[PROPERTY_VALUE_MAX + 4];
-
-    property_get("persist.sys.locale", propLocale, "");
-    if (propLocale[0] == 0) {
-        property_get("ro.product.locale", propLocale, "");
-
-        if (propLocale[0] == 0) {
-            // If persist.sys.locale and ro.product.locale are missing,
-            // construct a locale value from the individual locale components.
-            property_get("ro.product.locale.language", propLocale, "en");
-
-            // The language code is either two or three chars in length. If it
-            // isn't 2 chars long, assume three. Anything else is an error
-            // anyway.
-            const int offset = (propLocale[2] == 0) ? 2 : 3;
-            propLocale[offset] = '-';
-
-            property_get("ro.product.locale.region", propLocale + offset + 1, "US");
-        }
+    const std::string locale = getProperty("persist.sys.locale", "");
+    if (!locale.empty()) {
+        return locale;
     }
 
-    strncat(locale, propLocale, PROPERTY_VALUE_MAX);
-    // ALOGD("[DEBUG] locale=%s", locale);
+    const std::string language = getProperty("persist.sys.language", "");
+    if (!language.empty()) {
+        const std::string country = getProperty("persist.sys.country", "");
+        const std::string variant = getProperty("persist.sys.localevar", "");
+
+        std::string out = language;
+        if (!country.empty()) {
+            out = out + "-" + country;
+        }
+
+        if (!variant.empty()) {
+            out = out + "-" + variant;
+        }
+
+        return out;
+    }
+
+    const std::string productLocale = getProperty("ro.product.locale", "");
+    if (!productLocale.empty()) {
+        return productLocale;
+    }
+
+    // If persist.sys.locale and ro.product.locale are missing,
+    // construct a locale value from the individual locale components.
+    const std::string productLanguage = getProperty("ro.product.locale.language", "en");
+    const std::string productRegion = getProperty("ro.product.locale.region", "US");
+
+    return productLanguage + "-" + productRegion;
 }
 
 void AndroidRuntime::addOption(const char* optionString, void* extraInfo)
@@ -792,7 +823,8 @@
     /* Set the properties for locale */
     {
         strcpy(localeOption, "-Duser.locale=");
-        readLocale(localeOption);
+        const std::string locale = readLocale();
+        strncat(localeOption, locale.c_str(), PROPERTY_VALUE_MAX);
         addOption(localeOption);
     }
 
diff --git a/core/res/res/color/control_nodisable_material.xml b/core/res/res/color/control_nodisable_material.xml
new file mode 100644
index 0000000..4a73e93
--- /dev/null
+++ b/core/res/res/color/control_nodisable_material.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<selector xmlns:android="http://schemas.android.com/apk/res/android">
+    <item android:color="?attr/colorControlNormal" />
+</selector>
diff --git a/core/res/res/drawable/seekbar_thumb_material_anim.xml b/core/res/res/drawable/seekbar_thumb_material_anim.xml
index 9726e73..b1119cd 100644
--- a/core/res/res/drawable/seekbar_thumb_material_anim.xml
+++ b/core/res/res/drawable/seekbar_thumb_material_anim.xml
@@ -25,7 +25,7 @@
             android:opticalInsetLeft="3dp"
             android:opticalInsetRight="3dp">
             <solid
-                android:color="#ff000000" />
+                android:color="@color/white" />
             <size
                 android:width="18dp"
                 android:height="18dp" />
diff --git a/core/res/res/drawable/seekbar_track_material.xml b/core/res/res/drawable/seekbar_track_material.xml
index 01eb243..e88a73f 100644
--- a/core/res/res/drawable/seekbar_track_material.xml
+++ b/core/res/res/drawable/seekbar_track_material.xml
@@ -18,7 +18,7 @@
     <item android:id="@id/background"
           android:gravity="center_vertical|fill_horizontal">
         <shape android:shape="rectangle"
-               android:tint="?attr/colorControlNormal">
+               android:tint="@color/control_nodisable_material">
             <size android:height="@dimen/seekbar_track_background_height_material" />
             <solid android:color="@color/white_disabled_material" />
         </shape>
diff --git a/core/res/res/layout/non_client_decor_dark.xml b/core/res/res/layout/non_client_decor_dark.xml
index 00b4255..d1e2974 100644
--- a/core/res/res/layout/non_client_decor_dark.xml
+++ b/core/res/res/layout/non_client_decor_dark.xml
@@ -20,8 +20,7 @@
 <com.android.internal.widget.NonClientDecorView xmlns:android="http://schemas.android.com/apk/res/android"
     android:orientation="vertical"
     android:layout_width="match_parent"
-    android:layout_height="wrap_content"
-    android:layout_gravity="top|start"
+    android:layout_height="match_parent"
     android:descendantFocusability="beforeDescendants" >
     <LinearLayout
         android:layout_width="match_parent"
diff --git a/core/res/res/layout/non_client_decor_light.xml b/core/res/res/layout/non_client_decor_light.xml
index 0ce8fa7..f7c3fcd 100644
--- a/core/res/res/layout/non_client_decor_light.xml
+++ b/core/res/res/layout/non_client_decor_light.xml
@@ -20,8 +20,7 @@
 <com.android.internal.widget.NonClientDecorView xmlns:android="http://schemas.android.com/apk/res/android"
     android:orientation="vertical"
     android:layout_width="match_parent"
-    android:layout_height="wrap_content"
-    android:layout_gravity="top|start"
+    android:layout_height="match_parent"
     android:descendantFocusability="beforeDescendants" >
     <LinearLayout
         android:layout_width="match_parent"
diff --git a/core/res/res/values-af/strings.xml b/core/res/res/values-af/strings.xml
index 84161e0..a08f040 100644
--- a/core/res/res/values-af/strings.xml
+++ b/core/res/res/values-af/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Sien alle"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Kies aktiwiteit"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Deel met"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Stuur tans…"</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Begin webblaaier?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Aanvaar oproep?"</string>
diff --git a/core/res/res/values-am/strings.xml b/core/res/res/values-am/strings.xml
index 40c56cf..5d94a69 100644
--- a/core/res/res/values-am/strings.xml
+++ b/core/res/res/values-am/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"ሁሉንም ተመልከት"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"እንቅስቃሴ ምረጥ"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"ተጋራ ከ"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">"፣ "</string>
     <string name="sending" msgid="3245653681008218030">"በመላክ ላይ…"</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"ማሰሺያን አስነሳ?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"ጥሪ ተቀበል?"</string>
diff --git a/core/res/res/values-ar/strings.xml b/core/res/res/values-ar/strings.xml
index 8e4ffa5..209e1dc 100644
--- a/core/res/res/values-ar/strings.xml
+++ b/core/res/res/values-ar/strings.xml
@@ -1260,7 +1260,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"عرض الكل"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"اختيار نشاط"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"مشاركة مع"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">"، "</string>
     <string name="sending" msgid="3245653681008218030">"جارٍ الإرسال..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"تشغيل المتصفح؟"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"هل تريد قبول المكالمة؟"</string>
diff --git a/core/res/res/values-az-rAZ/strings.xml b/core/res/res/values-az-rAZ/strings.xml
index 868849d..16d123b 100644
--- a/core/res/res/values-az-rAZ/strings.xml
+++ b/core/res/res/values-az-rAZ/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Hamısını seçın"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Fəaliyyəti seçin"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Bununla paylaşın"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Göndərilir..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Brauzer işə salınsın?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Zəngi qəbul edək?"</string>
diff --git a/core/res/res/values-bg/strings.xml b/core/res/res/values-bg/strings.xml
index 110e677..5427659 100644
--- a/core/res/res/values-bg/strings.xml
+++ b/core/res/res/values-bg/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Вижте всички"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Избор на активност"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Споделяне със:"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Изпраща се..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Да се стартира ли браузърът?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Да се приеме ли обаждането?"</string>
diff --git a/core/res/res/values-bn-rBD/strings.xml b/core/res/res/values-bn-rBD/strings.xml
index fea800e..dde02d5 100644
--- a/core/res/res/values-bn-rBD/strings.xml
+++ b/core/res/res/values-bn-rBD/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"সবগুলো দেখুন"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"কার্যকলাপ চয়ন করুন"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"এর সাথে ভাগ করুন"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"পাঠানো হচ্ছে..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"ব্রাউজার লঞ্চ করতে চান?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"কল গ্রহণ করবেন?"</string>
diff --git a/core/res/res/values-ca/strings.xml b/core/res/res/values-ca/strings.xml
index 34fb95e..38baab2 100644
--- a/core/res/res/values-ca/strings.xml
+++ b/core/res/res/values-ca/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Mostra-les totes"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Selecció de l\'activitat"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Comparteix amb"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"S\'està enviant…"</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Vols iniciar el navegador?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Vols acceptar la trucada?"</string>
diff --git a/core/res/res/values-cs/strings.xml b/core/res/res/values-cs/strings.xml
index 3bebb9a..cd6bb4b 100644
--- a/core/res/res/values-cs/strings.xml
+++ b/core/res/res/values-cs/strings.xml
@@ -1244,7 +1244,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Zobrazit vše"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Vybrat aktivitu"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Sdílet s"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Odesílání..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Spustit prohlížeč?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Přijmout hovor?"</string>
diff --git a/core/res/res/values-da/strings.xml b/core/res/res/values-da/strings.xml
index 9973585..e718935 100644
--- a/core/res/res/values-da/strings.xml
+++ b/core/res/res/values-da/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Se alle"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Vælg aktivitet"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Del med"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Sender..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Vil du starte browseren?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Vil du besvare opkaldet?"</string>
diff --git a/core/res/res/values-de/strings.xml b/core/res/res/values-de/strings.xml
index 40519be..fcbd762 100644
--- a/core/res/res/values-de/strings.xml
+++ b/core/res/res/values-de/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Alle anzeigen"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Aktivität wählen"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Teilen mit"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Wird gesendet..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Browser starten?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Anruf annehmen?"</string>
diff --git a/core/res/res/values-el/strings.xml b/core/res/res/values-el/strings.xml
index e4b8aa4..f2bb1d5 100644
--- a/core/res/res/values-el/strings.xml
+++ b/core/res/res/values-el/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Εμφάνιση όλων"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Επιλογή δραστηριότητας"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Κοινή χρήση με"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Γίνεται αποστολή…"</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Εκκίνηση προγράμματος περιήγησης;"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Αποδοχή κλήσης;"</string>
diff --git a/core/res/res/values-en-rAU/strings.xml b/core/res/res/values-en-rAU/strings.xml
index 8062057..28d8eb4 100644
--- a/core/res/res/values-en-rAU/strings.xml
+++ b/core/res/res/values-en-rAU/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"See all"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Choose activity"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Share with"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Sending…"</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Launch Browser?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Accept call?"</string>
diff --git a/core/res/res/values-en-rGB/strings.xml b/core/res/res/values-en-rGB/strings.xml
index 8062057..28d8eb4 100644
--- a/core/res/res/values-en-rGB/strings.xml
+++ b/core/res/res/values-en-rGB/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"See all"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Choose activity"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Share with"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Sending…"</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Launch Browser?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Accept call?"</string>
diff --git a/core/res/res/values-en-rIN/strings.xml b/core/res/res/values-en-rIN/strings.xml
index 8062057..28d8eb4 100644
--- a/core/res/res/values-en-rIN/strings.xml
+++ b/core/res/res/values-en-rIN/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"See all"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Choose activity"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Share with"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Sending…"</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Launch Browser?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Accept call?"</string>
diff --git a/core/res/res/values-es-rUS/strings.xml b/core/res/res/values-es-rUS/strings.xml
index bfd1570..5782eab 100644
--- a/core/res/res/values-es-rUS/strings.xml
+++ b/core/res/res/values-es-rUS/strings.xml
@@ -629,7 +629,7 @@
     <string name="relationTypeFriend" msgid="7313106762483391262">"Amigo"</string>
     <string name="relationTypeManager" msgid="6365677861610137895">"Supervisor"</string>
     <string name="relationTypeMother" msgid="4578571352962758304">"Madre"</string>
-    <string name="relationTypeParent" msgid="4755635567562925226">"Padre"</string>
+    <string name="relationTypeParent" msgid="4755635567562925226">"Padre/madre"</string>
     <string name="relationTypePartner" msgid="7266490285120262781">"Socio"</string>
     <string name="relationTypeReferredBy" msgid="101573059844135524">"Recomendado por"</string>
     <string name="relationTypeRelative" msgid="1799819930085610271">"Pariente"</string>
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Ver todas"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Elige actividad"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Compartir con"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Enviando..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"¿Deseas iniciar el navegador?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"¿Aceptar la llamada?"</string>
diff --git a/core/res/res/values-es/strings.xml b/core/res/res/values-es/strings.xml
index b784cb3..9b65882 100644
--- a/core/res/res/values-es/strings.xml
+++ b/core/res/res/values-es/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Ver todo"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Seleccionar actividad"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Compartir con"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Enviando..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"¿Iniciar el navegador?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"¿Aceptar la llamada?"</string>
diff --git a/core/res/res/values-et-rEE/strings.xml b/core/res/res/values-et-rEE/strings.xml
index 9a6924c..98818ad 100644
--- a/core/res/res/values-et-rEE/strings.xml
+++ b/core/res/res/values-et-rEE/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Kuva kõik"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Tegevuse valimine"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Jagamine rakendusega:"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Saatmine ..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Kas käivitada brauser?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Kas vastata kõnele?"</string>
diff --git a/core/res/res/values-eu-rES/strings.xml b/core/res/res/values-eu-rES/strings.xml
index 5ec09f9..2c7a64d 100644
--- a/core/res/res/values-eu-rES/strings.xml
+++ b/core/res/res/values-eu-rES/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Ikusi guztiak"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Aukeratu jarduera"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Partekatu hauekin:"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Bidaltzen…"</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Arakatzailea abiarazi nahi duzu?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Deia onartu nahi duzu?"</string>
diff --git a/core/res/res/values-fa/strings.xml b/core/res/res/values-fa/strings.xml
index 586e25d..6422355 100644
--- a/core/res/res/values-fa/strings.xml
+++ b/core/res/res/values-fa/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"مشاهدهٔ همه"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"انتخاب فعالیت"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"اشتراک‌گذاری با"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">"، "</string>
     <string name="sending" msgid="3245653681008218030">"در حال ارسال..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"مرورگر راه‌اندازی شود؟"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"تماس را می‌پذیرید؟"</string>
diff --git a/core/res/res/values-fi/strings.xml b/core/res/res/values-fi/strings.xml
index 567c3ea..7298cba 100644
--- a/core/res/res/values-fi/strings.xml
+++ b/core/res/res/values-fi/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Näytä kaikki"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Valitse toiminto"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Jaa seuraavien kanssa"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Lähetetään…"</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Käynnistetäänkö selain?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Vastataanko puheluun?"</string>
diff --git a/core/res/res/values-fr-rCA/strings.xml b/core/res/res/values-fr-rCA/strings.xml
index 36e406e..ba17051 100644
--- a/core/res/res/values-fr-rCA/strings.xml
+++ b/core/res/res/values-fr-rCA/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Tout afficher"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Sélectionnez une activité"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Partagez avec"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Envoi…"</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Lancer le navigateur?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Prendre l\'appel?"</string>
diff --git a/core/res/res/values-fr/strings.xml b/core/res/res/values-fr/strings.xml
index f2e0fa6..2510e03 100644
--- a/core/res/res/values-fr/strings.xml
+++ b/core/res/res/values-fr/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Tout afficher"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Sélectionnez une activité"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Partager avec"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Envoi en cours…"</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Lancer le navigateur ?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Prendre l\'appel ?"</string>
diff --git a/core/res/res/values-gl-rES/strings.xml b/core/res/res/values-gl-rES/strings.xml
index ce68d3e..9979d0f 100644
--- a/core/res/res/values-gl-rES/strings.xml
+++ b/core/res/res/values-gl-rES/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Ver todas"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Seleccionar actividade"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Compartir con"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Enviando..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Iniciar o navegador?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Aceptar chamada?"</string>
diff --git a/core/res/res/values-gu-rIN/strings.xml b/core/res/res/values-gu-rIN/strings.xml
index 638bf02..9392997 100644
--- a/core/res/res/values-gu-rIN/strings.xml
+++ b/core/res/res/values-gu-rIN/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"બધું જુઓ"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"પ્રવૃત્તિ પસંદ કરો"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"આની સાથે શેર કરો"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"મોકલી રહ્યાં છે…"</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"બ્રાઉઝર લોન્ચ કરીએ?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"કૉલ સ્વીકારીએ?"</string>
diff --git a/core/res/res/values-hi/strings.xml b/core/res/res/values-hi/strings.xml
index cfe2279..96eb95c 100644
--- a/core/res/res/values-hi/strings.xml
+++ b/core/res/res/values-hi/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"सभी देखें"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"गतिविधि चुनें"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"इसके साथ साझा करें:"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"भेजा जा रहा है…"</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"ब्राउज़र लॉन्च करें?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"कॉल स्वीकार करें?"</string>
diff --git a/core/res/res/values-hr/strings.xml b/core/res/res/values-hr/strings.xml
index febe600..9b741bc 100644
--- a/core/res/res/values-hr/strings.xml
+++ b/core/res/res/values-hr/strings.xml
@@ -1236,7 +1236,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Prikaži sve"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Odabir aktivnosti"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Dijeljenje s"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Slanje..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Pokrenuti preglednik?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Prihvatiti poziv?"</string>
diff --git a/core/res/res/values-hu/strings.xml b/core/res/res/values-hu/strings.xml
index e393a4a..b063f0c 100644
--- a/core/res/res/values-hu/strings.xml
+++ b/core/res/res/values-hu/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Összes megtekintése"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Tevékenység kiválasztása"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Megosztás"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Küldés…"</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Böngésző indítása?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Fogadja a hívást?"</string>
diff --git a/core/res/res/values-hy-rAM/strings.xml b/core/res/res/values-hy-rAM/strings.xml
index 6d07aa4..a295306 100644
--- a/core/res/res/values-hy-rAM/strings.xml
+++ b/core/res/res/values-hy-rAM/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Տեսնել բոլորը"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Ընտրել գործունեությունը"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Տարածել"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Ուղարկվում է..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Գործարկե՞լ զննարկիչը:"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Ընդունե՞լ զանգը:"</string>
diff --git a/core/res/res/values-in/strings.xml b/core/res/res/values-in/strings.xml
index e93c91e4..27f26a2 100644
--- a/core/res/res/values-in/strings.xml
+++ b/core/res/res/values-in/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Lihat semua"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Pilih kegiatan"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Berbagi dengan"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Mengirim..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Luncurkan Browser?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Terima panggilan?"</string>
diff --git a/core/res/res/values-is-rIS/strings.xml b/core/res/res/values-is-rIS/strings.xml
index fdfdd72..c09914b 100644
--- a/core/res/res/values-is-rIS/strings.xml
+++ b/core/res/res/values-is-rIS/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Sjá allt"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Veldu aðgerð"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Deila með"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Sendir…"</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Opna vafra?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Samþykkja símtal?"</string>
diff --git a/core/res/res/values-it/strings.xml b/core/res/res/values-it/strings.xml
index 7312f2b..4271287 100644
--- a/core/res/res/values-it/strings.xml
+++ b/core/res/res/values-it/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Mostra tutto"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Scegli attività"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Condividi con"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Invio..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Avviare l\'applicazione Browser?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Accettare la chiamata?"</string>
diff --git a/core/res/res/values-iw/strings.xml b/core/res/res/values-iw/strings.xml
index ab9a635..a56332c 100644
--- a/core/res/res/values-iw/strings.xml
+++ b/core/res/res/values-iw/strings.xml
@@ -1244,7 +1244,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"הצג הכל"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"בחר פעילות"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"שתף עם"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"שולח…"</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"להפעיל את הדפדפן?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"האם לקבל את השיחה?"</string>
diff --git a/core/res/res/values-ja/strings.xml b/core/res/res/values-ja/strings.xml
index 67dc9de..2bb0972 100644
--- a/core/res/res/values-ja/strings.xml
+++ b/core/res/res/values-ja/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"すべて表示"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"操作の選択"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"共有"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">"、 "</string>
     <string name="sending" msgid="3245653681008218030">"送信中..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"ブラウザを起動しますか?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"通話を受けますか?"</string>
diff --git a/core/res/res/values-ka-rGE/strings.xml b/core/res/res/values-ka-rGE/strings.xml
index 40d91b4..df302f5 100644
--- a/core/res/res/values-ka-rGE/strings.xml
+++ b/core/res/res/values-ka-rGE/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"ყველას ნახვა"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"აქტივობის არჩევა"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"გაზიარება"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"იგზავნება..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"გსურთ ბრაუზერის გაშვება?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"უპასუხებთ ზარს?"</string>
diff --git a/core/res/res/values-kk-rKZ/strings.xml b/core/res/res/values-kk-rKZ/strings.xml
index 8d9e643f..d39ee05 100644
--- a/core/res/res/values-kk-rKZ/strings.xml
+++ b/core/res/res/values-kk-rKZ/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Барлығын көру"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Әрекет таңдау"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Бөлісу"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Жіберілуде..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Браузер қосылсын ба?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Қоңырауды қабылдау?"</string>
diff --git a/core/res/res/values-km-rKH/strings.xml b/core/res/res/values-km-rKH/strings.xml
index 23d16d6..3a02e76 100644
--- a/core/res/res/values-km-rKH/strings.xml
+++ b/core/res/res/values-km-rKH/strings.xml
@@ -1230,7 +1230,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"មើល​ទាំងអស់"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"ជ្រើស​សកម្មភាព"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"ចែករំលែក​ជា​មួយ"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"កំពុង​ផ្ញើ..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"ចាប់ផ្ដើម​កម្មវិធី​អ៊ីនធឺណិត?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"ទទួល​ការ​ហៅ​?"</string>
diff --git a/core/res/res/values-kn-rIN/strings.xml b/core/res/res/values-kn-rIN/strings.xml
index 9fbd533..0e98430 100644
--- a/core/res/res/values-kn-rIN/strings.xml
+++ b/core/res/res/values-kn-rIN/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"ಎಲ್ಲವನ್ನೂ ನೋಡಿ"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"ಚಟುವಟಿಕೆಯನ್ನು ಆರಿಸಿ"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"ಹಂಚಿಕೊಳ್ಳಿ"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"ಕಳುಹಿಸಲಾಗುತ್ತಿದೆ..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"ಬ್ರೌಸರ್ ಪ್ರಾರಂಭಿಸುವುದೇ?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"ಕರೆ ಸ್ವೀಕರಿಸುವುದೇ?"</string>
diff --git a/core/res/res/values-ko/strings.xml b/core/res/res/values-ko/strings.xml
index 353d6bb..1844214 100644
--- a/core/res/res/values-ko/strings.xml
+++ b/core/res/res/values-ko/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"전체 보기"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"작업 선택"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"공유 대상"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"전송 중..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"브라우저를 실행하시겠습니까?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"통화를 수락하시겠습니까?"</string>
diff --git a/core/res/res/values-ky-rKG/strings.xml b/core/res/res/values-ky-rKG/strings.xml
index aebe1c6..e7e43f0 100644
--- a/core/res/res/values-ky-rKG/strings.xml
+++ b/core/res/res/values-ky-rKG/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Бардыгын көрүү"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Аракетти тандаңыз"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Төмөнкү менен бөлүшүү"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Жөнөтүлүүдө…"</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Серепчи иштетилсинби?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Чалуу кабыл алынсынбы?"</string>
diff --git a/core/res/res/values-lo-rLA/strings.xml b/core/res/res/values-lo-rLA/strings.xml
index 051833f..2e58b116 100644
--- a/core/res/res/values-lo-rLA/strings.xml
+++ b/core/res/res/values-lo-rLA/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"ເບິ່ງທັງຫມົດ"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"ເລືອກກິດຈະກຳ"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"ແບ່ງປັນກັບ"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"ກຳລັງສົ່ງ..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"ເປີດໂປຣແກຣມທ່ອງເວັບ?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"ຮັບການໂທບໍ່?"</string>
diff --git a/core/res/res/values-lt/strings.xml b/core/res/res/values-lt/strings.xml
index 7189c4b..eb2903f3 100644
--- a/core/res/res/values-lt/strings.xml
+++ b/core/res/res/values-lt/strings.xml
@@ -1244,7 +1244,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Žr. viską"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Pasirinkti veiklą"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Bendrinti su"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Siunčiama…"</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Paleisti naršyklę?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Priimti skambutį?"</string>
diff --git a/core/res/res/values-lv/strings.xml b/core/res/res/values-lv/strings.xml
index 63ad122..7f10900 100644
--- a/core/res/res/values-lv/strings.xml
+++ b/core/res/res/values-lv/strings.xml
@@ -1236,7 +1236,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Skatīt visu"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Darbības izvēle"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Kopīgošana ar:"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Notiek sūtīšana…"</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Vai palaist pārlūkprogrammu?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Vai atbildēt uz zvanu?"</string>
diff --git a/core/res/res/values-mk-rMK/strings.xml b/core/res/res/values-mk-rMK/strings.xml
index d818a9d..f10fb19 100644
--- a/core/res/res/values-mk-rMK/strings.xml
+++ b/core/res/res/values-mk-rMK/strings.xml
@@ -1230,7 +1230,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Види ги сите"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Избери активност"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Сподели со"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Се праќа..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Стартувај прелистувач?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Прифати повик?"</string>
diff --git a/core/res/res/values-ml-rIN/strings.xml b/core/res/res/values-ml-rIN/strings.xml
index dc4749f..43264a7 100644
--- a/core/res/res/values-ml-rIN/strings.xml
+++ b/core/res/res/values-ml-rIN/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"എല്ലാം കാണുക"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"പ്രവർത്തനം തിരഞ്ഞെടുക്കുക"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"ഇവരുമായി പങ്കിടുക"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"അയയ്‌ക്കുന്നു…"</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"ബ്രൗസർ സമാരംഭിക്കണോ?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"കോൾ സ്വീകരിക്കണോ?"</string>
diff --git a/core/res/res/values-mn-rMN/strings.xml b/core/res/res/values-mn-rMN/strings.xml
index 4b568ec..3b5531d 100644
--- a/core/res/res/values-mn-rMN/strings.xml
+++ b/core/res/res/values-mn-rMN/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Бүгдийг харах"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Активити сонгох"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Хуваалцах"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Илгээж байна ..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Хөтөч ажиллуулах уу?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Дуудлагыг зөвшөөрөх үү?"</string>
diff --git a/core/res/res/values-mr-rIN/strings.xml b/core/res/res/values-mr-rIN/strings.xml
index 45e6358..5956634 100644
--- a/core/res/res/values-mr-rIN/strings.xml
+++ b/core/res/res/values-mr-rIN/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"सर्व पहा"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"क्रियाकलाप निवडा"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"यांच्यासह सामायिक करा"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"पाठवित आहे..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"ब्राउझर लाँच करायचा?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"कॉल स्वीकारायचा?"</string>
diff --git a/core/res/res/values-ms-rMY/strings.xml b/core/res/res/values-ms-rMY/strings.xml
index dc30d38..b69010e 100644
--- a/core/res/res/values-ms-rMY/strings.xml
+++ b/core/res/res/values-ms-rMY/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Lihat semua"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Pilih aktiviti"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Kongsi dengan"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Menghantar…"</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Lancarkan Penyemak Imbas?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Terima panggilan?"</string>
diff --git a/core/res/res/values-my-rMM/strings.xml b/core/res/res/values-my-rMM/strings.xml
index 135605b..a547ca7 100644
--- a/core/res/res/values-my-rMM/strings.xml
+++ b/core/res/res/values-my-rMM/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"အားလုံးကို ကြည့်ရန်"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"လှုပ်ရှားမှုကို ရွေးရန်"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"...နှင့် မျှဝေရန်"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"ပေးပို့နေစဉ်…"</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"ဘရောက်ဇာ ဖွင့်မည်လား။"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"ဖုန်းခေါ်ဆိုမှုကို လက်ခံမလား?"</string>
diff --git a/core/res/res/values-nb/strings.xml b/core/res/res/values-nb/strings.xml
index ae43e25..b43314b 100644
--- a/core/res/res/values-nb/strings.xml
+++ b/core/res/res/values-nb/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Se alle"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Velg aktivitet"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Deling med"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Sender …"</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Vil du starte nettleseren?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Vil du besvare anropet?"</string>
diff --git a/core/res/res/values-ne-rNP/strings.xml b/core/res/res/values-ne-rNP/strings.xml
index b0643ea..ac529114 100644
--- a/core/res/res/values-ne-rNP/strings.xml
+++ b/core/res/res/values-ne-rNP/strings.xml
@@ -1234,7 +1234,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"सबै हेर्नुहोस्"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"गतिविधि छनौट गर्नुहोस्"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"साझेदारी गर्नुहोस्..."</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"पठाउँदै..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"ब्राउजर सुरु गर्ने हो?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"कल स्वीकार गर्नुहुन्छ?"</string>
@@ -1501,7 +1500,7 @@
     <string name="usb_midi_peripheral_product_name" msgid="4971827859165280403">"USB पेरिफेरल पोर्ट"</string>
     <string name="floating_toolbar_open_overflow_description" msgid="4797287862999444631">"थप विकल्पहरू"</string>
     <string name="floating_toolbar_close_overflow_description" msgid="559796923090723804">"ओभरफ्लो बन्द गर्नुहोस्"</string>
-    <string name="maximize_button_text" msgid="7543285286182446254">"अधिकतम गर्नुहोस्"</string>
+    <string name="maximize_button_text" msgid="7543285286182446254">"ठूलो बनाउनुहोस्"</string>
     <string name="close_button_text" msgid="3937902162644062866">"बन्द गर्नुहोस्"</string>
     <plurals name="selected_count" formatted="false" msgid="7187339492915744615">
       <item quantity="other"><xliff:g id="COUNT_1">%1$d</xliff:g> चयन गरियो</item>
diff --git a/core/res/res/values-nl/strings.xml b/core/res/res/values-nl/strings.xml
index 5be486a..cfdd69b 100644
--- a/core/res/res/values-nl/strings.xml
+++ b/core/res/res/values-nl/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Alles weergeven"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Een activiteit kiezen"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Delen met"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Verzenden..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Browser starten?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Oproep accepteren?"</string>
diff --git a/core/res/res/values-pa-rIN/strings.xml b/core/res/res/values-pa-rIN/strings.xml
index 7306582..e1276f1 100644
--- a/core/res/res/values-pa-rIN/strings.xml
+++ b/core/res/res/values-pa-rIN/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"ਸਭ ਦੇਖੋ"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"ਗਤੀਵਿਧੀ ਚੁਣੋ"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"ਇਸ ਨਾਲ ਸ਼ੇਅਰ ਕਰੋ"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"ਭੇਜ ਰਿਹਾ ਹੈ..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"ਕੀ ਬ੍ਰਾਊਜ਼ਰ ਲੌਂਚ ਕਰਨਾ ਹੈ?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"ਕੀ ਕਾਲ ਸਵੀਕਾਰ ਕਰਨੀ ਹੈ?"</string>
diff --git a/core/res/res/values-pl/strings.xml b/core/res/res/values-pl/strings.xml
index f220b25..1086601 100644
--- a/core/res/res/values-pl/strings.xml
+++ b/core/res/res/values-pl/strings.xml
@@ -1244,7 +1244,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Zobacz wszystkie"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Wybierz działanie"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Udostępnij przez:"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Wysyłanie..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Uruchomić przeglądarkę?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Odebrać połączenie?"</string>
diff --git a/core/res/res/values-pt-rBR/strings.xml b/core/res/res/values-pt-rBR/strings.xml
index bd0c90c..d203a6a 100644
--- a/core/res/res/values-pt-rBR/strings.xml
+++ b/core/res/res/values-pt-rBR/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Ver tudo"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Selecione a atividade"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Compartilhar com"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Enviando..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Abrir Navegador?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Aceitar chamada?"</string>
diff --git a/core/res/res/values-pt-rPT/strings.xml b/core/res/res/values-pt-rPT/strings.xml
index 7eb3809..e14303d 100644
--- a/core/res/res/values-pt-rPT/strings.xml
+++ b/core/res/res/values-pt-rPT/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Ver tudo"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Escolher atividade"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Partilhar com"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"A enviar..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Iniciar Navegador?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Aceitar chamada?"</string>
diff --git a/core/res/res/values-pt/strings.xml b/core/res/res/values-pt/strings.xml
index bd0c90c..d203a6a 100644
--- a/core/res/res/values-pt/strings.xml
+++ b/core/res/res/values-pt/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Ver tudo"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Selecione a atividade"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Compartilhar com"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Enviando..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Abrir Navegador?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Aceitar chamada?"</string>
diff --git a/core/res/res/values-ro/strings.xml b/core/res/res/values-ro/strings.xml
index 515d23c..637ade49 100644
--- a/core/res/res/values-ro/strings.xml
+++ b/core/res/res/values-ro/strings.xml
@@ -1236,7 +1236,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Afişaţi-le pe toate"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Alegeţi activitatea"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Distribuiţi pentru"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Se trimite..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Lansaţi browserul?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Acceptați apelul?"</string>
diff --git a/core/res/res/values-ru/strings.xml b/core/res/res/values-ru/strings.xml
index c3e7411..e0ea9c0f0 100644
--- a/core/res/res/values-ru/strings.xml
+++ b/core/res/res/values-ru/strings.xml
@@ -1244,7 +1244,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Показать все"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Выберите"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Открыть доступ"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Отправка..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Запустить браузер?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Ответить?"</string>
diff --git a/core/res/res/values-si-rLK/strings.xml b/core/res/res/values-si-rLK/strings.xml
index c8fae8f..d5bafd25 100644
--- a/core/res/res/values-si-rLK/strings.xml
+++ b/core/res/res/values-si-rLK/strings.xml
@@ -1230,7 +1230,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"සියල්ල බලන්න"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"ක්‍රියාකාරකම තෝරන්න"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"සමඟ බෙදාගන්න"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"යවමින්..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"බ්‍රවුසරය දියත් කරන්නද?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"ඇමතුම පිළිගන්නවාද?"</string>
diff --git a/core/res/res/values-sk/strings.xml b/core/res/res/values-sk/strings.xml
index fc17568..8432348 100644
--- a/core/res/res/values-sk/strings.xml
+++ b/core/res/res/values-sk/strings.xml
@@ -1244,7 +1244,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Zobraziť všetky"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Vybrať aktivitu"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Zdieľať s"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Odosielanie..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Spustiť prehliadač?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Prijať hovor?"</string>
diff --git a/core/res/res/values-sl/strings.xml b/core/res/res/values-sl/strings.xml
index 941f3a1..cf87e2a 100644
--- a/core/res/res/values-sl/strings.xml
+++ b/core/res/res/values-sl/strings.xml
@@ -1244,7 +1244,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Pokaži vse"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Izberite dejavnost"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Delite z"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Pošiljanje ..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Ali želite odpreti brskalnik?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Ali želite sprejeti klic?"</string>
diff --git a/core/res/res/values-sq-rAL/strings.xml b/core/res/res/values-sq-rAL/strings.xml
index 65d4d19..86f9d11 100644
--- a/core/res/res/values-sq-rAL/strings.xml
+++ b/core/res/res/values-sq-rAL/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Shikoji të gjitha"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Zgjidh aktivitetin"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Shpërnda publikisht me"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Po dërgon…"</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Të hapet shfletuesi?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Dëshiron ta pranosh telefonatën?"</string>
diff --git a/core/res/res/values-sr/strings.xml b/core/res/res/values-sr/strings.xml
index 0b5be6b..a3a4b32 100644
--- a/core/res/res/values-sr/strings.xml
+++ b/core/res/res/values-sr/strings.xml
@@ -1236,7 +1236,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Прикажи све"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Избор активности"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Дели са"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Слање..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Желите ли да покренете прегледач?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Желите ли да прихватите позив?"</string>
diff --git a/core/res/res/values-sv/strings.xml b/core/res/res/values-sv/strings.xml
index f5bd759..237afe7 100644
--- a/core/res/res/values-sv/strings.xml
+++ b/core/res/res/values-sv/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Visa alla"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Välj aktivitet"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Dela med"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Skickar ..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Vill du öppna webbläsaren?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Vill du ta emot samtal?"</string>
diff --git a/core/res/res/values-sw/strings.xml b/core/res/res/values-sw/strings.xml
index b34c115..6445f6a 100644
--- a/core/res/res/values-sw/strings.xml
+++ b/core/res/res/values-sw/strings.xml
@@ -1230,7 +1230,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Angalia zote"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Chagua shughuli"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Shiriki na"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Inatuma…"</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Zindua Kivinjari?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Kubali simu?"</string>
diff --git a/core/res/res/values-ta-rIN/strings.xml b/core/res/res/values-ta-rIN/strings.xml
index 14d0c35..569fe82 100644
--- a/core/res/res/values-ta-rIN/strings.xml
+++ b/core/res/res/values-ta-rIN/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"எல்லாம் காட்டு"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"செயல்பாட்டைத் தேர்வுசெய்க"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"இதனுடன் பகிர்"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"அனுப்புகிறது…"</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"உலாவியைத் துவக்கவா?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"அழைப்பை ஏற்கவா?"</string>
diff --git a/core/res/res/values-te-rIN/strings.xml b/core/res/res/values-te-rIN/strings.xml
index d15148c..77588b3 100644
--- a/core/res/res/values-te-rIN/strings.xml
+++ b/core/res/res/values-te-rIN/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"అన్నీ చూడండి"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"కార్యాచరణను ఎంచుకోండి"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"వీటితో భాగస్వామ్యం చేయండి"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"పంపుతోంది..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"బ్రౌజర్‌ను ప్రారంభించాలా?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"కాల్‌ను ఆమోదించాలా?"</string>
diff --git a/core/res/res/values-th/strings.xml b/core/res/res/values-th/strings.xml
index 78d1c2e..9804f99 100644
--- a/core/res/res/values-th/strings.xml
+++ b/core/res/res/values-th/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"ดูทั้งหมด"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"เลือกกิจกรรม"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"แชร์กับ"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"กำลังส่ง…"</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"เปิดเบราว์เซอร์หรือไม่"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"รับสายหรือไม่"</string>
diff --git a/core/res/res/values-tl/strings.xml b/core/res/res/values-tl/strings.xml
index b8a82eb..78c9358c 100644
--- a/core/res/res/values-tl/strings.xml
+++ b/core/res/res/values-tl/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Tingnan lahat"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Pumili ng aktibidad"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Ibahagi sa"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Ipinapadala..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Ilunsad ang Browser?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Tanggapin ang tawag?"</string>
diff --git a/core/res/res/values-tr/strings.xml b/core/res/res/values-tr/strings.xml
index 8140caf..37d9bac 100644
--- a/core/res/res/values-tr/strings.xml
+++ b/core/res/res/values-tr/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Tümünü göster"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Etkinlik seçin"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Şununla paylaş:"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Gönderiliyor…"</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Tarayıcı Başlatılsın mı?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Çağrı kabul edilsin mi?"</string>
diff --git a/core/res/res/values-uk/strings.xml b/core/res/res/values-uk/strings.xml
index d3b6500..1aa1a51 100644
--- a/core/res/res/values-uk/strings.xml
+++ b/core/res/res/values-uk/strings.xml
@@ -1244,7 +1244,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Переглянути всі"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Вибрати дію"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Спільний доступ для:"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Надсилання…"</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Запустити веб-переглядач?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Прийняти виклик?"</string>
diff --git a/core/res/res/values-ur-rPK/strings.xml b/core/res/res/values-ur-rPK/strings.xml
index 21e9e03..aa46949 100644
--- a/core/res/res/values-ur-rPK/strings.xml
+++ b/core/res/res/values-ur-rPK/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"سبھی دیکھیں"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"سرگرمی منتخب کریں"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"اس کے ساتھ اشتراک کریں"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">"، "</string>
     <string name="sending" msgid="3245653681008218030">"بھیج رہا ہے…"</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"براؤزر شروع کریں؟"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"کال قبول کریں؟"</string>
diff --git a/core/res/res/values-uz-rUZ/strings.xml b/core/res/res/values-uz-rUZ/strings.xml
index 68a5d9d..492f3d7 100644
--- a/core/res/res/values-uz-rUZ/strings.xml
+++ b/core/res/res/values-uz-rUZ/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Barchasini ko‘rish"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Harakat turini tanlang"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Ulashish"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Jo‘natilmoqda…"</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Brauzer ishga tushirilsinmi?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Qo‘ng‘iroqni qabul qilasizmi?"</string>
diff --git a/core/res/res/values-vi/strings.xml b/core/res/res/values-vi/strings.xml
index 886bbec..439b9f2 100644
--- a/core/res/res/values-vi/strings.xml
+++ b/core/res/res/values-vi/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Xem tất cả"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Chọn hoạt động"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Chia sẻ với"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Đang gửi…"</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Chạy trình duyệt?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Chấp nhận cuộc gọi?"</string>
diff --git a/core/res/res/values-zh-rCN/strings.xml b/core/res/res/values-zh-rCN/strings.xml
index dc44593..c13ef14 100644
--- a/core/res/res/values-zh-rCN/strings.xml
+++ b/core/res/res/values-zh-rCN/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"查看全部"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"选择活动"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"分享方式"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"正在发送..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"要启动浏览器吗?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"要接听电话吗?"</string>
diff --git a/core/res/res/values-zh-rHK/strings.xml b/core/res/res/values-zh-rHK/strings.xml
index cfeb274..4c713c9 100644
--- a/core/res/res/values-zh-rHK/strings.xml
+++ b/core/res/res/values-zh-rHK/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"查看全部"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"選擇活動"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"分享活動"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">"、 "</string>
     <string name="sending" msgid="3245653681008218030">"正在傳送..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"要啟動「瀏覽器」嗎?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"接聽電話嗎?"</string>
diff --git a/core/res/res/values-zh-rTW/strings.xml b/core/res/res/values-zh-rTW/strings.xml
index 1ac240f..46f0d2c 100644
--- a/core/res/res/values-zh-rTW/strings.xml
+++ b/core/res/res/values-zh-rTW/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"全部顯示"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"選擇活動"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"分享活動"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">"、 "</string>
     <string name="sending" msgid="3245653681008218030">"傳送中…"</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"啟動「瀏覽器」嗎?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"接聽電話嗎?"</string>
diff --git a/core/res/res/values-zu/strings.xml b/core/res/res/values-zu/strings.xml
index e8c7ca3..0ecd571 100644
--- a/core/res/res/values-zu/strings.xml
+++ b/core/res/res/values-zu/strings.xml
@@ -1228,7 +1228,6 @@
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Buka konke"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Khetha okwenziwayo"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Yabelana no"</string>
-    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
     <string name="sending" msgid="3245653681008218030">"Iyathumela..."</string>
     <string name="launchBrowserDefault" msgid="2057951947297614725">"Qala Isiphequluli?"</string>
     <string name="SetupCallDefault" msgid="5834948469253758575">"Amukela ucingo?"</string>
diff --git a/core/res/res/values/arrays.xml b/core/res/res/values/arrays.xml
index a3cc4ae..33c41ef 100644
--- a/core/res/res/values/arrays.xml
+++ b/core/res/res/values/arrays.xml
@@ -77,50 +77,6 @@
        <item>@drawable/btn_default_disabled_focused_holo_dark</item>
        <item>@drawable/btn_default_holo_dark</item>
        <item>@drawable/btn_default_holo_light</item>
-       <item>@drawable/btn_star_off_normal_holo_light</item>
-       <item>@drawable/btn_star_on_normal_holo_light</item>
-       <item>@drawable/btn_star_on_disabled_holo_light</item>
-       <item>@drawable/btn_star_off_disabled_holo_light</item>
-       <item>@drawable/btn_star_on_pressed_holo_light</item>
-       <item>@drawable/btn_star_off_pressed_holo_light</item>
-       <item>@drawable/btn_star_on_focused_holo_light</item>
-       <item>@drawable/btn_star_off_focused_holo_light</item>
-       <item>@drawable/btn_star_on_disabled_focused_holo_light</item>
-       <item>@drawable/btn_star_off_disabled_focused_holo_light</item>
-       <item>@drawable/btn_star_holo_light</item>
-       <item>@drawable/btn_star_off_normal_holo_dark</item>
-       <item>@drawable/btn_star_on_normal_holo_dark</item>
-       <item>@drawable/btn_star_on_disabled_holo_dark</item>
-       <item>@drawable/btn_star_off_disabled_holo_dark</item>
-       <item>@drawable/btn_star_on_pressed_holo_dark</item>
-       <item>@drawable/btn_star_off_pressed_holo_dark</item>
-       <item>@drawable/btn_star_on_focused_holo_dark</item>
-       <item>@drawable/btn_star_off_focused_holo_dark</item>
-       <item>@drawable/btn_star_on_disabled_focused_holo_dark</item>
-       <item>@drawable/btn_star_off_disabled_focused_holo_dark</item>
-       <item>@drawable/btn_star_holo_dark</item>
-       <item>@drawable/btn_toggle_on_pressed_holo_light</item>
-       <item>@drawable/btn_toggle_on_pressed_holo_dark</item>
-       <item>@drawable/btn_toggle_on_normal_holo_light</item>
-       <item>@drawable/btn_toggle_on_normal_holo_dark</item>
-       <item>@drawable/btn_toggle_on_focused_holo_light</item>
-       <item>@drawable/btn_toggle_on_focused_holo_dark</item>
-       <item>@drawable/btn_toggle_on_disabled_holo_light</item>
-       <item>@drawable/btn_toggle_on_disabled_holo_dark</item>
-       <item>@drawable/btn_toggle_on_disabled_focused_holo_light</item>
-       <item>@drawable/btn_toggle_on_disabled_focused_holo_dark</item>
-       <item>@drawable/btn_toggle_off_pressed_holo_light</item>
-       <item>@drawable/btn_toggle_off_pressed_holo_dark</item>
-       <item>@drawable/btn_toggle_off_normal_holo_light</item>
-       <item>@drawable/btn_toggle_off_normal_holo_dark</item>
-       <item>@drawable/btn_toggle_off_focused_holo_light</item>
-       <item>@drawable/btn_toggle_off_focused_holo_dark</item>
-       <item>@drawable/btn_toggle_off_disabled_holo_light</item>
-       <item>@drawable/btn_toggle_off_disabled_holo_dark</item>
-       <item>@drawable/btn_toggle_off_disabled_focused_holo_light</item>
-       <item>@drawable/btn_toggle_off_disabled_focused_holo_dark</item>
-       <item>@drawable/btn_toggle_holo_light</item>
-       <item>@drawable/btn_toggle_holo_dark</item>
        <item>@drawable/edit_text_holo_light</item>
        <item>@drawable/edit_text_holo_dark</item>
        <item>@drawable/text_cursor_holo_light</item>
@@ -136,26 +92,18 @@
        <item>@drawable/list_selector_holo_light</item>
        <item>@drawable/list_section_divider_holo_light</item>
        <item>@drawable/list_section_divider_holo_dark</item>
-       <item>@drawable/menu_hardkey_panel_holo_dark</item>
-       <item>@drawable/menu_hardkey_panel_holo_light</item>
-       <item>@drawable/menu_submenu_background</item>
        <item>@drawable/menu_dropdown_panel_holo_light</item>
        <item>@drawable/menu_dropdown_panel_holo_dark</item>
-       <item>@drawable/menu_popup_panel_holo_light</item>
-       <item>@drawable/menu_popup_panel_holo_dark</item>
        <item>@drawable/menu_panel_holo_light</item>
        <item>@drawable/menu_panel_holo_dark</item>
        <item>@drawable/spinner_16_outer_holo</item>
        <item>@drawable/spinner_16_inner_holo</item>
        <item>@drawable/spinner_48_outer_holo</item>
        <item>@drawable/spinner_48_inner_holo</item>
-       <item>@drawable/spinner_76_outer_holo</item>
-       <item>@drawable/spinner_76_inner_holo</item>
        <item>@drawable/progress_bg_holo_dark</item>
        <item>@drawable/progress_bg_holo_light</item>
        <item>@drawable/progress_horizontal_holo_dark</item>
        <item>@drawable/progress_horizontal_holo_light</item>
-       <item>@drawable/progress_indeterminate_horizontal_holo</item>
        <item>@drawable/progress_large_holo</item>
        <item>@drawable/progress_medium_holo</item>
        <item>@drawable/progress_primary_holo_dark</item>
diff --git a/core/res/res/values/attrs.xml b/core/res/res/values/attrs.xml
index 99beef8..61af6c5 100644
--- a/core/res/res/values/attrs.xml
+++ b/core/res/res/values/attrs.xml
@@ -1814,6 +1814,10 @@
         <enum name="KEYCODE_DPAD_DOWN_LEFT" value="269" />
         <enum name="KEYCODE_DPAD_UP_RIGHT" value="270" />
         <enum name="KEYCODE_DPAD_DOWN_RIGHT" value="271" />
+        <enum name="KEYCODE_MEDIA_SKIP_FORWARD" value="272" />
+        <enum name="KEYCODE_MEDIA_SKIP_BACKWARD" value="273" />
+        <enum name="KEYCODE_MEDIA_STEP_FORWARD" value="274" />
+        <enum name="KEYCODE_MEDIA_STEP_BACKWARD" value="275" />
     </attr>
 
     <!-- ***************************************************************** -->
@@ -4481,6 +4485,8 @@
             <enum name="wrap_content" value="-2" />
         </attr>
         <attr name="inputType" />
+        <!-- Theme to use for the completion popup window. -->
+        <attr name="popupTheme" />
     </declare-styleable>
     <declare-styleable name="PopupWindow">
         <!-- The background to use for the popup window. -->
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index 398c584..01ab624 100755
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -1271,7 +1271,7 @@
 
          If this string is empty or the specified package does not exist, then
          the platform will search for an SMS app and use that (if there is one)-->
-    <string name="default_sms_application" translatable="false"></string>
+    <string name="default_sms_application" translatable="false">com.android.messaging</string>
 
     <!-- Default web browser.  This is the package name of the application that will
          be the default browser when the device first boots.  Afterwards the user
diff --git a/core/tests/coretests/src/android/animation/AnimatorSetActivityTest.java b/core/tests/coretests/src/android/animation/AnimatorSetActivityTest.java
index af0c9cd..c66fd15 100644
--- a/core/tests/coretests/src/android/animation/AnimatorSetActivityTest.java
+++ b/core/tests/coretests/src/android/animation/AnimatorSetActivityTest.java
@@ -3,6 +3,7 @@
 import com.android.frameworks.coretests.R;
 
 import android.test.ActivityInstrumentationTestCase2;
+import android.test.UiThreadTest;
 import android.test.suitebuilder.annotation.SmallTest;
 import android.view.View;
 
@@ -18,6 +19,32 @@
         super(AnimatorSetActivity.class);
     }
 
+    static class MyListener implements Animator.AnimatorListener {
+        boolean startIsCalled = false;
+        boolean endIsCalled = false;
+        boolean cancelIsCalled = false;
+
+        @Override
+        public void onAnimationStart(Animator animation) {
+            startIsCalled = true;
+        }
+
+        @Override
+        public void onAnimationEnd(Animator animation) {
+            endIsCalled = true;
+        }
+
+        @Override
+        public void onAnimationCancel(Animator animation) {
+            cancelIsCalled = true;
+        }
+
+        @Override
+        public void onAnimationRepeat(Animator animation) {
+
+        }
+    }
+
     @Override
     public void setUp() throws Exception {
         super.setUp();
@@ -86,12 +113,7 @@
 
     @SmallTest
     public void testTotalDuration() {
-        ArrayList<Animator> list = new ArrayList<>(5);
-        list.add(a1);
-        list.add(a2);
-        list.add(a3);
-        list.add(a4);
-        list.add(a5);
+        ArrayList<Animator> list = getAnimatorList();
 
         // Run animations sequentially and test the total duration against sum of durations.
         AnimatorSet s1 = new AnimatorSet();
@@ -152,4 +174,328 @@
 
     }
 
+    @SmallTest
+    public void testGetDuration() {
+        AnimatorSet s = new AnimatorSet();
+        assertTrue(s.getDuration() < 0);
+        s.play(a1).before(a2).before(a3).after(a4).after(a5);
+        assertTrue(s.getDuration() < 0);
+
+        long duration = 200;
+        s.setDuration(duration);
+        assertEquals(duration, s.getDuration());
+
+    }
+
+    @SmallTest
+    @UiThreadTest
+    public void testSetDuration() {
+        AnimatorSet s = getSequentialSet();
+        assertTrue(s.getDuration() < 0);
+
+        long duration = 300;
+        s.setDuration(duration);
+        assertEquals(duration, s.getDuration());
+
+        s.start();
+        assertEquals(duration, s.getDuration());
+        assertEquals(duration, a1.getDuration());
+        assertEquals(duration, a2.getDuration());
+        assertEquals(duration, a3.getDuration());
+        assertEquals(duration, a4.getDuration());
+        assertEquals(duration, a5.getDuration());
+    }
+
+    @SmallTest
+    public void testAddListener() throws InterruptedException {
+        // Verify that the listener is added to the list of listeners in the AnimatorSet
+        // and that newly added listener gets callback for lifecycle events of the animator
+        final AnimatorSet s = new AnimatorSet();
+        s.play(a1).before(a2).before(a3).after(a4).after(a5);
+        final MyListener listener = new MyListener();
+        if (s.getListeners() != null) {
+            assertFalse(s.getListeners().contains(listener));
+        }
+        s.addListener(listener);
+        assertTrue(s.getListeners().contains(listener));
+
+        assertFalse(listener.startIsCalled);
+        assertFalse(listener.endIsCalled);
+
+        try {
+            runTestOnUiThread(new Runnable() {
+                @Override
+                public void run() {
+                    s.start();
+                    assertTrue(listener.startIsCalled);
+                    assertFalse(listener.endIsCalled);
+                }
+            });
+        } catch (Throwable throwable) {
+            throwable.printStackTrace();
+        }
+
+        Thread.sleep(s.getTotalDuration() + 200);
+        assertTrue(listener.startIsCalled);
+        assertTrue(listener.endIsCalled);
+    }
+
+    @SmallTest
+    public void testRemoveListener() throws Throwable {
+        final AnimatorSet s = new AnimatorSet();
+        s.playTogether(a1, a2, a3, a4);
+        MyListener listener = new MyListener();
+        s.addListener(listener);
+        runTestOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                s.start();
+            }
+        });
+
+        Thread.sleep(s.getTotalDuration() + 100);
+        assertTrue(listener.startIsCalled);
+        assertTrue(listener.endIsCalled);
+
+        s.removeListener(listener);
+        if (s.getListeners() != null) {
+            assertFalse(s.getListeners().contains(listener));
+        }
+        listener.startIsCalled = false;
+        listener.endIsCalled = false;
+
+        runTestOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                s.start();
+            }
+        });
+        Thread.sleep(s.getTotalDuration() + 100);
+        assertFalse(listener.startIsCalled);
+        assertFalse(listener.endIsCalled);
+    }
+
+    @SmallTest
+    public void testEnd() throws Throwable {
+        // End animator set
+        final AnimatorSet s = new AnimatorSet();
+        s.play(a1).before(a2).after(a3).with(a4);
+        final MyListener listener = new MyListener();
+        s.addListener(listener);
+        assertFalse(listener.endIsCalled);
+        runTestOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                s.start();
+                assertTrue(s.isStarted());
+                assertTrue(listener.startIsCalled);
+                assertFalse(listener.endIsCalled);
+            }
+        });
+
+        Thread.sleep(a2.getTotalDuration());
+
+        runTestOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                s.end();
+                assertTrue(listener.startIsCalled);
+                assertTrue(listener.endIsCalled);
+                assertFalse(s.isRunning());
+                assertFalse(s.isStarted());
+
+                assertFalse(a1.isStarted());
+                assertFalse(a2.isStarted());
+                assertFalse(a3.isStarted());
+                assertFalse(a4.isStarted());
+            }
+        });
+
+    }
+
+    @SmallTest
+    public void testStart() throws Throwable {
+        final AnimatorSet s = new AnimatorSet();
+        ArrayList<Animator> animators = getAnimatorList();
+
+        s.playSequentially(animators);
+        final MyListener l = new MyListener();
+        s.addListener(l);
+
+        ArrayList<MyListener> listeners = new ArrayList<>(animators.size());
+        for (int i = 0; i < animators.size(); i++) {
+            MyListener listener = new MyListener();
+            listeners.add(listener);
+            animators.get(i).addListener(listener);
+        }
+
+        // Check the state before calling start()
+        assertFalse(l.startIsCalled);
+        assertFalse(l.endIsCalled);
+        for (int i = 0; i < listeners.size(); i++) {
+            assertFalse(l.startIsCalled);
+            assertFalse(l.endIsCalled);
+        }
+
+        runTestOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                s.start();
+                assertTrue(l.startIsCalled);
+            }
+        });
+
+        long timeout = s.getTotalDuration() * 2;
+        long wait = 0;
+
+        while (wait < timeout) {
+            if (l.endIsCalled) {
+                break;
+            }
+            Thread.sleep(200);
+            wait += 200;
+        }
+
+        // Now the set should finished
+        assertTrue(l.startIsCalled);
+        assertTrue(l.endIsCalled);
+        for (int i = 0; i < listeners.size(); i++) {
+            assertTrue(listeners.get(i).startIsCalled);
+            assertTrue(listeners.get(i).endIsCalled);
+        }
+    }
+
+    @SmallTest
+    public void testCancel() throws Throwable {
+        // Check whether cancel would trigger onAnimationCanceled and cancel all the unfinished
+        // animations
+        final AnimatorSet s = new AnimatorSet();
+        final ArrayList<Animator> animators = getAnimatorList();
+
+        s.playTogether(animators);
+        final MyListener l = new MyListener();
+        s.addListener(l);
+
+        final ArrayList<MyListener> listeners = new ArrayList<>(5);
+        for (int i = 0; i < animators.size(); i++) {
+            MyListener listener = new MyListener();
+            listeners.add(listener);
+            animators.get(i).addListener(listener);
+        }
+
+        // Check the state before calling start()
+        assertFalse(l.startIsCalled);
+        assertFalse(l.cancelIsCalled);
+        assertFalse(l.endIsCalled);
+        for (int i = 0; i < listeners.size(); i++) {
+            assertFalse(l.startIsCalled);
+            assertFalse(l.cancelIsCalled);
+            assertFalse(l.endIsCalled);
+        }
+
+        runTestOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                s.start();
+            }
+        });
+
+        Thread.sleep(a1.getTotalDuration());
+        runTestOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                assertTrue(s.isStarted());
+                ArrayList<Integer> runningAnimIds = new ArrayList<Integer>();
+                for (int i = 0; i < animators.size(); i++) {
+                    if (animators.get(i).isStarted()) {
+                        runningAnimIds.add(i);
+                    }
+                }
+                s.cancel();
+                assertTrue(l.startIsCalled);
+                assertTrue(l.cancelIsCalled);
+                assertTrue(l.endIsCalled);
+
+                for (int i = 0; i < listeners.size(); i++) {
+                    assertTrue(listeners.get(i).startIsCalled);
+                    if (runningAnimIds.contains(i)) {
+                        assertTrue(listeners.get(i).cancelIsCalled);
+                    }
+                    assertTrue(listeners.get(i).endIsCalled);
+                }
+            }
+        });
+
+    }
+
+    @SmallTest
+    public void testIsRunning() throws Throwable {
+        final AnimatorSet s = new AnimatorSet();
+        final long startDelay = 500;
+        s.play(a1).before(a2).after(a3).with(a4);
+        s.play(a3).after(a5);
+        s.setStartDelay(startDelay);
+        MyListener listener = new MyListener();
+        s.addListener(listener);
+        runTestOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                s.start();
+            }
+        });
+
+        while (!listener.endIsCalled) {
+            boolean passedStartDelay = a1.isStarted() || a2.isStarted() || a3.isStarted() ||
+                    a4.isStarted() || a5.isStarted();
+            assertEquals(passedStartDelay, s.isRunning());
+            Thread.sleep(50);
+        }
+        assertFalse(s.isRunning());
+    }
+
+    @SmallTest
+    public void testPauseAndResume() throws Throwable {
+        final AnimatorSet set = getSequentialSet();
+        runTestOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                // Calling pause before start should have no effect, per documentation
+                set.pause();
+                set.start();
+                assertFalse(set.isPaused());
+            }
+        });
+
+        while (!a2.isStarted()) {
+            Thread.sleep(50);
+        }
+        runTestOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                assertFalse(set.isPaused());
+                set.pause();
+                assertTrue(set.isPaused());
+                set.resume();
+                assertFalse(set.isPaused());
+            }
+        });
+    }
+
+    // Create an AnimatorSet with all the animators running sequentially
+    private AnimatorSet getSequentialSet() {
+        AnimatorSet set = new AnimatorSet();
+        set.playSequentially(a1, a2, a3, a4, a5);
+        return set;
+    }
+
+    private ArrayList<Animator> getAnimatorList() {
+        ArrayList<Animator> list = new ArrayList<>();
+        list.add(a1);
+        list.add(a2);
+        list.add(a3);
+        list.add(a4);
+        list.add(a5);
+        return list;
+    }
+
 }
diff --git a/core/tests/inputmethodtests/src/android/os/CursorAnchorInfoTest.java b/core/tests/coretests/src/android/view/inputmethod/CursorAnchorInfoTest.java
similarity index 99%
rename from core/tests/inputmethodtests/src/android/os/CursorAnchorInfoTest.java
rename to core/tests/coretests/src/android/view/inputmethod/CursorAnchorInfoTest.java
index d4244ba..e0664d9 100644
--- a/core/tests/inputmethodtests/src/android/os/CursorAnchorInfoTest.java
+++ b/core/tests/coretests/src/android/view/inputmethod/CursorAnchorInfoTest.java
@@ -14,14 +14,14 @@
  * limitations under the License.
  */
 
-package android.os;
+package android.view.inputmethod;
 
 import android.graphics.Matrix;
 import android.graphics.RectF;
+import android.os.Parcel;
 import android.test.InstrumentationTestCase;
 import android.test.suitebuilder.annotation.SmallTest;
 import android.text.TextUtils;
-import android.view.inputmethod.CursorAnchorInfo;
 import android.view.inputmethod.CursorAnchorInfo.Builder;
 
 import java.util.Objects;
diff --git a/core/tests/inputmethodtests/src/android/os/InputMethodSubtypeArrayTest.java b/core/tests/coretests/src/android/view/inputmethod/InputMethodSubtypeArrayTest.java
similarity index 95%
rename from core/tests/inputmethodtests/src/android/os/InputMethodSubtypeArrayTest.java
rename to core/tests/coretests/src/android/view/inputmethod/InputMethodSubtypeArrayTest.java
index 1e0a919..a339f61 100644
--- a/core/tests/inputmethodtests/src/android/os/InputMethodSubtypeArrayTest.java
+++ b/core/tests/coretests/src/android/view/inputmethod/InputMethodSubtypeArrayTest.java
@@ -14,12 +14,11 @@
  * limitations under the License.
  */
 
-package android.os;
+package android.view.inputmethod;
 
+import android.os.Parcel;
 import android.test.InstrumentationTestCase;
 import android.test.suitebuilder.annotation.SmallTest;
-import android.view.inputmethod.InputMethodSubtype;
-import android.view.inputmethod.InputMethodSubtypeArray;
 import android.view.inputmethod.InputMethodSubtype.InputMethodSubtypeBuilder;
 
 import java.util.ArrayList;
diff --git a/core/tests/inputmethodtests/src/android/os/InputMethodSubtypeTest.java b/core/tests/coretests/src/android/view/inputmethod/InputMethodSubtypeTest.java
similarity index 97%
rename from core/tests/inputmethodtests/src/android/os/InputMethodSubtypeTest.java
rename to core/tests/coretests/src/android/view/inputmethod/InputMethodSubtypeTest.java
index 8feac9b..0adac4c 100644
--- a/core/tests/inputmethodtests/src/android/os/InputMethodSubtypeTest.java
+++ b/core/tests/coretests/src/android/view/inputmethod/InputMethodSubtypeTest.java
@@ -14,11 +14,11 @@
  * limitations under the License.
  */
 
-package android.os;
+package android.view.inputmethod;
 
+import android.os.Parcel;
 import android.test.InstrumentationTestCase;
 import android.test.suitebuilder.annotation.SmallTest;
-import android.view.inputmethod.InputMethodSubtype;
 import android.view.inputmethod.InputMethodSubtype.InputMethodSubtypeBuilder;
 
 import java.util.Objects;
diff --git a/core/tests/inputmethodtests/src/android/os/SparseRectFArrayTest.java b/core/tests/coretests/src/android/view/inputmethod/SparseRectFArrayTest.java
similarity index 99%
rename from core/tests/inputmethodtests/src/android/os/SparseRectFArrayTest.java
rename to core/tests/coretests/src/android/view/inputmethod/SparseRectFArrayTest.java
index 47b0d2a..f9fa017 100644
--- a/core/tests/inputmethodtests/src/android/os/SparseRectFArrayTest.java
+++ b/core/tests/coretests/src/android/view/inputmethod/SparseRectFArrayTest.java
@@ -14,12 +14,12 @@
  * limitations under the License.
  */
 
-package android.os;
+package android.view.inputmethod;
 
 import android.graphics.RectF;
+import android.os.Parcel;
 import android.test.InstrumentationTestCase;
 import android.test.suitebuilder.annotation.SmallTest;
-import android.view.inputmethod.SparseRectFArray;
 import android.view.inputmethod.SparseRectFArray.SparseRectFArrayBuilder;
 
 import java.util.Objects;
diff --git a/core/tests/inputmethodtests/src/android/os/InputMethodSubtypeSwitchingControllerTest.java b/core/tests/coretests/src/com/android/internal/inputmethod/InputMethodSubtypeSwitchingControllerTest.java
similarity index 99%
rename from core/tests/inputmethodtests/src/android/os/InputMethodSubtypeSwitchingControllerTest.java
rename to core/tests/coretests/src/com/android/internal/inputmethod/InputMethodSubtypeSwitchingControllerTest.java
index 3a598f2..ec5220f 100644
--- a/core/tests/inputmethodtests/src/android/os/InputMethodSubtypeSwitchingControllerTest.java
+++ b/core/tests/coretests/src/com/android/internal/inputmethod/InputMethodSubtypeSwitchingControllerTest.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package android.os;
+package com.android.internal.inputmethod;
 
 import android.content.pm.ApplicationInfo;
 import android.content.pm.ResolveInfo;
diff --git a/core/tests/inputmethodtests/src/android/os/InputMethodTest.java b/core/tests/coretests/src/com/android/internal/inputmethod/InputMethodUtilsTest.java
similarity index 98%
rename from core/tests/inputmethodtests/src/android/os/InputMethodTest.java
rename to core/tests/coretests/src/com/android/internal/inputmethod/InputMethodUtilsTest.java
index 31a4703..67f87a3 100644
--- a/core/tests/inputmethodtests/src/android/os/InputMethodTest.java
+++ b/core/tests/coretests/src/com/android/internal/inputmethod/InputMethodUtilsTest.java
@@ -14,26 +14,25 @@
  * limitations under the License.
  */
 
-package android.os;
+package com.android.internal.inputmethod;
 
 import android.content.Context;
 import android.content.pm.ApplicationInfo;
 import android.content.pm.ResolveInfo;
 import android.content.pm.ServiceInfo;
+import android.os.Parcel;
 import android.test.InstrumentationTestCase;
 import android.test.suitebuilder.annotation.SmallTest;
 import android.view.inputmethod.InputMethodInfo;
 import android.view.inputmethod.InputMethodSubtype;
 import android.view.inputmethod.InputMethodSubtype.InputMethodSubtypeBuilder;
 
-import com.android.internal.inputmethod.InputMethodUtils;
-
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Locale;
 import java.util.Objects;
 
-public class InputMethodTest extends InstrumentationTestCase {
+public class InputMethodUtilsTest extends InstrumentationTestCase {
     private static final boolean IS_AUX = true;
     private static final boolean IS_DEFAULT = true;
     private static final boolean IS_OVERRIDES_IMPLICITLY_ENABLED_SUBTYPE = true;
diff --git a/core/tests/inputmethodtests/Android.mk b/core/tests/inputmethodtests/Android.mk
deleted file mode 100644
index 4631e65..0000000
--- a/core/tests/inputmethodtests/Android.mk
+++ /dev/null
@@ -1,18 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-# We only want this apk build for tests.
-LOCAL_MODULE_TAGS := tests
-
-# Include all test java files.
-LOCAL_SRC_FILES := \
-	$(call all-java-files-under, src)
-
-LOCAL_DX_FLAGS := --core-library
-LOCAL_STATIC_JAVA_LIBRARIES := core-tests android-common frameworks-core-util-lib
-LOCAL_JAVA_LIBRARIES := android.test.runner
-LOCAL_PACKAGE_NAME := FrameworksCoreInputMethodTests
-
-LOCAL_CERTIFICATE := platform
-
-include $(BUILD_PACKAGE)
diff --git a/core/tests/inputmethodtests/AndroidManifest.xml b/core/tests/inputmethodtests/AndroidManifest.xml
deleted file mode 100644
index 7f0b1aa..0000000
--- a/core/tests/inputmethodtests/AndroidManifest.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2013 The Android Open Source Project
-
-     Licensed under the Apache License, Version 2.0 (the "License");
-     you may not use this file except in compliance with the License.
-     You may obtain a copy of the License at
-
-          http://www.apache.org/licenses/LICENSE-2.0
-
-     Unless required by applicable law or agreed to in writing, software
-     distributed under the License is distributed on an "AS IS" BASIS,
-     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-     See the License for the specific language governing permissions and
-     limitations under the License.
--->
-
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-          android:installLocation="internalOnly"
-          package="com.android.frameworks.coretests.inputmethod"
-          android:sharedUserId="android.uid.system">
-
-    <application>
-        <uses-library android:name="android.test.runner" />
-    </application>
-
-    <instrumentation android:name="android.test.InstrumentationTestRunner"
-            android:targetPackage="com.android.frameworks.coretests.inputmethod"
-            android:label="Frameworks InputMethod Core Tests" />
-
-</manifest>
diff --git a/core/tests/inputmethodtests/run_core_inputmethod_test.sh b/core/tests/inputmethodtests/run_core_inputmethod_test.sh
deleted file mode 100755
index a11e49b..0000000
--- a/core/tests/inputmethodtests/run_core_inputmethod_test.sh
+++ /dev/null
@@ -1,24 +0,0 @@
-#!/bin/bash
-
-while [[ $# -gt 0 ]]; do
-  case "$1" in
-  --rebuild ) echo Rebuild && rebuild=true;;
-  * ) com_opts+=($1);;
-  esac
-  shift
-done
-
-if [[ -z $ANDROID_PRODUCT_OUT && $rebuilld == true ]]; then
-  echo You must lunch before running this test.
-  exit 0
-fi
-
-if [[ $rebuild == true ]]; then
-  make -j4 FrameworksCoreInputMethodTests
-  TESTAPP=${ANDROID_PRODUCT_OUT}/data/app/FrameworksCoreInputMethodTests/FrameworksCoreInputMethodTests.apk
-  COMMAND="adb install -r $TESTAPP"
-  echo $COMMAND
-  $COMMAND
-fi
-
-adb shell am instrument -w -e class android.os.InputMethodTest,android.os.InputMethodSubtypeTest,android.os.InputMethodSubtypeArrayTest,android.os.InputMethodSubtypeSwitchingControllerTest,android.os.CursorAnchorInfoTest,android.os.SparseRectFArrayTest com.android.frameworks.coretests.inputmethod/android.test.InstrumentationTestRunner
diff --git a/docs/html/guide/topics/manifest/uses-sdk-element.jd b/docs/html/guide/topics/manifest/uses-sdk-element.jd
index 3ac87ef..642b820 100644
--- a/docs/html/guide/topics/manifest/uses-sdk-element.jd
+++ b/docs/html/guide/topics/manifest/uses-sdk-element.jd
@@ -19,7 +19,6 @@
       <li><a href="#testing">Testing against higher API Levels</a></li>
     </ol>
   </li>
-  <li><a href="#provisional">Using a Provisional API Level</a></li>
   <li><a href="#filtering">Filtering the Reference Documentation by API Level</a></li>
 </ol>
 </div>
@@ -227,6 +226,11 @@
 <table>
   <tr><th>Platform Version</th><th>API Level</th><th>VERSION_CODE</th><th>Notes</th></tr>
 
+    <tr><td>Android 6.0</td>
+    <td><a href="{@docRoot}sdk/api_diff/23/changes.html" title="Diff Report">23</a></td>
+    <td>{@link android.os.Build.VERSION_CODES#M}</td>
+    <td><a href="{@docRoot}preview/api-overview.html">API Changes</a></td></tr>
+
     <tr><td><a href="{@docRoot}about/versions/android-5.1.html">Android 5.1</a></td>
     <td><a href="{@docRoot}sdk/api_diff/22/changes.html" title="Diff Report">22</a></td>
     <td>{@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1}</td>
@@ -552,29 +556,6 @@
 of the Android platform it runs. See the table at the top of this document for
 a list of platform versions and their API Levels. </p>
 
-<h2 id="provisional">Using a Provisional API Level</h2>
-
-<p>In some cases, an "Early Look" Android SDK platform may be available. To let
-you begin developing on the platform although the APIs may not be final, the
-platform's API Level integer will not be specified. You must instead use the
-platform's <em>provisional API Level</em> in your application manifest, in order
-to build applications against the platform. A provisional API Level is not an
-integer, but a string matching the codename of the unreleased platform version.
-The provisional API Level will be specified in the release notes for the Early
-Look SDK release notes and is case-sensitive.</p>
-
-<p>The use of a provisional API Level is designed to protect developers and
-device users from inadvertently publishing or installing applications based on
-the Early Look framework API, which may not run properly on actual devices
-running the final system image.</p>
-
-<p>The provisional API Level will only be valid while using the Early Look SDK
-and can only be used to run applications in the emulator. An application using
-the provisional API Level can never be installed on an Android device. At the
-final release of the platform, you must replace any instances of the provisional
-API Level in your application manifest with the final platform's actual API
-Level integer.</p>
-
 
 <h2 id="filtering">Filtering the Reference Documentation by API Level</h2>
 
diff --git a/docs/html/index.jd b/docs/html/index.jd
index c6dbbd5..eef7929 100644
--- a/docs/html/index.jd
+++ b/docs/html/index.jd
@@ -10,32 +10,31 @@
 <section class="dac-hero-carousel">
 
 <!-- <article class="dac-expand dac-hero dac-invert active" style="background-color: rgb(38, 50, 56);"> -->
-<article class="dac-expand dac-hero dac-invert active" style="background-color: #455A64;">
+<article class="dac-expand dac-hero dac-invert dac-darken mprev active" style="background-color: #75d1ff;">
 <a href="/preview/index.html">
-  <div class="wrap" style="max-width:1100px;">
+  <div class="wrap" style="max-width:1100px;margin-top:0">
     <div class="cols dac-hero-content">
-      <div class="col-10of16 col-push-6of16 dac-hero-figure">
-        <img class="dac-hero-image" src="{@docRoot}images/home/devices-hero_620px_2x.png"
-             srcset="{@docRoot}images/home/devices-hero_620px.png 1x,
-             {@docRoot}images/home/devices-hero_620px_2x.png 2x">
+      <div class="col-8of16 col-push-6of16 dac-hero-figure mprev">
       </div>
-      <div class="col-6of16 col-pull-10of16">
+      <div class="col-8of16 col-pull-7of16">
         <div class="dac-hero-tag"></div>
 
-        <h1 class="dac-hero-title">Android M Developer Preview</h1>
-        <p class="dac-hero-description">Get your apps ready for the next version
-        of Android. Test on Nexus 5, 6, 9, and Player. </p>
+        <h1 class="dac-hero-title" style="white-space:nowrap;">Android 6.0 Marshmallow</h1>
+        </div>
+        <div class="col-6of16 col-push-1of16">
+        <p class="dac-hero-description"><strong>Final SDK is now available!</strong> Get your apps ready for the next version
+        of Android. Test on Nexus 5, 6, 9, and Player.</p>
 
-        <a class="dac-hero-cta" href="{@docRoot}preview/index.html">
+        <a class="dac-hero-cta" href="/preview/index.html">
           <span class="dac-sprite dac-auto-chevron"></span>
           Get started
         </a><br>
 
-        <a class="dac-hero-cta" href="{@docRoot}preview/support.html">
+        <a class="dac-hero-cta" href="/preview/support.html">
           <span class="dac-sprite dac-auto-chevron"></span>
-          Update to Developer Preview 2
+          Update to Developer Preview 3 (final SDK)
         </a>
-
+      </div>
       </div>
     </div>
   </div>
diff --git a/docs/html/preview/download.jd b/docs/html/preview/download.jd
index 0dfabef..0b115f2 100644
--- a/docs/html/preview/download.jd
+++ b/docs/html/preview/download.jd
@@ -164,7 +164,7 @@
   <div id="qv">
     <h2>In this document</h2>
       <ol>
-        <li><a href="#sdk">Developer Preview 2 SDK</a></li>
+        <li><a href="#sdk">Developer Preview 3 SDK</a></li>
         <li><a href="#docs">Developer Documentation</a></li>
         <li><a href="#images">Hardware System Images</a></li>
       </ol>
@@ -178,13 +178,13 @@
 
 
 <p>
-  The Android M Preview SDK includes development tools, Android system files, and library files to
+  The Android M Preview SDK includes development tools, Android system images, and library files to
   help you test your app and the new APIs coming in the next release of the platform. This document
   describes how to get the downloadable components of the preview for testing your app.
 </p>
 
 
-<h2 id="sdk">Developer Preview 2 SDK</h2>
+<h2 id="sdk">Developer Preview 3 SDK</h2>
 
 <p>
   The Preview SDK is available for download through the <a href=
@@ -197,7 +197,10 @@
 <h2 id="docs">Developer Documentation</h2>
 
 <p>
-  The developer documentation download package provides detailed API reference information and an API difference report for the preview.
+	The developer documentation download package provides detailed API reference information and
+	an API difference report for the preview. Note that <a href="{@docRoot}reference/packages.html">API
+	level 23 reference</a> and <a href="{@docRoot}sdk/api_diff/23/changes.html">diffs</a> are now
+	also available online. 
 </p>
 
 <table>
@@ -206,11 +209,11 @@
     <th scope="col">Download / Checksums</th>
   </tr>
   <tr id="docs-dl">
-    <td>Android M Preview 2<br>Developer Docs</td>
+    <td>Android M Preview 3<br>Developer Docs</td>
     <td><a href="#top" onclick="onDownload(this)"
-      >m-preview-2-developer-docs.zip</a><br>
-      MD5: 1db6fff9c722b0339757e1cdf43663a8<br>
-      SHA-1: 5a4ae88d644e63824d21b0e18f8e3977a7665157
+      >m-preview-3-developer-docs.zip</a><br>
+      MD5: -<br>
+      SHA-1: -
     </td>
   </tr>
 <table>
diff --git a/docs/html/preview/download_mp2.jd b/docs/html/preview/download_mp2.jd
new file mode 100644
index 0000000..0dfabef
--- /dev/null
+++ b/docs/html/preview/download_mp2.jd
@@ -0,0 +1,367 @@
+page.title=Downloads
+page.image=images/cards/card-download_16-9_2x.png
+
+@jd:body
+
+<div style="position:relative; min-height:600px">
+
+  <div class="wrap" id="tos" style="position:absolute;display:none;width:inherit;">
+
+    <p class="sdk-terms-intro">Before downloading and installing components of the Android Preview
+      SDK, you must agree to the following terms and conditions.</p>
+
+    <h2 class="norule">Terms and Conditions</h2>
+
+    <div class="sdk-terms" onfocus="this.blur()" style="width:678px">
+This is the Android SDK Preview License Agreement (the “License Agreement”).
+
+1. Introduction
+
+1.1 The Android SDK Preview (referred to in the License Agreement as the “Preview” and specifically including the Android system files, packaged APIs, and Preview library files, if and when they are made available) is licensed to you subject to the terms of the License Agreement. The License Agreement forms a legally binding contract between you and Google in relation to your use of the Preview.
+
+1.2 "Android" means the Android software stack for devices, as made available under the Android Open Source Project, which is located at the following URL: http://source.android.com/, as updated from time to time.
+
+1.3 "Google" means Google Inc., a Delaware corporation with principal place of business at 1600 Amphitheatre Parkway, Mountain View, CA 94043, United States.
+
+2. Accepting the License Agreement
+
+2.1 In order to use the Preview, you must first agree to the License Agreement. You may not use the Preview if you do not accept the License Agreement.
+
+2.2 By clicking to accept and/or using the Preview, you hereby agree to the terms of the License Agreement.
+
+2.3 You may not use the Preview and may not accept the License Agreement if you are a person barred from receiving the Preview under the laws of the United States or other countries including the country in which you are resident or from which you use the Preview.
+
+2.4 If you will use the Preview internally within your company or organization you agree to be bound by the License Agreement on behalf of your employer or other entity, and you represent and warrant that you have full legal authority to bind your employer or such entity to the License Agreement. If you do not have the requisite authority, you may not accept the License Agreement or use the Preview on behalf of your employer or other entity.
+
+3. Preview License from Google
+
+3.1 Subject to the terms of the License Agreement, Google grants you a royalty-free, non-assignable, non-exclusive, non-sublicensable, limited, revocable license to use the Preview, personally or internally within your company or organization, solely to develop applications to run on the Android platform.
+
+3.2 You agree that Google or third parties owns all legal right, title and interest in and to the Preview, including any Intellectual Property Rights that subsist in the Preview. "Intellectual Property Rights" means any and all rights under patent law, copyright law, trade secret law, trademark law, and any and all other proprietary rights. Google reserves all rights not expressly granted to you.
+
+3.3 You may not use the Preview for any purpose not expressly permitted by the License Agreement. Except to the extent required by applicable third party licenses, you may not: (a) copy (except for backup purposes), modify, adapt, redistribute, decompile, reverse engineer, disassemble, or create derivative works of the Preview or any part of the Preview; or (b) load any part of the Preview onto a mobile handset or any other hardware device except a personal computer, combine any part of the Preview with other software, or distribute any software or device incorporating a part of the Preview.
+
+3.4 You agree that you will not take any actions that may cause or result in the fragmentation of Android, including but not limited to distributing, participating in the creation of, or promoting in any way a software development kit derived from the Preview.
+
+3.5 Use, reproduction and distribution of components of the Preview licensed under an open source software license are governed solely by the terms of that open source software license and not the License Agreement. You agree to remain a licensee in good standing in regard to such open source software licenses under all the rights granted and to refrain from any actions that may terminate, suspend, or breach such rights.
+
+3.6 You agree that the form and nature of the Preview that Google provides may change without prior notice to you and that future versions of the Preview may be incompatible with applications developed on previous versions of the Preview. You agree that Google may stop (permanently or temporarily) providing the Preview (or any features within the Preview) to you or to users generally at Google's sole discretion, without prior notice to you.
+
+3.7 Nothing in the License Agreement gives you a right to use any of Google's trade names, trademarks, service marks, logos, domain names, or other distinctive brand features.
+
+3.8 You agree that you will not remove, obscure, or alter any proprietary rights notices (including copyright and trademark notices) that may be affixed to or contained within the Preview.
+
+4. Use of the Preview by You
+
+4.1 Google agrees that nothing in the License Agreement gives Google any right, title or interest from you (or your licensors) under the License Agreement in or to any software applications that you develop using the Preview, including any intellectual property rights that subsist in those applications.
+
+4.2 You agree to use the Preview and write applications only for purposes that are permitted by (a) the License Agreement, and (b) any applicable law, regulation or generally accepted practices or guidelines in the relevant jurisdictions (including any laws regarding the export of data or software to and from the United States or other relevant countries).
+
+4.3 You agree that if you use the Preview to develop applications, you will protect the privacy and legal rights of users. If users provide you with user names, passwords, or other login information or personal information, you must make the users aware that the information will be available to your application, and you must provide legally adequate privacy notice and protection for those users. If your application stores personal or sensitive information provided by users, it must do so securely. If users provide you with Google Account information, your application may only use that information to access the user's Google Account when, and for the limited purposes for which, each user has given you permission to do so.
+
+4.4 You agree that you will not engage in any activity with the Preview, including the development or distribution of an application, that interferes with, disrupts, damages, or accesses in an unauthorized manner the servers, networks, or other properties or services of Google or any third party.
+
+4.5 You agree that you are solely responsible for (and that Google has no responsibility to you or to any third party for) any data, content, or resources that you create, transmit or display through Android and/or applications for Android, and for the consequences of your actions (including any loss or damage which Google may suffer) by doing so.
+
+4.6 You agree that you are solely responsible for (and that Google has no responsibility to you or to any third party for) any breach of your obligations under the License Agreement, any applicable third party contract or Terms of Service, or any applicable law or regulation, and for the consequences (including any loss or damage which Google or any third party may suffer) of any such breach.
+
+4.7 The Preview is in development, and your testing and feedback are an important part of the development process. By using the Preview, you acknowledge that implementation of some features are still under development and that you should not rely on the Preview having the full functionality of a stable release. You agree not to publicly distribute or ship any application using this Preview as this Preview will no longer be supported after the official Android SDK is released.
+
+5. Your Developer Credentials
+
+5.1 You agree that you are responsible for maintaining the confidentiality of any developer credentials that may be issued to you by Google or which you may choose yourself and that you will be solely responsible for all applications that are developed under your developer credentials.
+
+6. Privacy and Information
+
+6.1 In order to continually innovate and improve the Preview, Google may collect certain usage statistics from the software including but not limited to a unique identifier, associated IP address, version number of the software, and information on which tools and/or services in the Preview are being used and how they are being used. Before any of this information is collected, the Preview will notify you and seek your consent. If you withhold consent, the information will not be collected.
+
+6.2 The data collected is examined in the aggregate to improve the Preview and is maintained in accordance with Google's Privacy Policy located at http://www.google.com/policies/privacy/.
+
+7. Third Party Applications
+
+7.1 If you use the Preview to run applications developed by a third party or that access data, content or resources provided by a third party, you agree that Google is not responsible for those applications, data, content, or resources. You understand that all data, content or resources which you may access through such third party applications are the sole responsibility of the person from which they originated and that Google is not liable for any loss or damage that you may experience as a result of the use or access of any of those third party applications, data, content, or resources.
+
+7.2 You should be aware the data, content, and resources presented to you through such a third party application may be protected by intellectual property rights which are owned by the providers (or by other persons or companies on their behalf). You may not modify, rent, lease, loan, sell, distribute or create derivative works based on these data, content, or resources (either in whole or in part) unless you have been specifically given permission to do so by the relevant owners.
+
+7.3 You acknowledge that your use of such third party applications, data, content, or resources may be subject to separate terms between you and the relevant third party.
+
+8. Using Google APIs
+
+8.1 Google APIs
+
+8.1.1 If you use any API to retrieve data from Google, you acknowledge that the data may be protected by intellectual property rights which are owned by Google or those parties that provide the data (or by other persons or companies on their behalf). Your use of any such API may be subject to additional Terms of Service. You may not modify, rent, lease, loan, sell, distribute or create derivative works based on this data (either in whole or in part) unless allowed by the relevant Terms of Service.
+
+8.1.2 If you use any API to retrieve a user's data from Google, you acknowledge and agree that you shall retrieve data only with the user's explicit consent and only when, and for the limited purposes for which, the user has given you permission to do so.
+
+9. Terminating the License Agreement
+
+9.1 the License Agreement will continue to apply until terminated by either you or Google as set out below.
+
+9.2 If you want to terminate the License Agreement, you may do so by ceasing your use of the Preview and any relevant developer credentials.
+
+9.3 Google may at any time, terminate the License Agreement, with or without cause, upon notice to you.
+
+9.4 The License Agreement will automatically terminate without notice or other action upon the earlier of:
+(A) when Google ceases to provide the Preview or certain parts of the Preview to users in the country in which you are resident or from which you use the service; and
+(B) Google issues a final release version of the Android SDK.
+
+9.5 When the License Agreement is terminated, the license granted to you in the License Agreement will terminate, you will immediately cease all use of the Preview, and the provisions of paragraphs 10, 11, 12 and 14 shall survive indefinitely.
+
+10. DISCLAIMERS
+
+10.1 YOU EXPRESSLY UNDERSTAND AND AGREE THAT YOUR USE OF THE PREVIEW IS AT YOUR SOLE RISK AND THAT THE PREVIEW IS PROVIDED "AS IS" AND "AS AVAILABLE" WITHOUT WARRANTY OF ANY KIND FROM GOOGLE.
+
+10.2 YOUR USE OF THE PREVIEW AND ANY MATERIAL DOWNLOADED OR OTHERWISE OBTAINED THROUGH THE USE OF THE PREVIEW IS AT YOUR OWN DISCRETION AND RISK AND YOU ARE SOLELY RESPONSIBLE FOR ANY DAMAGE TO YOUR COMPUTER SYSTEM OR OTHER DEVICE OR LOSS OF DATA THAT RESULTS FROM SUCH USE. WITHOUT LIMITING THE FOREGOING, YOU UNDERSTAND THAT THE PREVIEW IS NOT A STABLE RELEASE AND MAY CONTAIN ERRORS, DEFECTS AND SECURITY VULNERABILITIES THAT CAN RESULT IN SIGNIFICANT DAMAGE, INCLUDING THE COMPLETE, IRRECOVERABLE LOSS OF USE OF YOUR COMPUTER SYSTEM OR OTHER DEVICE.
+
+10.3 GOOGLE FURTHER EXPRESSLY DISCLAIMS ALL WARRANTIES AND CONDITIONS OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
+
+11. LIMITATION OF LIABILITY
+
+11.1 YOU EXPRESSLY UNDERSTAND AND AGREE THAT GOOGLE, ITS SUBSIDIARIES AND AFFILIATES, AND ITS LICENSORS SHALL NOT BE LIABLE TO YOU UNDER ANY THEORY OF LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL OR EXEMPLARY DAMAGES THAT MAY BE INCURRED BY YOU, INCLUDING ANY LOSS OF DATA, WHETHER OR NOT GOOGLE OR ITS REPRESENTATIVES HAVE BEEN ADVISED OF OR SHOULD HAVE BEEN AWARE OF THE POSSIBILITY OF ANY SUCH LOSSES ARISING.
+
+12. Indemnification
+
+12.1 To the maximum extent permitted by law, you agree to defend, indemnify and hold harmless Google, its affiliates and their respective directors, officers, employees and agents from and against any and all claims, actions, suits or proceedings, as well as any and all losses, liabilities, damages, costs and expenses (including reasonable attorneys’ fees) arising out of or accruing from (a) your use of the Preview, (b) any application you develop on the Preview that infringes any Intellectual Property Rights of any person or defames any person or violates their rights of publicity or privacy, and (c) any non-compliance by you of the License Agreement.
+
+13. Changes to the License Agreement
+
+13.1 Google may make changes to the License Agreement as it distributes new versions of the Preview. When these changes are made, Google will make a new version of the License Agreement available on the website where the Preview is made available.
+
+14. General Legal Terms
+
+14.1 the License Agreement constitutes the whole legal agreement between you and Google and governs your use of the Preview (excluding any services which Google may provide to you under a separate written agreement), and completely replaces any prior agreements between you and Google in relation to the Preview.
+
+14.2 You agree that if Google does not exercise or enforce any legal right or remedy which is contained in the License Agreement (or which Google has the benefit of under any applicable law), this will not be taken to be a formal waiver of Google's rights and that those rights or remedies will still be available to Google.
+
+14.3 If any court of law, having the jurisdiction to decide on this matter, rules that any provision of the License Agreement is invalid, then that provision will be removed from the License Agreement without affecting the rest of the License Agreement. The remaining provisions of the License Agreement will continue to be valid and enforceable.
+
+14.4 You acknowledge and agree that each member of the group of companies of which Google is the parent shall be third party beneficiaries to the License Agreement and that such other companies shall be entitled to directly enforce, and rely upon, any provision of the License Agreement that confers a benefit on (or rights in favor of) them. Other than this, no other person or company shall be third party beneficiaries to the License Agreement.
+
+14.5 EXPORT RESTRICTIONS. THE PREVIEW IS SUBJECT TO UNITED STATES EXPORT LAWS AND REGULATIONS. YOU MUST COMPLY WITH ALL DOMESTIC AND INTERNATIONAL EXPORT LAWS AND REGULATIONS THAT APPLY TO THE PREVIEW. THESE LAWS INCLUDE RESTRICTIONS ON DESTINATIONS, END USERS AND END USE.
+
+14.6 The License Agreement may not be assigned or transferred by you without the prior written approval of Google, and any attempted assignment without such approval will be void. You shall not delegate your responsibilities or obligations under the License Agreement without the prior written approval of Google.
+
+14.7 The License Agreement, and your relationship with Google under the License Agreement, shall be governed by the laws of the State of California without regard to its conflict of laws provisions. You and Google agree to submit to the exclusive jurisdiction of the courts located within the county of Santa Clara, California to resolve any legal matter arising from the License Agreement. Notwithstanding this, you agree that Google shall still be allowed to apply for injunctive remedies (or an equivalent type of urgent legal relief) in any jurisdiction.
+  </div><!-- sdk terms -->
+
+
+
+    <div id="sdk-terms-form">
+      <p>
+        <input id="agree" type="checkbox" name="agree" value="1" onclick="onAgreeChecked()" />
+        <label id="agreeLabel" for="agree">I have read and agree with the above terms and conditions</label>
+      </p>
+      <p><a href="" class="button disabled" id="downloadForRealz" onclick="return onDownloadForRealz(this);"></a></p>
+    </div>
+
+
+  </div><!-- end TOS -->
+
+
+  <div id="landing">
+
+<div id="qv-wrapper">
+  <div id="qv">
+    <h2>In this document</h2>
+      <ol>
+        <li><a href="#sdk">Developer Preview 2 SDK</a></li>
+        <li><a href="#docs">Developer Documentation</a></li>
+        <li><a href="#images">Hardware System Images</a></li>
+      </ol>
+
+     <h2>Legacy downloads</h2>
+        <ol>
+           <li><a href="{@docRoot}preview/download_mp1.html">Developer Preview Archive</a></li>
+        </ol>
+  </div>
+</div>
+
+
+<p>
+  The Android M Preview SDK includes development tools, Android system files, and library files to
+  help you test your app and the new APIs coming in the next release of the platform. This document
+  describes how to get the downloadable components of the preview for testing your app.
+</p>
+
+
+<h2 id="sdk">Developer Preview 2 SDK</h2>
+
+<p>
+  The Preview SDK is available for download through the <a href=
+  "{@docRoot}tools/help/sdk-manager.html">Android SDK Manager</a>. For more information on
+  downloading and configuring the Preview SDK, see <a href=
+  "{@docRoot}preview/setup-sdk.html#downloadSdk">Set Up the Preview SDK</a>.
+</p>
+
+
+<h2 id="docs">Developer Documentation</h2>
+
+<p>
+  The developer documentation download package provides detailed API reference information and an API difference report for the preview.
+</p>
+
+<table>
+  <tr>
+    <th scope="col">Description</th>
+    <th scope="col">Download / Checksums</th>
+  </tr>
+  <tr id="docs-dl">
+    <td>Android M Preview 2<br>Developer Docs</td>
+    <td><a href="#top" onclick="onDownload(this)"
+      >m-preview-2-developer-docs.zip</a><br>
+      MD5: 1db6fff9c722b0339757e1cdf43663a8<br>
+      SHA-1: 5a4ae88d644e63824d21b0e18f8e3977a7665157
+    </td>
+  </tr>
+<table>
+
+
+<h2 id="images">Hardware System Images</h2>
+
+<p>
+  These system images allow you to install a preview version of the platform on a physical device for
+  testing. By configuring a device with one of these images, you can install and test your app to
+  see how it performs on the next version of the platform. The process of installing a system image
+  on a device <em>removes all data from the device</em>, so you should backup your data before
+  installing a system image.
+</p>
+
+<p class="warning">
+  <b>Warning:</b> The following Android system images are previews and are subject to change. Your
+  use of these system images is governed by the Android SDK Preview License Agreement. The Android
+  preview system images are not stable releases, and may contain errors and defects that can result
+  in damage to your computer systems, devices, and data. The preview Android system images are not
+  subject to the same testing as the factory OS and can cause your phone and installed services and
+  applications to stop working.
+</p>
+
+<table>
+  <tr>
+    <th scope="col">Device</th>
+    <th scope="col">Download / Checksums</th>
+  </tr>
+  <tr id="hammerhead">
+    <td>Nexus 5 (GSM/LTE) <br>"hammerhead"</td>
+    <td><a href="#top" onclick="onDownload(this)"
+      >hammerhead-MPZ79M-preview-b1f4bde4.tgz</a><br>
+      MD5: 2ca9f18bf47a061b339bab52647ceb0d<br>
+      SHA-1: b1f4bde447eccbf8ce5d9b8b8ba954e3eac8e939
+    </td>
+  </tr>
+  <tr id="shamu">
+    <td>Nexus 6 <br>"shamu"</td>
+    <td><a href="#top" onclick="onDownload(this)"
+      >shamu-MPZ79M-preview-e1024040.tgz</a><br>
+      MD5: 24a2118da340b9afedfbdfc026f6ff81<br>
+      SHA-1: e10240408859d5188c4aae140e1c539130ba614b
+    </td>
+  </tr>
+  <tr id="volantis">
+    <td>Nexus 9 <br>"volantis"</td>
+    <td><a href="#top" onclick="onDownload(this)"
+      >volantis-MPZ79M-preview-9f305342.tgz</a><br>
+      MD5: 9edabf0a4c61b247f1cbb9dfdc0a899e<br>
+      SHA-1: 9f30534216f10899a6a75495fc7e92408ea333a7
+    </td>
+  </tr>
+
+  <tr id="fugu">
+    <td>Nexus Player <br>"fugu"</td>
+    <td><a href="#top" onclick="onDownload(this)"
+      >fugu-MPZ79N-preview-fb63af98.tgz</a><br>
+      MD5: e8d081137a20b66df595ee69523314b5<br>
+      SHA-1: fb63af98302dd97be8de9313734d389ccdcce250
+    </td>
+  </tr>
+
+</table>
+
+<h3 id="install-image">Install an Image to a Device</h3>
+
+<p>
+  In order to use a device image for testing, you must install it on a compatible device. Follow
+  the instructions below to install a system image:
+</p>
+
+<ol>
+  <li>Download and uncompress one of the system image packages listed here.</li>
+  <li>Backup any data you want to preserve from the device.</li>
+  <li>Follow the instructions at
+  <a href="https://developers.google.com/android/nexus/images#instructions">developers.google.com/android</a>
+  to flash the image onto your device.</li>
+</ol>
+
+<h3 id="update-image">Updating a Device with the Preview</h3>
+
+<p>
+  Once you have installed a preview system image on a development device, the device is upgraded
+  automatically with the next preview release through over-the-air (OTA) updates. When the update
+  is available, the device displays notification that an update is available and allows you to
+  install it. You can also manually install the next preview image by repeating the procedure in
+  the previous section.
+</p>
+
+<h3 id="revertDevice">Revert a Device to Factory Specifications</h3>
+
+<p>
+  If you want to uninstall the preview and revert the device to factory specifications, go to
+  <a href="http://developers.google.com/android/nexus/images">developers.google.com/android</a> and
+  download the image you want to flash to for your device. Follow the instructions on that page to
+  flash the image to your device.
+</p>
+
+  </div><!-- landing -->
+
+</div><!-- relative wrapper -->
+
+
+
+<script>
+  var urlRoot = "http://storage.googleapis.com/androiddevelopers/shareables/preview/";
+  function onDownload(link) {
+
+    $("#downloadForRealz").html("Download " + $(link).text());
+    $("#downloadForRealz").attr('href', urlRoot + $(link).text());
+
+    $("#tos").fadeIn('fast');
+    $("#landing").fadeOut('fast');
+
+    return true;
+  }
+
+
+  function onAgreeChecked() {
+    /* verify that the TOS is agreed */
+    if ($("input#agree").is(":checked")) {
+      /* reveal the download button */
+      $("a#downloadForRealz").removeClass('disabled');
+    } else {
+      $("a#downloadForRealz").addClass('disabled');
+    }
+  }
+
+  function onDownloadForRealz(link) {
+    if ($("input#agree").is(':checked')) {
+    /*
+      $("#tos").fadeOut('fast');
+      $("#landing").fadeIn('fast');
+    */
+
+      ga('send', 'event', 'M Preview', 'System Image', $("#downloadForRealz").html());
+
+    /*
+      location.hash = "";
+    */
+      return true;
+    } else {
+      return false;
+    }
+  }
+
+  $(window).hashchange( function(){
+    if (location.hash == "") {
+      location.reload();
+    }
+  });
+
+</script>
diff --git a/docs/html/preview/index.jd b/docs/html/preview/index.jd
index 022838b..5410e4f 100644
--- a/docs/html/preview/index.jd
+++ b/docs/html/preview/index.jd
@@ -18,6 +18,7 @@
       <div class="col-7of16 col-pull-9of16">
         <h1 class="dac-hero-title">Android M Developer Preview</h1>
         <p class="dac-hero-description">
+          <strong>Final SDK is now available!</strong> 
           Get ready for the next version of Android. Test your apps on Nexus 5, 6, 9, and
           Player. Explore what's new &mdash; <strong>runtime permissions</strong>,
           <strong>Doze</strong> and <strong>App Standby</strong> power-saving features, new
@@ -30,7 +31,7 @@
         </a><br>
         <a class="dac-hero-cta" href="{@docRoot}preview/support.html">
           <span class="dac-sprite dac-auto-chevron"></span>
-          Update to Developer Preview 2
+          Update to Developer Preview 3 (final SDK)
         </a><br>
       </div>
     </div>
diff --git a/docs/html/preview/overview.jd b/docs/html/preview/overview.jd
index 009e268..9793592 100644
--- a/docs/html/preview/overview.jd
+++ b/docs/html/preview/overview.jd
@@ -6,20 +6,21 @@
 @jd:body
 
 <div class="cols" style=
-"background-color:#ffebc3; padding: 5px 0;margin-bottom:1em; text-align:center;">
+"background-color:#f2daf5; padding: 5px 0;margin-bottom:1em; text-align:center;">
 <h3>
-    Developer Preview 2 is now available
+    Developer Preview 3 is now available
   </h3>
-
+  <p>Includes final SDK and near-final system images</p>
+   <div style="margin:auto 1em">
  <ul class="dac-section-links">
     <li class="dac-section-link">
-      <a href="{@docRoot}preview/support.html#preview2-notes">
+      <a href="{@docRoot}preview/support.html#preview3-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">
+      <a href="{@docRoot}preview/support.html#preview3-get">
       <span class="dac-sprite dac-auto-chevron"></span>
       Get the Update</a>
     </li>
@@ -30,6 +31,7 @@
       Report Issues</a>
     </li>
   </ul>
+  </div>
 </div>
 
 <p>
@@ -143,14 +145,13 @@
 <img src="{@docRoot}preview/images/m-preview-timeline-crop.png" alt=
 "Preview program timeline" id="timeline">
 <p>
-  The M Developer Preview runs from May 28 until the final Android M SDK, which
-  we’ll release shortly before the public release during Q3
+  The M Developer Preview runs from May 28 until the final Android M public release planned for Q3
   2015.
 </p>
 
 <p>
   At key development milestones, we’ll deliver updates for your test devices.
-  The tentative milestones are
+  The milestones are
 </p>
 
 <ul>
@@ -163,12 +164,12 @@
   </li>
 
   <li>
-    <strong>Preview&nbsp;3</strong> (near final, late July).
+    <strong>Preview&nbsp;3</strong> (final APIs and SDK, now available).
   </li>
 </ul>
 
 <p>
-  These updates culminate in the <strong>final SDK</strong> (later in Q3),
+  These updates culminate in the <strong>final SDK</strong> (available now),
   which delivers the official APIs for the new version of Android, as well
   as the final system behaviors and features.
 </p>
@@ -181,8 +182,10 @@
   providing system images that you can download and flash manually.
 </p>
 <p class="note">
-  <strong>Note:</strong> The final SDK and system images can not be delivered
-  by OTA, but will instead need to be <strong>flashed manually</strong> to
+  <strong>Note:</strong> Developer Preview 3 includes final APIs and near-final
+  system images available by both download and OTA. At the full public release of
+  Android M later in Q3, final system images will be available by download only,
+  so you'll need to <strong>flash manually</strong> to
   your test devices.</strong>
 </p>
 
@@ -316,40 +319,29 @@
 
 
 <h2 id="preview_apis_and_publishing">
-  Targeting, preview APIs, and publishing
+  Final SDK, targeting, and publishing
 </h2>
 
 <p>
-  The Android M Developer Preview is a development-only release and
-  <strong>does not have a standard API level</strong>. If you want to opt out
+   <p>With Developer Preview 3, the platform APIs are now official (API level 23) and the
+   <strong>final SDK is now available</strong>.  We recommend updating your environment
+   right away through Android Studio. Once you've updated your environment, you can target
+   the new API level, compile against the new platform, and publish at your convenience
+   to Google Play (including alpha, beta, or release channels).
+
+  <p>If you want to opt out
   of compatibility behaviors to test your app (which is strongly recommended),
   you can target the M Developer Preview by setting your app's <code><a href=
   "/guide/topics/manifest/uses-sdk-element.html">targetSdkVersion</a></code>
   to <code>“MNC”</code>.
 </p>
 
-<p>
-  The Android M Developer Preview delivers <strong>preview APIs</strong>
-  &mdash; the APIs will not be official until the final SDK is released,
-  currently planned for the third quarter of 2015. This means that you can
-  <strong>expect minor API changes</strong> over time, especially during
-  initial weeks of the program. We’ll provide a summary of changes to you with
-  each update of the Android M Developer Preview.
-</p>
-
-<p class="note">
-  Note that although preview APIs may change, underlying system behaviors such
-  as runtime permissions and power-saving features are stable and ready for
-  testing right away.
-</p>
-
-<p>
-  In terms of publishing, Google Play <strong>prevents publishing of apps
-  targeting the M Developer Preview</strong>. When the Android M final SDK is
-  available, you’ll be able to target the official Android M API level and
-  publish your app to Google Play. Meanwhile, if you want to distribute an app
-  targeting Android M to testers, you can do so via email or by direct download
-  from your site.
+  <p>Before releasing your app targeting Android M, we strongly recommend distributing it
+  to a group of testers through the new <a
+  href="http://android-developers.blogspot.com/2015/07/iterate-faster-on-google-play-with.html"> 
+  beta testing features available in the Google Play Developer Console. See the
+  <a href="https://support.google.com/googleplay/android-developer/answer/3131213">Help
+  Center article</a> for more information. 
 </p>
 
 <h2 id="get_started">
@@ -357,7 +349,7 @@
 </h2>
 
 <p>
-  To get started testing your app:
+  To get started testing your app with Android M:
 </p>
 
 <ol>
@@ -379,7 +371,7 @@
     Preview updates will be delivered through over-the-air (OTA) updates.</a>
   </li>
 
-  <li>Download the <a href="{@docRoot}preview/download.html#docs">M Preview API
+  <li>Review the <a href="{@docRoot}reference/packages.html">API
   Reference</a> and <a href="{@docRoot}preview/samples.html">M Preview
   samples</a> to gain more insight into new API features and how to use them in
   your app.
diff --git a/docs/html/preview/support.jd b/docs/html/preview/support.jd
index d908f77..9ad9ac0 100644
--- a/docs/html/preview/support.jd
+++ b/docs/html/preview/support.jd
@@ -5,20 +5,21 @@
 @jd:body
 
 <div class="cols" style=
-"background-color:#ffebc3; padding: 5px 0;margin-bottom:1em; text-align:center;">
+"background-color:#f2daf5; padding: 5px 0;margin-bottom:1em; text-align:center;">
 <h3>
-    Developer Preview 2 is now available
+    Developer Preview 3 is now available
   </h3>
-
+  <p>Includes final SDK and near-final system images</p>
+   <div style="margin:auto 1em">
  <ul class="dac-section-links">
     <li class="dac-section-link">
-      <a href="#preview2-notes">
+      <a href="#preview3-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="#preview3-get">
       <span class="dac-sprite dac-auto-chevron"></span>
       Get the Update</a>
     </li>
@@ -29,6 +30,7 @@
       Report Issues</a>
     </li>
   </ul>
+  </div>
 </div>
 
 <p>
@@ -46,6 +48,191 @@
   community</a>.
 </p>
 
+<h2 id="preview3-notes">
+  Developer Preview 3
+</h2>
+
+<div class="wrap">
+  <div class="cols">
+    <div class="col-9of16">
+      <p>
+        <em>Date: August 2015<br>
+        Builds: XXXXXX (Nexus 5, 6, 9), MPZ79N (Nexus Player)<br>
+        Hardware support: Nexus 5, 6, 9, Player<br>
+        Emulator support: x86 &amp; ARM 32/64-bit<br>
+        Google Play services: 7.8</em>
+      </p>
+    </div>
+  </div>
+</div>
+
+<p>
+  Android M Developer Preview 3 is the <strong>final incremental update</strong>
+  to the Android M preview platform that was originally released in May 2015.
+  The update includes <strong>final APIs and final SDK</strong>, as well as
+  <strong>near-final system images</strong> for testing your apps. The
+  updated system images include a variety of fixes and enhancements across
+  the system, including those related to issues reported by developers
+  through the external issue tracker.
+</p>
+
+<p>
+  If you are currently developing or testing on Android M, you should <strong>update
+  your environment to Developer Preview 3</strong> as soon as possible, so that
+  you can begin <strong>final compatibility testing</strong> in preparation for the public
+  release to device manufacturers.</p>
+
+<p class="important">Updating to Developer Preview 3 ensures that
+   you are building against final platform APIs and testing against
+   the final behaviors. If you are just getting started with the Android
+   M Developer Preview SDK, follow the instructions in <a href=
+  "/preview/setup-sdk.html">Set up the Preview SDK</a>, then update your
+  environment for Developer Preview 3.
+</p>
+
+<h3>
+  What's included
+</h3>
+
+<p>
+  Developer Preview 3 includes an updated SDK and system images,
+  documentation, and samples for developing against the final Android M
+  development platform.
+</p>
+
+<ul>
+  <li>
+    <strong>SDK platform</strong> and <strong>system images</strong> (Nexus and
+    emulator) for building and testing. You can download the updated tools from
+    the SDK Manager, and the system images are available by over-the-air (OTA)
+    update or download (see below).
+  </li>
+
+  <li>
+    <strong>Updated documentation</strong>. The <a href=
+    "/preview/behavior-changes.html">Behavior Changes</a>, <a href=
+    "/preview/api-overview.html">API Overview</a>, and <a href=
+    "/preview/features/runtime-permissions.html">Permissions</a> documents have
+    been updated to reflect the latest changes in the platform. An updated
+    <a href="/preview/download.html">Developer Documentation download
+    package</a> is available, including full reference docs and API diff
+    reports.
+  </li>
+
+  <li>
+    <strong>Translations</strong> of the documentation are now available. Use
+    the language selector at the bottom right corner of any page to switch
+    languages. Note that some of the translated docs are not yet updated for
+    Developer Preview 3 (coming soon).
+  </li>
+
+  <li>The <a href="/preview/samples.html">Android M code samples</a> are also
+  updated to account for API and behavior changes:
+    <ul>
+      <li>
+        <a href=
+        "https://github.com/googlesamples/android-RuntimePermissions">RuntimePermissions</a>
+        / <a href=
+        "https://github.com/googlesamples/android-RuntimePermissionsBasic">RuntimePermissionsBasic</a>
+        are updated to reflect latest permissions API changes, including
+        <code>shouldShowRequestPermissionRationale()</code>.
+      </li>
+      <li>
+        <a href=
+        "https://github.com/googlesamples/android-FingerprintDialog">FingerprintDialog</a>
+        adds a flow to ask for passwords when new fingerprints are added as
+        well as a preference if the app will use fingerprints as a method of
+        authentication.
+      </li>
+    </ul>
+  </li>
+</ul>
+
+<h3 id="changes">
+  Key changes
+</h3>
+
+<ul>
+  <li>Add here
+    <ul>
+      <li>
+      </li>
+    </ul>
+  </li>
+
+  <li>Other changes
+    <ul>
+      <li>
+      </li>
+    </ul>
+  </li>
+</ul>
+
+<p>
+  For a complete list of changes, including renamed and removed APIs, please
+  refer to the API Diff reports below:</p>
+  <ul>
+  <li><a href="@docRoot"sdk/api_diff/mnc-preview-3/changes.html">API Differences: Preview 2 to Preview 3 (API level 23)</a></li>
+  <li><a href="@docRoot"sdk/api_diff/23/changes.html">API Differences: API level 22 to API level 23</a></li>
+  </ul>
+
+<h3 id="ki">
+  Known issues
+</h3>
+
+<ul>
+  <li>General issues:
+    <ul>
+      <li>Add
+      </li>
+    </ul>
+  </li>
+</ul>
+
+<p>
+  For a complete list of reported issues, please refer to the <a href=
+  "https://code.google.com/p/android/issues/list">open issues list</a> on the
+  Developer Preview <a href=
+  "https://code.google.com/p/android-developer-preview/">issue tracker</a>.
+</p>
+
+<h3 id="preview3-get">
+  Get Developer Preview 3
+</h3>
+
+<p>
+  You can download the Developer Preview 3 final SDK platform and
+  emulator images from the SDK Manager. 
+</p>
+
+<p>
+  Developer Preview 3 system images for supported Nexus devices are available
+  by download and by over-the-air (OTA) update. The OTA update is available
+  only to supported devices that are currently running a Developer Preview build.
+  If your device is running a Developer Preview build, you should automatically receive
+  the OTA update within a few days of availability.
+</p>
+
+<p>
+  If you are just getting started with Android M Developer Preview and want
+  to receive Developer Preview 3 via OTA, download the 
+  Developer Preview 2 <a href="{@docRoot}preview/download_mp2.html#images">
+  system image</a>, and flash it to your device. Then,
+  leave the device powered on for several hours. It registers with the
+  OTA service, and receives Developer Preview 3 by OTA.
+</p>
+
+<p>
+  For instructions on how to download and flash your device to the Developer
+  Preview, see the links and instructions on the <a href=
+  "/preview/download.html">Downloads</a> page.
+</p>
+
+<p>
+  For instructions on how to start developing and testing with Android M, read
+  <a href="/preview/setup-sdk.html">Setting up the SDK</a>.
+</p>
+
 <h2 id="preview2-notes">
   Developer Preview 2
 </h2>
@@ -164,8 +351,8 @@
       </li>
 
       <li>Remote Bluetooth/Wi-Fi MAC's now require either the
-      <code>android.permission.LOCATION_FINE</code> or
-      <code>android.permission.LOCATION_COARSE</code> permission.
+      <code>android.permission.ACCESS_COARSE_LOCATION</code> or
+      <code>android.permission.ACCESS_FINE_LOCATION</code> permission.
       </li>
 
       <li>Some accounts and identity permissions are moved to
diff --git a/graphics/java/android/graphics/Color.java b/graphics/java/android/graphics/Color.java
index 666dbd8..c627297 100644
--- a/graphics/java/android/graphics/Color.java
+++ b/graphics/java/android/graphics/Color.java
@@ -54,7 +54,6 @@
      * Return the alpha component of a color int. This is the same as saying
      * color >>> 24
      */
-    @ColorInt
     public static int alpha(int color) {
         return color >>> 24;
     }
@@ -63,7 +62,6 @@
      * Return the red component of a color int. This is the same as saying
      * (color >> 16) & 0xFF
      */
-    @ColorInt
     public static int red(int color) {
         return (color >> 16) & 0xFF;
     }
@@ -72,7 +70,6 @@
      * Return the green component of a color int. This is the same as saying
      * (color >> 8) & 0xFF
      */
-    @ColorInt
     public static int green(int color) {
         return (color >> 8) & 0xFF;
     }
@@ -81,7 +78,6 @@
      * Return the blue component of a color int. This is the same as saying
      * color & 0xFF
      */
-    @ColorInt
     public static int blue(int color) {
         return color & 0xFF;
     }
@@ -117,89 +113,21 @@
     }
 
     /**
-     * Returns the hue component of a color int.
-     * 
-     * @return A value between 0.0f and 1.0f
-     * 
-     * @hide Pending API council
-     */
-    public static float hue(@ColorInt int color) {
-        int r = (color >> 16) & 0xFF;
-        int g = (color >> 8) & 0xFF;
-        int b = color & 0xFF;
-
-        int V = Math.max(b, Math.max(r, g));
-        int temp = Math.min(b, Math.min(r, g));
-
-        float H;
-
-        if (V == temp) {
-            H = 0;
-        } else {
-            final float vtemp = (float) (V - temp);
-            final float cr = (V - r) / vtemp;
-            final float cg = (V - g) / vtemp;
-            final float cb = (V - b) / vtemp;
-
-            if (r == V) {
-                H = cb - cg;
-            } else if (g == V) {
-                H = 2 + cr - cb;
-            } else {
-                H = 4 + cg - cr;
-            }
-
-            H /= 6.f;
-            if (H < 0) {
-                H++;
-            }
-        }
-
-        return H;
-    }
-
-    /**
-     * Returns the saturation component of a color int.
-     * 
-     * @return A value between 0.0f and 1.0f
-     * 
-     * @hide Pending API council
-     */
-    public static float saturation(@ColorInt int color) {
-        int r = (color >> 16) & 0xFF;
-        int g = (color >> 8) & 0xFF;
-        int b = color & 0xFF;
-
-
-        int V = Math.max(b, Math.max(r, g));
-        int temp = Math.min(b, Math.min(r, g));
-
-        float S;
-
-        if (V == temp) {
-            S = 0;
-        } else {
-            S = (V - temp) / (float) V;
-        }
-
-        return S;
-    }
-
-    /**
-     * Returns the brightness component of a color int.
+     * Returns the relative luminance of a color.
+     * <p>
+     * Assumes sRGB encoding. Based on the formula for relative luminance
+     * defined in WCAG 2.0, W3C Recommendation 11 December 2008.
      *
-     * @return A value between 0.0f and 1.0f
-     *
-     * @hide Pending API council
+     * @return a value between 0 (darkest black) and 1 (lightest white)
      */
-    public static float brightness(@ColorInt int color) {
-        int r = (color >> 16) & 0xFF;
-        int g = (color >> 8) & 0xFF;
-        int b = color & 0xFF;
-
-        int V = Math.max(b, Math.max(r, g));
-
-        return (V / 255.f);
+    public static float luminance(@ColorInt int color) {
+        double red = Color.red(color) / 255.0;
+        red = red < 0.03928 ? red / 12.92 : Math.pow((red + 0.055) / 1.055, 2.4);
+        double green = Color.green(color) / 255.0;
+        green = green < 0.03928 ? green / 12.92 : Math.pow((green + 0.055) / 1.055, 2.4);
+        double blue = Color.blue(color) / 255.0;
+        blue = blue < 0.03928 ? blue / 12.92 : Math.pow((blue + 0.055) / 1.055, 2.4);
+        return (float) ((0.2126 * red) + (0.7152 * green) + (0.0722 * blue));
     }
 
     /**
@@ -236,89 +164,6 @@
     }
 
     /**
-     * Convert HSB components to an ARGB color. Alpha set to 0xFF.
-     *     hsv[0] is Hue [0 .. 1)
-     *     hsv[1] is Saturation [0...1]
-     *     hsv[2] is Value [0...1]
-     * If hsv values are out of range, they are pinned.
-     * @param hsb  3 element array which holds the input HSB components.
-     * @return the resulting argb color
-     * 
-     * @hide Pending API council
-     */
-    @ColorInt
-    public static int HSBtoColor(@Size(3) float[] hsb) {
-        return HSBtoColor(hsb[0], hsb[1], hsb[2]);
-    }
-    
-    /**
-     * Convert HSB components to an ARGB color. Alpha set to 0xFF.
-     *     hsv[0] is Hue [0 .. 1)
-     *     hsv[1] is Saturation [0...1]
-     *     hsv[2] is Value [0...1]
-     * If hsv values are out of range, they are pinned.
-     * @param h Hue component
-     * @param s Saturation component
-     * @param b Brightness component
-     * @return the resulting argb color
-     * 
-     * @hide Pending API council
-     */
-    @ColorInt
-    public static int HSBtoColor(float h, float s, float b) {
-        h = MathUtils.constrain(h, 0.0f, 1.0f);
-        s = MathUtils.constrain(s, 0.0f, 1.0f);
-        b = MathUtils.constrain(b, 0.0f, 1.0f);
-        
-        float red = 0.0f;
-        float green = 0.0f;
-        float blue = 0.0f;
-        
-        final float hf = (h - (int) h) * 6.0f;
-        final int ihf = (int) hf;
-        final float f = hf - ihf;
-        final float pv = b * (1.0f - s);
-        final float qv = b * (1.0f - s * f);
-        final float tv = b * (1.0f - s * (1.0f - f));
-
-        switch (ihf) {
-            case 0:         // Red is the dominant color
-                red = b;
-                green = tv;
-                blue = pv;
-                break;
-            case 1:         // Green is the dominant color
-                red = qv;
-                green = b;
-                blue = pv;
-                break;
-            case 2:
-                red = pv;
-                green = b;
-                blue = tv;
-                break;
-            case 3:         // Blue is the dominant color
-                red = pv;
-                green = qv;
-                blue = b;
-                break;
-            case 4:
-                red = tv;
-                green = pv;
-                blue = b;
-                break;
-            case 5:         // Red is the dominant color
-                red = b;
-                green = pv;
-                blue = qv;
-                break;
-        }
-
-        return 0xFF000000 | (((int) (red * 255.0f)) << 16) |
-                (((int) (green * 255.0f)) << 8) | ((int) (blue * 255.0f));
-    }
-
-    /**
      * Convert RGB components to HSV.
      *     hsv[0] is Hue [0 .. 360)
      *     hsv[1] is Saturation [0...1]
diff --git a/graphics/java/android/graphics/drawable/GradientDrawable.java b/graphics/java/android/graphics/drawable/GradientDrawable.java
index a11b2cd..d7fd8a5 100644
--- a/graphics/java/android/graphics/drawable/GradientDrawable.java
+++ b/graphics/java/android/graphics/drawable/GradientDrawable.java
@@ -17,10 +17,11 @@
 package android.graphics.drawable;
 
 import android.annotation.ColorInt;
+import android.annotation.Nullable;
 import android.content.res.ColorStateList;
 import android.content.res.Resources;
-import android.content.res.TypedArray;
 import android.content.res.Resources.Theme;
+import android.content.res.TypedArray;
 import android.graphics.Canvas;
 import android.graphics.Color;
 import android.graphics.ColorFilter;
@@ -198,34 +199,54 @@
     }
 
     /**
-     * <p>Specify radii for each of the 4 corners. For each corner, the array
-     * contains 2 values, <code>[X_radius, Y_radius]</code>. The corners are ordered
-     * top-left, top-right, bottom-right, bottom-left. This property
-     * is honored only when the shape is of type {@link #RECTANGLE}.</p>
-     * <p><strong>Note</strong>: changing this property will affect all instances
+     * Specifies radii for each of the 4 corners. For each corner, the array
+     * contains 2 values, <code>[X_radius, Y_radius]</code>. The corners are
+     * ordered top-left, top-right, bottom-right, bottom-left. This property
+     * is honored only when the shape is of type {@link #RECTANGLE}.
+     * <p>
+     * <strong>Note</strong>: changing this property will affect all instances
      * of a drawable loaded from a resource. It is recommended to invoke
-     * {@link #mutate()} before changing this property.</p>
+     * {@link #mutate()} before changing this property.
      *
-     * @param radii 4 pairs of X and Y radius for each corner, specified in pixels.
-     *              The length of this array must be >= 8
+     * @param radii an array of length >= 8 containing 4 pairs of X and Y
+     *              radius for each corner, specified in pixels
      *
      * @see #mutate()
-     * @see #setCornerRadii(float[])
      * @see #setShape(int)
+     * @see #setCornerRadius(float)
      */
-    public void setCornerRadii(float[] radii) {
+    public void setCornerRadii(@Nullable float[] radii) {
         mGradientState.setCornerRadii(radii);
         mPathIsDirty = true;
         invalidateSelf();
     }
 
     /**
-     * <p>Specify radius for the corners of the gradient. If this is > 0, then the
-     * drawable is drawn in a round-rectangle, rather than a rectangle. This property
-     * is honored only when the shape is of type {@link #RECTANGLE}.</p>
-     * <p><strong>Note</strong>: changing this property will affect all instances
+     * Returns the radii for each of the 4 corners. For each corner, the array
+     * contains 2 values, <code>[X_radius, Y_radius]</code>. The corners are
+     * ordered top-left, top-right, bottom-right, bottom-left.
+     * <p>
+     * If the radius was previously set with {@link #setCornerRadius(float)},
+     * or if the corners are not rounded, this method will return {@code null}.
+     *
+     * @return an array containing the radii for each of the 4 corners, or
+     *         {@code null}
+     * @see #setCornerRadii(float[])
+     */
+    @Nullable
+    public float[] getCornerRadii() {
+        return mGradientState.mRadiusArray.clone();
+    }
+
+    /**
+     * Specifies the radius for the corners of the gradient. If this is > 0,
+     * then the drawable is drawn in a round-rectangle, rather than a
+     * rectangle. This property is honored only when the shape is of type
+     * {@link #RECTANGLE}.
+     * <p>
+     * <strong>Note</strong>: changing this property will affect all instances
      * of a drawable loaded from a resource. It is recommended to invoke
-     * {@link #mutate()} before changing this property.</p>
+     * {@link #mutate()} before changing this property.
      *
      * @param radius The radius in pixels of the corners of the rectangle shape
      *
@@ -240,6 +261,19 @@
     }
 
     /**
+     * Returns the radius for the corners of the gradient.
+     * <p>
+     * If the radius was previously set with {@link #setCornerRadii(float[])},
+     * or if the corners are not rounded, this method will return {@code null}.
+     *
+     * @return the radius in pixels of the corners of the rectangle shape, or 0
+     * @see #setCornerRadius
+     */
+    public float getCornerRadius() {
+        return mGradientState.mRadius;
+    }
+
+    /**
      * <p>Set the stroke width and color for the drawable. If width is zero,
      * then no stroke is drawn.</p>
      * <p><strong>Note</strong>: changing this property will affect all instances
@@ -376,15 +410,17 @@
     }
 
     /**
-     * <p>Sets the type of gradient used by this drawable..</p>
-     * <p><strong>Note</strong>: changing this property will affect all instances
+     * Sets the type of gradient used by this drawable.
+     * <p>
+     * <strong>Note</strong>: changing this property will affect all instances
      * of a drawable loaded from a resource. It is recommended to invoke
-     * {@link #mutate()} before changing this property.</p>
+     * {@link #mutate()} before changing this property.
      *
      * @param gradient The type of the gradient: {@link #LINEAR_GRADIENT},
      *                 {@link #RADIAL_GRADIENT} or {@link #SWEEP_GRADIENT}
      *
      * @see #mutate()
+     * @see #getGradientType()
      */
     public void setGradientType(int gradient) {
         mGradientState.setGradientType(gradient);
@@ -393,17 +429,33 @@
     }
 
     /**
-     * <p>Sets the center location of the gradient. The radius is honored only when
-     * the gradient type is set to {@link #RADIAL_GRADIENT} or {@link #SWEEP_GRADIENT}.</p>
-     * <p><strong>Note</strong>: changing this property will affect all instances
-     * of a drawable loaded from a resource. It is recommended to invoke
-     * {@link #mutate()} before changing this property.</p>
+     * Returns the type of gradient used by this drawable, one of
+     * {@link #LINEAR_GRADIENT}, {@link #RADIAL_GRADIENT}, or
+     * {@link #SWEEP_GRADIENT}.
      *
-     * @param x The x coordinate of the gradient's center
-     * @param y The y coordinate of the gradient's center
+     * @return the type of gradient used by this drawable
+     * @see #setGradientType(int)
+     */
+    public int getGradientType() {
+        return mGradientState.mGradient;
+    }
+
+    /**
+     * Sets the center location in pixels of the gradient. The radius is
+     * honored only when the gradient type is set to {@link #RADIAL_GRADIENT}
+     * or {@link #SWEEP_GRADIENT}.
+     * <p>
+     * <strong>Note</strong>: changing this property will affect all instances
+     * of a drawable loaded from a resource. It is recommended to invoke
+     * {@link #mutate()} before changing this property.
+     *
+     * @param x the x coordinate of the gradient's center in pixels
+     * @param y the y coordinate of the gradient's center in pixels
      *
      * @see #mutate()
      * @see #setGradientType(int)
+     * @see #getGradientCenterX()
+     * @see #getGradientCenterY()
      */
     public void setGradientCenter(float x, float y) {
         mGradientState.setGradientCenter(x, y);
@@ -412,16 +464,38 @@
     }
 
     /**
-     * <p>Sets the radius of the gradient. The radius is honored only when the
-     * gradient type is set to {@link #RADIAL_GRADIENT}.</p>
-     * <p><strong>Note</strong>: changing this property will affect all instances
-     * of a drawable loaded from a resource. It is recommended to invoke
-     * {@link #mutate()} before changing this property.</p>
+     * Returns the center X location of this gradient in pixels.
      *
-     * @param gradientRadius The radius of the gradient in pixels
+     * @return the center X location of this gradient in pixels
+     * @see #setGradientCenter(float, float)
+     */
+    public float getGradientCenterX() {
+        return mGradientState.mCenterX;
+    }
+
+    /**
+     * Returns the center Y location of this gradient in pixels.
+     *
+     * @return the center Y location of this gradient in pixels
+     * @see #setGradientCenter(float, float)
+     */
+    public float getGradientCenterY() {
+        return mGradientState.mCenterY;
+    }
+
+    /**
+     * Sets the radius of the gradient. The radius is honored only when the
+     * gradient type is set to {@link #RADIAL_GRADIENT}.
+     * <p>
+     * <strong>Note</strong>: changing this property will affect all instances
+     * of a drawable loaded from a resource. It is recommended to invoke
+     * {@link #mutate()} before changing this property.
+     *
+     * @param gradientRadius the radius of the gradient in pixels
      *
      * @see #mutate()
      * @see #setGradientType(int)
+     * @see #getGradientRadius()
      */
     public void setGradientRadius(float gradientRadius) {
         mGradientState.setGradientRadius(gradientRadius, TypedValue.COMPLEX_UNIT_PX);
@@ -433,7 +507,8 @@
      * Returns the radius of the gradient in pixels. The radius is valid only
      * when the gradient type is set to {@link #RADIAL_GRADIENT}.
      *
-     * @return Radius in pixels.
+     * @return the radius of the gradient in pixels
+     * @see #setGradientRadius(float)
      */
     public float getGradientRadius() {
         if (mGradientState.mGradient != RADIAL_GRADIENT) {
@@ -445,17 +520,19 @@
     }
 
     /**
-     * <p>Sets whether or not this drawable will honor its <code>level</code>
-     * property.</p>
-     * <p><strong>Note</strong>: changing this property will affect all instances
+     * Sets whether or not this drawable will honor its {@code level} property.
+     * <p>
+     * <strong>Note</strong>: changing this property will affect all instances
      * of a drawable loaded from a resource. It is recommended to invoke
-     * {@link #mutate()} before changing this property.</p>
+     * {@link #mutate()} before changing this property.
      *
-     * @param useLevel True if this drawable should honor its level, false otherwise
+     * @param useLevel {@code true} if this drawable should honor its level,
+     *                 {@code false} otherwise
      *
      * @see #mutate()
      * @see #setLevel(int)
      * @see #getLevel()
+     * @see #isUseLevel()
      */
     public void setUseLevel(boolean useLevel) {
         mGradientState.mUseLevel = useLevel;
@@ -463,6 +540,18 @@
         invalidateSelf();
     }
 
+    /**
+     * Returns whether or not this drawable will honor its {@code level}
+     * property.
+     *
+     * @return {@code true} if this drawable should honor its level,
+     *         {@code false} otherwise
+     * @see #setUseLevel(boolean)
+     */
+    public boolean isUseLevel() {
+        return mGradientState.mUseLevel;
+    }
+
     private int modulateAlpha(int alpha) {
         int scale = mAlpha + (mAlpha >> 7);
         return alpha * scale >> 8;
@@ -470,20 +559,25 @@
 
     /**
      * Returns the orientation of the gradient defined in this drawable.
+     *
+     * @return the orientation of the gradient defined in this drawable
+     * @see #setOrientation(Orientation)
      */
     public Orientation getOrientation() {
         return mGradientState.mOrientation;
     }
 
     /**
-     * <p>Changes the orientation of the gradient defined in this drawable.</p>
-     * <p><strong>Note</strong>: changing orientation will affect all instances
+     * Sets the orientation of the gradient defined in this drawable.
+     * <p>
+     * <strong>Note</strong>: changing orientation will affect all instances
      * of a drawable loaded from a resource. It is recommended to invoke
-     * {@link #mutate()} before changing the orientation.</p>
+     * {@link #mutate()} before changing the orientation.
      *
-     * @param orientation The desired orientation (angle) of the gradient
+     * @param orientation the desired orientation (angle) of the gradient
      *
      * @see #mutate()
+     * @see #getOrientation()
      */
     public void setOrientation(Orientation orientation) {
         mGradientState.mOrientation = orientation;
@@ -511,6 +605,18 @@
         invalidateSelf();
     }
 
+    /**
+     * Returns the colors used to draw the gradient, or {@code null} if the
+     * gradient is drawn using a single color or no colors.
+     *
+     * @return the colors used to draw the gradient, or {@code null}
+     * @see #setColors(int[] colors)
+     */
+    @Nullable
+    public int[] getColors() {
+        return mGradientState.mGradientColors.clone();
+    }
+
     @Override
     public void draw(Canvas canvas) {
         if (!ensureValidRect()) {
@@ -707,15 +813,17 @@
     }
 
     /**
-     * <p>Changes this drawable to use a single color instead of a gradient.</p>
-     * <p><strong>Note</strong>: changing color will affect all instances
-     * of a drawable loaded from a resource. It is recommended to invoke
-     * {@link #mutate()} before changing the color.</p>
+     * Changes this drawable to use a single color instead of a gradient.
+     * <p>
+     * <strong>Note</strong>: changing color will affect all instances of a
+     * drawable loaded from a resource. It is recommended to invoke
+     * {@link #mutate()} before changing the color.
      *
      * @param argb The color used to fill the shape
      *
      * @see #mutate()
      * @see #setColors(int[])
+     * @see #getColor
      */
     public void setColor(@ColorInt int argb) {
         mGradientState.setSolidColors(ColorStateList.valueOf(argb));
@@ -734,7 +842,9 @@
      * {@link #mutate()} before changing the color.</p>
      *
      * @param colorStateList The color state list used to fill the shape
+     *
      * @see #mutate()
+     * @see #getColor
      */
     public void setColor(ColorStateList colorStateList) {
         mGradientState.setSolidColors(colorStateList);
@@ -749,6 +859,19 @@
         invalidateSelf();
     }
 
+    /**
+     * Returns the color state list used to fill the shape, or {@code null} if
+     * the shape is filled with a gradient or has no fill color.
+     *
+     * @return the color state list used to fill this gradient, or {@code null}
+     *
+     * @see #setColor(int)
+     * @see #setColor(ColorStateList)
+     */
+    public ColorStateList getColor() {
+        return mGradientState.mSolidColors;
+    }
+
     @Override
     protected boolean onStateChange(int[] stateSet) {
         boolean invalidateSelf = false;
diff --git a/graphics/java/android/graphics/drawable/NinePatchDrawable.java b/graphics/java/android/graphics/drawable/NinePatchDrawable.java
index 152fe6a..231405d 100644
--- a/graphics/java/android/graphics/drawable/NinePatchDrawable.java
+++ b/graphics/java/android/graphics/drawable/NinePatchDrawable.java
@@ -213,7 +213,12 @@
         }
     }
 
-    private void setNinePatch(NinePatch ninePatch) {
+    /**
+     * Sets the nine patch used by this drawable.
+     *
+     * @param ninePatch the nine patch for this drawable
+     */
+    public void setNinePatch(NinePatch ninePatch) {
         if (mNinePatch != ninePatch) {
             mNinePatch = ninePatch;
             if (ninePatch != null) {
@@ -226,6 +231,13 @@
         }
     }
 
+    /**
+     * @return the nine patch used by this drawable
+     */
+    public NinePatch getNinePatch() {
+        return mNinePatch;
+    }
+
     @Override
     public void draw(Canvas canvas) {
         final Rect bounds = getBounds();
diff --git a/graphics/java/android/graphics/drawable/RippleDrawable.java b/graphics/java/android/graphics/drawable/RippleDrawable.java
index bf069d3..32f6a89 100644
--- a/graphics/java/android/graphics/drawable/RippleDrawable.java
+++ b/graphics/java/android/graphics/drawable/RippleDrawable.java
@@ -786,12 +786,16 @@
             mMaskColorFilter = new PorterDuffColorFilter(0, PorterDuff.Mode.SRC_IN);
         }
 
-        // Draw the appropriate mask.
+        // Draw the appropriate mask anchored to (0,0).
+        final int left = bounds.left;
+        final int top = bounds.top;
+        mMaskCanvas.translate(-left, -top);
         if (maskType == MASK_EXPLICIT) {
             drawMask(mMaskCanvas);
         } else if (maskType == MASK_CONTENT) {
             drawContent(mMaskCanvas);
         }
+        mMaskCanvas.translate(left, top);
     }
 
     private int getMaskType() {
diff --git a/keystore/java/android/security/keystore/KeyGenParameterSpec.java b/keystore/java/android/security/keystore/KeyGenParameterSpec.java
index 7605231..f42d750 100644
--- a/keystore/java/android/security/keystore/KeyGenParameterSpec.java
+++ b/keystore/java/android/security/keystore/KeyGenParameterSpec.java
@@ -38,27 +38,35 @@
 /**
  * {@link AlgorithmParameterSpec} for initializing a {@link KeyPairGenerator} or a
  * {@link KeyGenerator} of the <a href="{@docRoot}training/articles/keystore.html">Android Keystore
- * system</a>. The spec determines whether user authentication is required for using the key, what
- * uses the key is authorized for (e.g., only for signing -- decryption not permitted), the key's
- * validity start and end dates.
+ * system</a>. The spec determines authorized uses of the key, such as whether user authentication
+ * is required for using the key, what operations are authorized (e.g., signing, but not
+ * decryption) and with what parameters (e.g., only with a particular padding scheme or digest), the
+ * key's validity start and end dates. Key use authorizations expressed in the spec apply only to
+ * secret keys and private keys -- public keys can be used for any supported operations.
  *
  * <p>To generate an asymmetric key pair or a symmetric key, create an instance of this class using
  * the {@link Builder}, initialize a {@code KeyPairGenerator} or a {@code KeyGenerator} of the
  * desired key type (e.g., {@code EC} or {@code AES} -- see
  * {@link KeyProperties}.{@code KEY_ALGORITHM} constants) from the {@code AndroidKeyStore} provider
- * with the {@code KeyPairGeneratorSpec} instance, and then generate a key or key pair using
- * {@link KeyPairGenerator#generateKeyPair()}.
+ * with the {@code KeyGenParameterSpec} instance, and then generate a key or key pair using
+ * {@link KeyGenerator#generateKey()} or {@link KeyPairGenerator#generateKeyPair()}.
  *
  * <p>The generated key pair or key will be returned by the generator and also stored in the Android
- * Keystore system under the alias specified in this spec. To obtain the secret or private key from
- * the Android KeyStore use {@link java.security.KeyStore#getKey(String, char[]) KeyStore.getKey(String, null)}
+ * Keystore under the alias specified in this spec. To obtain the secret or private key from the
+ * Android Keystore use {@link java.security.KeyStore#getKey(String, char[]) KeyStore.getKey(String, null)}
  * or {@link java.security.KeyStore#getEntry(String, java.security.KeyStore.ProtectionParameter) KeyStore.getEntry(String, null)}.
- * To obtain the public key from the Android Keystore system use
+ * To obtain the public key from the Android Keystore use
  * {@link java.security.KeyStore#getCertificate(String)} and then
  * {@link Certificate#getPublicKey()}.
  *
+ * <p>To help obtain algorithm-specific public parameters of key pairs stored in the Android
+ * Keystore, generated private keys implement {@link java.security.interfaces.ECKey} or
+ * {@link java.security.interfaces.RSAKey} interfaces whereas public keys implement
+ * {@link java.security.interfaces.ECPublicKey} or {@link java.security.interfaces.RSAPublicKey}
+ * interfaces.
+ *
  * <p>For asymmetric key pairs, a self-signed X.509 certificate will be also generated and stored in
- * the Android KeyStore. This is because the {@link java.security.KeyStore} abstraction does not
+ * the Android Keystore. This is because the {@link java.security.KeyStore} abstraction does not
  * support storing key pairs without a certificate. The subject, serial number, and validity dates
  * of the certificate can be customized in this spec. The self-signed certificate may be replaced at
  * a later time by a certificate signed by a Certificate Authority (CA).
@@ -82,27 +90,33 @@
  *
  * <p>Instances of this class are immutable.
  *
- * <p><h3>Example: Asymmetric key pair</h3>
- * The following example illustrates how to generate an EC key pair in the Android KeyStore system
- * under alias {@code key1} authorized to be used only for signing using SHA-256, SHA-384,
- * or SHA-512 digest and only if the user has been authenticated within the last five minutes.
+ * <p><h3>Example: NIST P-256 EC key pair for signing/verification using ECDSA</h3>
+ * This example illustrates how to generate a NIST P-256 (aka secp256r1 aka prime256v1) EC key pair
+ * in the Android KeyStore system under alias {@code key1} where the private key is authorized to be
+ * used only for signing using SHA-256, SHA-384, or SHA-512 digest and only if the user has been
+ * authenticated within the last five minutes. The use of public key is unrestricted, thus
+ * permitting signature verification using any padding schemes and digests, and without user
+ * authentication.
  * <pre> {@code
  * KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
- *         KeyProperties.KEY_ALGORITHM_EC,
- *         "AndroidKeyStore");
+ *         KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore");
  * keyPairGenerator.initialize(
  *         new KeyGenParameterSpec.Builder(
  *                 "key1",
- *                 KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY)
+ *                 KeyProperties.PURPOSE_SIGN)
+ *                 .setAlgorithmParameterSpec(new ECGenParameterSpec("secp256r1"))
  *                 .setDigests(KeyProperties.DIGEST_SHA256,
  *                         KeyProperties.DIGEST_SHA384,
  *                         KeyProperties.DIGEST_SHA512)
- *                 // Only permit this key to be used if the user authenticated
+ *                 // Only permit the private key to be used if the user authenticated
  *                 // within the last five minutes.
  *                 .setUserAuthenticationRequired(true)
  *                 .setUserAuthenticationValidityDurationSeconds(5 * 60)
  *                 .build());
  * KeyPair keyPair = keyPairGenerator.generateKeyPair();
+ * Signature signature = Signature.getInstance("SHA256withECDSA");
+ * signature.initSign(keyPair.getPrivate());
+ * ...
  *
  * // The key pair can also be obtained from the Android Keystore any time as follows:
  * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
@@ -111,14 +125,67 @@
  * PublicKey publicKey = keyStore.getCertificate("key1").getPublicKey();
  * }</pre>
  *
- * <p><h3>Example: Symmetric key</h3>
+ * <p><h3>Example: RSA key pair for signing/verification using RSA-PSS</h3>
+ * This example illustrates how to generate an RSA key pair in the Android KeyStore system under
+ * alias {@code key1} authorized to be used only for signing using the RSA-PSS signature padding
+ * scheme with SHA-256 or SHA-512 digests. The use of public key is unrestricted, thus permitting
+ * signature verification using any padding schemes and digests.
+ * <pre> {@code
+ * KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
+ *         KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
+ * keyPairGenerator.initialize(
+ *         new KeyGenParameterSpec.Builder(
+ *                 "key1",
+ *                 KeyProperties.PURPOSE_SIGN)
+ *                 .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
+ *                 .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PSS)
+ *                 .build());
+ * KeyPair keyPair = keyPairGenerator.generateKeyPair();
+ * Signature signature = Signature.getInstance("SHA256withRSA/PSS");
+ * signature.initSign(keyPair.getPrivate());
+ * ...
+ *
+ * // The key pair can also be obtained from the Android Keystore any time as follows:
+ * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
+ * keyStore.load(null);
+ * PrivateKey privateKey = (PrivateKey) keyStore.getKey("key1", null);
+ * PublicKey publicKey = keyStore.getCertificate("key1").getPublicKey();
+ * }</pre>
+ *
+ * <p><h3>Example: RSA key pair for encryption/decryption using RSA OAEP</h3>
+ * This example illustrates how to generate an RSA key pair in the Android KeyStore system under
+ * alias {@code key1} where the private key is authorized to be used only for decryption using RSA
+ * OAEP encryption padding scheme with SHA-256 or SHA-512 digests. The use of public key is
+ * unrestricted, thus permitting encryption using any padding schemes and digests.
+ * <pre> {@code
+ * KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
+ *         KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
+ * keyPairGenerator.initialize(
+ *         new KeyGenParameterSpec.Builder(
+ *                 "key1",
+ *                 KeyProperties.PURPOSE_DECRYPT)
+ *                 .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
+ *                 .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP)
+ *                 .build());
+ * KeyPair keyPair = keyPairGenerator.generateKeyPair();
+ * Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
+ * cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
+ * ...
+ *
+ * // The key pair can also be obtained from the Android Keystore any time as follows:
+ * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
+ * keyStore.load(null);
+ * PrivateKey privateKey = (PrivateKey) keyStore.getKey("key1", null);
+ * PublicKey publicKey = keyStore.getCertificate("key1").getPublicKey();
+ * }</pre>
+ *
+ * <p><h3>Example: AES key for encryption/decryption in GCM mode</h3>
  * The following example illustrates how to generate an AES key in the Android KeyStore system under
  * alias {@code key2} authorized to be used only for encryption/decryption in GCM mode with no
  * padding.
  * <pre> {@code
  * KeyGenerator keyGenerator = KeyGenerator.getInstance(
- *         KeyProperties.KEY_ALGORITHM_AES,
- *         "AndroidKeyStore");
+ *         KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
  * keyGenerator.initialize(
  *         new KeyGenParameterSpec.Builder("key2",
  *                 KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
@@ -127,6 +194,29 @@
  *                 .build());
  * SecretKey key = keyGenerator.generateKey();
  *
+ * Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
+ * cipher.init(Cipher.ENCRYPT_MODE, key);
+ * ...
+ *
+ * // The key can also be obtained from the Android Keystore any time as follows:
+ * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
+ * keyStore.load(null);
+ * key = (SecretKey) keyStore.getKey("key2", null);
+ * }</pre>
+ *
+ * <p><h3>Example: HMAC key for generating a MAC using SHA-256</h3>
+ * This example illustrates how to generate an HMAC key in the Android KeyStore system under alias
+ * {@code key2} authorized to be used only for generating an HMAC using SHA-256.
+ * <pre> {@code
+ * KeyGenerator keyGenerator = KeyGenerator.getInstance(
+ *         KeyProperties.KEY_ALGORITHM_HMAC_SHA256, "AndroidKeyStore");
+ * keyGenerator.initialize(
+ *         new KeyGenParameterSpec.Builder("key2", KeyProperties.PURPOSE_SIGN).build());
+ * SecretKey key = keyGenerator.generateKey();
+ * Mac mac = Mac.getInstance("HmacSHA256");
+ * mac.init(key);
+ * ...
+ *
  * // The key can also be obtained from the Android Keystore any time as follows:
  * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
  * keyStore.load(null);
diff --git a/keystore/java/android/security/keystore/KeyProtection.java b/keystore/java/android/security/keystore/KeyProtection.java
index b71dc82..c984439 100644
--- a/keystore/java/android/security/keystore/KeyProtection.java
+++ b/keystore/java/android/security/keystore/KeyProtection.java
@@ -33,28 +33,36 @@
 
 /**
  * Specification of how a key or key pair is secured when imported into the
- * <a href="{@docRoot}training/articles/keystore.html">Android KeyStore facility</a>. This class
- * specifies parameters such as whether user authentication is required for using the key, what uses
- * the key is authorized for (e.g., only in {@code GCM} mode, or only for signing -- decryption not
- * permitted), the key's and validity start and end dates.
+ * <a href="{@docRoot}training/articles/keystore.html">Android Keystore system</a>. This class
+ * specifies authorized uses of the imported key, such as whether user authentication is required
+ * for using the key, what operations the key is authorized for (e.g., decryption, but not signing)
+ * and with what parameters (e.g., only with a particular padding scheme or digest), the key's and
+ * validity start and end dates. Key use authorizations expressed in this class apply only to secret
+ * keys and private keys -- public keys can be used for any supported operations.
  *
- * <p>To import a key or key pair into the Android KeyStore, create an instance of this class using
+ * <p>To import a key or key pair into the Android Keystore, create an instance of this class using
  * the {@link Builder} and pass the instance into {@link java.security.KeyStore#setEntry(String, java.security.KeyStore.Entry, ProtectionParameter) KeyStore.setEntry}
  * with the key or key pair being imported.
  *
- * <p>To obtain the secret/symmetric or private key from the Android KeyStore use
+ * <p>To obtain the secret/symmetric or private key from the Android Keystore use
  * {@link java.security.KeyStore#getKey(String, char[]) KeyStore.getKey(String, null)} or
  * {@link java.security.KeyStore#getEntry(String, java.security.KeyStore.ProtectionParameter) KeyStore.getEntry(String, null)}.
- * To obtain the public key from the Android KeyStore use
+ * To obtain the public key from the Android Keystore use
  * {@link java.security.KeyStore#getCertificate(String)} and then
  * {@link Certificate#getPublicKey()}.
  *
- * <p>NOTE: The key material of keys stored in the Android KeyStore is not accessible.
+ * <p>To help obtain algorithm-specific public parameters of key pairs stored in the Android
+ * Keystore, its private keys implement {@link java.security.interfaces.ECKey} or
+ * {@link java.security.interfaces.RSAKey} interfaces whereas its public keys implement
+ * {@link java.security.interfaces.ECPublicKey} or {@link java.security.interfaces.RSAPublicKey}
+ * interfaces.
+ *
+ * <p>NOTE: The key material of keys stored in the Android Keystore is not accessible.
  *
  * <p>Instances of this class are immutable.
  *
- * <p><h3>Example: Symmetric Key</h3>
- * The following example illustrates how to import an AES key into the Android KeyStore under alias
+ * <p><h3>Example: AES key for encryption/decryption in GCM mode</h3>
+ * This example illustrates how to import an AES key into the Android KeyStore under alias
  * {@code key1} authorized to be used only for encryption/decryption in GCM mode with no padding.
  * The key must export its key material via {@link Key#getEncoded()} in {@code RAW} format.
  * <pre> {@code
@@ -71,15 +79,41 @@
  *                 .build());
  * // Key imported, obtain a reference to it.
  * SecretKey keyStoreKey = (SecretKey) keyStore.getKey("key1", null);
- * // The original key can now be thrown away.
+ * // The original key can now be discarded.
+ *
+ * Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
+ * cipher.init(Cipher.ENCRYPT_MODE, keyStoreKey);
+ * ...
  * }</pre>
  *
- * <p><h3>Example: Asymmetric Key Pair</h3>
- * The following example illustrates how to import an EC key pair into the Android KeyStore under
- * alias {@code key2} authorized to be used only for signing with SHA-256 digest and only if
- * the user has been authenticated within the last ten minutes. Both the private and the public key
- * must export their key material via {@link Key#getEncoded()} in {@code PKCS#8} and {@code X.509}
- * format respectively.
+ * <p><h3>Example: HMAC key for generating MACs using SHA-512</h3>
+ * This example illustrates how to import an HMAC key into the Android KeyStore under alias
+ * {@code key1} authorized to be used only for generating MACs using SHA-512 digest. The key must
+ * export its key material via {@link Key#getEncoded()} in {@code RAW} format.
+ * <pre> {@code
+ * SecretKey key = ...; // HMAC key of algorithm "HmacSHA512".
+ *
+ * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
+ * keyStore.load(null);
+ * keyStore.setEntry(
+ *         "key1",
+ *         new KeyStore.SecretKeyEntry(key),
+ *         new KeyProtection.Builder(KeyProperties.PURPOSE_SIGN).build());
+ * // Key imported, obtain a reference to it.
+ * SecretKey keyStoreKey = (SecretKey) keyStore.getKey("key1", null);
+ * // The original key can now be discarded.
+ *
+ * Mac mac = Mac.getInstance("HmacSHA512");
+ * mac.init(keyStoreKey);
+ * ...
+ * }</pre>
+ *
+ * <p><h3>Example: EC key pair for signing/verification using ECDSA</h3>
+ * This example illustrates how to import an EC key pair into the Android KeyStore under alias
+ * {@code key2} with the private key authorized to be used only for signing with SHA-256 or SHA-512
+ * digests. The use of public key is unrestricted, thus permitting signature verification using any
+ * digests. Both the private and the public key must export their key material via
+ * {@link Key#getEncoded()} in {@code PKCS#8} and {@code X.509} format respectively.
  * <pre> {@code
  * PrivateKey privateKey = ...;   // EC private key
  * Certificate[] certChain = ...; // Certificate chain with the first certificate
@@ -91,7 +125,39 @@
  *         "key2",
  *         new KeyStore.PrivateKeyEntry(privateKey, certChain),
  *         new KeyProtection.Builder(KeyProperties.PURPOSE_SIGN)
+ *                 .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
+ *                 .build());
+ * // Key pair imported, obtain a reference to it.
+ * PrivateKey keyStorePrivateKey = (PrivateKey) keyStore.getKey("key2", null);
+ * PublicKey publicKey = keyStore.getCertificate("key2").getPublicKey();
+ * // The original private key can now be discarded.
+ *
+ * Signature signature = Signature.getInstance("SHA256withECDSA");
+ * signature.initSign(keyStorePrivateKey);
+ * ...
+ * }</pre>
+ *
+ * <p><h3>Example: RSA key pair for signing/verification using PKCS#1 padding</h3>
+ * This example illustrates how to import an RSA key pair into the Android KeyStore under alias
+ * {@code key2} with the private key authorized to be used only for signing using the PKCS#1
+ * signature padding scheme with SHA-256 digest and only if the user has been authenticated within
+ * the last ten minutes. The use of public key is unrestricted, thus permitting signature
+ * verification using any padding schemes and digests, and without user authentication. Both the
+ * private and the public key must export their key material via {@link Key#getEncoded()} in
+ * {@code PKCS#8} and {@code X.509} format respectively.
+ * <pre> {@code
+ * PrivateKey privateKey = ...;   // RSA private key
+ * Certificate[] certChain = ...; // Certificate chain with the first certificate
+ *                                // containing the corresponding RSA public key.
+ *
+ * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
+ * keyStore.load(null);
+ * keyStore.setEntry(
+ *         "key2",
+ *         new KeyStore.PrivateKeyEntry(privateKey, certChain),
+ *         new KeyProtection.Builder(KeyProperties.PURPOSE_SIGN)
  *                 .setDigests(KeyProperties.DIGEST_SHA256)
+ *                 .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1)
  *                 // Only permit this key to be used if the user
  *                 // authenticated within the last ten minutes.
  *                 .setUserAuthenticationRequired(true)
@@ -100,7 +166,40 @@
  * // Key pair imported, obtain a reference to it.
  * PrivateKey keyStorePrivateKey = (PrivateKey) keyStore.getKey("key2", null);
  * PublicKey publicKey = keyStore.getCertificate("key2").getPublicKey();
- * // The original private key can now be thrown away.
+ * // The original private key can now be discarded.
+ *
+ * Signature signature = Signature.getInstance("SHA256withRSA");
+ * signature.initSign(keyStorePrivateKey);
+ * ...
+ * }</pre>
+ *
+ * <p><h3>Example: RSA key pair for encryption/decryption using PKCS#1 padding</h3>
+ * This example illustrates how to import an RSA key pair into the Android KeyStore under alias
+ * {@code key2} with the private key authorized to be used only for decryption using the PKCS#1
+ * encryption padding scheme. The use of public key is unrestricted, thus permitting encryption
+ * using any padding schemes and digests. Both the private and the public key must export their key
+ * material via {@link Key#getEncoded()} in {@code PKCS#8} and {@code X.509} format respectively.
+ * <pre> {@code
+ * PrivateKey privateKey = ...;   // RSA private key
+ * Certificate[] certChain = ...; // Certificate chain with the first certificate
+ *                                // containing the corresponding RSA public key.
+ *
+ * KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
+ * keyStore.load(null);
+ * keyStore.setEntry(
+ *         "key2",
+ *         new KeyStore.PrivateKeyEntry(privateKey, certChain),
+ *         new KeyProtection.Builder(KeyProperties.PURPOSE_DECRYPT)
+ *                 .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
+ *                 .build());
+ * // Key pair imported, obtain a reference to it.
+ * PrivateKey keyStorePrivateKey = (PrivateKey) keyStore.getKey("key2", null);
+ * PublicKey publicKey = keyStore.getCertificate("key2").getPublicKey();
+ * // The original private key can now be discarded.
+ *
+ * Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
+ * cipher.init(Cipher.DECRYPT_MODE, keyStorePrivateKey);
+ * ...
  * }</pre>
  */
 public final class KeyProtection implements ProtectionParameter {
diff --git a/libs/androidfw/AssetManager.cpp b/libs/androidfw/AssetManager.cpp
index 1c39ffe..623ea89 100644
--- a/libs/androidfw/AssetManager.cpp
+++ b/libs/androidfw/AssetManager.cpp
@@ -34,7 +34,7 @@
 #include <utils/String8.h>
 #include <utils/threads.h>
 #include <utils/Timers.h>
-#ifdef HAVE_ANDROID_OS
+#ifdef __ANDROID__
 #include <cutils/trace.h>
 #endif
 
@@ -54,7 +54,7 @@
     _rc; })
 #endif
 
-#ifdef HAVE_ANDROID_OS
+#ifdef __ANDROID__
 #define MY_TRACE_BEGIN(x) ATRACE_BEGIN(x)
 #define MY_TRACE_END() ATRACE_END()
 #else
@@ -229,7 +229,7 @@
         *cookie = static_cast<int32_t>(mAssetPaths.size());
     }
 
-#ifdef HAVE_ANDROID_OS
+#ifdef __ANDROID__
     // Load overlays, if any
     asset_path oap;
     for (size_t idx = 0; mZipSet.getOverlay(ap.path, idx, &oap); idx++) {
@@ -657,7 +657,7 @@
                 ALOGV("Creating shared resources for %s", ap.path.string());
                 sharedRes = new ResTable();
                 sharedRes->add(ass, idmap, nextEntryIdx + 1, false);
-#ifdef HAVE_ANDROID_OS
+#ifdef __ANDROID__
                 const char* data = getenv("ANDROID_DATA");
                 LOG_ALWAYS_FATAL_IF(data == NULL, "ANDROID_DATA not set");
                 String8 overlaysListPath(data);
diff --git a/libs/androidfw/ResourceTypes.cpp b/libs/androidfw/ResourceTypes.cpp
index 9e04964..37de89a 100644
--- a/libs/androidfw/ResourceTypes.cpp
+++ b/libs/androidfw/ResourceTypes.cpp
@@ -727,7 +727,7 @@
                     AutoMutex lock(mDecodeLock);
 
                     if (mCache == NULL) {
-#ifndef HAVE_ANDROID_OS
+#ifndef __ANDROID__
                         if (kDebugStringPoolNoisy) {
                             ALOGI("CREATING STRING CACHE OF %zu bytes",
                                     mHeader->stringCount*sizeof(char16_t**));
diff --git a/libs/androidfw/tests/BackupData_test.cpp b/libs/androidfw/tests/BackupData_test.cpp
index 92af7fe..e25b616 100644
--- a/libs/androidfw/tests/BackupData_test.cpp
+++ b/libs/androidfw/tests/BackupData_test.cpp
@@ -108,7 +108,7 @@
     EXPECT_EQ(DATA1[i], dataBytes[i])
              << "data character " << i << " should be equal";
   }
-  delete dataBytes;
+  delete[] dataBytes;
   delete writer;
   delete reader;
 }
diff --git a/libs/hwui/Android.common.mk b/libs/hwui/Android.common.mk
index 7b2bba1..fe4f1be 100644
--- a/libs/hwui/Android.common.mk
+++ b/libs/hwui/Android.common.mk
@@ -19,7 +19,6 @@
     renderthread/RenderTask.cpp \
     renderthread/RenderThread.cpp \
     renderthread/TimeLord.cpp \
-    renderthread/DirtyHistory.cpp \
     thread/TaskManager.cpp \
     utils/Blur.cpp \
     utils/GLUtils.cpp \
diff --git a/libs/hwui/Caches.cpp b/libs/hwui/Caches.cpp
index 693b28e..f663f07 100644
--- a/libs/hwui/Caches.cpp
+++ b/libs/hwui/Caches.cpp
@@ -68,8 +68,6 @@
     mRegionMesh = nullptr;
     mProgram = nullptr;
 
-    mFunctorsCount = 0;
-
     patchCache.init();
 
     mInitialized = true;
@@ -276,38 +274,6 @@
 }
 
 ///////////////////////////////////////////////////////////////////////////////
-// Tiling
-///////////////////////////////////////////////////////////////////////////////
-
-void Caches::startTiling(GLuint x, GLuint y, GLuint width, GLuint height, bool discard) {
-    if (mExtensions.hasTiledRendering() && !Properties::debugOverdraw) {
-        glStartTilingQCOM(x, y, width, height, (discard ? GL_NONE : GL_COLOR_BUFFER_BIT0_QCOM));
-    }
-}
-
-void Caches::endTiling() {
-    if (mExtensions.hasTiledRendering() && !Properties::debugOverdraw) {
-        glEndTilingQCOM(GL_COLOR_BUFFER_BIT0_QCOM);
-    }
-}
-
-bool Caches::hasRegisteredFunctors() {
-    return mFunctorsCount > 0;
-}
-
-void Caches::registerFunctors(uint32_t functorCount) {
-    mFunctorsCount += functorCount;
-}
-
-void Caches::unregisterFunctors(uint32_t functorCount) {
-    if (functorCount > mFunctorsCount) {
-        mFunctorsCount = 0;
-    } else {
-        mFunctorsCount -= functorCount;
-    }
-}
-
-///////////////////////////////////////////////////////////////////////////////
 // Regions
 ///////////////////////////////////////////////////////////////////////////////
 
diff --git a/libs/hwui/Caches.h b/libs/hwui/Caches.h
index 049d58b..a02e15d 100644
--- a/libs/hwui/Caches.h
+++ b/libs/hwui/Caches.h
@@ -124,10 +124,6 @@
      */
     void deleteLayerDeferred(Layer* layer);
 
-
-    void startTiling(GLuint x, GLuint y, GLuint width, GLuint height, bool discard);
-    void endTiling();
-
     /**
      * Returns the mesh used to draw regions. Calling this method will
      * bind a VBO of type GL_ELEMENT_ARRAY_BUFFER that contains the
@@ -141,10 +137,6 @@
     void dumpMemoryUsage();
     void dumpMemoryUsage(String8& log);
 
-    bool hasRegisteredFunctors();
-    void registerFunctors(uint32_t functorCount);
-    void unregisterFunctors(uint32_t functorCount);
-
     // Misc
     GLint maxTextureSize;
 
@@ -206,8 +198,6 @@
 
     bool mInitialized;
 
-    uint32_t mFunctorsCount;
-
     // TODO: move below to RenderState
     PixelBufferState* mPixelBufferState = nullptr;
     TextureState* mTextureState = nullptr;
diff --git a/libs/hwui/DamageAccumulator.cpp b/libs/hwui/DamageAccumulator.cpp
index 9bd3bdc..c2e14a2 100644
--- a/libs/hwui/DamageAccumulator.cpp
+++ b/libs/hwui/DamageAccumulator.cpp
@@ -121,7 +121,14 @@
 static inline void mapRect(const Matrix4* matrix, const SkRect& in, SkRect* out) {
     if (in.isEmpty()) return;
     Rect temp(in);
-    matrix->mapRect(temp);
+    if (CC_LIKELY(!matrix->isPerspective())) {
+        matrix->mapRect(temp);
+    } else {
+        // Don't attempt to calculate damage for a perspective transform
+        // as the numbers this works with can break the perspective
+        // calculations. Just give up and expand to DIRTY_MIN/DIRTY_MAX
+        temp.set(DIRTY_MIN, DIRTY_MIN, DIRTY_MAX, DIRTY_MAX);
+    }
     out->join(RECT_ARGS(temp));
 }
 
@@ -134,7 +141,14 @@
     const SkMatrix* transform = props.getTransformMatrix();
     SkRect temp(in);
     if (transform && !transform->isIdentity()) {
-        transform->mapRect(&temp);
+        if (CC_LIKELY(!transform->hasPerspective())) {
+            transform->mapRect(&temp);
+        } else {
+            // Don't attempt to calculate damage for a perspective transform
+            // as the numbers this works with can break the perspective
+            // calculations. Just give up and expand to DIRTY_MIN/DIRTY_MAX
+            temp.set(DIRTY_MIN, DIRTY_MIN, DIRTY_MAX, DIRTY_MAX);
+        }
     }
     temp.offset(props.getLeft(), props.getTop());
     out->join(temp);
diff --git a/libs/hwui/DamageAccumulator.h b/libs/hwui/DamageAccumulator.h
index dd3365a..e44fc20 100644
--- a/libs/hwui/DamageAccumulator.h
+++ b/libs/hwui/DamageAccumulator.h
@@ -24,6 +24,11 @@
 
 #include "utils/Macros.h"
 
+// Smaller than INT_MIN/INT_MAX because we offset these values
+// and thus don't want to be adding offsets to INT_MAX, that's bad
+#define DIRTY_MIN (-0x7ffffff-1)
+#define DIRTY_MAX (0x7ffffff)
+
 namespace android {
 namespace uirenderer {
 
diff --git a/libs/hwui/Extensions.cpp b/libs/hwui/Extensions.cpp
index 814bada..3d350c9 100644
--- a/libs/hwui/Extensions.cpp
+++ b/libs/hwui/Extensions.cpp
@@ -53,21 +53,10 @@
     mHasFramebufferFetch = hasGlExtension("GL_NV_shader_framebuffer_fetch");
     mHasDiscardFramebuffer = hasGlExtension("GL_EXT_discard_framebuffer");
     mHasDebugMarker = hasGlExtension("GL_EXT_debug_marker");
-    mHasTiledRendering = hasGlExtension("GL_QCOM_tiled_rendering");
     mHas1BitStencil = hasGlExtension("GL_OES_stencil1");
     mHas4BitStencil = hasGlExtension("GL_OES_stencil4");
     mHasUnpackSubImage = hasGlExtension("GL_EXT_unpack_subimage");
 
-    // Query EGL extensions
-    findExtensions(eglQueryString(eglGetCurrentDisplay(), EGL_EXTENSIONS), mEglExtensionList);
-
-    char property[PROPERTY_VALUE_MAX];
-    if (property_get(PROPERTY_DEBUG_NV_PROFILING, property, nullptr) > 0) {
-        mHasNvSystemTime = !strcmp(property, "true") && hasEglExtension("EGL_NV_system_time");
-    } else {
-        mHasNvSystemTime = false;
-    }
-
     const char* version = (const char*) glGetString(GL_VERSION);
 
     // Section 6.1.5 of the OpenGL ES specification indicates the GL version
diff --git a/libs/hwui/Extensions.h b/libs/hwui/Extensions.h
index a4eef0f..636b631 100644
--- a/libs/hwui/Extensions.h
+++ b/libs/hwui/Extensions.h
@@ -40,10 +40,8 @@
     inline bool hasFramebufferFetch() const { return mHasFramebufferFetch; }
     inline bool hasDiscardFramebuffer() const { return mHasDiscardFramebuffer; }
     inline bool hasDebugMarker() const { return mHasDebugMarker; }
-    inline bool hasTiledRendering() const { return mHasTiledRendering; }
     inline bool has1BitStencil() const { return mHas1BitStencil; }
     inline bool has4BitStencil() const { return mHas4BitStencil; }
-    inline bool hasNvSystemTime() const { return mHasNvSystemTime; }
     inline bool hasUnpackRowLength() const { return mVersionMajor >= 3 || mHasUnpackSubImage; }
     inline bool hasPixelBufferObjects() const { return mVersionMajor >= 3; }
     inline bool hasOcclusionQueries() const { return mVersionMajor >= 3; }
@@ -67,10 +65,8 @@
     bool mHasFramebufferFetch;
     bool mHasDiscardFramebuffer;
     bool mHasDebugMarker;
-    bool mHasTiledRendering;
     bool mHas1BitStencil;
     bool mHas4BitStencil;
-    bool mHasNvSystemTime;
     bool mHasUnpackSubImage;
 
     int mVersionMajor;
diff --git a/libs/hwui/OpenGLRenderer.cpp b/libs/hwui/OpenGLRenderer.cpp
index 8e04bdf..7a56d42 100644
--- a/libs/hwui/OpenGLRenderer.cpp
+++ b/libs/hwui/OpenGLRenderer.cpp
@@ -70,8 +70,6 @@
         , mRenderState(renderState)
         , mFrameStarted(false)
         , mScissorOptimizationDisabled(false)
-        , mSuppressTiling(false)
-        , mFirstFrameAfterResize(true)
         , mDirty(false)
         , mLightCenter((Vector3){FLT_MIN, FLT_MIN, FLT_MIN})
         , mLightRadius(FLT_MIN)
@@ -113,7 +111,6 @@
 void OpenGLRenderer::onViewportInitialized() {
     glDisable(GL_DITHER);
     glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
-    mFirstFrameAfterResize = true;
 }
 
 void OpenGLRenderer::setupFrameState(float left, float top,
@@ -134,15 +131,6 @@
 
     mRenderState.setViewport(mState.getWidth(), mState.getHeight());
 
-    // Functors break the tiling extension in pretty spectacular ways
-    // This ensures we don't use tiling when a functor is going to be
-    // invoked during the frame
-    mSuppressTiling = mCaches.hasRegisteredFunctors()
-            || mFirstFrameAfterResize;
-    mFirstFrameAfterResize = false;
-
-    startTilingCurrentClip(true);
-
     debugOverdraw(true, true);
 
     clear(mTilingClip.left, mTilingClip.top,
@@ -192,46 +180,8 @@
     mRenderState.scissor().reset();
 }
 
-void OpenGLRenderer::startTilingCurrentClip(bool opaque, bool expand) {
-    if (!mSuppressTiling) {
-        const Snapshot* snapshot = currentSnapshot();
-
-        const Rect* clip = &mTilingClip;
-        if (snapshot->flags & Snapshot::kFlagFboTarget) {
-            clip = &(snapshot->layer->clipRect);
-        }
-
-        startTiling(*clip, getViewportHeight(), opaque, expand);
-    }
-}
-
-void OpenGLRenderer::startTiling(const Rect& clip, int windowHeight, bool opaque, bool expand) {
-    if (!mSuppressTiling) {
-        if(expand) {
-            // Expand the startTiling region by 1
-            int leftNotZero = (clip.left > 0) ? 1 : 0;
-            int topNotZero = (windowHeight - clip.bottom > 0) ? 1 : 0;
-
-            mCaches.startTiling(
-                clip.left - leftNotZero,
-                windowHeight - clip.bottom - topNotZero,
-                clip.right - clip.left + leftNotZero + 1,
-                clip.bottom - clip.top + topNotZero + 1,
-                opaque);
-        } else {
-            mCaches.startTiling(clip.left, windowHeight - clip.bottom,
-                clip.right - clip.left, clip.bottom - clip.top, opaque);
-        }
-    }
-}
-
-void OpenGLRenderer::endTiling() {
-    if (!mSuppressTiling) mCaches.endTiling();
-}
-
 bool OpenGLRenderer::finish() {
     renderOverdraw();
-    endTiling();
     mTempPaths.clear();
 
     // When finish() is invoked on FBO 0 we've reached the end
@@ -381,7 +331,6 @@
             && layer->renderNode.get() && layer->renderNode->isRenderable()) {
 
         if (inFrame) {
-            endTiling();
             debugOverdraw(false, false);
         }
 
@@ -393,7 +342,6 @@
 
         if (inFrame) {
             resumeAfterLayer();
-            startTilingCurrentClip();
         }
 
         layer->debugDrawUpdate = Properties::debugLayersUpdates;
@@ -736,7 +684,6 @@
     writableSnapshot()->initializeViewport(bounds.getWidth(), bounds.getHeight());
     writableSnapshot()->roundRectClipState = nullptr;
 
-    endTiling();
     debugOverdraw(false, false);
     // Bind texture to FBO
     mRenderState.bindFramebuffer(layer->getFbo());
@@ -751,9 +698,6 @@
     glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
             layer->getTextureId(), 0);
 
-    // Expand the startTiling region by 1
-    startTilingCurrentClip(true, true);
-
     // Clear the FBO, expand the clear region by 1 to get nice bilinear filtering
     mRenderState.scissor().setEnabled(true);
     mRenderState.scissor().set(clip.left - 1.0f, bounds.getHeight() - clip.bottom - 1.0f,
@@ -786,8 +730,6 @@
     mRenderState.scissor().setEnabled(mScissorOptimizationDisabled || clipRequired);
 
     if (fboLayer) {
-        endTiling();
-
         // Detach the texture from the FBO
         glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
 
@@ -796,8 +738,6 @@
         // Unbind current FBO and restore previous one
         mRenderState.bindFramebuffer(restored.fbo);
         debugOverdraw(true, false);
-
-        startTilingCurrentClip();
     }
 
     if (!fboLayer && layer->getAlpha() < 255) {
@@ -1267,17 +1207,10 @@
 void OpenGLRenderer::attachStencilBufferToLayer(Layer* layer) {
     // The layer's FBO is already bound when we reach this stage
     if (!layer->getStencilRenderBuffer()) {
-        // GL_QCOM_tiled_rendering doesn't like it if a renderbuffer
-        // is attached after we initiated tiling. We must turn it off,
-        // attach the new render buffer then turn tiling back on
-        endTiling();
-
         RenderBuffer* buffer = mCaches.renderBufferCache.get(
                 Stencil::getLayerStencilFormat(),
                 layer->getWidth(), layer->getHeight());
         layer->setStencilRenderBuffer(buffer);
-
-        startTiling(layer->clipRect, layer->layer.getHeight());
     }
 }
 
diff --git a/libs/hwui/OpenGLRenderer.h b/libs/hwui/OpenGLRenderer.h
index 390f620..4f75482 100755
--- a/libs/hwui/OpenGLRenderer.h
+++ b/libs/hwui/OpenGLRenderer.h
@@ -555,27 +555,6 @@
     void discardFramebuffer(float left, float top, float right, float bottom);
 
     /**
-     * Tells the GPU what part of the screen is about to be redrawn.
-     * This method will use the current layer space clip rect.
-     * This method needs to be invoked every time getTargetFbo() is
-     * bound again.
-     */
-    void startTilingCurrentClip(bool opaque = false, bool expand = false);
-
-    /**
-     * Tells the GPU what part of the screen is about to be redrawn.
-     * This method needs to be invoked every time getTargetFbo() is
-     * bound again.
-     */
-    void startTiling(const Rect& clip, int windowHeight, bool opaque = false, bool expand = false);
-
-    /**
-     * Tells the GPU that we are done drawing the frame or that we
-     * are switching to another render target.
-     */
-    void endTiling();
-
-    /**
      * Sets the clipping rectangle using glScissor. The clip is defined by
      * the current snapshot's clipRect member.
      */
@@ -862,10 +841,6 @@
     // Properties.h
     bool mScissorOptimizationDisabled;
 
-    // No-ops start/endTiling when set
-    bool mSuppressTiling;
-    bool mFirstFrameAfterResize;
-
     bool mSkipOutlineClip;
 
     // True if anything has been drawn since the last call to
diff --git a/libs/hwui/Properties.cpp b/libs/hwui/Properties.cpp
index 2e63793..b8f8585 100644
--- a/libs/hwui/Properties.cpp
+++ b/libs/hwui/Properties.cpp
@@ -30,6 +30,8 @@
 bool Properties::showDirtyRegions = false;
 bool Properties::skipEmptyFrames = true;
 bool Properties::swapBuffersWithDamage = true;
+bool Properties::useBufferAge = true;
+bool Properties::enablePartialUpdates = true;
 
 DebugLevel Properties::debugLevel = kDebugDisabled;
 OverdrawColorSet Properties::overdrawColorSet = OverdrawColorSet::Default;
@@ -105,6 +107,8 @@
 
     skipEmptyFrames = property_get_bool(PROPERTY_SKIP_EMPTY_DAMAGE, true);
     swapBuffersWithDamage = property_get_bool(PROPERTY_SWAP_WITH_DAMAGE, true);
+    useBufferAge = property_get_bool(PROPERTY_USE_BUFFER_AGE, true);
+    enablePartialUpdates = property_get_bool(PROPERTY_ENABLE_PARTIAL_UPDATES, true);
 
     return (prevDebugLayersUpdates != debugLayersUpdates)
             || (prevDebugOverdraw != debugOverdraw)
diff --git a/libs/hwui/Properties.h b/libs/hwui/Properties.h
index 1a70d7c..7602848 100644
--- a/libs/hwui/Properties.h
+++ b/libs/hwui/Properties.h
@@ -84,12 +84,6 @@
 #define PROPERTY_DEBUG_OVERDRAW "debug.hwui.overdraw"
 
 /**
- * Used to enable/disable PerfHUD ES profiling. The accepted values
- * are "true" and "false". The default value is "false".
- */
-#define PROPERTY_DEBUG_NV_PROFILING "debug.hwui.nv_profiling"
-
-/**
  *  System property used to enable or disable hardware rendering profiling.
  * The default value of this property is assumed to be false.
  *
@@ -150,9 +144,25 @@
 /**
  * Setting this property will enable or disable usage of EGL_KHR_swap_buffers_with_damage
  * See: https://www.khronos.org/registry/egl/extensions/KHR/EGL_KHR_swap_buffers_with_damage.txt
+ * Default is "true"
  */
 #define PROPERTY_SWAP_WITH_DAMAGE "debug.hwui.swap_with_damage"
 
+/**
+ * Controls whether or not HWUI will use the EGL_EXT_buffer_age extension
+ * to do partial invalidates. Setting this to "false" will fall back to
+ * using BUFFER_PRESERVED instead
+ * Default is "true"
+ */
+#define PROPERTY_USE_BUFFER_AGE "debug.hwui.use_buffer_age"
+
+/**
+ * Setting this to "false" will force HWUI to always do full-redraws of the surface.
+ * This will disable the use of EGL_EXT_buffer_age and BUFFER_PRESERVED.
+ * Default is "true"
+ */
+#define PROPERTY_ENABLE_PARTIAL_UPDATES "debug.hwui.enable_partial_updates"
+
 ///////////////////////////////////////////////////////////////////////////////
 // Runtime configuration properties
 ///////////////////////////////////////////////////////////////////////////////
@@ -287,6 +297,8 @@
     static bool skipEmptyFrames;
     // TODO: Remove after stabilization period
     static bool swapBuffersWithDamage;
+    static bool useBufferAge;
+    static bool enablePartialUpdates;
 
     static DebugLevel debugLevel;
     static OverdrawColorSet overdrawColorSet;
diff --git a/libs/hwui/RenderNode.cpp b/libs/hwui/RenderNode.cpp
index af8aaa20..fbfed12 100644
--- a/libs/hwui/RenderNode.cpp
+++ b/libs/hwui/RenderNode.cpp
@@ -134,7 +134,7 @@
         } else {
             // Hope this is big enough?
             // TODO: Get this from the display list ops or something
-            info.damageAccumulator->dirty(INT_MIN, INT_MIN, INT_MAX, INT_MAX);
+            info.damageAccumulator->dirty(DIRTY_MIN, DIRTY_MIN, DIRTY_MAX, DIRTY_MAX);
         }
     }
 }
@@ -303,10 +303,6 @@
         // changes in isRenderable or, in the future, bounds
         damageSelf(info);
         deleteDisplayListData();
-        // TODO: Remove this caches stuff
-        if (mStagingDisplayListData && mStagingDisplayListData->functors.size()) {
-            Caches::getInstance().registerFunctors(mStagingDisplayListData->functors.size());
-        }
         mDisplayListData = mStagingDisplayListData;
         mStagingDisplayListData = nullptr;
         if (mDisplayListData) {
@@ -323,9 +319,6 @@
         for (size_t i = 0; i < mDisplayListData->children().size(); i++) {
             mDisplayListData->children()[i]->mRenderNode->decParentRefCount();
         }
-        if (mDisplayListData->functors.size()) {
-            Caches::getInstance().unregisterFunctors(mDisplayListData->functors.size());
-        }
     }
     delete mDisplayListData;
     mDisplayListData = nullptr;
diff --git a/libs/hwui/renderthread/CanvasContext.cpp b/libs/hwui/renderthread/CanvasContext.cpp
index ea73387..67c42f3 100644
--- a/libs/hwui/renderthread/CanvasContext.cpp
+++ b/libs/hwui/renderthread/CanvasContext.cpp
@@ -35,6 +35,14 @@
 #define TRIM_MEMORY_COMPLETE 80
 #define TRIM_MEMORY_UI_HIDDEN 20
 
+#define LOG_FRAMETIME_MMA 0
+
+#if LOG_FRAMETIME_MMA
+static float sBenchMma = 0;
+static int sFrameCount = 0;
+static const float NANOS_PER_MILLIS_F = 1000000.0f;
+#endif
+
 namespace android {
 namespace uirenderer {
 namespace renderthread {
@@ -93,16 +101,6 @@
     }
 }
 
-void CanvasContext::swapBuffers(const SkRect& dirty, EGLint width, EGLint height) {
-    if (CC_UNLIKELY(!mEglManager.swapBuffers(mEglSurface, dirty, width, height))) {
-        setSurface(nullptr);
-    }
-    mHaveNewSurface = false;
-    if (mEglManager.useBufferAgeExt()) {
-        mDirtyHistory.prepend(Rect(dirty));
-    }
-}
-
 void CanvasContext::requireSurface() {
     LOG_ALWAYS_FATAL_IF(mEglSurface == EGL_NO_SURFACE,
             "requireSurface() called but no surface set!");
@@ -230,8 +228,6 @@
             "drawRenderNode called on a context with no canvas or surface!");
 
     SkRect dirty;
-    bool useBufferAgeExt = mEglManager.useBufferAgeExt();
-    Rect patchedDirty;
     mDamageAccumulator.finish(&dirty);
 
     // TODO: Re-enable after figuring out cause of b/22592975
@@ -242,40 +238,59 @@
 
     mCurrentFrameInfo->markIssueDrawCommandsStart();
 
-    EGLint width, height, framebufferAge;
-    mEglManager.beginFrame(mEglSurface, &width, &height, &framebufferAge);
-
-    if (useBufferAgeExt && mHaveNewSurface) {
-        mDirtyHistory.clear();
-    }
-
-    if (width != mCanvas->getViewportWidth() || height != mCanvas->getViewportHeight()) {
-        mCanvas->setViewport(width, height);
+    Frame frame = mEglManager.beginFrame(mEglSurface);
+    if (frame.width() != mCanvas->getViewportWidth()
+            || frame.height() != mCanvas->getViewportHeight()) {
+        mCanvas->setViewport(frame.width(), frame.height());
         dirty.setEmpty();
-    } else if (!mBufferPreserved || mHaveNewSurface) {
-        mDirtyHistory.clear();
+    } else if (mHaveNewSurface || frame.bufferAge() == 0) {
+        // New surface needs a full draw
         dirty.setEmpty();
     } else {
-        if (!dirty.isEmpty() && !dirty.intersect(0, 0, width, height)) {
+        if (!dirty.isEmpty() && !dirty.intersect(0, 0, frame.width(), frame.height())) {
             ALOGW("Dirty " RECT_STRING " doesn't intersect with 0 0 %d %d ?",
-                    SK_RECT_ARGS(dirty), width, height);
+                    SK_RECT_ARGS(dirty), frame.width(), frame.height());
             dirty.setEmpty();
         }
         profiler().unionDirty(&dirty);
     }
 
-    patchedDirty = dirty;
-    if (useBufferAgeExt && !dirty.isEmpty()) {
-        patchedDirty = mDirtyHistory.unionWith(Rect(dirty), framebufferAge-1);
+    if (dirty.isEmpty()) {
+        dirty.set(0, 0, frame.width(), frame.height());
     }
 
-    if (!patchedDirty.isEmpty()) {
-        mCanvas->prepareDirty(patchedDirty.left, patchedDirty.top,
-                patchedDirty.right, patchedDirty.bottom, mOpaque);
-    } else {
-        mCanvas->prepare(mOpaque);
+    // At this point dirty is the area of the screen to update. However,
+    // the area of the frame we need to repaint is potentially different, so
+    // stash the screen area for later
+    SkRect screenDirty(dirty);
+
+    // If the buffer age is 0 we do a full-screen repaint (handled above)
+    // If the buffer age is 1 the buffer contents are the same as they were
+    // last frame so there's nothing to union() against
+    // Therefore we only care about the > 1 case.
+    if (frame.bufferAge() > 1) {
+        if (frame.bufferAge() > (int) mDamageHistory.size()) {
+            // We don't have enough history to handle this old of a buffer
+            // Just do a full-draw
+            dirty.set(0, 0, frame.width(), frame.height());
+        } else {
+            // At this point we haven't yet added the latest frame
+            // to the damage history (happens below)
+            // So we need to damage
+            for (int i = mDamageHistory.size() - 1;
+                    i > ((int) mDamageHistory.size()) - frame.bufferAge(); i--) {
+                dirty.join(mDamageHistory[i]);
+            }
+        }
     }
 
+    // Add the screen damage to the ring buffer.
+    mDamageHistory.next() = screenDirty;
+
+    mEglManager.damageFrame(frame, dirty);
+    mCanvas->prepareDirty(dirty.fLeft, dirty.fTop,
+            dirty.fRight, dirty.fBottom, mOpaque);
+
     Rect outBounds;
     mCanvas->drawRenderNode(mRootRenderNode.get(), outBounds);
 
@@ -288,11 +303,30 @@
     mCurrentFrameInfo->markSwapBuffers();
 
     if (drew) {
-        swapBuffers(dirty, width, height);
+        if (CC_UNLIKELY(!mEglManager.swapBuffers(frame, screenDirty))) {
+            setSurface(nullptr);
+        }
+        mHaveNewSurface = false;
     }
 
     // TODO: Use a fence for real completion?
     mCurrentFrameInfo->markFrameCompleted();
+
+#if LOG_FRAMETIME_MMA
+    float thisFrame = mCurrentFrameInfo->duration(
+            FrameInfoIndex::IssueDrawCommandsStart,
+            FrameInfoIndex::FrameCompleted) / NANOS_PER_MILLIS_F;
+    if (sFrameCount) {
+        sBenchMma = ((9 * sBenchMma) + thisFrame) / 10;
+    } else {
+        sBenchMma = thisFrame;
+    }
+    if (++sFrameCount == 10) {
+        sFrameCount = 1;
+        ALOGD("Average frame time: %.4f", sBenchMma);
+    }
+#endif
+
     mJankTracker.addFrame(*mCurrentFrameInfo);
     mRenderThread.jankTracker().addFrame(*mCurrentFrameInfo);
 }
diff --git a/libs/hwui/renderthread/CanvasContext.h b/libs/hwui/renderthread/CanvasContext.h
index 59f9c3a..0ceb9f1 100644
--- a/libs/hwui/renderthread/CanvasContext.h
+++ b/libs/hwui/renderthread/CanvasContext.h
@@ -25,7 +25,6 @@
 #include "utils/RingBuffer.h"
 #include "renderthread/RenderTask.h"
 #include "renderthread/RenderThread.h"
-#include "renderthread/DirtyHistory.h"
 
 #include <cutils/compiler.h>
 #include <EGL/egl.h>
@@ -119,7 +118,6 @@
     friend class android::uirenderer::RenderState;
 
     void setSurface(ANativeWindow* window);
-    void swapBuffers(const SkRect& dirty, EGLint width, EGLint height);
     void requireSurface();
 
     void freePrefetechedLayers();
@@ -130,6 +128,7 @@
     EGLSurface mEglSurface = EGL_NO_SURFACE;
     bool mBufferPreserved = false;
     SwapBehavior mSwapBehavior = kSwap_default;
+    RingBuffer<SkRect, 3> mDamageHistory;
 
     bool mOpaque;
     OpenGLRenderer* mCanvas = nullptr;
@@ -147,8 +146,6 @@
     FrameInfoVisualizer mProfiler;
 
     std::set<RenderNode*> mPrefetechedLayers;
-
-    DirtyHistory mDirtyHistory;
 };
 
 } /* namespace renderthread */
diff --git a/libs/hwui/renderthread/DirtyHistory.cpp b/libs/hwui/renderthread/DirtyHistory.cpp
deleted file mode 100644
index 1419e84..0000000
--- a/libs/hwui/renderthread/DirtyHistory.cpp
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include "DirtyHistory.h"
-
-namespace android {
-namespace uirenderer {
-namespace renderthread {
-
-DirtyHistory::DirtyHistory()
-        : mBack(DIRTY_HISTORY_SIZE - 1) {
-    clear();
-}
-
-void DirtyHistory::clear()
-{
-    for (int i = 0; i < DIRTY_HISTORY_SIZE; i++) {
-        mHistory[i].clear();
-    }
-}
-
-Rect DirtyHistory::get(int index) {
-    if (index >= DIRTY_HISTORY_SIZE || index < 0)
-        return Rect();
-    return mHistory[(1 + mBack + index) % DIRTY_HISTORY_SIZE];
-}
-
-Rect DirtyHistory::unionWith(Rect rect, int count) {
-    if (rect.isEmpty() || count > DIRTY_HISTORY_SIZE || count < 0)
-        return Rect();
-
-    for (int i = 0; i < count; i++) {
-        Rect ith = get(i);
-        if (ith.isEmpty())
-            return Rect();
-
-        // rect union
-        rect.left = fminf(rect.left, ith.left);
-        rect.top = fminf(rect.top, ith.top);
-        rect.right = fmaxf(rect.right, ith.right);
-        rect.bottom = fmaxf(rect.bottom, ith.bottom);
-    }
-    return rect;
-}
-
-void DirtyHistory::prepend(Rect rect) {
-    if (rect.isEmpty()) {
-        mHistory[mBack].clear();
-    } else {
-        mHistory[mBack].set(rect);
-    }
-    mBack = (mBack + DIRTY_HISTORY_SIZE - 1) % DIRTY_HISTORY_SIZE;
-}
-
-} /* namespace renderthread */
-} /* namespace uirenderer */
-} /* namespace android */
diff --git a/libs/hwui/renderthread/DirtyHistory.h b/libs/hwui/renderthread/DirtyHistory.h
deleted file mode 100644
index d5ea597..0000000
--- a/libs/hwui/renderthread/DirtyHistory.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#ifndef DIRTYHISTORY_H
-#define DIRTYHISTORY_H
-
-#include <Rect.h>
-
-namespace android {
-namespace uirenderer {
-namespace renderthread {
-
-#define DIRTY_HISTORY_SIZE 4
-
-class DirtyHistory {
-public:
-    DirtyHistory();
-    ~DirtyHistory() {}
-
-    Rect get(int index);
-    Rect unionWith(Rect rect, int count);
-    void prepend(Rect rect);
-    void clear();
-private:
-    Rect mHistory[DIRTY_HISTORY_SIZE];
-    int mBack;
-};
-
-} /* namespace renderthread */
-} /* namespace uirenderer */
-} /* namespace android */
-
-#endif /* DIRTYHISTORY_H */
diff --git a/libs/hwui/renderthread/EglManager.cpp b/libs/hwui/renderthread/EglManager.cpp
index ac36f53..d2ce49f 100644
--- a/libs/hwui/renderthread/EglManager.cpp
+++ b/libs/hwui/renderthread/EglManager.cpp
@@ -25,7 +25,8 @@
 #include <cutils/properties.h>
 #include <EGL/eglext.h>
 
-#define PROPERTY_RENDER_DIRTY_REGIONS "debug.hwui.render_dirty_regions"
+#include <string>
+
 #define GLES_VERSION 2
 
 #define WAIT_FOR_GPU_COMPLETION 0
@@ -63,10 +64,27 @@
     return egl_error_str(eglGetError());
 }
 
-static bool load_dirty_regions_property() {
-    char buf[PROPERTY_VALUE_MAX];
-    int len = property_get(PROPERTY_RENDER_DIRTY_REGIONS, buf, "true");
-    return !strncasecmp("true", buf, len);
+static struct {
+    bool bufferAge = false;
+    bool setDamage = false;
+} EglExtensions;
+
+void Frame::map(const SkRect& in, EGLint* out) const {
+    /* The rectangles are specified relative to the bottom-left of the surface
+     * and the x and y components of each rectangle specify the bottom-left
+     * position of that rectangle.
+     *
+     * HWUI does everything with 0,0 being top-left, so need to map
+     * the rect
+     */
+    SkIRect idirty;
+    in.roundOut(&idirty);
+    EGLint y = mHeight - (idirty.y() + idirty.height());
+    // layout: {x, y, width, height}
+    out[0] = idirty.x();
+    out[1] = y;
+    out[2] = idirty.width();
+    out[3] = idirty.height();
 }
 
 EglManager::EglManager(RenderThread& thread)
@@ -75,13 +93,9 @@
         , mEglConfig(nullptr)
         , mEglContext(EGL_NO_CONTEXT)
         , mPBufferSurface(EGL_NO_SURFACE)
-        , mAllowPreserveBuffer(load_dirty_regions_property())
-        , mHasBufferAgeExt(false)
         , mCurrentSurface(EGL_NO_SURFACE)
         , mAtlasMap(nullptr)
         , mAtlasMapSize(0) {
-    mCanSetPreserveBuffer = mAllowPreserveBuffer;
-    ALOGD("Use EGL_SWAP_BEHAVIOR_PRESERVED: %s", mAllowPreserveBuffer ? "true" : "false");
 }
 
 void EglManager::initialize() {
@@ -99,10 +113,18 @@
 
     ALOGI("Initialized EGL, version %d.%d", (int)major, (int)minor);
 
-    findExtensions(eglQueryString(mEglDisplay, EGL_EXTENSIONS), mEglExtensionList);
-    mHasBufferAgeExt = hasEglExtension("EGL_EXT_buffer_age");
+    initExtensions();
 
-    loadConfig(mHasBufferAgeExt);
+    // Now that extensions are loaded, pick a swap behavior
+    if (Properties::enablePartialUpdates) {
+        if (Properties::useBufferAge && EglExtensions.bufferAge) {
+            mSwapBehavior = SwapBehavior::BufferAge;
+        } else {
+            mSwapBehavior = SwapBehavior::Preserved;
+        }
+    }
+
+    loadConfig();
     createContext();
     createPBufferSurface();
     makeCurrent(mPBufferSurface);
@@ -110,17 +132,23 @@
     initAtlas();
 }
 
+void EglManager::initExtensions() {
+    std::string extensions(eglQueryString(mEglDisplay, EGL_EXTENSIONS));
+    auto has = [&](const char* ext) {
+        return extensions.find(ext) != std::string::npos;
+    };
+    EglExtensions.bufferAge = has("EGL_EXT_buffer_age");
+    EglExtensions.setDamage = has("EGL_KHR_partial_update");
+}
+
 bool EglManager::hasEglContext() {
     return mEglDisplay != EGL_NO_DISPLAY;
 }
 
-bool EglManager::hasEglExtension(const char* extension) const {
-   const std::string s(extension);
-   return mEglExtensionList.find(s) != mEglExtensionList.end();
-}
-
-void EglManager::loadConfig(bool useBufferAgeExt) {
-    EGLint swapBehavior = (!useBufferAgeExt && mCanSetPreserveBuffer) ? EGL_SWAP_BEHAVIOR_PRESERVED_BIT : 0;
+void EglManager::loadConfig() {
+    ALOGD("Swap behavior %d", static_cast<int>(mSwapBehavior));
+    EGLint swapBehavior = (mSwapBehavior == SwapBehavior::Preserved)
+            ? EGL_SWAP_BEHAVIOR_PRESERVED_BIT : 0;
     EGLint attribs[] = {
             EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
             EGL_RED_SIZE, 8,
@@ -137,13 +165,13 @@
     EGLint num_configs = 1;
     if (!eglChooseConfig(mEglDisplay, attribs, &mEglConfig, num_configs, &num_configs)
             || num_configs != 1) {
-        // Failed to get a valid config
-        if (mCanSetPreserveBuffer) {
-            ALOGW("Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...");
+        if (mSwapBehavior == SwapBehavior::Preserved) {
             // Try again without dirty regions enabled
-            mCanSetPreserveBuffer = false;
-            loadConfig(useBufferAgeExt);
+            ALOGW("Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...");
+            mSwapBehavior = SwapBehavior::Discard;
+            loadConfig();
         } else {
+            // Failed to get a valid config
             LOG_ALWAYS_FATAL("Failed to choose config, error = %s", egl_error_str());
         }
     }
@@ -247,24 +275,47 @@
     return true;
 }
 
-void EglManager::beginFrame(EGLSurface surface, EGLint* width, EGLint* height, EGLint* framebufferAge) {
+EGLint EglManager::queryBufferAge(EGLSurface surface) {
+    switch (mSwapBehavior) {
+    case SwapBehavior::Discard:
+        return 0;
+    case SwapBehavior::Preserved:
+        return 1;
+    case SwapBehavior::BufferAge:
+        EGLint bufferAge;
+        eglQuerySurface(mEglDisplay, surface, EGL_BUFFER_AGE_EXT, &bufferAge);
+        return bufferAge;
+    }
+    return 0;
+}
+
+Frame EglManager::beginFrame(EGLSurface surface) {
     LOG_ALWAYS_FATAL_IF(surface == EGL_NO_SURFACE,
             "Tried to beginFrame on EGL_NO_SURFACE!");
     makeCurrent(surface);
-    if (width) {
-        eglQuerySurface(mEglDisplay, surface, EGL_WIDTH, width);
-    }
-    if (height) {
-        eglQuerySurface(mEglDisplay, surface, EGL_HEIGHT, height);
-    }
-    if (useBufferAgeExt()) {
-        eglQuerySurface(mEglDisplay, surface, EGL_BUFFER_AGE_EXT, framebufferAge);
-    }
+    Frame frame;
+    frame.mSurface = surface;
+    eglQuerySurface(mEglDisplay, surface, EGL_WIDTH, &frame.mWidth);
+    eglQuerySurface(mEglDisplay, surface, EGL_HEIGHT, &frame.mHeight);
+    frame.mBufferAge = queryBufferAge(surface);
     eglBeginFrame(mEglDisplay, surface);
+    return frame;
 }
 
-bool EglManager::swapBuffers(EGLSurface surface, const SkRect& dirty,
-        EGLint width, EGLint height) {
+void EglManager::damageFrame(const Frame& frame, const SkRect& dirty) {
+#ifdef EGL_KHR_partial_update
+    if (EglExtensions.setDamage && mSwapBehavior == SwapBehavior::BufferAge) {
+        EGLint rects[4];
+        frame.map(dirty, rects);
+        if (!eglSetDamageRegionKHR(mEglDisplay, frame.mSurface, rects, 1)) {
+            LOG_ALWAYS_FATAL("Failed to set damage region on surface %p, error=%s",
+                    (void*)frame.mSurface, egl_error_str());
+        }
+    }
+#endif
+}
+
+bool EglManager::swapBuffers(const Frame& frame, const SkRect& screenDirty) {
 
 #if WAIT_FOR_GPU_COMPLETION
     {
@@ -275,28 +326,15 @@
 
 #ifdef EGL_KHR_swap_buffers_with_damage
     if (CC_LIKELY(Properties::swapBuffersWithDamage)) {
-        SkIRect idirty;
-        dirty.roundOut(&idirty);
-        /*
-         * EGL_KHR_swap_buffers_with_damage spec states:
-         *
-         * The rectangles are specified relative to the bottom-left of the surface
-         * and the x and y components of each rectangle specify the bottom-left
-         * position of that rectangle.
-         *
-         * HWUI does everything with 0,0 being top-left, so need to map
-         * the rect
-         */
-        EGLint y = height - (idirty.y() + idirty.height());
-        // layout: {x, y, width, height}
-        EGLint rects[4] = { idirty.x(), y, idirty.width(), idirty.height() };
-        EGLint numrects = dirty.isEmpty() ? 0 : 1;
-        eglSwapBuffersWithDamageKHR(mEglDisplay, surface, rects, numrects);
+        EGLint rects[4];
+        frame.map(screenDirty, rects);
+        eglSwapBuffersWithDamageKHR(mEglDisplay, frame.mSurface, rects,
+                screenDirty.isEmpty() ? 0 : 1);
     } else {
-        eglSwapBuffers(mEglDisplay, surface);
+        eglSwapBuffers(mEglDisplay, frame.mSurface);
     }
 #else
-    eglSwapBuffers(mEglDisplay, surface);
+    eglSwapBuffers(mEglDisplay, frame.mSurface);
 #endif
 
     EGLint err = eglGetError();
@@ -307,7 +345,8 @@
         // For some reason our surface was destroyed out from under us
         // This really shouldn't happen, but if it does we can recover easily
         // by just not trying to use the surface anymore
-        ALOGW("swapBuffers encountered EGL_BAD_SURFACE on %p, halting rendering...", surface);
+        ALOGW("swapBuffers encountered EGL_BAD_SURFACE on %p, halting rendering...",
+                frame.mSurface);
         return false;
     }
     LOG_ALWAYS_FATAL("Encountered EGL error %d %s during rendering",
@@ -316,10 +355,6 @@
     return false;
 }
 
-bool EglManager::useBufferAgeExt() {
-    return mAllowPreserveBuffer && mHasBufferAgeExt;
-}
-
 void EglManager::fence() {
     EGLSyncKHR fence = eglCreateSyncKHR(mEglDisplay, EGL_SYNC_FENCE_KHR, NULL);
     eglClientWaitSyncKHR(mEglDisplay, fence,
@@ -328,21 +363,13 @@
 }
 
 bool EglManager::setPreserveBuffer(EGLSurface surface, bool preserve) {
-    if (CC_UNLIKELY(!mAllowPreserveBuffer)) return false;
+    if (mSwapBehavior != SwapBehavior::Preserved) return false;
 
-    // Use EGL_EXT_buffer_age instead if supported
-    if (mHasBufferAgeExt) return true;
-
-    bool preserved = false;
-    if (mCanSetPreserveBuffer) {
-        preserved = eglSurfaceAttrib(mEglDisplay, surface, EGL_SWAP_BEHAVIOR,
-                preserve ? EGL_BUFFER_PRESERVED : EGL_BUFFER_DESTROYED);
-        if (CC_UNLIKELY(!preserved)) {
-            ALOGW("Failed to set EGL_SWAP_BEHAVIOR on surface %p, error=%s",
-                    (void*) surface, egl_error_str());
-        }
-    }
-    if (CC_UNLIKELY(!preserved)) {
+    bool preserved = eglSurfaceAttrib(mEglDisplay, surface, EGL_SWAP_BEHAVIOR,
+            preserve ? EGL_BUFFER_PRESERVED : EGL_BUFFER_DESTROYED);
+    if (!preserved) {
+        ALOGW("Failed to set EGL_SWAP_BEHAVIOR on surface %p, error=%s",
+                (void*) surface, egl_error_str());
         // Maybe it's already set?
         EGLint swapBehavior;
         if (eglQuerySurface(mEglDisplay, surface, EGL_SWAP_BEHAVIOR, &swapBehavior)) {
@@ -356,19 +383,6 @@
     return preserved;
 }
 
-void EglManager::findExtensions(const char* extensions, std::set<std::string>& list) const {
-    const char* current = extensions;
-    const char* head = current;
-    do {
-        head = strchr(current, ' ');
-        std::string s(current, head ? head - current : strlen(current));
-        if (s.length()) {
-            list.insert(s);
-        }
-        current = head + 1;
-    } while (head);
-}
-
 } /* namespace renderthread */
 } /* namespace uirenderer */
 } /* namespace android */
diff --git a/libs/hwui/renderthread/EglManager.h b/libs/hwui/renderthread/EglManager.h
index bb5d24b..62b5b99 100644
--- a/libs/hwui/renderthread/EglManager.h
+++ b/libs/hwui/renderthread/EglManager.h
@@ -21,13 +21,35 @@
 #include <SkRect.h>
 #include <ui/GraphicBuffer.h>
 #include <utils/StrongPointer.h>
-#include <set>
 
 namespace android {
 namespace uirenderer {
 namespace renderthread {
 
 class RenderThread;
+class EglManager;
+
+class Frame {
+public:
+    EGLint width() const { return mWidth; }
+    EGLint height() const { return mHeight; }
+
+    // See: https://www.khronos.org/registry/egl/extensions/EXT/EGL_EXT_buffer_age.txt
+    // for what this means
+    EGLint bufferAge() const { return mBufferAge; }
+
+private:
+    friend class EglManager;
+
+    EGLSurface mSurface;
+    EGLint mWidth;
+    EGLint mHeight;
+    EGLint mBufferAge;
+
+    // Maps from 0,0 in top-left to 0,0 in bottom-left
+    // If out is not an EGLint[4] you're going to have a bad time
+    void map(const SkRect& in, EGLint* out) const;
+};
 
 // This class contains the shared global EGL objects, such as EGLDisplay
 // and EGLConfig, which are re-used by CanvasContext
@@ -38,8 +60,6 @@
 
     bool hasEglContext();
 
-    bool hasEglExtension(const char* extension) const;
-
     EGLSurface createSurface(EGLNativeWindowType window);
     void destroySurface(EGLSurface surface);
 
@@ -48,14 +68,13 @@
     bool isCurrent(EGLSurface surface) { return mCurrentSurface == surface; }
     // Returns true if the current surface changed, false if it was already current
     bool makeCurrent(EGLSurface surface, EGLint* errOut = nullptr);
-    void beginFrame(EGLSurface surface, EGLint* width, EGLint* height, EGLint* framebufferAge);
-    bool swapBuffers(EGLSurface surface, const SkRect& dirty, EGLint width, EGLint height);
+    Frame beginFrame(EGLSurface surface);
+    void damageFrame(const Frame& frame, const SkRect& dirty);
+    bool swapBuffers(const Frame& frame, const SkRect& screenDirty);
 
     // Returns true iff the surface is now preserving buffers.
     bool setPreserveBuffer(EGLSurface surface, bool preserve);
 
-    bool useBufferAgeExt();
-
     void setTextureAtlas(const sp<GraphicBuffer>& buffer, int64_t* map, size_t mapSize);
 
     void fence();
@@ -67,12 +86,12 @@
     // EglContext is never destroyed, method is purposely not implemented
     ~EglManager();
 
+    void initExtensions();
     void createPBufferSurface();
-    void loadConfig(bool useBufferAgeExt);
+    void loadConfig();
     void createContext();
     void initAtlas();
-
-    void findExtensions(const char* extensions, std::set<std::string>& list) const;
+    EGLint queryBufferAge(EGLSurface surface);
 
     RenderThread& mRenderThread;
 
@@ -81,18 +100,18 @@
     EGLContext mEglContext;
     EGLSurface mPBufferSurface;
 
-    const bool mAllowPreserveBuffer;
-    bool mCanSetPreserveBuffer;
-
-    bool mHasBufferAgeExt;
-
     EGLSurface mCurrentSurface;
 
     sp<GraphicBuffer> mAtlasBuffer;
     int64_t* mAtlasMap;
     size_t mAtlasMapSize;
 
-    std::set<std::string> mEglExtensionList;
+    enum class SwapBehavior {
+        Discard,
+        Preserved,
+        BufferAge,
+    };
+    SwapBehavior mSwapBehavior = SwapBehavior::Discard;
 };
 
 } /* namespace renderthread */
diff --git a/libs/hwui/tests/main.cpp b/libs/hwui/tests/main.cpp
index 69e8225..483fb35 100644
--- a/libs/hwui/tests/main.cpp
+++ b/libs/hwui/tests/main.cpp
@@ -283,6 +283,69 @@
     }
 };
 
+class PartialInvalTest : public TreeContentAnimation {
+public:
+    std::vector< sp<RenderNode> > cards;
+    void createContent(int width, int height, DisplayListCanvas* renderer) override {
+        static SkColor COLORS[] = {
+                0xFFF44336,
+                0xFF9C27B0,
+                0xFF2196F3,
+                0xFF4CAF50,
+        };
+
+        renderer->drawColor(0xFFFFFFFF, SkXfermode::kSrcOver_Mode);
+
+        for (int x = dp(16); x < (width - dp(116)); x += dp(116)) {
+            for (int y = dp(16); y < (height - dp(116)); y += dp(116)) {
+                sp<RenderNode> card = createCard(x, y, dp(100), dp(100),
+                        COLORS[static_cast<int>((y / dp(116))) % 4]);
+                renderer->drawRenderNode(card.get());
+                cards.push_back(card);
+            }
+        }
+    }
+    void doFrame(int frameNr) override {
+        int curFrame = frameNr % 150;
+        cards[0]->mutateStagingProperties().setTranslationX(curFrame);
+        cards[0]->mutateStagingProperties().setTranslationY(curFrame);
+        cards[0]->setPropertyFieldsDirty(RenderNode::X | RenderNode::Y);
+
+        DisplayListCanvas* renderer = startRecording(cards[0].get());
+        renderer->drawColor(interpolateColor(curFrame / 150.0f, 0xFFF44336, 0xFFF8BBD0),
+                SkXfermode::kSrcOver_Mode);
+        endRecording(renderer, cards[0].get());
+    }
+
+    static SkColor interpolateColor(float fraction, SkColor start, SkColor end) {
+        int startA = (start >> 24) & 0xff;
+        int startR = (start >> 16) & 0xff;
+        int startG = (start >> 8) & 0xff;
+        int startB = start & 0xff;
+
+        int endA = (end >> 24) & 0xff;
+        int endR = (end >> 16) & 0xff;
+        int endG = (end >> 8) & 0xff;
+        int endB = end & 0xff;
+
+        return (int)((startA + (int)(fraction * (endA - startA))) << 24) |
+                (int)((startR + (int)(fraction * (endR - startR))) << 16) |
+                (int)((startG + (int)(fraction * (endG - startG))) << 8) |
+                (int)((startB + (int)(fraction * (endB - startB))));
+    }
+private:
+    sp<RenderNode> createCard(int x, int y, int width, int height, SkColor color) {
+        sp<RenderNode> node = new RenderNode();
+        node->mutateStagingProperties().setLeftTopRightBottom(x, y, x + width, y + height);
+        node->setPropertyFieldsDirty(RenderNode::X | RenderNode::Y);
+
+        DisplayListCanvas* renderer = startRecording(node.get());
+        renderer->drawColor(color, SkXfermode::kSrcOver_Mode);
+        endRecording(renderer, node.get());
+        return node;
+    }
+};
+
 struct cstr_cmp {
     bool operator()(const char *a, const char *b) const {
         return std::strcmp(a, b) < 0;
@@ -296,6 +359,7 @@
     {"shadowgrid2", TreeContentAnimation::run<ShadowGrid2Animation>},
     {"rectgrid", TreeContentAnimation::run<RectGridAnimation> },
     {"oval", TreeContentAnimation::run<OvalAnimation> },
+    {"partialinval", TreeContentAnimation::run<PartialInvalTest> },
 };
 
 int main(int argc, char* argv[]) {
diff --git a/libs/hwui/tests/nullgles.cpp b/libs/hwui/tests/nullgles.cpp
index 8ca7598..f8e8c98 100644
--- a/libs/hwui/tests/nullgles.cpp
+++ b/libs/hwui/tests/nullgles.cpp
@@ -261,8 +261,6 @@
 void glPushGroupMarkerEXT(GLsizei length, const GLchar *marker) {}
 void glPopGroupMarkerEXT(void) {}
 void glDiscardFramebufferEXT(GLenum target, GLsizei numAttachments, const GLenum *attachments) {}
-void glStartTilingQCOM(GLuint x, GLuint y, GLuint width, GLuint height, GLbitfield preserveMask) {}
-void glEndTilingQCOM(GLbitfield preserveMask) {}
 void glEGLImageTargetTexture2DOES(GLenum target, GLeglImageOES image) {}
 
 // GLES3
diff --git a/libs/hwui/unit_tests/Android.mk b/libs/hwui/unit_tests/Android.mk
index 917e646..93cee4a 100644
--- a/libs/hwui/unit_tests/Android.mk
+++ b/libs/hwui/unit_tests/Android.mk
@@ -14,7 +14,6 @@
 # limitations under the License.
 #
 
-local_target_dir := $(TARGET_OUT_DATA)/local/tmp
 LOCAL_PATH:= $(call my-dir)/..
 
 include $(CLEAR_VARS)
@@ -28,8 +27,7 @@
 LOCAL_SRC_FILES += \
     unit_tests/ClipAreaTests.cpp \
     unit_tests/DamageAccumulatorTests.cpp \
-    unit_tests/LinearAllocatorTests.cpp \
-    unit_tests/main.cpp
+    unit_tests/LinearAllocatorTests.cpp
 
 
 include $(BUILD_NATIVE_TEST)
diff --git a/libs/hwui/unit_tests/DamageAccumulatorTests.cpp b/libs/hwui/unit_tests/DamageAccumulatorTests.cpp
index c8d6004..29354a7 100644
--- a/libs/hwui/unit_tests/DamageAccumulatorTests.cpp
+++ b/libs/hwui/unit_tests/DamageAccumulatorTests.cpp
@@ -18,6 +18,7 @@
 
 #include <DamageAccumulator.h>
 #include <Matrix.h>
+#include <RenderNode.h>
 #include <utils/LinearAllocator.h>
 
 #include <SkRect.h>
@@ -35,10 +36,12 @@
     identity.loadIdentity();
     da.pushTransform(&identity);
     da.dirty(50, 50, 100, 100);
-    da.pushTransform(&identity);
-    da.peekAtDirty(&curDirty);
-    ASSERT_EQ(SkRect(), curDirty);
-    da.popTransform();
+    {
+        da.pushTransform(&identity);
+        da.peekAtDirty(&curDirty);
+        ASSERT_EQ(SkRect(), curDirty);
+        da.popTransform();
+    }
     da.peekAtDirty(&curDirty);
     ASSERT_EQ(SkRect::MakeLTRB(50, 50, 100, 100), curDirty);
     da.popTransform();
@@ -69,13 +72,62 @@
     SkRect curDirty;
     identity.loadIdentity();
     da.pushTransform(&identity);
-    da.pushTransform(&identity);
-    da.dirty(50, 50, 100, 100);
-    da.popTransform();
-    da.pushTransform(&identity);
-    da.dirty(150, 50, 200, 125);
-    da.popTransform();
+    {
+        da.pushTransform(&identity);
+        da.dirty(50, 50, 100, 100);
+        da.popTransform();
+        da.pushTransform(&identity);
+        da.dirty(150, 50, 200, 125);
+        da.popTransform();
+    }
     da.popTransform();
     da.finish(&curDirty);
     ASSERT_EQ(SkRect::MakeLTRB(50, 50, 200, 125), curDirty);
 }
+
+TEST(DamageAccumulator, basicRenderNode) {
+    DamageAccumulator da;
+    RenderNode node1;
+    node1.animatorProperties().setLeftTopRightBottom(50, 50, 500, 500);
+    node1.animatorProperties().updateMatrix();
+    da.pushTransform(&node1);
+    {
+        RenderNode node2;
+        node2.animatorProperties().setLeftTopRightBottom(50, 50, 100, 100);
+        node2.animatorProperties().updateMatrix();
+        da.pushTransform(&node2);
+        da.dirty(0, 0, 25, 25);
+        da.popTransform();
+    }
+    da.popTransform();
+    SkRect dirty;
+    da.finish(&dirty);
+    ASSERT_EQ(SkRect::MakeLTRB(100, 100, 125, 125), dirty);
+}
+
+TEST(DamageAccumulator, perspectiveTransform) {
+    DamageAccumulator da;
+    RenderNode node1;
+    node1.animatorProperties().setLeftTopRightBottom(50, 50, 500, 500);
+    node1.animatorProperties().setClipToBounds(true);
+    node1.animatorProperties().updateMatrix();
+    da.pushTransform(&node1);
+    {
+        RenderNode node2;
+        node2.animatorProperties().setLeftTopRightBottom(50, 50, 100, 100);
+        node2.animatorProperties().setClipToBounds(false);
+        node2.animatorProperties().setRotationX(1.0f);
+        node2.animatorProperties().setRotationY(1.0f);
+        node2.animatorProperties().setRotation(20.0f);
+        node2.animatorProperties().setCameraDistance(500.0f);
+        node2.animatorProperties().setTranslationZ(30.0f);
+        node2.animatorProperties().updateMatrix();
+        da.pushTransform(&node2);
+        da.dirty(DIRTY_MIN, DIRTY_MIN, DIRTY_MAX, DIRTY_MAX);
+        da.popTransform();
+    }
+    da.popTransform();
+    SkRect dirty;
+    da.finish(&dirty);
+    ASSERT_EQ(SkRect::MakeLTRB(50, 50, 500, 500), dirty);
+}
diff --git a/libs/hwui/unit_tests/main.cpp b/libs/hwui/unit_tests/main.cpp
deleted file mode 100644
index c9b9636..0000000
--- a/libs/hwui/unit_tests/main.cpp
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <gtest/gtest.h>
-
-int main(int argc, char **argv) {
-    ::testing::InitGoogleTest(&argc, argv);
-    return RUN_ALL_TESTS();
-}
diff --git a/media/java/android/media/ImageReader.java b/media/java/android/media/ImageReader.java
index c97de5d..2164eec 100644
--- a/media/java/android/media/ImageReader.java
+++ b/media/java/android/media/ImageReader.java
@@ -679,17 +679,31 @@
         @Override
         public int getWidth() {
             throwISEIfImageIsInvalid();
-            mWidth = (getFormat() == ImageFormat.JPEG) ? ImageReader.this.getWidth() :
-                    nativeGetWidth(mFormat);
-            return mWidth;
+            int width;
+            switch(getFormat()) {
+                case ImageFormat.JPEG:
+                case ImageFormat.DEPTH_POINT_CLOUD:
+                    width = ImageReader.this.getWidth();
+                    break;
+                default:
+                    width = nativeGetWidth(mFormat);
+            }
+            return width;
         }
 
         @Override
         public int getHeight() {
             throwISEIfImageIsInvalid();
-            mHeight = (getFormat() == ImageFormat.JPEG) ? ImageReader.this.getHeight() :
-                    nativeGetHeight(mFormat);
-            return mHeight;
+            int height;
+            switch(getFormat()) {
+                case ImageFormat.JPEG:
+                case ImageFormat.DEPTH_POINT_CLOUD:
+                    height = ImageReader.this.getHeight();
+                    break;
+                default:
+                    height = nativeGetHeight(mFormat);
+            }
+            return height;
         }
 
         @Override
@@ -826,8 +840,6 @@
         private long mTimestamp;
 
         private SurfacePlane[] mPlanes;
-        private int mHeight = -1;
-        private int mWidth = -1;
         private int mFormat = ImageFormat.UNKNOWN;
         // If this image is detached from the ImageReader.
         private AtomicBoolean mIsDetached = new AtomicBoolean(false);
diff --git a/media/java/android/media/MediaPlayer.java b/media/java/android/media/MediaPlayer.java
index bbd4c30..bc1aeda 100644
--- a/media/java/android/media/MediaPlayer.java
+++ b/media/java/android/media/MediaPlayer.java
@@ -2243,10 +2243,14 @@
         final InputStream fIs = is;
         final MediaFormat fFormat = format;
 
-        // Ensure all input streams are closed.  It is also a handy
-        // way to implement timeouts in the future.
-        synchronized(mOpenSubtitleSources) {
-            mOpenSubtitleSources.add(is);
+        if (is != null) {
+            // Ensure all input streams are closed.  It is also a handy
+            // way to implement timeouts in the future.
+            synchronized(mOpenSubtitleSources) {
+                mOpenSubtitleSources.add(is);
+            }
+        } else {
+            Log.w(TAG, "addSubtitleSource called with null InputStream");
         }
 
         // process each subtitle in its own thread
diff --git a/packages/DocumentsUI/src/com/android/documentsui/DirectoryFragment.java b/packages/DocumentsUI/src/com/android/documentsui/DirectoryFragment.java
index 7e6ec8b..5223d76 100644
--- a/packages/DocumentsUI/src/com/android/documentsui/DirectoryFragment.java
+++ b/packages/DocumentsUI/src/com/android/documentsui/DirectoryFragment.java
@@ -85,7 +85,6 @@
 import android.view.View.OnLayoutChangeListener;
 import android.view.ViewGroup;
 import android.widget.ImageView;
-import android.widget.ListView;
 import android.widget.TextView;
 import android.widget.Toast;
 
@@ -153,7 +152,6 @@
     // These are lazily initialized.
     private LinearLayoutManager mListLayout;
     private GridLayoutManager mGridLayout;
-    private OnLayoutChangeListener mRecyclerLayoutListener;
     private int mColumnCount = 1;  // This will get updated when layout changes.
 
     public static void showNormal(FragmentManager fm, RootInfo root, DocumentInfo doc, int anim) {
@@ -294,7 +292,13 @@
                     }
                 };
 
-        mSelectionManager = new MultiSelectManager(mRecView, listener);
+        mSelectionManager = new MultiSelectManager(
+                mRecView,
+                listener,
+                state.allowMultiple
+                    ? MultiSelectManager.MODE_MULTIPLE
+                    : MultiSelectManager.MODE_SINGLE);
+
         mSelectionManager.addCallback(new SelectionModeListener());
 
         mType = getArguments().getInt(EXTRA_TYPE);
@@ -431,7 +435,7 @@
     }
 
     private boolean onSingleTapUp(MotionEvent e) {
-        if (!Events.isMouseEvent(e)) {
+        if (Events.isTouchEvent(e) && mSelectionManager.getSelection().isEmpty()) {
             int position = getEventAdapterPosition(e);
             if (position != RecyclerView.NO_POSITION) {
                 return handleViewItem(position);
@@ -531,13 +535,6 @@
 
         updateLayout(state.derivedMode);
 
-        final int choiceMode;
-        if (state.allowMultiple) {
-            choiceMode = ListView.CHOICE_MODE_MULTIPLE_MODAL;
-        } else {
-            choiceMode = ListView.CHOICE_MODE_NONE;
-        }
-
         final int thumbSize = getResources().getDimensionPixelSize(R.dimen.icon_size);
         mThumbSize = new Point(thumbSize, thumbSize);
         mRecView.setAdapter(mAdapter);
@@ -622,7 +619,10 @@
             if ((docFlags & Document.FLAG_SUPPORTS_DELETE) == 0) {
                 mNoDeleteCount += selected ? 1 : -1;
             }
+        }
 
+        @Override
+        public void onSelectionChanged() {
             mSelectionManager.getSelection(mSelected);
             if (mSelected.size() > 0) {
                 if (DEBUG) Log.d(TAG, "Maybe starting action mode.");
diff --git a/packages/DocumentsUI/src/com/android/documentsui/Events.java b/packages/DocumentsUI/src/com/android/documentsui/Events.java
index 2e06903..025b94f 100644
--- a/packages/DocumentsUI/src/com/android/documentsui/Events.java
+++ b/packages/DocumentsUI/src/com/android/documentsui/Events.java
@@ -28,7 +28,14 @@
      * Returns true if event was triggered by a mouse.
      */
     static boolean isMouseEvent(MotionEvent e) {
-        return e.getToolType(0) == MotionEvent.TOOL_TYPE_MOUSE;
+        return isMouseType(e.getToolType(0));
+    }
+
+    /**
+     * Returns true if event was triggered by a finger or stylus touch.
+     */
+    static boolean isTouchEvent(MotionEvent e) {
+        return isTouchType(e.getToolType(0));
     }
 
     /**
@@ -39,6 +46,14 @@
     }
 
     /**
+     * Returns true if event was triggered by a finger or stylus touch.
+     */
+    static boolean isTouchType(int toolType) {
+        return toolType == MotionEvent.TOOL_TYPE_FINGER
+                || toolType == MotionEvent.TOOL_TYPE_STYLUS;
+    }
+
+    /**
      * Returns true if the shift is pressed.
      */
     boolean isShiftPressed(MotionEvent e) {
diff --git a/packages/DocumentsUI/src/com/android/documentsui/MultiSelectManager.java b/packages/DocumentsUI/src/com/android/documentsui/MultiSelectManager.java
index 91b4456..02edd0c 100644
--- a/packages/DocumentsUI/src/com/android/documentsui/MultiSelectManager.java
+++ b/packages/DocumentsUI/src/com/android/documentsui/MultiSelectManager.java
@@ -37,10 +37,18 @@
 import java.util.List;
 
 /**
- * MultiSelectManager adds traditional multi-item selection support to RecyclerView.
+ * MultiSelectManager provides support traditional multi-item selection support to RecyclerView.
+ * Additionally it can be configured to restrict selection to a single element, @see
+ * #setSelectMode.
  */
 public final class MultiSelectManager {
 
+    /** Selection mode for multiple select. **/
+    public static final int MODE_MULTIPLE = 0;
+
+    /** Selection mode for multiple select. **/
+    public static final int MODE_SINGLE = 1;
+
     private static final String TAG = "MultiSelectManager";
     private static final boolean DEBUG = false;
 
@@ -54,15 +62,18 @@
 
     private Adapter<?> mAdapter;
     private RecyclerViewHelper mHelper;
+    private boolean mSingleSelect;
 
     /**
      * @param recyclerView
      * @param gestureDelegate Option delage gesture listener.
+     * @param mode Selection mode
      * @template A gestureDelegate that implements both {@link OnGestureListener}
      *     and {@link OnDoubleTapListener}
      */
     public <L extends OnGestureListener & OnDoubleTapListener> MultiSelectManager(
-            final RecyclerView recyclerView, L gestureDelegate) {
+            final RecyclerView recyclerView, L gestureDelegate, int mode) {
+
         this(
                 recyclerView.getAdapter(),
                 new RecyclerViewHelper() {
@@ -73,7 +84,8 @@
                                 ? recyclerView.getChildAdapterPosition(view)
                                 : RecyclerView.NO_POSITION;
                     }
-                });
+                },
+                mode);
 
         GestureDetector.SimpleOnGestureListener listener =
                 new GestureDetector.SimpleOnGestureListener() {
@@ -110,15 +122,15 @@
 
     /**
      * Constructs a new instance with {@code adapter} and {@code helper}.
-     * @param adapter
-     * @param helper
      * @hide
      */
     @VisibleForTesting
-    MultiSelectManager(Adapter<?> adapter, RecyclerViewHelper helper) {
+    MultiSelectManager(Adapter<?> adapter, RecyclerViewHelper helper, int mode) {
         checkNotNull(adapter, "'adapter' cannot be null.");
         checkNotNull(helper, "'helper' cannot be null.");
 
+        mSingleSelect = mode == MODE_SINGLE;
+
         mHelper = helper;
         mAdapter = adapter;
 
@@ -196,34 +208,44 @@
      * @return True if the selection state of the item changed.
      */
     public boolean setItemSelected(int position, boolean selected) {
-        boolean changed = (selected)
-                ? mSelection.add(position)
-                : mSelection.remove(position);
-
-        if (changed) {
-            notifyItemStateChanged(position, true);
+        if (mSingleSelect && !mSelection.isEmpty()) {
+            clearSelectionQuietly();
         }
-        return changed;
+        return setItemsSelected(position, 1, selected);
     }
 
     /**
-     * @param position
-     * @param length
-     * @param selected
+     * Sets the selected state of the specified items. Note that the callback will NOT
+     * be consulted to see if an item can be selected.
+     *
      * @return True if the selection state of any of the items changed.
      */
     public boolean setItemsSelected(int position, int length, boolean selected) {
         boolean changed = false;
         for (int i = position; i < position + length; i++) {
-            changed |= setItemSelected(i, selected);
+            boolean itemChanged = selected ? mSelection.add(i) : mSelection.remove(i);
+            if (itemChanged) {
+                notifyItemStateChanged(i, selected);
+            }
+            changed |= itemChanged;
         }
+
+        notifySelectionChanged();
         return changed;
     }
 
     /**
-     * Clears the selection.
+     * Clears the selection and notifies (even if nothing changes).
      */
     public void clearSelection() {
+        clearSelectionQuietly();
+        notifySelectionChanged();
+    }
+
+    /**
+     * Clears the selection, without notifying anyone.
+     */
+    private void clearSelectionQuietly() {
         mRanger = null;
 
         if (mSelection.isEmpty()) {
@@ -265,7 +287,9 @@
             if (DEBUG) Log.i(TAG, "View is null. Cannot handle tap event.");
         }
 
-        toggleSelection(position);
+        if (toggleSelection(position)) {
+            notifySelectionChanged();
+        }
     }
 
     /**
@@ -309,6 +333,10 @@
             toggleSelection(position);
         }
 
+        // We're being lazy here notifying even when something might not have changed.
+        // To make this more correct, we'd need to update the Ranger class to return
+        // information about what has changed.
+        notifySelectionChanged();
         return false;
     }
 
@@ -327,20 +355,29 @@
             return false;
         }
 
+        boolean changed = false;
         if (mSelection.contains(position)) {
-            return attemptDeselect(position);
+            changed = attemptDeselect(position);
         } else {
-            boolean selected = attemptSelect(position);
+            boolean canSelect = notifyBeforeItemStateChange(position, true);
+            if (!canSelect) {
+                return false;
+            }
+            if (mSingleSelect && !mSelection.isEmpty()) {
+                clearSelectionQuietly();
+            }
+
             // Here we're already in selection mode. In that case
             // When a simple click/tap (without SHIFT) creates causes
             // an item to be selected.
             // By recreating Ranger at this point, we allow the user to create
             // multiple separate contiguous ranges with SHIFT+Click & Click.
-            if (selected) {
-                setSelectionFocusBegin(position);
-            }
-            return selected;
+            selectAndNotify(position);
+            setSelectionFocusBegin(position);
+            changed = true;
         }
+
+        return changed;
     }
 
     /**
@@ -367,10 +404,15 @@
      */
     private void updateRange(int begin, int end, boolean selected) {
         checkState(end >= begin);
-        if (DEBUG) Log.i(TAG, String.format("Updating range begin=%d, end=%d, selected=%b.", begin, end, selected));
         for (int i = begin; i <= end; i++) {
             if (selected) {
-                attemptSelect(i);
+                boolean canSelect = notifyBeforeItemStateChange(i, true);
+                if (canSelect) {
+                    if (mSingleSelect && !mSelection.isEmpty()) {
+                        clearSelectionQuietly();
+                    }
+                    selectAndNotify(i);
+                }
             } else {
                 attemptDeselect(i);
             }
@@ -381,16 +423,12 @@
      * @param position
      * @return True if the update was applied.
      */
-    private boolean attemptSelect(int position) {
-        if (notifyBeforeItemStateChange(position, true)) {
-            mSelection.add(position);
+    private boolean selectAndNotify(int position) {
+        boolean changed = mSelection.add(position);
+        if (changed) {
             notifyItemStateChanged(position, true);
-            if (DEBUG) Log.d(TAG, "Selection after select: " + mSelection);
-            return true;
-        } else {
-            if (DEBUG) Log.d(TAG, "Select cancelled by listener.");
-            return false;
         }
+        return changed;
     }
 
     /**
@@ -420,10 +458,8 @@
     }
 
     /**
-     * Notifies registered listeners when a selection changes.
-     *
-     * @param position
-     * @param selected
+     * Notifies registered listeners when the selection status of a single item
+     * (identified by {@code position}) changes.
      */
     private void notifyItemStateChanged(int position, boolean selected) {
         int lastListener = mCallbacks.size() - 1;
@@ -434,6 +470,19 @@
     }
 
     /**
+     * Notifies registered listeners when the selection has changed. This
+     * notification should be sent only once a full series of changes
+     * is complete, e.g. clearingSelection, or updating the single
+     * selection from one item to another.
+     */
+    private void notifySelectionChanged() {
+        int lastListener = mCallbacks.size() - 1;
+        for (int i = lastListener; i > -1; i--) {
+            mCallbacks.get(i).onSelectionChanged();
+        }
+    }
+
+    /**
      * Class providing support for managing range selections.
      */
     private final class Range {
@@ -443,7 +492,7 @@
         int mEnd = UNDEFINED;
 
         public Range(int begin) {
-            if (DEBUG) Log.d(TAG, String.format("New Ranger(%d) created.", begin));
+            if (DEBUG) Log.d(TAG, "New Ranger created beginning @ " + begin);
             mBegin = begin;
         }
 
@@ -680,8 +729,10 @@
             }
 
             StringBuilder buffer = new StringBuilder(mSelection.size() * 28);
-            buffer.append(String.format("{size=%d, ", mSelection.size()));
-            buffer.append("items=[");
+            buffer.append("{size=")
+                    .append(mSelection.size())
+                    .append(", ")
+                    .append("items=[");
             for (int i=0; i < mSelection.size(); i++) {
                 if (i > 0) {
                     buffer.append(", ");
@@ -726,11 +777,19 @@
         public void onItemStateChanged(int position, boolean selected);
 
         /**
-         * @param position
-         * @param selected
-         * @return false to cancel the change.
+         * Called prior to an item changing state. Callbacks can cancel
+         * the change at {@code position} by returning {@code false}.
+         *
+         * @param position Adapter position of the item that was checked or unchecked
+         * @param selected <code>true</code> if the item is to be selected, <code>false</code>
+         *                if the item is to be unselected.
          */
         public boolean onBeforeItemStateChange(int position, boolean selected);
+
+        /**
+         * Called immediately after completion of any set of changes.
+         */
+        public void onSelectionChanged();
     }
 
     /**
diff --git a/packages/DocumentsUI/tests/src/com/android/documentsui/MultiSelectManagerTest.java b/packages/DocumentsUI/tests/src/com/android/documentsui/MultiSelectManagerTest.java
index d9f2261..03ad3d4 100644
--- a/packages/DocumentsUI/tests/src/com/android/documentsui/MultiSelectManagerTest.java
+++ b/packages/DocumentsUI/tests/src/com/android/documentsui/MultiSelectManagerTest.java
@@ -60,7 +60,7 @@
         mAdapter = new TestAdapter(items);
         mCallback = new TestCallback();
         mEventHelper = new EventHelper();
-        mManager = new MultiSelectManager(mAdapter, mEventHelper);
+        mManager = new MultiSelectManager(mAdapter, mEventHelper, MultiSelectManager.MODE_MULTIPLE);
         mManager.addCallback(mCallback);
     }
 
@@ -188,6 +188,24 @@
         assertRangeSelection(0, 7);
     }
 
+    @Test
+    public void singleSelectMode() {
+        mManager = new MultiSelectManager(mAdapter, mEventHelper, MultiSelectManager.MODE_SINGLE);
+        mManager.addCallback(mCallback);
+        tap(20);
+        tap(13);
+        assertSelection(13);
+    }
+
+    @Test
+    public void singleSelectMode_ShiftTap() {
+        mManager = new MultiSelectManager(mAdapter, mEventHelper, MultiSelectManager.MODE_SINGLE);
+        mManager.addCallback(mCallback);
+        tap(13);
+        shiftTap(20);
+        assertSelection(20);
+    }
+
     private void tap(int position) {
         mManager.onSingleTapUp(position, 0, MotionEvent.TOOL_TYPE_MOUSE);
     }
@@ -257,6 +275,9 @@
         public boolean onBeforeItemStateChange(int position, boolean selected) {
             return !ignored.contains(position);
         }
+
+        @Override
+        public void onSelectionChanged() {}
     }
 
     private static final class TestHolder extends RecyclerView.ViewHolder {
diff --git a/packages/Keyguard/res/values/strings.xml b/packages/Keyguard/res/values/strings.xml
index 41b1059..d1e84f5 100644
--- a/packages/Keyguard/res/values/strings.xml
+++ b/packages/Keyguard/res/values/strings.xml
@@ -316,6 +316,15 @@
     <!-- An explanation text that the password needs to be entered since the device has just been restarted. [CHAR LIMIT=80] -->
     <string name="kg_prompt_reason_restart_password">Password required when you restart device.</string>
 
+    <!-- An explanation text that the pattern needs to be solved since the user hasn't used strong authentication since quite some time. [CHAR LIMIT=80] -->
+    <string name="kg_prompt_reason_timeout_pattern">Pattern required for additional security.</string>
+
+    <!-- An explanation text that the pin needs to be entered since the user hasn't used strong authentication since quite some time. [CHAR LIMIT=80] -->
+    <string name="kg_prompt_reason_timeout_pin">PIN required for additional security.</string>
+
+    <!-- An explanation text that the password needs to be entered since the user hasn't used strong authentication since quite some time. [CHAR LIMIT=80] -->
+    <string name="kg_prompt_reason_timeout_password">Password required for additional security.</string>
+
     <!-- An explanation text that the pattern needs to be solved since profiles have just been switched. [CHAR LIMIT=80] -->
     <string name="kg_prompt_reason_switch_profiles_pattern">Pattern required when you switch profiles.</string>
 
diff --git a/packages/Keyguard/src/com/android/keyguard/KeyguardAbsKeyInputView.java b/packages/Keyguard/src/com/android/keyguard/KeyguardAbsKeyInputView.java
index 8f792de..dfc31ab 100644
--- a/packages/Keyguard/src/com/android/keyguard/KeyguardAbsKeyInputView.java
+++ b/packages/Keyguard/src/com/android/keyguard/KeyguardAbsKeyInputView.java
@@ -234,6 +234,12 @@
         }
     }
 
+    @Override
+    public void showMessage(String message, int color) {
+        mSecurityMessageDisplay.setNextMessageColor(color);
+        mSecurityMessageDisplay.setMessage(message, true /* important */);
+    }
+
     protected abstract int getPromtReasonStringRes(int reason);
 
     // Cause a VIRTUAL_KEY vibration
diff --git a/packages/Keyguard/src/com/android/keyguard/KeyguardHostView.java b/packages/Keyguard/src/com/android/keyguard/KeyguardHostView.java
index ff4e815..ec2a173 100644
--- a/packages/Keyguard/src/com/android/keyguard/KeyguardHostView.java
+++ b/packages/Keyguard/src/com/android/keyguard/KeyguardHostView.java
@@ -163,13 +163,18 @@
      * Show a string explaining why the security view needs to be solved.
      *
      * @param reason a flag indicating which string should be shown, see
-     *               {@link KeyguardSecurityView#PROMPT_REASON_NONE}
-     *               and {@link KeyguardSecurityView#PROMPT_REASON_RESTART}
+     *               {@link KeyguardSecurityView#PROMPT_REASON_NONE},
+     *               {@link KeyguardSecurityView#PROMPT_REASON_RESTART} and
+     *               {@link KeyguardSecurityView#PROMPT_REASON_TIMEOUT}.
      */
     public void showPromptReason(int reason) {
         mSecurityContainer.showPromptReason(reason);
     }
 
+    public void showMessage(String message, int color) {
+        mSecurityContainer.showMessage(message, color);
+    }
+
     /**
      *  Dismisses the keyguard by going to the next screen or making it gone.
      *
@@ -209,9 +214,12 @@
     /**
      * Authentication has happened and it's time to dismiss keyguard. This function
      * should clean up and inform KeyguardViewMediator.
+     *
+     * @param strongAuth whether the user has authenticated with strong authentication like
+     *                   pattern, password or PIN but not by trust agents or fingerprint
      */
     @Override
-    public void finish() {
+    public void finish(boolean strongAuth) {
         // If there's a pending runnable because the user interacted with a widget
         // and we're leaving keyguard, then run it.
         boolean deferKeyguardDone = false;
@@ -222,9 +230,9 @@
         }
         if (mViewMediatorCallback != null) {
             if (deferKeyguardDone) {
-                mViewMediatorCallback.keyguardDonePending();
+                mViewMediatorCallback.keyguardDonePending(strongAuth);
             } else {
-                mViewMediatorCallback.keyguardDone(true);
+                mViewMediatorCallback.keyguardDone(strongAuth);
             }
         }
     }
@@ -281,32 +289,6 @@
     }
 
     /**
-     * Verify that the user can get past the keyguard securely.  This is called,
-     * for example, when the phone disables the keyguard but then wants to launch
-     * something else that requires secure access.
-     *
-     * The result will be propogated back via {@link KeyguardViewCallback#keyguardDone(boolean)}
-     */
-    public void verifyUnlock() {
-        SecurityMode securityMode = mSecurityContainer.getSecurityMode();
-        if (securityMode == KeyguardSecurityModel.SecurityMode.None) {
-            if (mViewMediatorCallback != null) {
-                mViewMediatorCallback.keyguardDone(true);
-            }
-        } else if (securityMode != KeyguardSecurityModel.SecurityMode.Pattern
-                && securityMode != KeyguardSecurityModel.SecurityMode.PIN
-                && securityMode != KeyguardSecurityModel.SecurityMode.Password) {
-            // can only verify unlock when in pattern/password mode
-            if (mViewMediatorCallback != null) {
-                mViewMediatorCallback.keyguardDone(false);
-            }
-        } else {
-            // otherwise, go to the unlock screen, see if they can verify it
-            mSecurityContainer.verifyUnlock();
-        }
-    }
-
-    /**
      * Called before this view is being removed.
      */
     public void cleanUp() {
diff --git a/packages/Keyguard/src/com/android/keyguard/KeyguardMessageArea.java b/packages/Keyguard/src/com/android/keyguard/KeyguardMessageArea.java
index 2951af9..c8adf64 100644
--- a/packages/Keyguard/src/com/android/keyguard/KeyguardMessageArea.java
+++ b/packages/Keyguard/src/com/android/keyguard/KeyguardMessageArea.java
@@ -39,15 +39,18 @@
      * lift-to-type from interrupting itself.
      */
     private static final long ANNOUNCEMENT_DELAY = 250;
+    private static final int DEFAULT_COLOR = -1;
 
     private static final int SECURITY_MESSAGE_DURATION = 5000;
 
     private final KeyguardUpdateMonitor mUpdateMonitor;
     private final Handler mHandler;
+    private final int mDefaultColor;
 
     // Timeout before we reset the message to show charging/owner info
     long mTimeout = SECURITY_MESSAGE_DURATION;
     CharSequence mMessage;
+    private int mNextMessageColor = DEFAULT_COLOR;
 
     private final Runnable mClearMessageRunnable = new Runnable() {
         @Override
@@ -78,10 +81,16 @@
         mUpdateMonitor.registerCallback(mInfoCallback);
         mHandler = new Handler(Looper.myLooper());
 
+        mDefaultColor = getCurrentTextColor();
         update();
     }
 
     @Override
+    public void setNextMessageColor(int color) {
+        mNextMessageColor = color;
+    }
+
+    @Override
     public void setMessage(CharSequence msg, boolean important) {
         if (!TextUtils.isEmpty(msg) && important) {
             securityMessageChanged(msg);
@@ -151,6 +160,12 @@
         CharSequence status = mMessage;
         setVisibility(TextUtils.isEmpty(status) ? INVISIBLE : VISIBLE);
         setText(status);
+        int color = mDefaultColor;
+        if (mNextMessageColor != DEFAULT_COLOR) {
+            color = mNextMessageColor;
+            mNextMessageColor = DEFAULT_COLOR;
+        }
+        setTextColor(color);
     }
 
 
diff --git a/packages/Keyguard/src/com/android/keyguard/KeyguardPasswordView.java b/packages/Keyguard/src/com/android/keyguard/KeyguardPasswordView.java
index 2db87b3..3a7e6d0 100644
--- a/packages/Keyguard/src/com/android/keyguard/KeyguardPasswordView.java
+++ b/packages/Keyguard/src/com/android/keyguard/KeyguardPasswordView.java
@@ -115,6 +115,8 @@
         switch (reason) {
             case PROMPT_REASON_RESTART:
                 return R.string.kg_prompt_reason_restart_password;
+            case PROMPT_REASON_TIMEOUT:
+                return R.string.kg_prompt_reason_timeout_password;
             default:
                 return 0;
         }
diff --git a/packages/Keyguard/src/com/android/keyguard/KeyguardPatternView.java b/packages/Keyguard/src/com/android/keyguard/KeyguardPatternView.java
index 4bd1a2e..9a91ca4 100644
--- a/packages/Keyguard/src/com/android/keyguard/KeyguardPatternView.java
+++ b/packages/Keyguard/src/com/android/keyguard/KeyguardPatternView.java
@@ -15,10 +15,6 @@
  */
 package com.android.keyguard;
 
-import android.animation.Animator;
-import android.animation.AnimatorListenerAdapter;
-import android.animation.ObjectAnimator;
-import android.animation.ValueAnimator;
 import android.content.Context;
 import android.graphics.Rect;
 import android.os.AsyncTask;
@@ -28,7 +24,6 @@
 import android.util.AttributeSet;
 import android.util.Log;
 import android.view.MotionEvent;
-import android.view.RenderNodeAnimator;
 import android.view.View;
 import android.view.ViewGroup;
 import android.view.animation.AnimationUtils;
@@ -337,11 +332,22 @@
                 mSecurityMessageDisplay.setMessage(R.string.kg_prompt_reason_restart_pattern,
                         true /* important */);
                 break;
+            case PROMPT_REASON_TIMEOUT:
+                mSecurityMessageDisplay.setMessage(R.string.kg_prompt_reason_timeout_pattern,
+                        true /* important */);
+                break;
             default:
+                break;
         }
     }
 
     @Override
+    public void showMessage(String message, int color) {
+        mSecurityMessageDisplay.setNextMessageColor(color);
+        mSecurityMessageDisplay.setMessage(message, true /* important */);
+    }
+
+    @Override
     public void startAppearAnimation() {
         enableClipping(false);
         setAlpha(1f);
diff --git a/packages/Keyguard/src/com/android/keyguard/KeyguardPinBasedInputView.java b/packages/Keyguard/src/com/android/keyguard/KeyguardPinBasedInputView.java
index 07947b1..4cd4845 100644
--- a/packages/Keyguard/src/com/android/keyguard/KeyguardPinBasedInputView.java
+++ b/packages/Keyguard/src/com/android/keyguard/KeyguardPinBasedInputView.java
@@ -98,6 +98,8 @@
         switch (reason) {
             case PROMPT_REASON_RESTART:
                 return R.string.kg_prompt_reason_restart_pin;
+            case PROMPT_REASON_TIMEOUT:
+                return R.string.kg_prompt_reason_timeout_pin;
             default:
                 return 0;
         }
diff --git a/packages/Keyguard/src/com/android/keyguard/KeyguardSecurityContainer.java b/packages/Keyguard/src/com/android/keyguard/KeyguardSecurityContainer.java
index 85da298..77215a7 100644
--- a/packages/Keyguard/src/com/android/keyguard/KeyguardSecurityContainer.java
+++ b/packages/Keyguard/src/com/android/keyguard/KeyguardSecurityContainer.java
@@ -54,7 +54,12 @@
         public boolean dismiss(boolean authenticated);
         public void userActivity();
         public void onSecurityModeChanged(SecurityMode securityMode, boolean needsInput);
-        public void finish();
+
+        /**
+         * @param strongAuth wheher the user has authenticated with strong authentication like
+         *                   pattern, password or PIN but not by trust agents or fingerprint
+         */
+        public void finish(boolean strongAuth);
         public void reset();
     }
 
@@ -282,7 +287,7 @@
                 showWipeDialog(failedAttempts, userType);
             }
         }
-        monitor.reportFailedUnlockAttempt();
+        monitor.reportFailedStrongAuthUnlockAttempt();
         mLockPatternUtils.reportFailedPasswordAttempt(KeyguardUpdateMonitor.getCurrentUser());
         if (timeoutMs > 0) {
             showTimeoutDialog(timeoutMs);
@@ -308,6 +313,7 @@
     boolean showNextSecurityScreenOrFinish(boolean authenticated) {
         if (DEBUG) Log.d(TAG, "showNextSecurityScreenOrFinish(" + authenticated + ")");
         boolean finish = false;
+        boolean strongAuth = false;
         if (mUpdateMonitor.getUserCanSkipBouncer(
                 KeyguardUpdateMonitor.getCurrentUser())) {
             finish = true;
@@ -323,6 +329,7 @@
                 case Pattern:
                 case Password:
                 case PIN:
+                    strongAuth = true;
                     finish = true;
                     break;
 
@@ -346,7 +353,7 @@
             }
         }
         if (finish) {
-            mSecurityCallback.finish();
+            mSecurityCallback.finish(strongAuth);
         }
         return finish;
     }
@@ -518,6 +525,13 @@
         }
     }
 
+
+    public void showMessage(String message, int color) {
+        if (mCurrentSecuritySelection != SecurityMode.None) {
+            getSecurityView(mCurrentSecuritySelection).showMessage(message, color);
+        }
+    }
+
     @Override
     public void showUsabilityHint() {
         mSecurityViewFlipper.showUsabilityHint();
diff --git a/packages/Keyguard/src/com/android/keyguard/KeyguardSecurityView.java b/packages/Keyguard/src/com/android/keyguard/KeyguardSecurityView.java
index 5658a74..38302fb 100644
--- a/packages/Keyguard/src/com/android/keyguard/KeyguardSecurityView.java
+++ b/packages/Keyguard/src/com/android/keyguard/KeyguardSecurityView.java
@@ -22,9 +22,18 @@
     static public final int VIEW_REVEALED = 2;
 
     int PROMPT_REASON_NONE = 0;
+
+    /**
+     * Strong auth is required because the device has just booted.
+     */
     int PROMPT_REASON_RESTART = 1;
 
     /**
+     * Strong auth is required because the user hasn't used strong auth since a while.
+     */
+    int PROMPT_REASON_TIMEOUT = 2;
+
+    /**
      * Interface back to keyguard to tell it when security
      * @param callback
      */
@@ -77,6 +86,14 @@
     void showPromptReason(int reason);
 
     /**
+     * Show a message on the security view with a specified color
+     *
+     * @param message the message to show
+     * @param color the color to use
+     */
+    void showMessage(String message, int color);
+
+    /**
      * Instruct the view to show usability hints, if any.
      *
      */
diff --git a/packages/Keyguard/src/com/android/keyguard/KeyguardSecurityViewFlipper.java b/packages/Keyguard/src/com/android/keyguard/KeyguardSecurityViewFlipper.java
index a0ff21b..6012c45 100644
--- a/packages/Keyguard/src/com/android/keyguard/KeyguardSecurityViewFlipper.java
+++ b/packages/Keyguard/src/com/android/keyguard/KeyguardSecurityViewFlipper.java
@@ -139,6 +139,14 @@
     }
 
     @Override
+    public void showMessage(String message, int color) {
+        KeyguardSecurityView ksv = getSecurityView();
+        if (ksv != null) {
+            ksv.showMessage(message, color);
+        }
+    }
+
+    @Override
     public void showUsabilityHint() {
         KeyguardSecurityView ksv = getSecurityView();
         if (ksv != null) {
diff --git a/packages/Keyguard/src/com/android/keyguard/KeyguardUpdateMonitor.java b/packages/Keyguard/src/com/android/keyguard/KeyguardUpdateMonitor.java
index 55d85206..3232f65 100644
--- a/packages/Keyguard/src/com/android/keyguard/KeyguardUpdateMonitor.java
+++ b/packages/Keyguard/src/com/android/keyguard/KeyguardUpdateMonitor.java
@@ -64,6 +64,7 @@
 import android.telephony.SubscriptionManager;
 import android.telephony.SubscriptionManager.OnSubscriptionsChangedListener;
 import android.telephony.TelephonyManager;
+import android.util.ArraySet;
 import android.util.Log;
 import android.util.SparseBooleanArray;
 import android.util.SparseIntArray;
@@ -103,6 +104,12 @@
             = "com.android.facelock.FACE_UNLOCK_STOPPED";
     private static final String FINGERPRINT_WAKE_LOCK_NAME = "wake-and-unlock wakelock";
 
+    private static final String ACTION_STRONG_AUTH_TIMEOUT =
+            "com.android.systemui.ACTION_STRONG_AUTH_TIMEOUT";
+    private static final String USER_ID = "com.android.systemui.USER_ID";
+
+    private static final String PERMISSION_SELF = "com.android.systemui.permission.SELF";
+
     /**
      * Mode in which we don't need to wake up the device when we get a fingerprint.
      */
@@ -118,7 +125,19 @@
      * Mode in which we wake up the device, but play the normal dismiss animation. Active when we
      * acquire a fingerprint pulsing in doze mode.
      * */
-    private static final int FP_WAKE_WAKE_TO_BOUNCER = 2;
+    private static final int FP_WAKE_TO_BOUNCER = 2;
+
+    /**
+     * Mode in which we only wake up the device, and keyguard was not showing when we acquired a
+     * fingerprint.
+     * */
+    private static final int FP_ONLY_WAKE = 3;
+
+    /**
+     * Milliseconds after unlocking with fingerprint times out, i.e. the user has to use a
+     * strong auth method like password, PIN or pattern.
+     */
+    private static final long FINGERPRINT_UNLOCK_TIMEOUT_MS = 72 * 60 * 60 * 1000;
 
     // Callback messages
     private static final int MSG_TIME_UPDATE = 301;
@@ -167,7 +186,8 @@
     // Password attempts
     private SparseIntArray mFailedAttempts = new SparseIntArray();
 
-    private boolean mClockVisible;
+    /** Tracks whether strong authentication hasn't been used since quite some time per user. */
+    private ArraySet<Integer> mStrongAuthTimedOut = new ArraySet<>();
 
     private final ArrayList<WeakReference<KeyguardUpdateMonitorCallback>>
             mCallbacks = Lists.newArrayList();
@@ -178,6 +198,7 @@
     private boolean mDeviceInteractive;
     private boolean mScreenOn;
     private SubscriptionManager mSubscriptionManager;
+    private AlarmManager mAlarmManager;
     private List<SubscriptionInfo> mSubscriptionInfo;
     private boolean mFingerprintDetectionRunning;
     private TrustManager mTrustManager;
@@ -401,14 +422,14 @@
             mWakeLock = mPowerManager.newWakeLock(
                     PowerManager.PARTIAL_WAKE_LOCK, FINGERPRINT_WAKE_LOCK_NAME);
             mWakeLock.acquire();
-            mFpWakeMode = FP_WAKE_DIRECT_UNLOCK;
+            mFpWakeMode = mKeyguardIsVisible ? FP_WAKE_DIRECT_UNLOCK : FP_ONLY_WAKE;
             if (DEBUG_FP_WAKELOCK) {
                 Log.i(TAG, "fingerprint acquired, grabbing fp wakelock");
             }
             mHandler.postDelayed(mReleaseFingerprintWakeLockRunnable,
                     FINGERPRINT_WAKELOCK_TIMEOUT_MS);
         } else if (!mDeviceInteractive) {
-            mFpWakeMode = FP_WAKE_WAKE_TO_BOUNCER;
+            mFpWakeMode = FP_WAKE_TO_BOUNCER;
         } else {
             mFpWakeMode = FP_WAKE_NONE;
         }
@@ -436,7 +457,8 @@
     }
 
     private void handleFingerprintAuthenticated() {
-        if (mFpWakeMode == FP_WAKE_WAKE_TO_BOUNCER || mFpWakeMode == FP_WAKE_DIRECT_UNLOCK) {
+        if (mFpWakeMode == FP_WAKE_TO_BOUNCER || mFpWakeMode == FP_WAKE_DIRECT_UNLOCK
+                || mFpWakeMode == FP_ONLY_WAKE) {
             if (DEBUG_FP_WAKELOCK) {
                 Log.i(TAG, "fp wakelock: Authenticated, waking up...");
             }
@@ -542,7 +564,39 @@
     }
 
     public boolean isUnlockingWithFingerprintAllowed() {
-        return mUserHasAuthenticatedSinceBoot;
+        return mUserHasAuthenticatedSinceBoot && !hasFingerprintUnlockTimedOut(sCurrentUser);
+    }
+
+    /**
+     * @return true if the user hasn't use strong authentication (pattern, PIN, password) since a
+     *         while and thus can't unlock with fingerprint, false otherwise
+     */
+    public boolean hasFingerprintUnlockTimedOut(int userId) {
+        return mStrongAuthTimedOut.contains(userId);
+    }
+
+    public void reportSuccessfulStrongAuthUnlockAttempt() {
+        mStrongAuthTimedOut.remove(sCurrentUser);
+        scheduleStrongAuthTimeout();
+    }
+
+    private void scheduleStrongAuthTimeout() {
+        long when = SystemClock.elapsedRealtime() + FINGERPRINT_UNLOCK_TIMEOUT_MS;
+        Intent intent = new Intent(ACTION_STRONG_AUTH_TIMEOUT);
+        intent.putExtra(USER_ID, sCurrentUser);
+        PendingIntent sender = PendingIntent.getBroadcast(mContext,
+                sCurrentUser, intent, PendingIntent.FLAG_CANCEL_CURRENT);
+        mAlarmManager.set(AlarmManager.ELAPSED_REALTIME, when, sender);
+        notifyStrongAuthTimedOutChanged(sCurrentUser);
+    }
+
+    private void notifyStrongAuthTimedOutChanged(int userId) {
+        for (int i = 0; i < mCallbacks.size(); i++) {
+            KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
+            if (cb != null) {
+                cb.onStrongAuthTimeoutExpiredChanged(userId);
+            }
+        }
     }
 
     static class DisplayClientState {
@@ -632,6 +686,17 @@
         }
     };
 
+    private final BroadcastReceiver mStrongAuthTimeoutReceiver = new BroadcastReceiver() {
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            if (ACTION_STRONG_AUTH_TIMEOUT.equals(intent.getAction())) {
+                int userId = intent.getIntExtra(USER_ID, -1);
+                mStrongAuthTimedOut.add(userId);
+                notifyStrongAuthTimedOutChanged(userId);
+            }
+        }
+    };
+
     private FingerprintManager.AuthenticationCallback mAuthenticationCallback
             = new AuthenticationCallback() {
 
@@ -864,7 +929,9 @@
         mContext = context;
         mSubscriptionManager = SubscriptionManager.from(context);
         mPowerManager = context.getSystemService(PowerManager.class);
+        mAlarmManager = context.getSystemService(AlarmManager.class);
         mDeviceProvisioned = isDeviceProvisionedInSettingsDb();
+
         // Since device can't be un-provisioned, we only need to register a content observer
         // to update mDeviceProvisioned when we are...
         if (!mDeviceProvisioned) {
@@ -925,6 +992,10 @@
             e.printStackTrace();
         }
 
+        IntentFilter strongAuthTimeoutFilter = new IntentFilter();
+        strongAuthTimeoutFilter.addAction(ACTION_STRONG_AUTH_TIMEOUT);
+        context.registerReceiver(mStrongAuthTimeoutReceiver, strongAuthTimeoutFilter,
+                PERMISSION_SELF, null /* handler */);
         mTrustManager = (TrustManager) context.getSystemService(Context.TRUST_SERVICE);
         mTrustManager.registerTrustListener(this);
 
@@ -942,15 +1013,13 @@
     }
 
     private boolean shouldListenForFingerprint() {
-        return mKeyguardIsVisible && !mSwitchingUser &&
-                mTrustManager.hasUserAuthenticatedSinceBoot(
-                        ActivityManager.getCurrentUser());
+        return (mKeyguardIsVisible || !mDeviceInteractive) && !mSwitchingUser;
     }
 
     private void startListeningForFingerprint() {
         if (DEBUG) Log.v(TAG, "startListeningForFingerprint()");
         int userId = ActivityManager.getCurrentUser();
-        if (isUnlockWithFingerPrintPossible(userId)) {
+        if (isUnlockWithFingerprintPossible(userId)) {
             mUserHasAuthenticatedSinceBoot = mTrustManager.hasUserAuthenticatedSinceBoot(
                     ActivityManager.getCurrentUser());
             if (mFingerprintCancelSignal != null) {
@@ -962,7 +1031,7 @@
         }
     }
 
-    public boolean isUnlockWithFingerPrintPossible(int userId) {
+    public boolean isUnlockWithFingerprintPossible(int userId) {
         return mFpm != null && mFpm.isHardwareDetected() && !isFingerprintDisabled(userId)
                 && mFpm.getEnrolledFingerprints(userId).size() > 0;
     }
@@ -1428,7 +1497,7 @@
         return mFailedAttempts.get(sCurrentUser, 0);
     }
 
-    public void reportFailedUnlockAttempt() {
+    public void reportFailedStrongAuthUnlockAttempt() {
         mFailedAttempts.put(sCurrentUser, getFailedUnlockAttempts() + 1);
     }
 
diff --git a/packages/Keyguard/src/com/android/keyguard/KeyguardUpdateMonitorCallback.java b/packages/Keyguard/src/com/android/keyguard/KeyguardUpdateMonitorCallback.java
index 6cda2b7..52412f7 100644
--- a/packages/Keyguard/src/com/android/keyguard/KeyguardUpdateMonitorCallback.java
+++ b/packages/Keyguard/src/com/android/keyguard/KeyguardUpdateMonitorCallback.java
@@ -217,4 +217,10 @@
      * Called when the fingerprint running state changed.
      */
     public void onFingerprintRunningStateChanged(boolean running) { }
+
+    /**
+     * Called when the state that the user hasn't used strong authentication since quite some time
+     * has changed.
+     */
+    public void onStrongAuthTimeoutExpiredChanged(int userId) { }
 }
diff --git a/packages/Keyguard/src/com/android/keyguard/SecurityMessageDisplay.java b/packages/Keyguard/src/com/android/keyguard/SecurityMessageDisplay.java
index b38cfd5..ddb1f6e 100644
--- a/packages/Keyguard/src/com/android/keyguard/SecurityMessageDisplay.java
+++ b/packages/Keyguard/src/com/android/keyguard/SecurityMessageDisplay.java
@@ -17,11 +17,14 @@
 package com.android.keyguard;
 
 public interface SecurityMessageDisplay {
-    public void setMessage(CharSequence msg, boolean important);
 
-    public void setMessage(int resId, boolean important);
+    void setNextMessageColor(int color);
 
-    public void setMessage(int resId, boolean important, Object... formatArgs);
+    void setMessage(CharSequence msg, boolean important);
 
-    public void setTimeout(int timeout_ms);
+    void setMessage(int resId, boolean important);
+
+    void setMessage(int resId, boolean important, Object... formatArgs);
+
+    void setTimeout(int timeout_ms);
 }
diff --git a/packages/Keyguard/src/com/android/keyguard/ViewMediatorCallback.java b/packages/Keyguard/src/com/android/keyguard/ViewMediatorCallback.java
index ff463c6..8ab3011 100644
--- a/packages/Keyguard/src/com/android/keyguard/ViewMediatorCallback.java
+++ b/packages/Keyguard/src/com/android/keyguard/ViewMediatorCallback.java
@@ -28,12 +28,11 @@
 
     /**
      * Report that the keyguard is done.
-     * @param authenticated Whether the user securely got past the keyguard.
-     *   the only reason for this to be false is if the keyguard was instructed
-     *   to appear temporarily to verify the user is supposed to get past the
-     *   keyguard, and the user fails to do so.
+     *
+     * @param strongAuth whether the user has authenticated with strong authentication like
+     *                   pattern, password or PIN but not by trust agents or fingerprint
      */
-    void keyguardDone(boolean authenticated);
+    void keyguardDone(boolean strongAuth);
 
     /**
      * Report that the keyguard is done drawing.
@@ -48,8 +47,11 @@
 
     /**
      * Report that the keyguard is dismissable, pending the next keyguardDone call.
+     *
+     * @param strongAuth whether the user has authenticated with strong authentication like
+     *                   pattern, password or PIN but not by trust agents or fingerprint
      */
-    void keyguardDonePending();
+    void keyguardDonePending(boolean strongAuth);
 
     /**
      * Report when keyguard is actually gone
@@ -85,8 +87,9 @@
     /**
      * @return one of the reasons why the bouncer needs to be shown right now and the user can't use
      *         his normal unlock method like fingerprint or trust agents. See
-     *         {@link KeyguardSecurityView#PROMPT_REASON_NONE}
-     *         and {@link KeyguardSecurityView#PROMPT_REASON_RESTART}.
+     *         {@link KeyguardSecurityView#PROMPT_REASON_NONE},
+     *         {@link KeyguardSecurityView#PROMPT_REASON_RESTART} and
+     *         {@link KeyguardSecurityView#PROMPT_REASON_TIMEOUT}.
      */
     int getBouncerPromptReason();
 }
diff --git a/packages/MtpDocumentsProvider/src/com/android/mtp/DocumentLoader.java b/packages/MtpDocumentsProvider/src/com/android/mtp/DocumentLoader.java
new file mode 100644
index 0000000..2353205
--- /dev/null
+++ b/packages/MtpDocumentsProvider/src/com/android/mtp/DocumentLoader.java
@@ -0,0 +1,222 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.mtp;
+
+import android.content.ContentResolver;
+import android.database.Cursor;
+import android.database.MatrixCursor;
+import android.net.Uri;
+import android.os.Bundle;
+import android.os.Process;
+import android.provider.DocumentsContract;
+import android.util.Log;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.LinkedList;
+
+class DocumentLoader {
+    static final int NUM_INITIAL_ENTRIES = 10;
+    static final int NUM_LOADING_ENTRIES = 20;
+    static final int NOTIFY_PERIOD_MS = 500;
+
+    private final MtpManager mMtpManager;
+    private final ContentResolver mResolver;
+    private final LinkedList<LoaderTask> mTasks = new LinkedList<LoaderTask>();
+    private boolean mHasBackgroundThread = false;
+
+    DocumentLoader(MtpManager mtpManager, ContentResolver resolver) {
+        mMtpManager = mtpManager;
+        mResolver = resolver;
+    }
+
+    private static MtpDocument[] loadDocuments(MtpManager manager, int deviceId, int[] handles)
+            throws IOException {
+        final MtpDocument[] documents = new MtpDocument[handles.length];
+        for (int i = 0; i < handles.length; i++) {
+            documents[i] = manager.getDocument(deviceId, handles[i]);
+        }
+        return documents;
+    }
+
+    synchronized Cursor queryChildDocuments(String[] columnNames, Identifier parent)
+            throws IOException {
+        LoaderTask task = findTask(parent);
+        if (task == null) {
+            int parentHandle = parent.mObjectHandle;
+            // Need to pass the special value MtpManager.OBJECT_HANDLE_ROOT_CHILDREN to
+            // getObjectHandles if we would like to obtain children under the root.
+            if (parentHandle == MtpDocument.DUMMY_HANDLE_FOR_ROOT) {
+                parentHandle = MtpManager.OBJECT_HANDLE_ROOT_CHILDREN;
+            }
+            task = new LoaderTask(parent, mMtpManager.getObjectHandles(
+                    parent.mDeviceId, parent.mStorageId, parentHandle));
+            task.fillDocuments(loadDocuments(
+                    mMtpManager,
+                    parent.mDeviceId,
+                    task.getUnloadedObjectHandles(NUM_INITIAL_ENTRIES)));
+        }
+
+        // Move this task to the head of the list to prioritize it.
+        mTasks.remove(task);
+        mTasks.addFirst(task);
+        if (!task.completed() && !mHasBackgroundThread) {
+            mHasBackgroundThread = true;
+            new BackgroundLoaderThread().start();
+        }
+
+        return task.createCursor(mResolver, columnNames);
+    }
+
+    synchronized void clearCache(int deviceId) {
+        int i = 0;
+        while (i < mTasks.size()) {
+            if (mTasks.get(i).mIdentifier.mDeviceId == deviceId) {
+                mTasks.remove(i);
+            } else {
+                i++;
+            }
+        }
+    }
+
+    synchronized void clearCache() {
+        int i = 0;
+        while (i < mTasks.size()) {
+            if (mTasks.get(i).completed()) {
+                mTasks.remove(i);
+            } else {
+                i++;
+            }
+        }
+    }
+
+    private LoaderTask findTask(Identifier parent) {
+        for (int i = 0; i < mTasks.size(); i++) {
+            if (mTasks.get(i).mIdentifier.equals(parent))
+                return mTasks.get(i);
+        }
+        return null;
+    }
+
+    private LoaderTask findUncompletedTask() {
+        for (int i = 0; i < mTasks.size(); i++) {
+            if (!mTasks.get(i).completed())
+                return mTasks.get(i);
+        }
+        return null;
+    }
+
+    private class BackgroundLoaderThread extends Thread {
+        @Override
+        public void run() {
+            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
+            while (true) {
+                LoaderTask task;
+                int deviceId;
+                int[] handles;
+                synchronized (DocumentLoader.this) {
+                    task = findUncompletedTask();
+                    if (task == null) {
+                        mHasBackgroundThread = false;
+                        return;
+                    }
+                    deviceId = task.mIdentifier.mDeviceId;
+                    handles = task.getUnloadedObjectHandles(NUM_LOADING_ENTRIES);
+                }
+                MtpDocument[] documents;
+                try {
+                    documents = loadDocuments(mMtpManager, deviceId, handles);
+                } catch (IOException exception) {
+                    documents = null;
+                    Log.d(MtpDocumentsProvider.TAG, exception.getMessage());
+                }
+                synchronized (DocumentLoader.this) {
+                    if (documents != null) {
+                        task.fillDocuments(documents);
+                        final boolean shouldNotify =
+                                task.mLastNotified.getTime() <
+                                new Date().getTime() - NOTIFY_PERIOD_MS ||
+                                task.completed();
+                        if (shouldNotify) {
+                            task.notify(mResolver);
+                        }
+                    } else {
+                        mTasks.remove(task);
+                    }
+                }
+            }
+        }
+    }
+
+    private static class LoaderTask {
+        final Identifier mIdentifier;
+        final int[] mObjectHandles;
+        final MtpDocument[] mDocuments;
+        Date mLastNotified;
+        int mNumLoaded;
+
+        LoaderTask(Identifier identifier, int[] objectHandles) {
+            mIdentifier = identifier;
+            mObjectHandles = objectHandles;
+            mDocuments = new MtpDocument[mObjectHandles.length];
+            mNumLoaded = 0;
+            mLastNotified = new Date();
+        }
+
+        Cursor createCursor(ContentResolver resolver, String[] columnNames) {
+            final MatrixCursor cursor = new MatrixCursor(columnNames);
+            final Identifier rootIdentifier = new Identifier(
+                    mIdentifier.mDeviceId, mIdentifier.mStorageId);
+            for (int i = 0; i < mNumLoaded; i++) {
+                mDocuments[i].addToCursor(rootIdentifier, cursor.newRow());
+            }
+            final Bundle extras = new Bundle();
+            extras.putBoolean(DocumentsContract.EXTRA_LOADING, !completed());
+            cursor.setNotificationUri(resolver, createUri());
+            cursor.respond(extras);
+            return cursor;
+        }
+
+        boolean completed() {
+            return mNumLoaded == mDocuments.length;
+        }
+
+        int[] getUnloadedObjectHandles(int count) {
+            return Arrays.copyOfRange(
+                    mObjectHandles,
+                    mNumLoaded,
+                    Math.min(mNumLoaded + count, mObjectHandles.length));
+        }
+
+        void notify(ContentResolver resolver) {
+            resolver.notifyChange(createUri(), null, false);
+            mLastNotified = new Date();
+        }
+
+        void fillDocuments(MtpDocument[] documents) {
+            for (int i = 0; i < documents.length; i++) {
+                mDocuments[mNumLoaded++] = documents[i];
+            }
+        }
+
+        private Uri createUri() {
+            return DocumentsContract.buildChildDocumentsUri(
+                    MtpDocumentsProvider.AUTHORITY, mIdentifier.toDocumentId());
+        }
+    }
+}
diff --git a/packages/MtpDocumentsProvider/src/com/android/mtp/MtpDocumentsProvider.java b/packages/MtpDocumentsProvider/src/com/android/mtp/MtpDocumentsProvider.java
index 32882c8..bcdfb71 100644
--- a/packages/MtpDocumentsProvider/src/com/android/mtp/MtpDocumentsProvider.java
+++ b/packages/MtpDocumentsProvider/src/com/android/mtp/MtpDocumentsProvider.java
@@ -40,12 +40,12 @@
 public class MtpDocumentsProvider extends DocumentsProvider {
     static final String AUTHORITY = "com.android.mtp.documents";
     static final String TAG = "MtpDocumentsProvider";
-    private static final String[] DEFAULT_ROOT_PROJECTION = new String[] {
+    static final String[] DEFAULT_ROOT_PROJECTION = new String[] {
             Root.COLUMN_ROOT_ID, Root.COLUMN_FLAGS, Root.COLUMN_ICON,
             Root.COLUMN_TITLE, Root.COLUMN_DOCUMENT_ID,
             Root.COLUMN_AVAILABLE_BYTES,
     };
-    private static final String[] DEFAULT_DOCUMENT_PROJECTION = new String[] {
+    static final String[] DEFAULT_DOCUMENT_PROJECTION = new String[] {
             Document.COLUMN_DOCUMENT_ID, Document.COLUMN_MIME_TYPE,
             Document.COLUMN_DISPLAY_NAME, Document.COLUMN_LAST_MODIFIED,
             Document.COLUMN_FLAGS, Document.COLUMN_SIZE,
@@ -56,6 +56,7 @@
     private MtpManager mMtpManager;
     private ContentResolver mResolver;
     private PipeManager mPipeManager;
+    private DocumentLoader mDocumentLoader;
 
     /**
      * Provides singleton instance to MtpDocumentsService.
@@ -70,14 +71,15 @@
         mMtpManager = new MtpManager(getContext());
         mResolver = getContext().getContentResolver();
         mPipeManager = new PipeManager();
-
+        mDocumentLoader = new DocumentLoader(mMtpManager, mResolver);
         return true;
     }
 
     @VisibleForTesting
     void onCreateForTesting(MtpManager mtpManager, ContentResolver resolver) {
-        this.mMtpManager = mtpManager;
-        this.mResolver = resolver;
+        mMtpManager = mtpManager;
+        mResolver = resolver;
+        mDocumentLoader = new DocumentLoader(mMtpManager, mResolver);
     }
 
     @Override
@@ -152,7 +154,6 @@
         return cursor;
     }
 
-    // TODO: Support background loading for large number of files.
     @Override
     public Cursor queryChildDocuments(String parentDocumentId,
             String[] projection, String sortOrder) throws FileNotFoundException {
@@ -160,29 +161,8 @@
             projection = MtpDocumentsProvider.DEFAULT_DOCUMENT_PROJECTION;
         }
         final Identifier parentIdentifier = Identifier.createFromDocumentId(parentDocumentId);
-        int parentHandle = parentIdentifier.mObjectHandle;
-        // Need to pass the special value MtpManager.OBJECT_HANDLE_ROOT_CHILDREN to
-        // getObjectHandles if we would like to obtain children under the root.
-        if (parentHandle == MtpDocument.DUMMY_HANDLE_FOR_ROOT) {
-            parentHandle = MtpManager.OBJECT_HANDLE_ROOT_CHILDREN;
-        }
         try {
-            final MatrixCursor cursor = new MatrixCursor(projection);
-            final Identifier rootIdentifier = new Identifier(
-                    parentIdentifier.mDeviceId, parentIdentifier.mStorageId);
-            final int[] objectHandles = mMtpManager.getObjectHandles(
-                    parentIdentifier.mDeviceId, parentIdentifier.mStorageId, parentHandle);
-            for (int i = 0; i < objectHandles.length; i++) {
-                try {
-                    final MtpDocument document = mMtpManager.getDocument(
-                            parentIdentifier.mDeviceId,  objectHandles[i]);
-                    document.addToCursor(rootIdentifier, cursor.newRow());
-                } catch (IOException error) {
-                    cursor.close();
-                    throw new FileNotFoundException(error.getMessage());
-                }
-            }
-            return cursor;
+            return mDocumentLoader.queryChildDocuments(projection, parentIdentifier);
         } catch (IOException exception) {
             throw new FileNotFoundException(exception.getMessage());
         }
@@ -234,6 +214,11 @@
         }
     }
 
+    @Override
+    public void onTrimMemory(int level) {
+        mDocumentLoader.clearCache();
+    }
+
     void openDevice(int deviceId) throws IOException {
         mMtpManager.openDevice(deviceId);
         notifyRootsChange();
@@ -241,6 +226,7 @@
 
     void closeDevice(int deviceId) throws IOException {
         mMtpManager.closeDevice(deviceId);
+        mDocumentLoader.clearCache(deviceId);
         notifyRootsChange();
     }
 
@@ -249,6 +235,7 @@
         for (int deviceId : mMtpManager.getOpenedDeviceIds()) {
             try {
                 mMtpManager.closeDevice(deviceId);
+                mDocumentLoader.clearCache(deviceId);
                 closed = true;
             } catch (IOException d) {
                 Log.d(TAG, "Failed to close the MTP device: " + deviceId);
diff --git a/packages/MtpDocumentsProvider/src/com/android/mtp/MtpManager.java b/packages/MtpDocumentsProvider/src/com/android/mtp/MtpManager.java
index f266592..141d118 100644
--- a/packages/MtpDocumentsProvider/src/com/android/mtp/MtpManager.java
+++ b/packages/MtpDocumentsProvider/src/com/android/mtp/MtpManager.java
@@ -35,7 +35,7 @@
 
     private final UsbManager mManager;
     // TODO: Save and restore the set of opened device.
-    private final SparseArray<MtpDevice> mDevices = new SparseArray<MtpDevice>();
+    private final SparseArray<MtpDevice> mDevices = new SparseArray<>();
 
     MtpManager(Context context) {
         mManager = (UsbManager)context.getSystemService(Context.USB_SERVICE);
@@ -142,7 +142,8 @@
 
     synchronized void importFile(int deviceId, int objectHandle, ParcelFileDescriptor target)
             throws IOException {
-        throw new UnsupportedOperationException("Importing files is not supported.");
+        final MtpDevice device = getDevice(deviceId);
+        device.importFile(objectHandle, target);
     }
 
     private MtpDevice getDevice(int deviceId) throws IOException {
diff --git a/packages/MtpDocumentsProvider/src/com/android/mtp/PipeManager.java b/packages/MtpDocumentsProvider/src/com/android/mtp/PipeManager.java
index 7f498f5..ba13b31 100644
--- a/packages/MtpDocumentsProvider/src/com/android/mtp/PipeManager.java
+++ b/packages/MtpDocumentsProvider/src/com/android/mtp/PipeManager.java
@@ -47,12 +47,12 @@
     }
 
     private static abstract class Task implements Runnable {
-        protected final MtpManager mModel;
+        protected final MtpManager mManager;
         protected final Identifier mIdentifier;
         protected final ParcelFileDescriptor[] mDescriptors;
 
-        Task(MtpManager model, Identifier identifier) throws IOException {
-            mModel = model;
+        Task(MtpManager manager, Identifier identifier) throws IOException {
+            mManager = manager;
             mIdentifier = identifier;
             mDescriptors = ParcelFileDescriptor.createReliablePipe();
         }
@@ -70,7 +70,7 @@
         @Override
         public void run() {
             try {
-                mModel.importFile(
+                mManager.importFile(
                         mIdentifier.mDeviceId, mIdentifier.mObjectHandle, mDescriptors[1]);
                 mDescriptors[1].close();
             } catch (IOException error) {
@@ -94,7 +94,7 @@
                 try (final ParcelFileDescriptor.AutoCloseOutputStream stream =
                         new ParcelFileDescriptor.AutoCloseOutputStream(mDescriptors[1])) {
                     try {
-                        stream.write(mModel.getThumbnail(
+                        stream.write(mManager.getThumbnail(
                                 mIdentifier.mDeviceId, mIdentifier.mObjectHandle));
                     } catch (IOException error) {
                         mDescriptors[1].closeWithError("Failed to stream a thumbnail.");
diff --git a/packages/MtpDocumentsProvider/tests/src/com/android/mtp/DocumentLoaderTest.java b/packages/MtpDocumentsProvider/tests/src/com/android/mtp/DocumentLoaderTest.java
new file mode 100644
index 0000000..49fcddd
--- /dev/null
+++ b/packages/MtpDocumentsProvider/tests/src/com/android/mtp/DocumentLoaderTest.java
@@ -0,0 +1,127 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.mtp;
+
+import android.content.Context;
+import android.database.Cursor;
+import android.net.Uri;
+import android.provider.DocumentsContract;
+import android.test.AndroidTestCase;
+import android.test.suitebuilder.annotation.SmallTest;
+
+import java.io.IOException;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+
+@SmallTest
+public class DocumentLoaderTest extends AndroidTestCase {
+    private BlockableTestMtpMaanger mManager;
+    private TestContentResolver mResolver;
+    private DocumentLoader mLoader;
+    final private Identifier mParentIdentifier = new Identifier(0, 0, 0);
+
+    @Override
+    public void setUp() {
+        mManager = new BlockableTestMtpMaanger(getContext());
+        mResolver = new TestContentResolver();
+        mLoader = new DocumentLoader(mManager, mResolver);
+    }
+
+    public void testBasic() throws IOException, InterruptedException {
+        final Uri uri = DocumentsContract.buildChildDocumentsUri(
+                MtpDocumentsProvider.AUTHORITY, mParentIdentifier.toDocumentId());
+        setUpDocument(mManager, 40);
+        mManager.blockDocument(0, 15);
+        mManager.blockDocument(0, 35);
+
+        {
+            final Cursor cursor = mLoader.queryChildDocuments(
+                    MtpDocumentsProvider.DEFAULT_DOCUMENT_PROJECTION, mParentIdentifier);
+            assertEquals(DocumentLoader.NUM_INITIAL_ENTRIES, cursor.getCount());
+        }
+
+        Thread.sleep(DocumentLoader.NOTIFY_PERIOD_MS);
+        mManager.unblockDocument(0, 15);
+        mResolver.waitForNotification(uri, 1);
+
+        {
+            final Cursor cursor = mLoader.queryChildDocuments(
+                    MtpDocumentsProvider.DEFAULT_DOCUMENT_PROJECTION, mParentIdentifier);
+            assertEquals(
+                    DocumentLoader.NUM_INITIAL_ENTRIES + DocumentLoader.NUM_LOADING_ENTRIES,
+                    cursor.getCount());
+        }
+
+        mManager.unblockDocument(0, 35);
+        mResolver.waitForNotification(uri, 2);
+
+        {
+            final Cursor cursor = mLoader.queryChildDocuments(
+                    MtpDocumentsProvider.DEFAULT_DOCUMENT_PROJECTION, mParentIdentifier);
+            assertEquals(40, cursor.getCount());
+        }
+
+        assertEquals(2, mResolver.getChangeCount(uri));
+    }
+
+    private void setUpDocument(TestMtpManager manager, int count) {
+        int[] childDocuments = new int[count];
+        for (int i = 0; i < childDocuments.length; i++) {
+            final int objectHandle = i + 1;
+            childDocuments[i] = objectHandle;
+            manager.setDocument(0, objectHandle, new MtpDocument(
+                    objectHandle,
+                    0 /* format */,
+                    "file" + objectHandle,
+                    new Date(),
+                    1024,
+                    0 /* thumbnail size */));
+        }
+        manager.setObjectHandles(0, 0, MtpManager.OBJECT_HANDLE_ROOT_CHILDREN, childDocuments);
+    }
+
+    private static class BlockableTestMtpMaanger extends TestMtpManager {
+        final private Map<String, CountDownLatch> blockedDocuments = new HashMap<>();
+
+        BlockableTestMtpMaanger(Context context) {
+            super(context);
+        }
+
+        void blockDocument(int deviceId, int objectHandle) {
+            blockedDocuments.put(pack(deviceId, objectHandle), new CountDownLatch(1));
+        }
+
+        void unblockDocument(int deviceId, int objectHandle) {
+            blockedDocuments.get(pack(deviceId, objectHandle)).countDown();
+        }
+
+        @Override
+        MtpDocument getDocument(int deviceId, int objectHandle) throws IOException {
+            final CountDownLatch latch = blockedDocuments.get(pack(deviceId, objectHandle));
+            if (latch != null) {
+                try {
+                    latch.await();
+                } catch(InterruptedException e) {
+                    fail();
+                }
+            }
+            return super.getDocument(deviceId, objectHandle);
+        }
+    }
+}
diff --git a/packages/MtpDocumentsProvider/tests/src/com/android/mtp/MtpDocumentsProviderTest.java b/packages/MtpDocumentsProvider/tests/src/com/android/mtp/MtpDocumentsProviderTest.java
index 1031d8a..e0e3ce6 100644
--- a/packages/MtpDocumentsProvider/tests/src/com/android/mtp/MtpDocumentsProviderTest.java
+++ b/packages/MtpDocumentsProvider/tests/src/com/android/mtp/MtpDocumentsProviderTest.java
@@ -16,30 +16,26 @@
 
 package com.android.mtp;
 
-import android.database.ContentObserver;
 import android.database.Cursor;
 import android.net.Uri;
 import android.provider.DocumentsContract;
 import android.provider.DocumentsContract.Root;
 import android.test.AndroidTestCase;
-import android.test.mock.MockContentResolver;
 import android.test.suitebuilder.annotation.SmallTest;
 
 import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.util.Date;
-import java.util.HashMap;
-import java.util.Map;
 
 @SmallTest
 public class MtpDocumentsProviderTest extends AndroidTestCase {
-    private ContentResolver mResolver;
+    private TestContentResolver mResolver;
     private MtpDocumentsProvider mProvider;
     private TestMtpManager mMtpManager;
 
     @Override
     public void setUp() {
-        mResolver = new ContentResolver();
+        mResolver = new TestContentResolver();
         mMtpManager = new TestMtpManager(getContext());
         mProvider = new MtpDocumentsProvider();
         mProvider.onCreateForTesting(mMtpManager, mResolver);
@@ -291,21 +287,4 @@
                 DocumentsContract.buildChildDocumentsUri(
                         MtpDocumentsProvider.AUTHORITY, "0_0_2")));
     }
-
-    private static class ContentResolver extends MockContentResolver {
-        final Map<Uri, Integer> mChangeCounts = new HashMap<Uri, Integer>();
-
-        @Override
-        public void notifyChange(Uri uri, ContentObserver observer, boolean syncToNetwork) {
-            mChangeCounts.put(uri, getChangeCount(uri) + 1);
-        }
-
-        int getChangeCount(Uri uri) {
-            if (mChangeCounts.containsKey(uri)) {
-                return mChangeCounts.get(uri);
-            } else {
-                return 0;
-            }
-        }
-    }
 }
diff --git a/packages/MtpDocumentsProvider/tests/src/com/android/mtp/TestContentResolver.java b/packages/MtpDocumentsProvider/tests/src/com/android/mtp/TestContentResolver.java
new file mode 100644
index 0000000..33e559f
--- /dev/null
+++ b/packages/MtpDocumentsProvider/tests/src/com/android/mtp/TestContentResolver.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.mtp;
+
+import android.database.ContentObserver;
+import android.net.Uri;
+import android.test.mock.MockContentResolver;
+
+import junit.framework.Assert;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.Phaser;
+
+class TestContentResolver extends MockContentResolver {
+    final private Map<Uri, Phaser> mPhasers = new HashMap<>();
+
+    @Override
+    public void notifyChange(Uri uri, ContentObserver observer, boolean syncToNetwork) {
+        getPhaser(uri).arrive();
+    }
+
+    void waitForNotification(Uri uri, int count) {
+        Assert.assertEquals(count, getPhaser(uri).awaitAdvance(count - 1));
+    }
+
+    int getChangeCount(Uri uri) {
+        if (mPhasers.containsKey(uri)) {
+            return mPhasers.get(uri).getPhase();
+        } else {
+            return 0;
+        }
+    }
+
+    private synchronized Phaser getPhaser(Uri uri) {
+        Phaser phaser = mPhasers.get(uri);
+        if (phaser == null) {
+            phaser = new Phaser(1);
+            mPhasers.put(uri, phaser);
+        }
+        return phaser;
+    }
+}
diff --git a/packages/MtpDocumentsProvider/tests/src/com/android/mtp/TestMtpManager.java b/packages/MtpDocumentsProvider/tests/src/com/android/mtp/TestMtpManager.java
index 7f81686..40de7b4 100644
--- a/packages/MtpDocumentsProvider/tests/src/com/android/mtp/TestMtpManager.java
+++ b/packages/MtpDocumentsProvider/tests/src/com/android/mtp/TestMtpManager.java
@@ -28,7 +28,7 @@
 import java.util.TreeSet;
 
 public class TestMtpManager extends MtpManager {
-    private static String pack(int... args) {
+    protected static String pack(int... args) {
         return Arrays.toString(args);
     }
 
diff --git a/packages/SystemUI/res/drawable-hdpi/ic_sysbar_back_ime_land.png b/packages/SystemUI/res/drawable-hdpi/ic_sysbar_back_ime_land.png
new file mode 100644
index 0000000..165ef4f
--- /dev/null
+++ b/packages/SystemUI/res/drawable-hdpi/ic_sysbar_back_ime_land.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-hdpi/ic_sysbar_back_land.png b/packages/SystemUI/res/drawable-hdpi/ic_sysbar_back_land.png
index d6e2065..f95f09f 100644
--- a/packages/SystemUI/res/drawable-hdpi/ic_sysbar_back_land.png
+++ b/packages/SystemUI/res/drawable-hdpi/ic_sysbar_back_land.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-hdpi/ic_sysbar_home_land.png b/packages/SystemUI/res/drawable-hdpi/ic_sysbar_home_land.png
index 6be4161..860a906 100644
--- a/packages/SystemUI/res/drawable-hdpi/ic_sysbar_home_land.png
+++ b/packages/SystemUI/res/drawable-hdpi/ic_sysbar_home_land.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-hdpi/ic_sysbar_recent_land.png b/packages/SystemUI/res/drawable-hdpi/ic_sysbar_recent_land.png
index b031273..bab268e 100644
--- a/packages/SystemUI/res/drawable-hdpi/ic_sysbar_recent_land.png
+++ b/packages/SystemUI/res/drawable-hdpi/ic_sysbar_recent_land.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/ic_sysbar_back_ime_land.png b/packages/SystemUI/res/drawable-mdpi/ic_sysbar_back_ime_land.png
new file mode 100644
index 0000000..0feb405
--- /dev/null
+++ b/packages/SystemUI/res/drawable-mdpi/ic_sysbar_back_ime_land.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/ic_sysbar_back_land.png b/packages/SystemUI/res/drawable-mdpi/ic_sysbar_back_land.png
index 12ceb90..cabab0d 100644
--- a/packages/SystemUI/res/drawable-mdpi/ic_sysbar_back_land.png
+++ b/packages/SystemUI/res/drawable-mdpi/ic_sysbar_back_land.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/ic_sysbar_home_land.png b/packages/SystemUI/res/drawable-mdpi/ic_sysbar_home_land.png
index dc8809e..16e1bf5 100644
--- a/packages/SystemUI/res/drawable-mdpi/ic_sysbar_home_land.png
+++ b/packages/SystemUI/res/drawable-mdpi/ic_sysbar_home_land.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/ic_sysbar_recent_land.png b/packages/SystemUI/res/drawable-mdpi/ic_sysbar_recent_land.png
index 5178ac5..40375de 100644
--- a/packages/SystemUI/res/drawable-mdpi/ic_sysbar_recent_land.png
+++ b/packages/SystemUI/res/drawable-mdpi/ic_sysbar_recent_land.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-xhdpi/ic_sysbar_back_ime_land.png b/packages/SystemUI/res/drawable-xhdpi/ic_sysbar_back_ime_land.png
new file mode 100644
index 0000000..b7b8f98
--- /dev/null
+++ b/packages/SystemUI/res/drawable-xhdpi/ic_sysbar_back_ime_land.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-xhdpi/ic_sysbar_back_land.png b/packages/SystemUI/res/drawable-xhdpi/ic_sysbar_back_land.png
index 98be526..69b7449 100644
--- a/packages/SystemUI/res/drawable-xhdpi/ic_sysbar_back_land.png
+++ b/packages/SystemUI/res/drawable-xhdpi/ic_sysbar_back_land.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-xhdpi/ic_sysbar_home_land.png b/packages/SystemUI/res/drawable-xhdpi/ic_sysbar_home_land.png
index eed3f54..57d243c 100644
--- a/packages/SystemUI/res/drawable-xhdpi/ic_sysbar_home_land.png
+++ b/packages/SystemUI/res/drawable-xhdpi/ic_sysbar_home_land.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-xhdpi/ic_sysbar_recent_land.png b/packages/SystemUI/res/drawable-xhdpi/ic_sysbar_recent_land.png
index 22ae09d..e53eaff 100644
--- a/packages/SystemUI/res/drawable-xhdpi/ic_sysbar_recent_land.png
+++ b/packages/SystemUI/res/drawable-xhdpi/ic_sysbar_recent_land.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-xxhdpi/ic_sysbar_back_ime_land.png b/packages/SystemUI/res/drawable-xxhdpi/ic_sysbar_back_ime_land.png
new file mode 100644
index 0000000..695e7a4
--- /dev/null
+++ b/packages/SystemUI/res/drawable-xxhdpi/ic_sysbar_back_ime_land.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-xxhdpi/ic_sysbar_back_land.png b/packages/SystemUI/res/drawable-xxhdpi/ic_sysbar_back_land.png
index c819545..88294c0 100644
--- a/packages/SystemUI/res/drawable-xxhdpi/ic_sysbar_back_land.png
+++ b/packages/SystemUI/res/drawable-xxhdpi/ic_sysbar_back_land.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-xxhdpi/ic_sysbar_home_land.png b/packages/SystemUI/res/drawable-xxhdpi/ic_sysbar_home_land.png
index 6075caf..09d684a 100644
--- a/packages/SystemUI/res/drawable-xxhdpi/ic_sysbar_home_land.png
+++ b/packages/SystemUI/res/drawable-xxhdpi/ic_sysbar_home_land.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-xxhdpi/ic_sysbar_recent_land.png b/packages/SystemUI/res/drawable-xxhdpi/ic_sysbar_recent_land.png
index bccda1b..e31ea32 100644
--- a/packages/SystemUI/res/drawable-xxhdpi/ic_sysbar_recent_land.png
+++ b/packages/SystemUI/res/drawable-xxhdpi/ic_sysbar_recent_land.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-xxxhdpi/ic_sysbar_back_ime_land.png b/packages/SystemUI/res/drawable-xxxhdpi/ic_sysbar_back_ime_land.png
new file mode 100644
index 0000000..24f12d7
--- /dev/null
+++ b/packages/SystemUI/res/drawable-xxxhdpi/ic_sysbar_back_ime_land.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-xxxhdpi/ic_sysbar_back_land.png b/packages/SystemUI/res/drawable-xxxhdpi/ic_sysbar_back_land.png
new file mode 100644
index 0000000..51482f5
--- /dev/null
+++ b/packages/SystemUI/res/drawable-xxxhdpi/ic_sysbar_back_land.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-xxxhdpi/ic_sysbar_home_land.png b/packages/SystemUI/res/drawable-xxxhdpi/ic_sysbar_home_land.png
new file mode 100644
index 0000000..46c7b18
--- /dev/null
+++ b/packages/SystemUI/res/drawable-xxxhdpi/ic_sysbar_home_land.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-xxxhdpi/ic_sysbar_recent_land.png b/packages/SystemUI/res/drawable-xxxhdpi/ic_sysbar_recent_land.png
new file mode 100644
index 0000000..396ad7d
--- /dev/null
+++ b/packages/SystemUI/res/drawable-xxxhdpi/ic_sysbar_recent_land.png
Binary files differ
diff --git a/packages/SystemUI/res/values/config.xml b/packages/SystemUI/res/values/config.xml
index ba7974c..daf42fb 100644
--- a/packages/SystemUI/res/values/config.xml
+++ b/packages/SystemUI/res/values/config.xml
@@ -261,12 +261,6 @@
     <!-- Doze: pulse parameter - how long does it take to fade in after a pickup? -->
     <integer name="doze_pulse_duration_in_pickup">300</integer>
 
-    <!-- Doze: pulse parameter - delay to wait for the screen to wake up -->
-    <integer name="doze_pulse_delay_in">200</integer>
-
-    <!-- Doze: pulse parameter - delay to wait for the screen to wake up after a pickup -->
-    <integer name="doze_pulse_delay_in_pickup">200</integer>
-
     <!-- Doze: pulse parameter - once faded in, how long does it stay visible? -->
     <integer name="doze_pulse_duration_visible">3000</integer>
 
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardService.java b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardService.java
index d78800f..d2c60ef 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardService.java
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardService.java
@@ -80,7 +80,8 @@
         @Override // Binder interface
         public void keyguardDone(boolean authenticated, boolean wakeup) {
             checkPermission();
-            mKeyguardViewMediator.keyguardDone(authenticated, wakeup);
+            // TODO: Remove wakeup
+            mKeyguardViewMediator.keyguardDone(authenticated);
         }
 
         @Override // Binder interface
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
index e44d109..9239eac 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
@@ -465,14 +465,15 @@
                     mUpdateMonitor.isUnlockingWithFingerprintAllowed();
             if (mStatusBarKeyguardViewManager.isBouncerShowing()) {
                 if (unlockingWithFingerprintAllowed) {
-                    mStatusBarKeyguardViewManager.notifyKeyguardAuthenticated();
+                    mStatusBarKeyguardViewManager.notifyKeyguardAuthenticated(
+                            false /* strongAuth */);
                 }
             } else {
                 if (wakeAndUnlocking && mShowing && unlockingWithFingerprintAllowed) {
                     mWakeAndUnlocking = true;
                     mStatusBarKeyguardViewManager.setWakeAndUnlocking();
-                    keyguardDone(true, true);
-                } else if (mShowing && mDeviceInteractive) {
+                    keyguardDone(true);
+                } else if (mShowing) {
                     if (wakeAndUnlocking) {
                         mStatusBarKeyguardViewManager.notifyDeviceWakeUpRequested();
                     }
@@ -490,9 +491,12 @@
             KeyguardViewMediator.this.userActivity();
         }
 
-        public void keyguardDone(boolean authenticated) {
+        public void keyguardDone(boolean strongAuth) {
             if (!mKeyguardDonePending) {
-                KeyguardViewMediator.this.keyguardDone(authenticated, true);
+                KeyguardViewMediator.this.keyguardDone(true /* authenticated */);
+            }
+            if (strongAuth) {
+                mUpdateMonitor.reportSuccessfulStrongAuthUnlockAttempt();
             }
         }
 
@@ -506,12 +510,15 @@
         }
 
         @Override
-        public void keyguardDonePending() {
+        public void keyguardDonePending(boolean strongAuth) {
             mKeyguardDonePending = true;
             mHideAnimationRun = true;
             mStatusBarKeyguardViewManager.startPreHideAnimation(null /* finishRunnable */);
             mHandler.sendEmptyMessageDelayed(KEYGUARD_DONE_PENDING_TIMEOUT,
                     KEYGUARD_DONE_PENDING_TIMEOUT_MS);
+            if (strongAuth) {
+                mUpdateMonitor.reportSuccessfulStrongAuthUnlockAttempt();
+            }
         }
 
         @Override
@@ -524,7 +531,7 @@
             if (mKeyguardDonePending) {
                 // Somebody has called keyguardDonePending before, which means that we are
                 // authenticated
-                KeyguardViewMediator.this.keyguardDone(true /* authenticated */, true /* wakeUp */);
+                KeyguardViewMediator.this.keyguardDone(true /* authenticated */);
             }
         }
 
@@ -552,9 +559,12 @@
         public int getBouncerPromptReason() {
             int currentUser = ActivityManager.getCurrentUser();
             if ((mUpdateMonitor.getUserTrustIsManaged(currentUser)
-                    || mUpdateMonitor.isUnlockWithFingerPrintPossible(currentUser))
+                    || mUpdateMonitor.isUnlockWithFingerprintPossible(currentUser))
                     && !mTrustManager.hasUserAuthenticatedSinceBoot(currentUser)) {
                 return KeyguardSecurityView.PROMPT_REASON_RESTART;
+            } else if (mUpdateMonitor.isUnlockWithFingerprintPossible(currentUser)
+                    && mUpdateMonitor.hasFingerprintUnlockTimedOut(currentUser)) {
+                return KeyguardSecurityView.PROMPT_REASON_TIMEOUT;
             }
             return KeyguardSecurityView.PROMPT_REASON_NONE;
         }
@@ -1194,10 +1204,10 @@
         }
     };
 
-    public void keyguardDone(boolean authenticated, boolean wakeup) {
-        if (DEBUG) Log.d(TAG, "keyguardDone(" + authenticated + ")");
+    public void keyguardDone(boolean authenticated) {
+        if (DEBUG) Log.d(TAG, "keyguardDone(" + authenticated +")");
         EventLog.writeEvent(70000, 2);
-        Message msg = mHandler.obtainMessage(KEYGUARD_DONE, authenticated ? 1 : 0, wakeup ? 1 : 0);
+        Message msg = mHandler.obtainMessage(KEYGUARD_DONE, authenticated ? 1 : 0);
         mHandler.sendMessage(msg);
     }
 
@@ -1240,14 +1250,11 @@
                     handleNotifyStartedWakingUp();
                     break;
                 case KEYGUARD_DONE:
-                    handleKeyguardDone(msg.arg1 != 0, msg.arg2 != 0);
+                    handleKeyguardDone(msg.arg1 != 0);
                     break;
                 case KEYGUARD_DONE_DRAWING:
                     handleKeyguardDoneDrawing();
                     break;
-                case KEYGUARD_DONE_AUTHENTICATING:
-                    keyguardDone(true, true);
-                    break;
                 case SET_OCCLUDED:
                     handleSetOccluded(msg.arg1 != 0);
                     break;
@@ -1277,7 +1284,7 @@
      * @see #keyguardDone
      * @see #KEYGUARD_DONE
      */
-    private void handleKeyguardDone(boolean authenticated, boolean wakeup) {
+    private void handleKeyguardDone(boolean authenticated) {
         if (DEBUG) Log.d(TAG, "handleKeyguardDone");
         synchronized (this) {
             resetKeyguardDonePendingLocked();
@@ -1578,6 +1585,7 @@
     private void handleNotifyScreenTurningOn(IKeyguardDrawnCallback callback) {
         synchronized (KeyguardViewMediator.this) {
             if (DEBUG) Log.d(TAG, "handleNotifyScreenTurningOn");
+            mStatusBarKeyguardViewManager.onScreenTurningOn();
             if (callback != null) {
                 if (mWakeAndUnlocking) {
                     mDrawnCallback = callback;
@@ -1599,6 +1607,7 @@
         synchronized (this) {
             if (DEBUG) Log.d(TAG, "handleNotifyScreenTurnedOff");
             mStatusBarKeyguardViewManager.onScreenTurnedOff();
+            mWakeAndUnlocking = false;
         }
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/media/RingtonePlayer.java b/packages/SystemUI/src/com/android/systemui/media/RingtonePlayer.java
index fe876d7..7f68e29 100644
--- a/packages/SystemUI/src/com/android/systemui/media/RingtonePlayer.java
+++ b/packages/SystemUI/src/com/android/systemui/media/RingtonePlayer.java
@@ -159,7 +159,9 @@
             if (Binder.getCallingUid() != Process.SYSTEM_UID) {
                 throw new SecurityException("Async playback only available from system UID.");
             }
-
+            if (UserHandle.ALL.equals(user)) {
+                user = UserHandle.OWNER;
+            }
             mAsyncPlayer.play(getContextForUser(user), uri, looping, aa);
         }
 
diff --git a/packages/SystemUI/src/com/android/systemui/qs/UsageTracker.java b/packages/SystemUI/src/com/android/systemui/qs/UsageTracker.java
index f36019b..e64f6a0 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/UsageTracker.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/UsageTracker.java
@@ -21,7 +21,6 @@
 import android.content.DialogInterface;
 import android.content.Intent;
 import android.content.IntentFilter;
-import android.content.SharedPreferences;
 
 import com.android.systemui.Prefs;
 import com.android.systemui.R;
diff --git a/packages/SystemUI/src/com/android/systemui/recents/RecentsActivity.java b/packages/SystemUI/src/com/android/systemui/recents/RecentsActivity.java
index b47fb304..d0876fa 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/RecentsActivity.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/RecentsActivity.java
@@ -33,7 +33,6 @@
 import android.view.ViewStub;
 import android.widget.Toast;
 
-import com.android.internal.logging.MetricsConstants;
 import com.android.internal.logging.MetricsLogger;
 import com.android.systemui.Prefs;
 import com.android.systemui.R;
diff --git a/packages/SystemUI/src/com/android/systemui/recents/misc/SystemServicesProxy.java b/packages/SystemUI/src/com/android/systemui/recents/misc/SystemServicesProxy.java
index afa32cb..89aeabc 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/misc/SystemServicesProxy.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/misc/SystemServicesProxy.java
@@ -20,10 +20,8 @@
 import android.app.ActivityManagerNative;
 import android.app.ActivityOptions;
 import android.app.AppGlobals;
-import android.app.IActivityContainer;
 import android.app.IActivityManager;
 import android.app.ITaskStackListener;
-import android.app.SearchManager;
 import android.appwidget.AppWidgetHost;
 import android.appwidget.AppWidgetManager;
 import android.appwidget.AppWidgetProviderInfo;
@@ -54,15 +52,12 @@
 import android.os.RemoteException;
 import android.os.SystemProperties;
 import android.os.UserHandle;
-import android.os.UserManager;
 import android.provider.Settings;
 import android.util.Log;
 import android.util.MutableBoolean;
 import android.util.Pair;
 import android.util.SparseArray;
 import android.view.Display;
-import android.view.DisplayInfo;
-import android.view.SurfaceControl;
 import android.view.WindowManager;
 import android.view.accessibility.AccessibilityManager;
 
@@ -71,7 +66,6 @@
 import com.android.systemui.R;
 import com.android.systemui.recents.Constants;
 import com.android.systemui.recents.Recents;
-import com.android.systemui.recents.RecentsAppWidgetHost;
 import com.android.systemui.recents.RecentsConfiguration;
 
 import java.io.IOException;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/BaseStatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/BaseStatusBar.java
index a6cea62..a55256d 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/BaseStatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/BaseStatusBar.java
@@ -171,13 +171,7 @@
     // on-screen navigation buttons
     protected NavigationBarView mNavigationBarView = null;
 
-    protected Boolean mScreenOn;
-
-    // The second field is a bit different from the first one because it only listens to screen on/
-    // screen of events from Keyguard. We need this so we don't have a race condition with the
-    // broadcast. In the future, we should remove the first field altogether and rename the second
-    // field.
-    protected boolean mScreenOnFromKeyguard;
+    protected boolean mDeviceInteractive;
 
     protected boolean mVisible;
 
@@ -1722,7 +1716,7 @@
 
     protected void updateVisibleToUser() {
         boolean oldVisibleToUser = mVisibleToUser;
-        mVisibleToUser = mVisible && mScreenOnFromKeyguard;
+        mVisibleToUser = mVisible && mDeviceInteractive;
 
         if (oldVisibleToUser != mVisibleToUser) {
             handleVisibleToUserChanged(mVisibleToUser);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/KeyguardIndicationController.java b/packages/SystemUI/src/com/android/systemui/statusbar/KeyguardIndicationController.java
index 46b00c7..ac4dee2 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/KeyguardIndicationController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/KeyguardIndicationController.java
@@ -16,18 +16,13 @@
 
 package com.android.systemui.statusbar;
 
-import com.android.internal.app.IBatteryStats;
-import com.android.keyguard.KeyguardUpdateMonitor;
-import com.android.keyguard.KeyguardUpdateMonitorCallback;
-import com.android.systemui.R;
-import com.android.systemui.statusbar.phone.KeyguardIndicationTextView;
-
 import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.content.res.Resources;
 import android.graphics.Color;
+import android.hardware.fingerprint.FingerprintManager;
 import android.os.BatteryManager;
 import android.os.BatteryStats;
 import android.os.Handler;
@@ -40,8 +35,16 @@
 import android.util.Log;
 import android.view.View;
 
+import com.android.internal.app.IBatteryStats;
+import com.android.keyguard.KeyguardUpdateMonitor;
+import com.android.keyguard.KeyguardUpdateMonitorCallback;
+import com.android.systemui.R;
+import com.android.systemui.statusbar.phone.KeyguardIndicationTextView;
+import com.android.systemui.statusbar.phone.LockIcon;
+import com.android.systemui.statusbar.phone.StatusBarKeyguardViewManager;
+
 /**
- * Controls the little text indicator on the keyguard.
+ * Controls the indications and error messages shown on the Keyguard
  */
 public class KeyguardIndicationController {
 
@@ -49,6 +52,8 @@
     private static final boolean DEBUG_CHARGING_CURRENT = false;
 
     private static final int MSG_HIDE_TRANSIENT = 1;
+    private static final int MSG_CLEAR_FP_MSG = 2;
+    private static final long TRANSIENT_FP_ERROR_TIMEOUT = 1300;
 
     private final Context mContext;
     private final KeyguardIndicationTextView mTextView;
@@ -56,6 +61,8 @@
 
     private final int mSlowThreshold;
     private final int mFastThreshold;
+    private final LockIcon mLockIcon;
+    private StatusBarKeyguardViewManager mStatusBarKeyguardViewManager;
 
     private String mRestingIndication;
     private String mTransientIndication;
@@ -66,10 +73,13 @@
     private boolean mPowerCharged;
     private int mChargingSpeed;
     private int mChargingCurrent;
+    private String mMessageToShowOnScreenOn;
 
-    public KeyguardIndicationController(Context context, KeyguardIndicationTextView textView) {
+    public KeyguardIndicationController(Context context, KeyguardIndicationTextView textView,
+                                        LockIcon lockIcon) {
         mContext = context;
         mTextView = textView;
+        mLockIcon = lockIcon;
 
         Resources res = context.getResources();
         mSlowThreshold = res.getInteger(R.integer.config_chargingSlowlyThreshold);
@@ -216,6 +226,64 @@
             mChargingSpeed = status.getChargingSpeed(mSlowThreshold, mFastThreshold);
             updateIndication();
         }
+
+        @Override
+        public void onFingerprintHelp(int msgId, String helpString) {
+            KeyguardUpdateMonitor updateMonitor = KeyguardUpdateMonitor.getInstance(mContext);
+            if (!updateMonitor.isUnlockingWithFingerprintAllowed()) {
+                return;
+            }
+            int errorColor = mContext.getResources().getColor(R.color.system_warning_color, null);
+            if (mStatusBarKeyguardViewManager.isBouncerShowing()) {
+                mStatusBarKeyguardViewManager.showBouncerMessage(helpString, errorColor);
+            } else if (updateMonitor.isDeviceInteractive()) {
+                mLockIcon.setTransientFpError(true);
+                showTransientIndication(helpString, errorColor);
+                mHandler.removeMessages(MSG_CLEAR_FP_MSG);
+                mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_CLEAR_FP_MSG),
+                        TRANSIENT_FP_ERROR_TIMEOUT);
+            }
+        }
+
+        @Override
+        public void onFingerprintError(int msgId, String errString) {
+            KeyguardUpdateMonitor updateMonitor = KeyguardUpdateMonitor.getInstance(mContext);
+            if (!updateMonitor.isUnlockingWithFingerprintAllowed()
+                    || msgId == FingerprintManager.FINGERPRINT_ERROR_CANCELED) {
+                return;
+            }
+            int errorColor = mContext.getResources().getColor(R.color.system_warning_color, null);
+            if (mStatusBarKeyguardViewManager.isBouncerShowing()) {
+                mStatusBarKeyguardViewManager.showBouncerMessage(errString, errorColor);
+            } else if (updateMonitor.isDeviceInteractive()) {
+                    showTransientIndication(errString, errorColor);
+                    // We want to keep this message around in case the screen was off
+                    mHandler.removeMessages(MSG_HIDE_TRANSIENT);
+                    hideTransientIndicationDelayed(5000);
+             } else {
+                    mMessageToShowOnScreenOn = errString;
+            }
+        }
+
+        @Override
+        public void onScreenTurnedOn() {
+            if (mMessageToShowOnScreenOn != null) {
+                int errorColor = mContext.getResources().getColor(R.color.system_warning_color,
+                        null);
+                showTransientIndication(mMessageToShowOnScreenOn, errorColor);
+                // We want to keep this message around in case the screen was off
+                mHandler.removeMessages(MSG_HIDE_TRANSIENT);
+                hideTransientIndicationDelayed(5000);
+                mMessageToShowOnScreenOn = null;
+            }
+        }
+
+        @Override
+        public void onFingerprintRunningStateChanged(boolean running) {
+            if (running) {
+                mMessageToShowOnScreenOn = null;
+            }
+        }
     };
 
     BroadcastReceiver mReceiver = new BroadcastReceiver() {
@@ -233,7 +301,15 @@
             if (msg.what == MSG_HIDE_TRANSIENT && mTransientIndication != null) {
                 mTransientIndication = null;
                 updateIndication();
+            } else if (msg.what == MSG_CLEAR_FP_MSG) {
+                mLockIcon.setTransientFpError(false);
+                hideTransientIndication();
             }
         }
     };
+
+    public void setStatusBarKeyguardViewManager(
+            StatusBarKeyguardViewManager statusBarKeyguardViewManager) {
+        mStatusBarKeyguardViewManager = statusBarKeyguardViewManager;
+    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/DozeParameters.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/DozeParameters.java
index 6b167b4..5a2fa3b 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/DozeParameters.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/DozeParameters.java
@@ -50,8 +50,6 @@
         pw.print("    getPulseDuration(pickup=true): "); pw.println(getPulseDuration(true));
         pw.print("    getPulseInDuration(pickup=false): "); pw.println(getPulseInDuration(false));
         pw.print("    getPulseInDuration(pickup=true): "); pw.println(getPulseInDuration(true));
-        pw.print("    getPulseInDelay(pickup=false): "); pw.println(getPulseInDelay(false));
-        pw.print("    getPulseInDelay(pickup=true): "); pw.println(getPulseInDelay(true));
         pw.print("    getPulseInVisibleDuration(): "); pw.println(getPulseVisibleDuration());
         pw.print("    getPulseOutDuration(): "); pw.println(getPulseOutDuration());
         pw.print("    getPulseOnSigMotion(): "); pw.println(getPulseOnSigMotion());
@@ -80,12 +78,6 @@
                 : getInt("doze.pulse.duration.in", R.integer.doze_pulse_duration_in);
     }
 
-    public int getPulseInDelay(boolean pickup) {
-        return pickup
-                ? getInt("doze.pulse.delay.in.pickup", R.integer.doze_pulse_delay_in_pickup)
-                : getInt("doze.pulse.delay.in", R.integer.doze_pulse_delay_in);
-    }
-
     public int getPulseVisibleDuration() {
         return getInt("doze.pulse.duration.visible", R.integer.doze_pulse_duration_visible);
     }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/DozeScrimController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/DozeScrimController.java
index 3e17328..86b8972 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/DozeScrimController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/DozeScrimController.java
@@ -100,6 +100,16 @@
         mHandler.post(mPulseIn);
     }
 
+    public void onScreenTurnedOn() {
+        if (isPulsing()) {
+            final boolean pickup = mPulseReason == DozeLog.PULSE_REASON_SENSOR_PICKUP;
+            startScrimAnimation(true /* inFront */, 0f,
+                    mDozeParameters.getPulseInDuration(pickup),
+                    pickup ? mPulseInInterpolatorPickup : mPulseInInterpolator,
+                    mPulseInFinished);
+        }
+    }
+
     public boolean isPulsing() {
         return mPulseCallback != null;
     }
@@ -138,12 +148,11 @@
 
     private void startScrimAnimation(final boolean inFront, float target, long duration,
             Interpolator interpolator) {
-        startScrimAnimation(inFront, target, duration, interpolator, 0 /* delay */,
-                null /* endRunnable */);
+        startScrimAnimation(inFront, target, duration, interpolator, null /* endRunnable */);
     }
 
     private void startScrimAnimation(final boolean inFront, float target, long duration,
-            Interpolator interpolator, long delay, final Runnable endRunnable) {
+            Interpolator interpolator, final Runnable endRunnable) {
         Animator current = getCurrentAnimator(inFront);
         if (current != null) {
             float currentTarget = getCurrentTarget(inFront);
@@ -162,7 +171,6 @@
         });
         anim.setInterpolator(interpolator);
         anim.setDuration(duration);
-        anim.setStartDelay(delay);
         anim.addListener(new AnimatorListenerAdapter() {
             @Override
             public void onAnimationEnd(Animator animation) {
@@ -222,12 +230,6 @@
                     + DozeLog.pulseReasonToString(mPulseReason));
             if (!mDozing) return;
             DozeLog.tracePulseStart(mPulseReason);
-            final boolean pickup = mPulseReason == DozeLog.PULSE_REASON_SENSOR_PICKUP;
-            startScrimAnimation(true /* inFront */, 0f,
-                    mDozeParameters.getPulseInDuration(pickup),
-                    pickup ? mPulseInInterpolatorPickup : mPulseInInterpolator,
-                    mDozeParameters.getPulseInDelay(pickup),
-                    mPulseInFinished);
 
             // Signal that the pulse is ready to turn the screen on and draw.
             pulseStarted();
@@ -249,7 +251,7 @@
             if (DEBUG) Log.d(TAG, "Pulse out, mDozing=" + mDozing);
             if (!mDozing) return;
             startScrimAnimation(true /* inFront */, 1f, mDozeParameters.getPulseOutDuration(),
-                    mPulseOutInterpolator, 0 /* delay */, mPulseOutFinished);
+                    mPulseOutInterpolator, mPulseOutFinished);
         }
     };
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java
index 7b67c6c..f1b8873 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java
@@ -29,7 +29,6 @@
 import android.content.pm.PackageManager;
 import android.content.pm.ResolveInfo;
 import android.content.res.Configuration;
-import android.hardware.fingerprint.FingerprintManager;
 import android.os.AsyncTask;
 import android.os.Bundle;
 import android.os.IBinder;
@@ -86,7 +85,6 @@
     private static final Intent PHONE_INTENT = new Intent(Intent.ACTION_DIAL);
     private static final int DOZE_ANIMATION_STAGGER_DELAY = 48;
     private static final int DOZE_ANIMATION_ELEMENT_DURATION = 250;
-    private static final long TRANSIENT_FP_ERROR_TIMEOUT = 1300;
 
     private KeyguardAffordanceView mCameraImageView;
     private KeyguardAffordanceView mLeftAffordanceView;
@@ -528,7 +526,7 @@
         return mCameraPreview;
     }
 
-    public KeyguardAffordanceView getLockIcon() {
+    public LockIcon getLockIcon() {
         return mLockIcon;
     }
 
@@ -613,21 +611,6 @@
         }
     };
 
-    private final Runnable mTransientFpErrorClearRunnable = new Runnable() {
-        @Override
-        public void run() {
-            mLockIcon.setTransientFpError(false);
-            mIndicationController.hideTransientIndication();
-        }
-    };
-
-    private final Runnable mHideTransientIndicationRunnable = new Runnable() {
-        @Override
-        public void run() {
-            mIndicationController.hideTransientIndication();
-        }
-    };
-
     private final KeyguardUpdateMonitorCallback mUpdateMonitorCallback =
             new KeyguardUpdateMonitorCallback() {
         @Override
@@ -661,37 +644,13 @@
         }
 
         @Override
-        public void onFingerprintAuthenticated(int userId, boolean wakeAndUnlocking) {
-        }
-
-        @Override
         public void onFingerprintRunningStateChanged(boolean running) {
             mLockIcon.update();
         }
 
         @Override
-        public void onFingerprintHelp(int msgId, String helpString) {
-            if (!KeyguardUpdateMonitor.getInstance(mContext).isUnlockingWithFingerprintAllowed()) {
-                return;
-            }
-            mLockIcon.setTransientFpError(true);
-            mIndicationController.showTransientIndication(helpString,
-                    getResources().getColor(R.color.system_warning_color, null));
-            removeCallbacks(mTransientFpErrorClearRunnable);
-            postDelayed(mTransientFpErrorClearRunnable, TRANSIENT_FP_ERROR_TIMEOUT);
-        }
-
-        @Override
-        public void onFingerprintError(int msgId, String errString) {
-            if (!KeyguardUpdateMonitor.getInstance(mContext).isUnlockingWithFingerprintAllowed()
-                    || msgId == FingerprintManager.FINGERPRINT_ERROR_CANCELED) {
-                return;
-            }
-            // TODO: Go to bouncer if this is "too many attempts" (lockout) error.
-            mIndicationController.showTransientIndication(errString,
-                    getResources().getColor(R.color.system_warning_color, null));
-            removeCallbacks(mHideTransientIndicationRunnable);
-            postDelayed(mHideTransientIndicationRunnable, 5000);
+        public void onStrongAuthTimeoutExpiredChanged(int userId) {
+            mLockIcon.update();
         }
     };
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBouncer.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBouncer.java
index e9b2c61..8b96e5f 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBouncer.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBouncer.java
@@ -17,7 +17,6 @@
 package com.android.systemui.statusbar.phone;
 
 import android.content.Context;
-import android.view.Choreographer;
 import android.view.KeyEvent;
 import android.view.LayoutInflater;
 import android.view.View;
@@ -27,6 +26,8 @@
 import com.android.internal.widget.LockPatternUtils;
 import com.android.keyguard.KeyguardHostView;
 import com.android.keyguard.KeyguardSecurityView;
+import com.android.keyguard.KeyguardUpdateMonitor;
+import com.android.keyguard.KeyguardUpdateMonitorCallback;
 import com.android.keyguard.R;
 import com.android.keyguard.ViewMediatorCallback;
 import com.android.systemui.DejankUtils;
@@ -48,6 +49,13 @@
     private ViewGroup mRoot;
     private boolean mShowingSoon;
     private int mBouncerPromptReason;
+    private KeyguardUpdateMonitorCallback mUpdateMonitorCallback =
+            new KeyguardUpdateMonitorCallback() {
+                @Override
+                public void onStrongAuthTimeoutExpiredChanged(int userId) {
+                    mBouncerPromptReason = mCallback.getBouncerPromptReason();
+                }
+            };
 
     public KeyguardBouncer(Context context, ViewMediatorCallback callback,
             LockPatternUtils lockPatternUtils, StatusBarWindowManager windowManager,
@@ -57,6 +65,7 @@
         mLockPatternUtils = lockPatternUtils;
         mContainer = container;
         mWindowManager = windowManager;
+        KeyguardUpdateMonitor.getInstance(mContext).registerCallback(mUpdateMonitorCallback);
     }
 
     public void show(boolean resetSecuritySelection) {
@@ -103,6 +112,10 @@
         mKeyguardView.showPromptReason(reason);
     }
 
+    public void showMessage(String message, int color) {
+        mKeyguardView.showMessage(message, color);
+    }
+
     private void cancelShowRunnable() {
         DejankUtils.removeCallbacks(mShowRunnable);
         mShowingSoon = false;
@@ -244,8 +257,8 @@
         return mKeyguardView.interceptMediaKey(event);
     }
 
-    public void notifyKeyguardAuthenticated() {
+    public void notifyKeyguardAuthenticated(boolean strongAuth) {
         ensureView();
-        mKeyguardView.finish();
+        mKeyguardView.finish(strongAuth);
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarRecents.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarRecents.java
index 1787de5..b024ec4 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarRecents.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarRecents.java
@@ -89,8 +89,7 @@
                 MAX_RECENTS,
                 ActivityManager.RECENT_IGNORE_HOME_STACK_TASKS |
                 ActivityManager.RECENT_IGNORE_UNAVAILABLE |
-                ActivityManager.RECENT_INCLUDE_PROFILES |
-                ActivityManager.RECENT_WITH_EXCLUDED,
+                ActivityManager.RECENT_INCLUDE_PROFILES,
                 UserHandle.USER_CURRENT);
         if (DEBUG) Slog.d(TAG, "Got recents " + recentTasks.size());
         removeMissingRecents(recentTasks);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java
index 367ff1a..1649acb 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java
@@ -262,7 +262,7 @@
         mBackIcon = res.getDrawable(R.drawable.ic_sysbar_back);
         mBackLandIcon = res.getDrawable(R.drawable.ic_sysbar_back_land);
         mBackAltIcon = res.getDrawable(R.drawable.ic_sysbar_back_ime);
-        mBackAltLandIcon = res.getDrawable(R.drawable.ic_sysbar_back_ime);
+        mBackAltLandIcon = res.getDrawable(R.drawable.ic_sysbar_back_ime_land);
         mRecentIcon = res.getDrawable(R.drawable.ic_sysbar_recent);
         mRecentLandIcon = res.getDrawable(R.drawable.ic_sysbar_recent_land);
     }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java
index c4c8e3d..710c335 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java
@@ -918,7 +918,7 @@
     }
 
     private int getFalsingThreshold() {
-        float factor = mStatusBar.isScreenOnComingFromTouch() ? 1.5f : 1.0f;
+        float factor = mStatusBar.isWakeUpComingFromTouch() ? 1.5f : 1.0f;
         return (int) (mQsFalsingThreshold * factor);
     }
 
@@ -2075,7 +2075,7 @@
 
     @Override
     public float getAffordanceFalsingFactor() {
-        return mStatusBar.isScreenOnComingFromTouch() ? 1.5f : 1.0f;
+        return mStatusBar.isWakeUpComingFromTouch() ? 1.5f : 1.0f;
     }
 
     @Override
@@ -2226,7 +2226,7 @@
         }
     };
 
-    public void onScreenTurnedOn() {
+    public void onScreenTurningOn() {
         mKeyguardStatusView.refreshTime();
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelView.java
index 5995fe1..9cd6ea3 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelView.java
@@ -391,7 +391,7 @@
                     || forceCancel;
             DozeLog.traceFling(expand, mTouchAboveFalsingThreshold,
                     mStatusBar.isFalsingThresholdNeeded(),
-                    mStatusBar.isScreenOnComingFromTouch());
+                    mStatusBar.isWakeUpComingFromTouch());
                     // Log collapse gesture if on lock screen.
                     if (!expand && mStatusBar.getBarState() == StatusBarState.KEYGUARD) {
                         float displayDensity = mStatusBar.getDisplayDensity();
@@ -420,7 +420,7 @@
     }
 
     private int getFalsingThreshold() {
-        float factor = mStatusBar.isScreenOnComingFromTouch() ? 1.5f : 1.0f;
+        float factor = mStatusBar.isWakeUpComingFromTouch() ? 1.5f : 1.0f;
         return (int) (mUnlockFalsingThreshold * factor);
     }
 
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 400f167..0635847 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
@@ -282,8 +282,8 @@
     private StatusBarWindowManager mStatusBarWindowManager;
     private UnlockMethodCache mUnlockMethodCache;
     private DozeServiceHost mDozeServiceHost;
-    private boolean mScreenOnComingFromTouch;
-    private PointF mScreenOnTouchLocation;
+    private boolean mWakeUpComingFromTouch;
+    private PointF mWakeUpTouchLocation;
 
     int mPixelFormat;
     Object mQueueLock = new Object();
@@ -785,7 +785,8 @@
         mKeyguardBottomArea.setAssistManager(mAssistManager);
         mKeyguardIndicationController = new KeyguardIndicationController(mContext,
                 (KeyguardIndicationTextView) mStatusBarWindow.findViewById(
-                        R.id.keyguard_indication_text));
+                        R.id.keyguard_indication_text),
+                mKeyguardBottomArea.getLockIcon());
         mKeyguardBottomArea.setKeyguardIndicationController(mKeyguardIndicationController);
 
         // set the inital view visibility
@@ -1031,6 +1032,8 @@
         KeyguardViewMediator keyguardViewMediator = getComponent(KeyguardViewMediator.class);
         mStatusBarKeyguardViewManager = keyguardViewMediator.registerStatusBar(this,
                 mStatusBarWindow, mStatusBarWindowManager, mScrimController);
+        mKeyguardIndicationController.setStatusBarKeyguardViewManager(
+                mStatusBarKeyguardViewManager);
         mKeyguardViewMediatorCallback = keyguardViewMediator.getViewMediatorCallback();
     }
 
@@ -1930,8 +1933,8 @@
         return mNotificationPanel.isQsExpanded();
     }
 
-    public boolean isScreenOnComingFromTouch() {
-        return mScreenOnComingFromTouch;
+    public boolean isWakeUpComingFromTouch() {
+        return mWakeUpComingFromTouch;
     }
 
     public boolean isFalsingThresholdNeeded() {
@@ -2491,7 +2494,7 @@
     private void checkBarMode(int mode, int windowState, BarTransitions transitions,
             boolean noAnimation) {
         final boolean powerSave = mBatteryController.isPowerSave();
-        final boolean anim = !noAnimation && (mScreenOn == null || mScreenOn)
+        final boolean anim = !noAnimation && mDeviceInteractive
                 && windowState != WINDOW_STATE_HIDDEN && !powerSave;
         if (powerSave && getBarState() == StatusBarState.SHADE) {
             mode = MODE_WARNING;
@@ -2899,14 +2902,12 @@
                 }
             }
             else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
-                mScreenOn = false;
                 notifyNavigationBarScreenOn(false);
                 notifyHeadsUpScreenOff();
                 finishBarAnimations();
                 resetUserExpandedStates();
             }
             else if (Intent.ACTION_SCREEN_ON.equals(action)) {
-                mScreenOn = true;
                 notifyNavigationBarScreenOn(true);
             }
         }
@@ -3360,7 +3361,7 @@
         mHandler.removeMessages(MSG_LAUNCH_TRANSITION_TIMEOUT);
         setBarState(StatusBarState.KEYGUARD);
         updateKeyguardState(false /* goingToFullShade */, false /* fromShadeLocked */);
-        if (!mScreenOnFromKeyguard) {
+        if (!mDeviceInteractive) {
 
             // If the screen is off already, we need to disable touch events because these might
             // collapse the panel after we expanded it, and thus we would end up with a blank
@@ -3580,7 +3581,7 @@
     private void updateDozingState() {
         boolean animate = !mDozing && mDozeScrimController.isPulsing();
         mNotificationPanel.setDozing(mDozing, animate);
-        mStackScroller.setDark(mDozing, animate, mScreenOnTouchLocation);
+        mStackScroller.setDark(mDozing, animate, mWakeUpTouchLocation);
         mScrimController.setDozing(mDozing);
         mDozeScrimController.setDozing(mDozing, animate);
     }
@@ -3633,7 +3634,7 @@
     }
 
     public boolean onSpacePressed() {
-        if (mScreenOn != null && mScreenOn
+        if (mDeviceInteractive
                 && (mState == StatusBarState.KEYGUARD || mState == StatusBarState.SHADE_LOCKED)) {
             animateCollapsePanels(
                     CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL /* flags */, true /* force */);
@@ -3843,22 +3844,29 @@
         disable(mDisabledUnmodified1, mDisabledUnmodified2, true /* animate */);
     }
 
-    public void onScreenTurnedOff() {
-        mScreenOnFromKeyguard = false;
-        mScreenOnComingFromTouch = false;
-        mScreenOnTouchLocation = null;
+    public void onFinishedGoingToSleep() {
+        mDeviceInteractive = false;
+        mWakeUpComingFromTouch = false;
+        mWakeUpTouchLocation = null;
         mStackScroller.setAnimationsEnabled(false);
         updateVisibleToUser();
     }
 
-    public void onScreenTurnedOn() {
-        mScreenOnFromKeyguard = true;
+    public void onStartedWakingUp() {
+        mDeviceInteractive = true;
         mStackScroller.setAnimationsEnabled(true);
-        mNotificationPanel.onScreenTurnedOn();
         mNotificationPanel.setTouchDisabled(false);
         updateVisibleToUser();
     }
 
+    public void onScreenTurningOn() {
+        mNotificationPanel.onScreenTurningOn();
+    }
+
+    public void onScreenTurnedOn() {
+        mDozeScrimController.onScreenTurnedOn();
+    }
+
     /**
      * This handles long-press of both back and recents.  They are
      * handled together to capture them both being long-pressed
@@ -3973,8 +3981,8 @@
         if (mDozing && mDozeScrimController.isPulsing()) {
             PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
             pm.wakeUp(time, "com.android.systemui:NODOZE");
-            mScreenOnComingFromTouch = true;
-            mScreenOnTouchLocation = new PointF(event.getX(), event.getY());
+            mWakeUpComingFromTouch = true;
+            mWakeUpTouchLocation = new PointF(event.getX(), event.getY());
             mNotificationPanel.setTouchDisabled(false);
             mStatusBarKeyguardViewManager.notifyDeviceWakeUpRequested();
         }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java
index 44aa780..9d47713 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java
@@ -162,14 +162,18 @@
 
     public void onFinishedGoingToSleep() {
         mDeviceInteractive = false;
-        mPhoneStatusBar.onScreenTurnedOff();
+        mPhoneStatusBar.onFinishedGoingToSleep();
         mBouncer.onScreenTurnedOff();
     }
 
     public void onStartedWakingUp() {
         mDeviceInteractive = true;
         mDeviceWillWakeUp = false;
-        mPhoneStatusBar.onScreenTurnedOn();
+        mPhoneStatusBar.onStartedWakingUp();
+    }
+
+    public void onScreenTurningOn() {
+        mPhoneStatusBar.onScreenTurningOn();
     }
 
     public void onScreenTurnedOn() {
@@ -180,6 +184,7 @@
             animateScrimControllerKeyguardFadingOut(0, 200);
             updateStates();
         }
+        mPhoneStatusBar.onScreenTurnedOn();
     }
 
     public void onScreenTurnedOff() {
@@ -480,8 +485,8 @@
      * Notifies that the user has authenticated by other means than using the bouncer, for example,
      * fingerprint.
      */
-    public void notifyKeyguardAuthenticated() {
-        mBouncer.notifyKeyguardAuthenticated();
+    public void notifyKeyguardAuthenticated(boolean strongAuth) {
+        mBouncer.notifyKeyguardAuthenticated(strongAuth);
     }
 
     public void setWakeAndUnlocking() {
@@ -491,4 +496,8 @@
             mPhoneStatusBar.getNavigationBarView().setWakeAndUnlocking(true);
         }
     }
+
+    public void showBouncerMessage(String message, int color) {
+        mBouncer.showMessage(message, color);
+    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/UnlockMethodCache.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/UnlockMethodCache.java
index bd537f7..d646d0d 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/UnlockMethodCache.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/UnlockMethodCache.java
@@ -143,6 +143,11 @@
         public void onFaceUnlockStateChanged(boolean running, int userId) {
             update(false /* updateAlways */);
         }
+
+        @Override
+        public void onStrongAuthTimeoutExpiredChanged(int userId) {
+            update(false /* updateAlways */);
+        }
     };
 
     public boolean isTrustManaged() {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/BluetoothControllerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/BluetoothControllerImpl.java
index daa84ad..a04edf7 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/BluetoothControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/BluetoothControllerImpl.java
@@ -164,11 +164,18 @@
             // Our current device is still valid.
             return;
         }
+        mLastDevice = null;
         for (CachedBluetoothDevice device : getDevices()) {
             if (device.isConnected()) {
                 mLastDevice = device;
             }
         }
+        if (mLastDevice == null && mConnectionState == BluetoothAdapter.STATE_CONNECTED) {
+            // If somehow we think we are connected, but have no connected devices, we aren't
+            // connected.
+            mConnectionState = BluetoothAdapter.STATE_DISCONNECTED;
+            mHandler.sendEmptyMessage(H.MSG_STATE_CHANGED);
+        }
     }
 
     @Override
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/stack/NotificationStackScrollLayout.java b/packages/SystemUI/src/com/android/systemui/statusbar/stack/NotificationStackScrollLayout.java
index 6b30183..82c1aa8 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/stack/NotificationStackScrollLayout.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/stack/NotificationStackScrollLayout.java
@@ -653,7 +653,7 @@
 
     @Override
     public float getFalsingThresholdFactor() {
-        return mPhoneStatusBar.isScreenOnComingFromTouch() ? 1.5f : 1.0f;
+        return mPhoneStatusBar.isWakeUpComingFromTouch() ? 1.5f : 1.0f;
     }
 
     public View getChildAtPosition(MotionEvent ev) {
diff --git a/packages/SystemUI/src/com/android/systemui/tuner/TunerService.java b/packages/SystemUI/src/com/android/systemui/tuner/TunerService.java
index d3f33ab..50234b2 100644
--- a/packages/SystemUI/src/com/android/systemui/tuner/TunerService.java
+++ b/packages/SystemUI/src/com/android/systemui/tuner/TunerService.java
@@ -16,7 +16,6 @@
 package com.android.systemui.tuner;
 
 import android.app.ActivityManager;
-import android.app.AlertDialog;
 import android.content.BroadcastReceiver;
 import android.content.ComponentName;
 import android.content.ContentResolver;
@@ -25,10 +24,12 @@
 import android.content.DialogInterface.OnClickListener;
 import android.content.Intent;
 import android.content.pm.PackageManager;
+import android.content.pm.PackageManager.NameNotFoundException;
 import android.database.ContentObserver;
 import android.net.Uri;
 import android.os.Handler;
 import android.os.Looper;
+import android.os.UserHandle;
 import android.provider.Settings;
 import android.util.ArrayMap;
 
@@ -169,6 +170,7 @@
 
     public static final void showResetRequest(final Context context, final Runnable onDisabled) {
         SystemUIDialog dialog = new SystemUIDialog(context);
+        dialog.setShowForAllUsers(true);
         dialog.setMessage(R.string.remove_from_settings_prompt);
         dialog.setButton(DialogInterface.BUTTON_NEGATIVE, context.getString(R.string.cancel),
                 (OnClickListener) null);
@@ -192,7 +194,7 @@
     }
 
     public static final void setTunerEnabled(Context context, boolean enabled) {
-        context.getPackageManager().setComponentEnabledSetting(
+        userContext(context).getPackageManager().setComponentEnabledSetting(
                 new ComponentName(context, TunerActivity.class),
                 enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
                         : PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
@@ -200,11 +202,20 @@
     }
 
     public static final boolean isTunerEnabled(Context context) {
-        return context.getPackageManager().getComponentEnabledSetting(
+        return userContext(context).getPackageManager().getComponentEnabledSetting(
                 new ComponentName(context, TunerActivity.class))
                 == PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
     }
 
+    private static Context userContext(Context context) {
+        try {
+            return context.createPackageContextAsUser(context.getPackageName(), 0,
+                    new UserHandle(ActivityManager.getCurrentUser()));
+        } catch (NameNotFoundException e) {
+            return context;
+        }
+    }
+
     private class Observer extends ContentObserver {
         public Observer() {
             super(new Handler(Looper.getMainLooper()));
diff --git a/services/appwidget/java/com/android/server/appwidget/AppWidgetServiceImpl.java b/services/appwidget/java/com/android/server/appwidget/AppWidgetServiceImpl.java
index 30680ed..fa87270 100644
--- a/services/appwidget/java/com/android/server/appwidget/AppWidgetServiceImpl.java
+++ b/services/appwidget/java/com/android/server/appwidget/AppWidgetServiceImpl.java
@@ -2905,9 +2905,9 @@
                             }
                             // Now that we've told the host, push out an update.
                             sendUpdateIntentLocked(provider, appWidgetIds);
-                            providersUpdated = true;
                         }
                     }
+                    providersUpdated = true;
                 }
             }
         }
diff --git a/services/core/java/com/android/server/InputMethodManagerService.java b/services/core/java/com/android/server/InputMethodManagerService.java
index 4e11070..f9f617e 100644
--- a/services/core/java/com/android/server/InputMethodManagerService.java
+++ b/services/core/java/com/android/server/InputMethodManagerService.java
@@ -32,7 +32,6 @@
 import com.android.internal.view.IInputMethodManager;
 import com.android.internal.view.IInputMethodSession;
 import com.android.internal.view.InputBindResult;
-import com.android.server.pm.UserManagerService;
 import com.android.server.statusbar.StatusBarManagerService;
 import com.android.server.wm.WindowManagerService;
 
@@ -134,7 +133,6 @@
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.HashMap;
-import java.util.HashSet;
 import java.util.List;
 import java.util.Locale;
 
@@ -197,10 +195,10 @@
 
     // All known input methods.  mMethodMap also serves as the global
     // lock for this class.
-    final ArrayList<InputMethodInfo> mMethodList = new ArrayList<InputMethodInfo>();
-    final HashMap<String, InputMethodInfo> mMethodMap = new HashMap<String, InputMethodInfo>();
+    final ArrayList<InputMethodInfo> mMethodList = new ArrayList<>();
+    final HashMap<String, InputMethodInfo> mMethodMap = new HashMap<>();
     private final LruCache<SuggestionSpan, InputMethodInfo> mSecureSuggestionSpans =
-            new LruCache<SuggestionSpan, InputMethodInfo>(SECURE_SUGGESTION_SPANS_MAX_SIZE);
+            new LruCache<>(SECURE_SUGGESTION_SPANS_MAX_SIZE);
     private final InputMethodSubtypeSwitchingController mSwitchingController;
 
     // Used to bring IME service up to visible adjustment while it is being shown.
@@ -277,8 +275,7 @@
         }
     }
 
-    final HashMap<IBinder, ClientState> mClients
-            = new HashMap<IBinder, ClientState>();
+    final HashMap<IBinder, ClientState> mClients = new HashMap<>();
 
     /**
      * Set once the system is ready to run third party code.
@@ -329,8 +326,7 @@
 
     // This list contains the pairs of InputMethodInfo and InputMethodSubtype.
     private final HashMap<InputMethodInfo, ArrayList<InputMethodSubtype>>
-            mShortcutInputMethodsAndSubtypes =
-                new HashMap<InputMethodInfo, ArrayList<InputMethodSubtype>>();
+            mShortcutInputMethodsAndSubtypes = new HashMap<>();
 
     // Was the keyguard locked when this client became current?
     private boolean mCurClientInKeyguard;
@@ -540,7 +536,7 @@
             final String imeId = entry.getKey();
             ArraySet<String> prevSubtypes = prevMap.get(imeId);
             if (prevSubtypes == null) {
-                prevSubtypes = new ArraySet<String>(2);
+                prevSubtypes = new ArraySet<>(2);
                 prevMap.put(imeId, prevSubtypes);
             }
             prevSubtypes.addAll(entry.getValue());
@@ -559,16 +555,15 @@
     static String buildInputMethodsAndSubtypesString(ArrayMap<String, ArraySet<String>> map) {
         // we want to use the canonical InputMethodSettings implementation,
         // so we convert data structures first.
-        List<Pair<String, ArrayList<String>>> imeMap =
-                new ArrayList<Pair<String, ArrayList<String>>>(4);
+        List<Pair<String, ArrayList<String>>> imeMap = new ArrayList<>(4);
         for (ArrayMap.Entry<String, ArraySet<String>> entry : map.entrySet()) {
             final String imeName = entry.getKey();
             final ArraySet<String> subtypeSet = entry.getValue();
-            final ArrayList<String> subtypes = new ArrayList<String>(2);
+            final ArrayList<String> subtypes = new ArrayList<>(2);
             if (subtypeSet != null) {
                 subtypes.addAll(subtypeSet);
             }
-            imeMap.add(new Pair<String, ArrayList<String>>(imeName, subtypes));
+            imeMap.add(new Pair<>(imeName, subtypes));
         }
         return InputMethodSettings.buildInputMethodsSettingString(imeMap);
     }
@@ -576,8 +571,7 @@
     // TODO: Move this method to InputMethodUtils with adding unit tests.
     static ArrayMap<String, ArraySet<String>> parseInputMethodsAndSubtypesString(
             final String inputMethodsAndSubtypesString) {
-        final ArrayMap<String, ArraySet<String>> imeMap =
-                new ArrayMap<String, ArraySet<String>>();
+        final ArrayMap<String, ArraySet<String>> imeMap = new ArrayMap<>();
         if (TextUtils.isEmpty(inputMethodsAndSubtypesString)) {
             return imeMap;
         }
@@ -591,7 +585,7 @@
                         typeSplitter,
                         subtypeSplitter);
         for (Pair<String, ArrayList<String>> ime : allImeSettings) {
-            ArraySet<String> subtypes = new ArraySet<String>();
+            ArraySet<String> subtypes = new ArraySet<>();
             if (ime.second != null) {
                 subtypes.addAll(ime.second);
             }
@@ -1166,7 +1160,7 @@
             return Collections.emptyList();
         }
         synchronized (mMethodMap) {
-            return new ArrayList<InputMethodInfo>(mMethodList);
+            return new ArrayList<>(mMethodList);
         }
     }
 
@@ -1190,7 +1184,7 @@
             boolean allowsImplicitlySelectedSubtypes) {
         // TODO: Make this work even for non-current users?
         if (!calledFromValidUser()) {
-            return Collections.<InputMethodSubtype>emptyList();
+            return Collections.emptyList();
         }
         synchronized (mMethodMap) {
             final InputMethodInfo imi;
@@ -1200,7 +1194,7 @@
                 imi = mMethodMap.get(imiId);
             }
             if (imi == null) {
-                return Collections.<InputMethodSubtype>emptyList();
+                return Collections.emptyList();
             }
             return mSettings.getEnabledInputMethodSubtypeListLocked(
                     mContext, imi, allowsImplicitlySelectedSubtypes);
@@ -2898,8 +2892,6 @@
 
         // Use for queryIntentServicesAsUser
         final PackageManager pm = mContext.getPackageManager();
-        String disabledSysImes = mSettings.getDisabledSystemInputMethods();
-        if (disabledSysImes == null) disabledSysImes = "";
 
         final List<ResolveInfo> services = pm.queryIntentServicesAsUser(
                 new Intent(InputMethod.SERVICE_INTERFACE),
@@ -2931,10 +2923,7 @@
                 if (DEBUG) {
                     Slog.d(TAG, "Found an input method " + p);
                 }
-
-            } catch (XmlPullParserException e) {
-                Slog.w(TAG, "Unable to load input method " + compName, e);
-            } catch (IOException e) {
+            } catch (XmlPullParserException | IOException e) {
                 Slog.w(TAG, "Unable to load input method " + compName, e);
             }
         }
@@ -3408,8 +3397,7 @@
             }
         }
         if (mostApplicableIMI != null) {
-            return new Pair<InputMethodInfo, InputMethodSubtype> (mostApplicableIMI,
-                    mostApplicableSubtype);
+            return new Pair<> (mostApplicableIMI, mostApplicableSubtype);
         } else {
             return null;
         }
@@ -3468,23 +3456,12 @@
         return mCurrentSubtype;
     }
 
-    private void addShortcutInputMethodAndSubtypes(InputMethodInfo imi,
-            InputMethodSubtype subtype) {
-        if (mShortcutInputMethodsAndSubtypes.containsKey(imi)) {
-            mShortcutInputMethodsAndSubtypes.get(imi).add(subtype);
-        } else {
-            ArrayList<InputMethodSubtype> subtypes = new ArrayList<InputMethodSubtype>();
-            subtypes.add(subtype);
-            mShortcutInputMethodsAndSubtypes.put(imi, subtypes);
-        }
-    }
-
     // TODO: We should change the return type from List to List<Parcelable>
     @SuppressWarnings("rawtypes")
     @Override
     public List getShortcutInputMethodsAndSubtypes() {
         synchronized (mMethodMap) {
-            ArrayList<Object> ret = new ArrayList<Object>();
+            ArrayList<Object> ret = new ArrayList<>();
             if (mShortcutInputMethodsAndSubtypes.size() == 0) {
                 // If there are no selected shortcut subtypes, the framework will try to find
                 // the most applicable subtype from all subtypes whose mode is
@@ -3545,7 +3522,7 @@
         private final AtomicFile mAdditionalInputMethodSubtypeFile;
         private final HashMap<String, InputMethodInfo> mMethodMap;
         private final HashMap<String, List<InputMethodSubtype>> mAdditionalSubtypesMap =
-                new HashMap<String, List<InputMethodSubtype>>();
+                new HashMap<>();
         public InputMethodFileManager(HashMap<String, InputMethodInfo> methodMap, int userId) {
             if (methodMap == null) {
                 throw new NullPointerException("methodMap is null");
@@ -3581,7 +3558,7 @@
         public void addInputMethodSubtypes(
                 InputMethodInfo imi, InputMethodSubtype[] additionalSubtypes) {
             synchronized (mMethodMap) {
-                final ArrayList<InputMethodSubtype> subtypes = new ArrayList<InputMethodSubtype>();
+                final ArrayList<InputMethodSubtype> subtypes = new ArrayList<>();
                 final int N = additionalSubtypes.length;
                 for (int i = 0; i < N; ++i) {
                     final InputMethodSubtype subtype = additionalSubtypes[i];
@@ -3655,9 +3632,7 @@
                 HashMap<String, List<InputMethodSubtype>> allSubtypes, AtomicFile subtypesFile) {
             if (allSubtypes == null || subtypesFile == null) return;
             allSubtypes.clear();
-            FileInputStream fis = null;
-            try {
-                fis = subtypesFile.openRead();
+            try (final FileInputStream fis = subtypesFile.openRead()) {
                 final XmlPullParser parser = Xml.newPullParser();
                 parser.setInput(fis, StandardCharsets.UTF_8.name());
                 int type = parser.getEventType();
@@ -3682,7 +3657,7 @@
                             Slog.w(TAG, "Invalid imi id found in subtypes.xml");
                             continue;
                         }
-                        tempSubtypesArray = new ArrayList<InputMethodSubtype>();
+                        tempSubtypesArray = new ArrayList<>();
                         allSubtypes.put(currentImiId, tempSubtypesArray);
                     } else if (NODE_SUBTYPE.equals(nodeName)) {
                         if (TextUtils.isEmpty(currentImiId) || tempSubtypesArray == null) {
@@ -3712,23 +3687,9 @@
                         tempSubtypesArray.add(subtype);
                     }
                 }
-            } catch (XmlPullParserException e) {
-                Slog.w(TAG, "Error reading subtypes: " + e);
+            } catch (XmlPullParserException | IOException | NumberFormatException e) {
+                Slog.w(TAG, "Error reading subtypes", e);
                 return;
-            } catch (java.io.IOException e) {
-                Slog.w(TAG, "Error reading subtypes: " + e);
-                return;
-            } catch (NumberFormatException e) {
-                Slog.w(TAG, "Error reading subtypes: " + e);
-                return;
-            } finally {
-                if (fis != null) {
-                    try {
-                        fis.close();
-                    } catch (java.io.IOException e1) {
-                        Slog.w(TAG, "Failed to close.");
-                    }
-                }
             }
         }
     }
diff --git a/services/core/java/com/android/server/ServiceWatcher.java b/services/core/java/com/android/server/ServiceWatcher.java
index 9274295..6062137 100644
--- a/services/core/java/com/android/server/ServiceWatcher.java
+++ b/services/core/java/com/android/server/ServiceWatcher.java
@@ -165,7 +165,7 @@
             intent.setPackage(justCheckThisPackage);
         }
         List<ResolveInfo> rInfos = mPm.queryIntentServicesAsUser(intent,
-                PackageManager.GET_META_DATA, UserHandle.USER_OWNER);
+                PackageManager.GET_META_DATA, UserHandle.USER_SYSTEM);
         int bestVersion = Integer.MIN_VALUE;
         String bestPackage = null;
         boolean bestIsMultiuser = false;
@@ -242,7 +242,7 @@
         if (D) Log.d(mTag, "binding " + packageName + " (version " + version + ") ("
                 + (isMultiuser ? "multi" : "single") + "-user)");
         mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE | Context.BIND_NOT_FOREGROUND
-                | Context.BIND_NOT_VISIBLE, mIsMultiuser ? UserHandle.OWNER : UserHandle.CURRENT);
+                | Context.BIND_NOT_VISIBLE, mIsMultiuser ? UserHandle.SYSTEM : UserHandle.CURRENT);
     }
 
     public static boolean isSignatureMatch(Signature[] signatures,
diff --git a/services/core/java/com/android/server/accounts/AccountManagerService.java b/services/core/java/com/android/server/accounts/AccountManagerService.java
index aab6374..8b0e6f2 100644
--- a/services/core/java/com/android/server/accounts/AccountManagerService.java
+++ b/services/core/java/com/android/server/accounts/AccountManagerService.java
@@ -283,7 +283,22 @@
                 // Don't delete accounts when updating a authenticator's
                 // package.
                 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
-                    purgeOldGrantsAll();
+                    /* Purging data requires file io, don't block the main thread. This is probably
+                     * less than ideal because we are introducing a race condition where old grants
+                     * could be exercised until they are purged. But that race condition existed
+                     * anyway with the broadcast receiver.
+                     *
+                     * Ideally, we would completely clear the cache, purge data from the database,
+                     * and then rebuild the cache. All under the cache lock. But that change is too
+                     * large at this point.
+                     */
+                    Runnable r = new Runnable() {
+                        @Override
+                        public void run() {
+                            purgeOldGrantsAll();
+                        }
+                    };
+                    new Thread(r).start();
                 }
             }
         }, intentFilter);
@@ -329,52 +344,6 @@
         return mUserManager;
     }
 
-    /* Caller should lock mUsers */
-    private UserAccounts initUserLocked(int userId) {
-        UserAccounts accounts = mUsers.get(userId);
-        if (accounts == null) {
-            accounts = new UserAccounts(mContext, userId);
-            initializeDebugDbSizeAndCompileSqlStatementForLogging(
-                    accounts.openHelper.getWritableDatabase(), accounts);
-            mUsers.append(userId, accounts);
-            purgeOldGrants(accounts);
-            validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
-        }
-        return accounts;
-    }
-
-    private void purgeOldGrantsAll() {
-        synchronized (mUsers) {
-            for (int i = 0; i < mUsers.size(); i++) {
-                purgeOldGrants(mUsers.valueAt(i));
-            }
-        }
-    }
-
-    private void purgeOldGrants(UserAccounts accounts) {
-        synchronized (accounts.cacheLock) {
-            final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
-            final Cursor cursor = db.query(TABLE_GRANTS,
-                    new String[]{GRANTS_GRANTEE_UID},
-                    null, null, GRANTS_GRANTEE_UID, null, null);
-            try {
-                while (cursor.moveToNext()) {
-                    final int uid = cursor.getInt(0);
-                    final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
-                    if (packageExists) {
-                        continue;
-                    }
-                    Log.d(TAG, "deleting grants for UID " + uid
-                            + " because its package is no longer installed");
-                    db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
-                            new String[]{Integer.toString(uid)});
-                }
-            } finally {
-                cursor.close();
-            }
-        }
-    }
-
     /**
      * Validate internal set of accounts against installed authenticators for
      * given user. Clears cached authenticators before validating.
@@ -469,13 +438,49 @@
         synchronized (mUsers) {
             UserAccounts accounts = mUsers.get(userId);
             if (accounts == null) {
-                accounts = initUserLocked(userId);
+                accounts = new UserAccounts(mContext, userId);
+                initializeDebugDbSizeAndCompileSqlStatementForLogging(
+                        accounts.openHelper.getWritableDatabase(), accounts);
                 mUsers.append(userId, accounts);
+                purgeOldGrants(accounts);
+                validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
             }
             return accounts;
         }
     }
 
+    private void purgeOldGrantsAll() {
+        synchronized (mUsers) {
+            for (int i = 0; i < mUsers.size(); i++) {
+                purgeOldGrants(mUsers.valueAt(i));
+            }
+        }
+    }
+
+    private void purgeOldGrants(UserAccounts accounts) {
+        synchronized (accounts.cacheLock) {
+            final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
+            final Cursor cursor = db.query(TABLE_GRANTS,
+                    new String[]{GRANTS_GRANTEE_UID},
+                    null, null, GRANTS_GRANTEE_UID, null, null);
+            try {
+                while (cursor.moveToNext()) {
+                    final int uid = cursor.getInt(0);
+                    final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
+                    if (packageExists) {
+                        continue;
+                    }
+                    Log.d(TAG, "deleting grants for UID " + uid
+                            + " because its package is no longer installed");
+                    db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
+                            new String[]{Integer.toString(uid)});
+                }
+            } finally {
+                cursor.close();
+            }
+        }
+    }
+
     private void onUserRemoved(Intent intent) {
         int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
         if (userId < 1) return;
@@ -2510,8 +2515,9 @@
         }
         long identityToken = clearCallingIdentity();
         try {
+            UserAccounts accounts = getUserAccounts(userId);
             return getAccountsInternal(
-                    userId,
+                    accounts,
                     callingUid,
                     null,  // packageName
                     visibleAccountTypes);
@@ -2609,8 +2615,9 @@
 
         long identityToken = clearCallingIdentity();
         try {
+            UserAccounts accounts = getUserAccounts(userId);
             return getAccountsInternal(
-                    userId,
+                    accounts,
                     callingUid,
                     callingPackage,
                     visibleAccountTypes);
@@ -2620,13 +2627,11 @@
     }
 
     private Account[] getAccountsInternal(
-            int userId,
+            UserAccounts userAccounts,
             int callingUid,
             String callingPackage,
             List<String> visibleAccountTypes) {
-        UserAccounts accounts = getUserAccounts(userId);
-        synchronized (accounts.cacheLock) {
-            UserAccounts userAccounts = getUserAccounts(userId);
+        synchronized (userAccounts.cacheLock) {
             ArrayList<Account> visibleAccounts = new ArrayList<>();
             for (String visibleType : visibleAccountTypes) {
                 Account[] accountsForType = getAccountsFromCacheLocked(
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index 2be3bf7..19ad930 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -8639,6 +8639,54 @@
     }
 
     @Override
+    public void setActivityBounds(IBinder token, Rect bounds) {
+        long ident = Binder.clearCallingIdentity();
+        try {
+            synchronized (this) {
+                final ActivityRecord r = ActivityRecord.isInStackLocked(token);
+                if (r == null) {
+                    Slog.w(TAG, "setActivityBounds: token=" + token + " not found");
+                    return;
+                }
+                final TaskRecord task = r.task;
+                if (task == null) {
+                    Slog.e(TAG, "setActivityBounds: No TaskRecord for the ActivityRecord r=" + r);
+                    return;
+                }
+                mStackSupervisor.resizeTaskLocked(task, bounds);
+            }
+        } finally {
+            Binder.restoreCallingIdentity(ident);
+        }
+    }
+
+    @Override
+    public Rect getActivityBounds(IBinder token) {
+        long ident = Binder.clearCallingIdentity();
+        Rect rect = null;
+        try {
+            synchronized (this) {
+                final ActivityRecord r = ActivityRecord.isInStackLocked(token);
+                if (r == null) {
+                    Slog.w(TAG, "getActivityBounds: token=" + token + " not found");
+                    return rect;
+                }
+                final TaskRecord task = r.task;
+                if (task == null) {
+                    Slog.e(TAG, "getActivityBounds: No TaskRecord for the ActivityRecord r=" + r);
+                    return rect;
+                }
+                if (task.mBounds != null) {
+                    rect = new Rect(task.mBounds);
+                }
+            }
+        } finally {
+            Binder.restoreCallingIdentity(ident);
+        }
+        return rect;
+    }
+
+    @Override
     public Bitmap getTaskDescriptionIcon(String filename) {
         if (!FileUtils.isValidExtFilename(filename)
                 || !filename.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
diff --git a/services/core/java/com/android/server/am/ActivityStack.java b/services/core/java/com/android/server/am/ActivityStack.java
index b997926..18a0a36 100644
--- a/services/core/java/com/android/server/am/ActivityStack.java
+++ b/services/core/java/com/android/server/am/ActivityStack.java
@@ -363,8 +363,7 @@
     }
 
     boolean okToShowLocked(ActivityRecord r) {
-        return mStackSupervisor.isCurrentProfileLocked(r.userId)
-                || (r.info.flags & FLAG_SHOW_FOR_ALL_USERS) != 0;
+        return mStackSupervisor.okToShowLocked(r);
     }
 
     final ActivityRecord topRunningActivityLocked(ActivityRecord notTop) {
@@ -690,6 +689,13 @@
                 "Launch completed; removing icicle of " + r.icicle);
     }
 
+    private void addRecentActivityLocked(ActivityRecord r) {
+        if (r != null) {
+            mRecentTasks.addLocked(r.task);
+            r.task.touchActiveTime();
+        }
+    }
+
     private void startLaunchTraces(String packageName) {
         if (mFullyDrawnStartTime != 0)  {
             Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, "drawing", 0);
@@ -2285,6 +2291,8 @@
 
         if (doResume) {
             mStackSupervisor.resumeTopActivitiesLocked(this, r, options);
+        } else {
+            addRecentActivityLocked(r);
         }
     }
 
@@ -3730,6 +3738,14 @@
         // of the stack, keeping them in the same internal order.
         insertTaskAtTop(tr, null);
 
+        // Don't refocus if invisible to current user
+        ActivityRecord top = tr.getTopActivity();
+        if (!okToShowLocked(top)) {
+            addRecentActivityLocked(top);
+            ActivityOptions.abort(options);
+            return;
+        }
+
         // Set focus to the top running activity of this stack.
         ActivityRecord r = topRunningActivityLocked(null);
         mService.setFocusedActivityLocked(r, reason);
@@ -3800,7 +3816,12 @@
         if (DEBUG_TRANSITION) Slog.v(TAG_TRANSITION, "Prepare to back transition: task=" + taskId);
 
         boolean prevIsHome = false;
-        if (tr.isOverHomeStack()) {
+
+        // If true, we should resume the home activity next if the task we are moving to the
+        // back is over the home stack. We force to false if the task we are moving to back
+        // is the home task and we don't want it resumed after moving to the back.
+        final boolean canGoHome = !tr.isHomeTask() && tr.isOverHomeStack();
+        if (canGoHome) {
             final TaskRecord nextTask = getNextTask(tr);
             if (nextTask != null) {
                 nextTask.setTaskToReturnTo(tr.getTaskToReturnTo());
@@ -3834,8 +3855,7 @@
         }
 
         final TaskRecord task = mResumedActivity != null ? mResumedActivity.task : null;
-        if (prevIsHome || task == tr && tr.isOverHomeStack()
-                || numTasks <= 1 && isOnHomeDisplay()) {
+        if (prevIsHome || (task == tr && canGoHome) || (numTasks <= 1 && isOnHomeDisplay())) {
             if (!mService.mBooting && !mService.mBooted) {
                 // Not ready yet!
                 return false;
diff --git a/services/core/java/com/android/server/am/ActivityStackSupervisor.java b/services/core/java/com/android/server/am/ActivityStackSupervisor.java
index 2e9272c..a449baf 100644
--- a/services/core/java/com/android/server/am/ActivityStackSupervisor.java
+++ b/services/core/java/com/android/server/am/ActivityStackSupervisor.java
@@ -1499,13 +1499,6 @@
             err = ActivityManager.START_CLASS_NOT_FOUND;
         }
 
-        if (err == ActivityManager.START_SUCCESS
-                && !isCurrentProfileLocked(userId)
-                && (aInfo.flags & FLAG_SHOW_FOR_ALL_USERS) == 0) {
-            // Trying to launch a background activity that doesn't show for all users.
-            err = ActivityManager.START_NOT_CURRENT_USER_ACTIVITY;
-        }
-
         if (err == ActivityManager.START_SUCCESS && sourceRecord != null
                 && sourceRecord.task.voiceSession != null) {
             // If this activity is being launched as part of a voice session, we need
@@ -1922,8 +1915,9 @@
         // If the caller has asked not to resume at this point, we make note
         // of this in the record so that we can skip it when trying to find
         // the top running activity.
-        if (!doResume) {
+        if (!doResume || !okToShowLocked(r)) {
             r.delayedResume = true;
+            doResume = false;
         }
 
         ActivityRecord notTop =
@@ -2128,7 +2122,7 @@
                             options = null;
                         }
                     }
-                    if (!movedToFront) {
+                    if (!movedToFront && doResume) {
                         if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Bring to front target: " + targetStack
                                 + " from " + intentActivity);
                         targetStack.moveToFront("intentActivityFound");
@@ -2155,6 +2149,7 @@
                         } else {
                             ActivityOptions.abort(options);
                         }
+                        updateUserStackLocked(r.userId, targetStack);
                         return ActivityManager.START_RETURN_INTENT_TO_CALLER;
                     }
                     if ((launchFlags & (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK))
@@ -2257,6 +2252,7 @@
                         } else {
                             ActivityOptions.abort(options);
                         }
+                        updateUserStackLocked(r.userId, targetStack);
                         return ActivityManager.START_TASK_TO_FRONT;
                     }
                 }
@@ -2322,7 +2318,9 @@
                 && (launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
             newTask = true;
             targetStack = computeStackFocus(r, newTask);
-            targetStack.moveToFront("startingNewTask");
+            if (doResume) {
+                targetStack.moveToFront("startingNewTask");
+            }
 
             if (reuseTask == null) {
                 r.setTask(targetStack.createTaskRecord(getNextTaskId(),
@@ -2355,7 +2353,9 @@
                 return ActivityManager.START_RETURN_LOCK_TASK_MODE_VIOLATION;
             }
             targetStack = sourceTask.stack;
-            targetStack.moveToFront("sourceStackToFront");
+            if (doResume) {
+                targetStack.moveToFront("sourceStackToFront");
+            }
             final TaskRecord topTask = targetStack.topTask();
             if (topTask != sourceTask) {
                 targetStack.moveTaskToFrontLocked(sourceTask, noAnimation, options,
@@ -2450,7 +2450,9 @@
             // of a new task...  just put it in the top task, though these days
             // this case should never happen.
             targetStack = computeStackFocus(r, newTask);
-            targetStack.moveToFront("addingToTopTask");
+            if (doResume) {
+                targetStack.moveToFront("addingToTopTask");
+            }
             ActivityRecord prev = targetStack.topActivity();
             r.setTask(prev != null ? prev.task : targetStack.createTaskRecord(getNextTaskId(),
                             r.info, intent, null, null, true), null);
@@ -2471,10 +2473,10 @@
         ActivityStack.logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
         targetStack.mLastPausedActivity = null;
         targetStack.startActivityLocked(r, newTask, doResume, keepCurTransition, options);
-        if (!launchTaskBehind) {
-            // Don't set focus on an activity that's going to the back.
+        if (!launchTaskBehind && doResume) {
             mService.setFocusedActivityLocked(r, "startedActivity");
         }
+        updateUserStackLocked(r.userId, targetStack);
         return ActivityManager.START_SUCCESS;
     }
 
@@ -2676,6 +2678,16 @@
     }
 
     /**
+     * Update the last used stack id for non-current user (current user's last
+     * used stack is the focused stack)
+     */
+    void updateUserStackLocked(int userId, ActivityStack stack) {
+        if (userId != mCurrentUser) {
+            mUserStackInFront.put(userId, stack != null ? stack.getStackId() : HOME_STACK_ID);
+        }
+    }
+
+    /**
      * @return true if some activity was finished (or would have finished if doit were true).
      */
     boolean finishDisabledPackageActivitiesLocked(String packageName, Set<String> filterByClasses,
@@ -3511,6 +3523,12 @@
         return false;
     }
 
+    /** Checks whether the activity should be shown for current user. */
+    boolean okToShowLocked(ActivityRecord r) {
+        return r != null && (isCurrentProfileLocked(r.userId)
+                || (r.info.flags & FLAG_SHOW_FOR_ALL_USERS) != 0);
+    }
+
     final ArrayList<ActivityRecord> processStoppingActivitiesLocked(boolean remove) {
         ArrayList<ActivityRecord> stops = null;
 
diff --git a/services/core/java/com/android/server/content/ContentService.java b/services/core/java/com/android/server/content/ContentService.java
index c13401f..b766894 100644
--- a/services/core/java/com/android/server/content/ContentService.java
+++ b/services/core/java/com/android/server/content/ContentService.java
@@ -157,7 +157,7 @@
         mFactoryTest = factoryTest;
 
         // Let the package manager query for the sync adapters for a given authority
-        // as we grant default permissions to sync adapters for specifix authorities.
+        // as we grant default permissions to sync adapters for specific authorities.
         PackageManagerInternal packageManagerInternal = LocalServices.getService(
                 PackageManagerInternal.class);
         packageManagerInternal.setSyncAdapterPackagesprovider(
diff --git a/services/core/java/com/android/server/fingerprint/FingerprintService.java b/services/core/java/com/android/server/fingerprint/FingerprintService.java
index c705fbf..ffad69d 100644
--- a/services/core/java/com/android/server/fingerprint/FingerprintService.java
+++ b/services/core/java/com/android/server/fingerprint/FingerprintService.java
@@ -454,6 +454,18 @@
                 "Must have " + permission + " permission.");
     }
 
+    int getEffectiveUserId(int userId) {
+        UserManager um = UserManager.get(mContext);
+        if (um != null) {
+            final long callingIdentity = Binder.clearCallingIdentity();
+            userId = um.getCredentialOwnerProfile(userId);
+            Binder.restoreCallingIdentity(callingIdentity);
+        } else {
+            Slog.e(TAG, "Unable to acquire UserManager");
+        }
+        return userId;
+    }
+
     boolean isCurrentUserOrProfile(int userId) {
         UserManager um = UserManager.get(mContext);
 
@@ -577,10 +589,14 @@
                 result = true; // client not listening
 	    }
 	    if (fpId == 0) {
-                FingerprintUtils.vibrateFingerprintError(getContext());
+                if (receiver != null) {
+                    FingerprintUtils.vibrateFingerprintError(getContext());
+                }
                 result |= handleFailedAttempt(this);
             } else {
-                FingerprintUtils.vibrateFingerprintSuccess(getContext());
+                if (receiver != null) {
+                    FingerprintUtils.vibrateFingerprintSuccess(getContext());
+                }
                 result |= true; // we have a valid fingerprint
                 mLockoutReset.run();
             }
@@ -686,11 +702,15 @@
             }
             final byte [] cryptoClone = Arrays.copyOf(cryptoToken, cryptoToken.length);
 
+            // Group ID is arbitrarily set to parent profile user ID. It just represents
+            // the default fingerprints for the user.
+            final int effectiveGroupId = getEffectiveUserId(groupId);
+
             final boolean restricted = isRestricted();
             mHandler.post(new Runnable() {
                 @Override
                 public void run() {
-                    startEnrollment(token, cryptoClone, groupId, receiver, flags, restricted);
+                    startEnrollment(token, cryptoClone, effectiveGroupId, receiver, flags, restricted);
                 }
             });
         }
@@ -724,11 +744,16 @@
                 Slog.w(TAG, "Calling not granted permission to use fingerprint");
                 return;
             }
+
+            // Group ID is arbitrarily set to parent profile user ID. It just represents
+            // the default fingerprints for the user.
+            final int effectiveGroupId = getEffectiveUserId(groupId);
+
             final boolean restricted = isRestricted();
             mHandler.post(new Runnable() {
                 @Override
                 public void run() {
-                    startAuthentication(token, opId, groupId, receiver, flags, restricted);
+                    startAuthentication(token, opId, effectiveGroupId, receiver, flags, restricted);
                 }
             });
         }
@@ -751,10 +776,14 @@
                 final IFingerprintServiceReceiver receiver) {
             checkPermission(MANAGE_FINGERPRINT); // TODO: Maybe have another permission
             final boolean restricted = isRestricted();
+
+            // Group ID is arbitrarily set to parent profile user ID. It just represents
+            // the default fingerprints for the user.
+            final int effectiveGroupId = getEffectiveUserId(groupId);
             mHandler.post(new Runnable() {
                 @Override
                 public void run() {
-                    startRemove(token, fingerId, groupId, receiver, restricted);
+                    startRemove(token, fingerId, effectiveGroupId, receiver, restricted);
                 }
             });
 
@@ -771,10 +800,15 @@
         @Override // Binder call
         public void rename(final int fingerId, final int groupId, final String name) {
             checkPermission(MANAGE_FINGERPRINT);
+
+            // Group ID is arbitrarily set to parent profile user ID. It just represents
+            // the default fingerprints for the user.
+            final int effectiveGroupId = getEffectiveUserId(groupId);
             mHandler.post(new Runnable() {
                 @Override
                 public void run() {
-                    mFingerprintUtils.renameFingerprintForUser(mContext, fingerId, groupId, name);
+                    mFingerprintUtils.renameFingerprintForUser(mContext, fingerId,
+                            effectiveGroupId, name);
                 }
             });
         }
@@ -784,15 +818,19 @@
             if (!canUseFingerprint(opPackageName)) {
                 return Collections.emptyList();
             }
-            return FingerprintService.this.getEnrolledFingerprints(userId);
+            int effectiveUserId = getEffectiveUserId(userId);
+
+            return FingerprintService.this.getEnrolledFingerprints(effectiveUserId);
         }
 
         @Override // Binder call
-        public boolean hasEnrolledFingerprints(int groupId, String opPackageName) {
+        public boolean hasEnrolledFingerprints(int userId, String opPackageName) {
             if (!canUseFingerprint(opPackageName)) {
                 return false;
             }
-            return FingerprintService.this.hasEnrolledFingerprints(groupId);
+
+            int effectiveUserId  = getEffectiveUserId(userId);
+            return FingerprintService.this.hasEnrolledFingerprints(effectiveUserId);
         }
 
         @Override // Binder call
@@ -829,8 +867,7 @@
         IFingerprintDaemon daemon = getFingerprintDaemon();
         if (daemon != null) {
             try {
-                // TODO: if this is a managed profile, use the profile parent's directory for
-                // storage.
+                userId = getEffectiveUserId(userId);
                 final File systemDir = Environment.getUserSystemDirectory(userId);
                 final File fpDir = new File(systemDir, FP_DATA_DIR);
                 if (!fpDir.exists()) {
diff --git a/services/core/java/com/android/server/net/NetworkPolicyManagerService.java b/services/core/java/com/android/server/net/NetworkPolicyManagerService.java
index 7d16a35..e69dda1 100644
--- a/services/core/java/com/android/server/net/NetworkPolicyManagerService.java
+++ b/services/core/java/com/android/server/net/NetworkPolicyManagerService.java
@@ -1772,7 +1772,7 @@
         maybeRefreshTrustedTime();
         synchronized (mRulesLock) {
             mRestrictBackground = restrictBackground;
-            updateRulesForGlobalChangeLocked(false);
+            updateRulesForGlobalChangeLocked(true);
             updateNotificationsLocked();
             writePolicyLocked();
         }
diff --git a/services/core/java/com/android/server/notification/NotificationManagerService.java b/services/core/java/com/android/server/notification/NotificationManagerService.java
index 9426b76..4351798 100644
--- a/services/core/java/com/android/server/notification/NotificationManagerService.java
+++ b/services/core/java/com/android/server/notification/NotificationManagerService.java
@@ -3615,22 +3615,28 @@
 
         public ArraySet<String> getGrantedPackages() {
             final ArraySet<String> pkgs = new ArraySet<>();
-            final String setting = Settings.Secure.getStringForUser(
-                    getContext().getContentResolver(),
-                    Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES,
-                    ActivityManager.getCurrentUser());
-            if (setting != null) {
-                final String[] tokens = setting.split(SEPARATOR);
-                for (int i = 0; i < tokens.length; i++) {
-                    String token = tokens[i];
-                    if (token != null) {
-                        token.trim();
+
+            long identity = Binder.clearCallingIdentity();
+            try {
+                final String setting = Settings.Secure.getStringForUser(
+                        getContext().getContentResolver(),
+                        Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES,
+                        ActivityManager.getCurrentUser());
+                if (setting != null) {
+                    final String[] tokens = setting.split(SEPARATOR);
+                    for (int i = 0; i < tokens.length; i++) {
+                        String token = tokens[i];
+                        if (token != null) {
+                            token.trim();
+                        }
+                        if (TextUtils.isEmpty(token)) {
+                            continue;
+                        }
+                        pkgs.add(token);
                     }
-                    if (TextUtils.isEmpty(token)) {
-                        continue;
-                    }
-                    pkgs.add(token);
                 }
+            } finally {
+                Binder.restoreCallingIdentity(identity);
             }
             return pkgs;
         }
diff --git a/services/core/java/com/android/server/pm/BasePermission.java b/services/core/java/com/android/server/pm/BasePermission.java
index 18407c9..52d0928 100644
--- a/services/core/java/com/android/server/pm/BasePermission.java
+++ b/services/core/java/com/android/server/pm/BasePermission.java
@@ -88,4 +88,10 @@
         return (protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
                 == PermissionInfo.PROTECTION_DANGEROUS;
     }
+
+    public boolean isDevelopment() {
+        return (protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
+                == PermissionInfo.PROTECTION_SIGNATURE
+                && (protectionLevel & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0;
+    }
 }
diff --git a/services/core/java/com/android/server/pm/DefaultPermissionGrantPolicy.java b/services/core/java/com/android/server/pm/DefaultPermissionGrantPolicy.java
index 71a2d59..d2a70df 100644
--- a/services/core/java/com/android/server/pm/DefaultPermissionGrantPolicy.java
+++ b/services/core/java/com/android/server/pm/DefaultPermissionGrantPolicy.java
@@ -296,7 +296,7 @@
             PackageParser.Package storagePackage = getDefaultProviderAuthorityPackageLPr(
                     "com.android.externalstorage.documents", userId);
             if (storagePackage != null) {
-                grantRuntimePermissionsLPw(storagePackage, STORAGE_PERMISSIONS, userId);
+                grantRuntimePermissionsLPw(storagePackage, STORAGE_PERMISSIONS, true, userId);
             }
 
             // CertInstaller
@@ -360,7 +360,7 @@
             PackageParser.Package cbrPackage =
                     getDefaultSystemHandlerActivityPackageLPr(cbrIntent, userId);
             if (cbrPackage != null && doesPackageSupportRuntimePermissions(cbrPackage)) {
-                grantRuntimePermissionsLPw(cbrPackage, SMS_PERMISSIONS, false, userId);
+                grantRuntimePermissionsLPw(cbrPackage, SMS_PERMISSIONS, userId);
             }
 
             // Calendar
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index dc6e17d9..e8ec8b9 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -56,6 +56,7 @@
 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
+import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
 import static android.content.pm.PackageManager.MATCH_ALL;
 import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
 import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
@@ -481,12 +482,21 @@
         new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
 
     /**
-     * Tracks new system packages [receiving in an OTA] that we expect to
+     * Tracks new system packages [received in an OTA] that we expect to
      * find updated user-installed versions. Keys are package name, values
      * are package location.
      */
     final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
 
+    /**
+     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
+     */
+    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
+    /**
+     * Whether or not system app permissions should be promoted from install to runtime.
+     */
+    boolean mPromoteSystemApps;
+
     final Settings mSettings;
     boolean mRestoredSettings;
 
@@ -2047,6 +2057,24 @@
                 }
             }
 
+            final VersionInfo ver = mSettings.getInternalVersion();
+            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
+            // when upgrading from pre-M, promote system app permissions from install to runtime
+            mPromoteSystemApps =
+                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
+
+            // save off the names of pre-existing system packages prior to scanning; we don't
+            // want to automatically grant runtime permissions for new system apps
+            if (mPromoteSystemApps) {
+                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
+                while (pkgSettingIter.hasNext()) {
+                    PackageSetting ps = pkgSettingIter.next();
+                    if (isSystemApp(ps)) {
+                        mExistingSystemPackages.add(ps.name);
+                    }
+                }
+            }
+
             // Collect vendor overlay packages.
             // (Do this before scanning any apps.)
             // For security and version matching reason, only consider
@@ -2266,8 +2294,6 @@
             // cases get permissions that the user didn't initially explicitly
             // allow...  it would be nice to have some better way to handle
             // this situation.
-            final VersionInfo ver = mSettings.getInternalVersion();
-
             int updateFlags = UPDATE_PERMISSIONS_ALL;
             if (ver.sdkVersion != mSdkVersion) {
                 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
@@ -2276,6 +2302,9 @@
             }
             updatePermissionsLPw(null, null, updateFlags);
             ver.sdkVersion = mSdkVersion;
+            // clear only after permissions have been updated
+            mExistingSystemPackages.clear();
+            mPromoteSystemApps = false;
 
             // If this is the first boot, and it is a normal boot, then
             // we need to initialize the default preferred apps.
@@ -2287,7 +2316,6 @@
 
             // If this is first boot after an OTA, and a normal boot, then
             // we need to clear code cache directories.
-            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
             if (mIsUpgrade && !onlyCore) {
                 Slog.i(TAG, "Build fingerprint changed; clearing code caches");
                 for (int i = 0; i < mSettings.mPackages.size(); i++) {
@@ -3424,14 +3452,14 @@
         }
     }
 
-    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
+    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
             BasePermission bp) {
         int index = pkg.requestedPermissions.indexOf(bp.name);
         if (index == -1) {
             throw new SecurityException("Package " + pkg.packageName
                     + " has not requested permission " + bp.name);
         }
-        if (!bp.isRuntime()) {
+        if (!bp.isRuntime() && !bp.isDevelopment()) {
             throw new SecurityException("Permission " + bp.name
                     + " is not a changeable permission type");
         }
@@ -3465,7 +3493,7 @@
                 throw new IllegalArgumentException("Unknown permission: " + name);
             }
 
-            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
+            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
 
             uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
             sb = (SettingBase) pkg.mExtras;
@@ -3481,6 +3509,16 @@
                         + name + " for package: " + packageName);
             }
 
+            if (bp.isDevelopment()) {
+                // Development permissions must be handled specially, since they are not
+                // normal runtime permissions.  For now they apply to all users.
+                if (permissionsState.grantInstallPermission(bp) !=
+                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
+                    scheduleWriteSettingsLocked();
+                }
+                return;
+            }
+
             final int result = permissionsState.grantRuntimePermission(bp, userId);
             switch (result) {
                 case PermissionsState.PERMISSION_OPERATION_FAILURE: {
@@ -3549,7 +3587,7 @@
                 throw new IllegalArgumentException("Unknown permission: " + name);
             }
 
-            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
+            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
 
             SettingBase sb = (SettingBase) pkg.mExtras;
             if (sb == null) {
@@ -3564,6 +3602,16 @@
                         + name + " for package: " + packageName);
             }
 
+            if (bp.isDevelopment()) {
+                // Development permissions must be handled specially, since they are not
+                // normal runtime permissions.  For now they apply to all users.
+                if (permissionsState.revokeInstallPermission(bp) !=
+                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
+                    scheduleWriteSettingsLocked();
+                }
+                return;
+            }
+
             if (permissionsState.revokeRuntimePermission(bp, userId) ==
                     PermissionsState.PERMISSION_OPERATION_FAILURE) {
                 return;
@@ -3791,21 +3839,6 @@
         return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
     }
 
-    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
-        BasePermission bp = mSettings.mPermissions.get(permission);
-        if (bp == null) {
-            throw new SecurityException("Missing " + permission + " permission");
-        }
-
-        SettingBase sb = (SettingBase) pkg.mExtras;
-        PermissionsState permissionsState = sb.getPermissionsState();
-
-        if (permissionsState.grantInstallPermission(bp) !=
-                PermissionsState.PERMISSION_OPERATION_FAILURE) {
-            scheduleWriteSettingsLocked();
-        }
-    }
-
     @Override
     public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
         mContext.enforceCallingOrSelfPermission(
@@ -4693,6 +4726,7 @@
         ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
         ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
         ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
+        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
         ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
         ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
 
@@ -4729,6 +4763,11 @@
                             Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
                         }
                         neverList.add(info);
+                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
+                        if (DEBUG_DOMAIN_VERIFICATION) {
+                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
+                        }
+                        alwaysAskList.add(info);
                     } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
                             status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
                         if (DEBUG_DOMAIN_VERIFICATION) {
@@ -4738,6 +4777,10 @@
                     }
                 }
             }
+
+            // We'll want to include browser possibilities in a few cases
+            boolean includeBrowser = false;
+
             // First try to add the "always" resolution(s) for the current user, if any
             if (alwaysList.size() > 0) {
                 result.addAll(alwaysList);
@@ -4746,7 +4789,7 @@
                     == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
                 result.add(xpDomainInfo.resolveInfo);
             } else {
-                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
+                // Add all undefined apps as we want them to appear in the disambiguation dialog.
                 result.addAll(undefinedList);
                 if (xpDomainInfo != null && (
                         xpDomainInfo.bestDomainVerificationStatus
@@ -4755,7 +4798,25 @@
                         == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
                     result.add(xpDomainInfo.resolveInfo);
                 }
-                // Also add Browsers (all of them or only the default one)
+                includeBrowser = true;
+            }
+
+            // The presence of any 'always ask' alternatives means we'll also offer browsers.
+            // If there were 'always' entries their preferred order has been set, so we also
+            // back that off to make the alternatives equivalent
+            if (alwaysAskList.size() > 0) {
+                for (ResolveInfo i : result) {
+                    i.preferredOrder = 0;
+                }
+                result.addAll(alwaysAskList);
+                includeBrowser = true;
+            }
+
+            if (includeBrowser) {
+                // Also add browsers (all of them or only the default one)
+                if (DEBUG_DOMAIN_VERIFICATION) {
+                    Slog.v(TAG, "   ...including browsers in candidate set");
+                }
                 if ((matchFlags & MATCH_ALL) != 0) {
                     result.addAll(matchAllList);
                 } else {
@@ -8422,6 +8483,13 @@
                     } else if (origPermissions.hasInstallPermission(bp.name)) {
                         // For legacy apps that became modern, install becomes runtime.
                         grant = GRANT_UPGRADE;
+                    } else if (mPromoteSystemApps
+                            && isSystemApp(ps)
+                            && mExistingSystemPackages.contains(ps.name)) {
+                        // For legacy system apps, install becomes runtime.
+                        // We cannot check hasInstallPermission() for system apps since those
+                        // permissions were granted implicitly and not persisted pre-M.
+                        grant = GRANT_UPGRADE;
                     } else {
                         // For modern apps keep runtime permissions unchanged.
                         grant = GRANT_RUNTIME;
@@ -14842,6 +14910,7 @@
                 pw.println("    version: print database version info");
                 pw.println("    write: write current settings now");
                 pw.println("    installs: details about install sessions");
+                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
                 pw.println("    <package.name>: info about given package");
                 return;
             } else if ("--checkin".equals(opt)) {
@@ -14863,6 +14932,31 @@
                 // When dumping a single package, we always dump all of its
                 // filter information since the amount of data will be reasonable.
                 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
+            } else if ("check-permission".equals(cmd)) {
+                if (opti >= args.length) {
+                    pw.println("Error: check-permission missing permission argument");
+                    return;
+                }
+                String perm = args[opti];
+                opti++;
+                if (opti >= args.length) {
+                    pw.println("Error: check-permission missing package argument");
+                    return;
+                }
+                String pkg = args[opti];
+                opti++;
+                int user = UserHandle.getUserId(Binder.getCallingUid());
+                if (opti < args.length) {
+                    try {
+                        user = Integer.parseInt(args[opti]);
+                    } catch (NumberFormatException e) {
+                        pw.println("Error: check-permission user argument is not a number: "
+                                + args[opti]);
+                        return;
+                    }
+                }
+                pw.println(checkPermission(perm, pkg, user));
+                return;
             } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
                 dumpState.setDump(DumpState.DUMP_LIBS);
             } else if ("f".equals(cmd) || "features".equals(cmd)) {
diff --git a/services/core/java/com/android/server/pm/Settings.java b/services/core/java/com/android/server/pm/Settings.java
index bd7ec31..943e649 100644
--- a/services/core/java/com/android/server/pm/Settings.java
+++ b/services/core/java/com/android/server/pm/Settings.java
@@ -3952,7 +3952,7 @@
 
     void dumpPackageLPr(PrintWriter pw, String prefix, String checkinTag,
             ArraySet<String> permissionNames, PackageSetting ps, SimpleDateFormat sdf,
-            Date date, List<UserInfo> users) {
+            Date date, List<UserInfo> users, boolean dumpAll) {
         if (checkinTag != null) {
             pw.print(checkinTag);
             pw.print(",");
@@ -4154,7 +4154,7 @@
                     pw.print(", COSTS_MONEY");
                 }
                 if ((perm.info.flags&PermissionInfo.FLAG_HIDDEN) != 0) {
-                    pw.print(", COSTS_HIDDEN");
+                    pw.print(", HIDDEN");
                 }
                 if ((perm.info.flags&PermissionInfo.FLAG_INSTALLED) != 0) {
                     pw.print(", INSTALLED");
@@ -4163,7 +4163,21 @@
             }
         }
 
-        if (ps.sharedUser == null || permissionNames != null) {
+        if ((permissionNames != null || dumpAll) && ps.pkg.requestedPermissions != null
+                && ps.pkg.requestedPermissions.size() > 0) {
+            final ArrayList<String> perms = ps.pkg.requestedPermissions;
+            pw.print(prefix); pw.println("  requested permissions:");
+            for (int i=0; i<perms.size(); i++) {
+                String perm = perms.get(i);
+                if (permissionNames != null
+                        && !permissionNames.contains(perm)) {
+                    continue;
+                }
+                pw.print(prefix); pw.print("    "); pw.println(perm);
+            }
+        }
+
+        if (ps.sharedUser == null || permissionNames != null || dumpAll) {
             PermissionsState permissionsState = ps.getPermissionsState();
             dumpInstallPermissionsLPr(pw, prefix + "  ", permissionNames, permissionsState);
         }
@@ -4190,7 +4204,7 @@
                 PermissionsState permissionsState = ps.getPermissionsState();
                 dumpGidsLPr(pw, prefix + "    ", permissionsState.computeGids(user.id));
                 dumpRuntimePermissionsLPr(pw, prefix + "    ", permissionNames, permissionsState
-                        .getRuntimePermissionStates(user.id));
+                        .getRuntimePermissionStates(user.id), dumpAll);
             }
 
             if (permissionNames == null) {
@@ -4238,11 +4252,12 @@
                 pw.println("Packages:");
                 printedSomething = true;
             }
-            dumpPackageLPr(pw, "  ", checkin ? "pkg" : null, permissionNames, ps, sdf, date, users);
+            dumpPackageLPr(pw, "  ", checkin ? "pkg" : null, permissionNames, ps, sdf, date, users,
+                    packageName != null);
         }
 
         printedSomething = false;
-        if (!checkin && mRenamedPackages.size() > 0 && permissionNames == null) {
+        if (mRenamedPackages.size() > 0 && permissionNames == null) {
             for (final Map.Entry<String, String> e : mRenamedPackages.entrySet()) {
                 if (packageName != null && !packageName.equals(e.getKey())
                         && !packageName.equals(e.getValue())) {
@@ -4279,7 +4294,7 @@
                     printedSomething = true;
                 }
                 dumpPackageLPr(pw, "  ", checkin ? "dis" : null, permissionNames, ps, sdf, date,
-                        users);
+                        users, packageName != null);
             }
         }
     }
@@ -4364,7 +4379,8 @@
                     if (!ArrayUtils.isEmpty(gids) || !permissions.isEmpty()) {
                         pw.print(prefix); pw.print("User "); pw.print(userId); pw.println(": ");
                         dumpGidsLPr(pw, prefix + "  ", gids);
-                        dumpRuntimePermissionsLPr(pw, prefix + "  ", permissionNames, permissions);
+                        dumpRuntimePermissionsLPr(pw, prefix + "  ", permissionNames, permissions,
+                                packageName != null);
                     }
                 }
             } else {
@@ -4410,8 +4426,8 @@
     }
 
     void dumpRuntimePermissionsLPr(PrintWriter pw, String prefix, ArraySet<String> permissionNames,
-            List<PermissionState> permissionStates) {
-        if (!permissionStates.isEmpty()) {
+            List<PermissionState> permissionStates, boolean dumpAll) {
+        if (!permissionStates.isEmpty() || dumpAll) {
             pw.print(prefix); pw.println("runtime permissions:");
             for (PermissionState permissionState : permissionStates) {
                 if (permissionNames != null
diff --git a/services/core/java/com/android/server/policy/PhoneWindowManager.java b/services/core/java/com/android/server/policy/PhoneWindowManager.java
index 454cdcf..45bbf37 100644
--- a/services/core/java/com/android/server/policy/PhoneWindowManager.java
+++ b/services/core/java/com/android/server/policy/PhoneWindowManager.java
@@ -1699,8 +1699,7 @@
      *         navigation bar and touch exploration is not enabled
      */
     private boolean canHideNavigationBar() {
-        return mHasNavigationBar
-                && !mAccessibilityManager.isTouchExplorationEnabled();
+        return mHasNavigationBar;
     }
 
     @Override
@@ -3646,7 +3645,8 @@
                         // We currently want to hide the navigation UI.
                         mNavigationBarController.setBarShowingLw(false);
                     }
-                    if (navVisible && !navTranslucent && !mNavigationBar.isAnimatingLw()
+                    if (navVisible && !navTranslucent && !navAllowedHidden
+                            && !mNavigationBar.isAnimatingLw()
                             && !mNavigationBarController.wasRecentlyTranslucent()) {
                         // If the nav bar is currently requested to be visible,
                         // and not in the process of animating on or off, then
@@ -5521,10 +5521,6 @@
         // may happen in a future call to goToSleep.
         synchronized (mLock) {
             mAwake = true;
-            if (mKeyguardDelegate != null) {
-                mHandler.removeMessages(MSG_KEYGUARD_DRAWN_TIMEOUT);
-                mHandler.sendEmptyMessageDelayed(MSG_KEYGUARD_DRAWN_TIMEOUT, 1000);
-            }
 
             updateWakeGestureListenerLp();
             updateOrientationListenerLp();
@@ -5614,6 +5610,8 @@
             mScreenOnListener = screenOnListener;
 
             if (mKeyguardDelegate != null) {
+                mHandler.removeMessages(MSG_KEYGUARD_DRAWN_TIMEOUT);
+                mHandler.sendEmptyMessageDelayed(MSG_KEYGUARD_DRAWN_TIMEOUT, 1000);
                 mKeyguardDelegate.onScreenTurningOn(mKeyguardDrawnCallback);
             } else {
                 if (DEBUG_WAKEUP) Slog.d(TAG,
@@ -6779,8 +6777,7 @@
      * R.boolean.config_enableTranslucentDecor is false.
      */
     private boolean areTranslucentBarsAllowed() {
-        return mTranslucentDecorEnabled
-                && !mAccessibilityManager.isTouchExplorationEnabled();
+        return mTranslucentDecorEnabled;
     }
 
     // Use this instead of checking config_showNavigationBar so that it can be consistently
diff --git a/services/core/java/com/android/server/policy/WindowOrientationListener.java b/services/core/java/com/android/server/policy/WindowOrientationListener.java
index 147efdd..c71b48f 100644
--- a/services/core/java/com/android/server/policy/WindowOrientationListener.java
+++ b/services/core/java/com/android/server/policy/WindowOrientationListener.java
@@ -465,6 +465,9 @@
             pw.println(prefix + "mLastFilteredX=" + mLastFilteredX);
             pw.println(prefix + "mLastFilteredY=" + mLastFilteredY);
             pw.println(prefix + "mLastFilteredZ=" + mLastFilteredZ);
+            final long delta = SystemClock.elapsedRealtimeNanos() - mLastFilteredTimestampNanos;
+            pw.println(prefix + "mLastFilteredTimestampNanos=" + mLastFilteredTimestampNanos
+                    + " (" + (delta * 0.000001f) + "ms ago)");
             pw.println(prefix + "mTiltHistory={last: " + getLastTiltLocked() + "}");
             pw.println(prefix + "mFlat=" + mFlat);
             pw.println(prefix + "mSwinging=" + mSwinging);
diff --git a/services/core/java/com/android/server/updates/SELinuxPolicyInstallReceiver.java b/services/core/java/com/android/server/updates/SELinuxPolicyInstallReceiver.java
index 4e53687..c81398f 100644
--- a/services/core/java/com/android/server/updates/SELinuxPolicyInstallReceiver.java
+++ b/services/core/java/com/android/server/updates/SELinuxPolicyInstallReceiver.java
@@ -36,7 +36,7 @@
     private static final String TAG = "SELinuxPolicyInstallReceiver";
 
     private static final String sepolicyPath = "sepolicy";
-    private static final String fileContextsPath = "file_contexts";
+    private static final String fileContextsPath = "file_contexts.bin";
     private static final String propertyContextsPath = "property_contexts";
     private static final String seappContextsPath = "seapp_contexts";
     private static final String versionPath = "selinux_version";
diff --git a/services/core/java/com/android/server/wm/AppTransition.java b/services/core/java/com/android/server/wm/AppTransition.java
index 7bd0635..a2307f9 100644
--- a/services/core/java/com/android/server/wm/AppTransition.java
+++ b/services/core/java/com/android/server/wm/AppTransition.java
@@ -16,6 +16,7 @@
 
 package com.android.server.wm;
 
+import android.annotation.Nullable;
 import android.content.Context;
 import android.content.res.Configuration;
 import android.graphics.Bitmap;
@@ -651,7 +652,7 @@
      * when a thumbnail is specified with the activity options.
      */
     Animation createThumbnailAspectScaleAnimationLocked(int appWidth, int appHeight,
-            int deviceWidth, int transit) {
+            int deviceWidth) {
         Animation a;
         final int thumbWidthI = mNextAppTransitionThumbnail.getWidth();
         final float thumbWidth = thumbWidthI > 0 ? thumbWidthI : 1;
@@ -659,7 +660,6 @@
         final float thumbHeight = thumbHeightI > 0 ? thumbHeightI : 1;
 
         float scaleW = deviceWidth / thumbWidth;
-        float unscaledWidth = deviceWidth;
         float unscaledHeight = thumbHeight * scaleW;
         float unscaledStartY = mNextAppTransitionStartY - (unscaledHeight - thumbHeight) / 2f;
         if (mNextAppTransitionScaleUp) {
@@ -716,7 +716,7 @@
      */
     Animation createAspectScaledThumbnailEnterExitAnimationLocked(int thumbTransitState,
             int appWidth, int appHeight, int orientation, int transit, Rect containingFrame,
-            Rect contentInsets) {
+            Rect contentInsets, @Nullable Rect surfaceInsets, boolean resizedWindow) {
         Animation a;
         final int thumbWidthI = mNextAppTransitionStartWidth;
         final float thumbWidth = thumbWidthI > 0 ? thumbWidthI : 1;
@@ -729,40 +729,45 @@
 
         switch (thumbTransitState) {
             case THUMBNAIL_TRANSITION_ENTER_SCALE_UP: {
-                // App window scaling up to become full screen
-                if (orientation == Configuration.ORIENTATION_PORTRAIT) {
-                    // In portrait, we scale the width and clip to the top/left square
-                    scale = thumbWidth / appWidth;
-                    scaledTopDecor = (int) (scale * contentInsets.top);
-                    int unscaledThumbHeight = (int) (thumbHeight / scale);
-                    mTmpFromClipRect.set(containingFrame);
-                    mTmpFromClipRect.bottom = (mTmpFromClipRect.top + unscaledThumbHeight);
-                    mTmpToClipRect.set(containingFrame);
+                if (resizedWindow) {
+                    a = createAspectScaledThumbnailEnterNonFullscreenAnimationLocked(
+                            containingFrame, surfaceInsets);
                 } else {
-                    // In landscape, we scale the height and clip to the top/left square
-                    scale = thumbHeight / (appHeight - contentInsets.top);
-                    scaledTopDecor = (int) (scale * contentInsets.top);
-                    int unscaledThumbWidth = (int) (thumbWidth / scale);
-                    mTmpFromClipRect.set(containingFrame);
-                    mTmpFromClipRect.right = (mTmpFromClipRect.left + unscaledThumbWidth);
-                    mTmpToClipRect.set(containingFrame);
+                    // App window scaling up to become full screen
+                    if (orientation == Configuration.ORIENTATION_PORTRAIT) {
+                        // In portrait, we scale the width and clip to the top/left square
+                        scale = thumbWidth / appWidth;
+                        scaledTopDecor = (int) (scale * contentInsets.top);
+                        int unscaledThumbHeight = (int) (thumbHeight / scale);
+                        mTmpFromClipRect.set(containingFrame);
+                        mTmpFromClipRect.bottom = (mTmpFromClipRect.top + unscaledThumbHeight);
+                        mTmpToClipRect.set(containingFrame);
+                    } else {
+                        // In landscape, we scale the height and clip to the top/left square
+                        scale = thumbHeight / (appHeight - contentInsets.top);
+                        scaledTopDecor = (int) (scale * contentInsets.top);
+                        int unscaledThumbWidth = (int) (thumbWidth / scale);
+                        mTmpFromClipRect.set(containingFrame);
+                        mTmpFromClipRect.right = (mTmpFromClipRect.left + unscaledThumbWidth);
+                        mTmpToClipRect.set(containingFrame);
+                    }
+                    // exclude top screen decor (status bar) region from the source clip.
+                    mTmpFromClipRect.top = contentInsets.top;
+
+                    mNextAppTransitionInsets.set(contentInsets);
+
+                    Animation scaleAnim = new ScaleAnimation(scale, 1, scale, 1,
+                            computePivot(mNextAppTransitionStartX, scale),
+                            computePivot(mNextAppTransitionStartY, scale));
+                    Animation clipAnim = new ClipRectAnimation(mTmpFromClipRect, mTmpToClipRect);
+                    Animation translateAnim = new TranslateAnimation(0, 0, -scaledTopDecor, 0);
+
+                    AnimationSet set = new AnimationSet(true);
+                    set.addAnimation(clipAnim);
+                    set.addAnimation(scaleAnim);
+                    set.addAnimation(translateAnim);
+                    a = set;
                 }
-                // exclude top screen decor (status bar) region from the source clip.
-                mTmpFromClipRect.top = contentInsets.top;
-
-                mNextAppTransitionInsets.set(contentInsets);
-
-                Animation scaleAnim = new ScaleAnimation(scale, 1, scale, 1,
-                        computePivot(mNextAppTransitionStartX, scale),
-                        computePivot(mNextAppTransitionStartY, scale));
-                Animation clipAnim = new ClipRectAnimation(mTmpFromClipRect, mTmpToClipRect);
-                Animation translateAnim = new TranslateAnimation(0, 0, -scaledTopDecor, 0);
-
-                AnimationSet set = new AnimationSet(true);
-                set.addAnimation(clipAnim);
-                set.addAnimation(scaleAnim);
-                set.addAnimation(translateAnim);
-                a = set;
                 break;
             }
             case THUMBNAIL_TRANSITION_EXIT_SCALE_UP: {
@@ -836,6 +841,31 @@
                 mTouchResponseInterpolator);
     }
 
+    private Animation createAspectScaledThumbnailEnterNonFullscreenAnimationLocked(
+            Rect containingFrame, @Nullable Rect surfaceInsets) {
+        float width = containingFrame.width();
+        float height = containingFrame.height();
+        float scaleWidth = mNextAppTransitionStartWidth / width;
+        float scaleHeight = mNextAppTransitionStartHeight / height;
+        AnimationSet set = new AnimationSet(true);
+        int surfaceInsetsHorizontal = surfaceInsets == null
+                ? 0 : surfaceInsets.left + surfaceInsets.right;
+        int surfaceInsetsVertical = surfaceInsets == null
+                ? 0 : surfaceInsets.top + surfaceInsets.bottom;
+        // We want the scaling to happen from the center of the surface. In order to achieve that,
+        // we need to account for surface insets that will be used to enlarge the surface.
+        ScaleAnimation scale = new ScaleAnimation(scaleWidth, 1, scaleHeight, 1,
+                (width + surfaceInsetsHorizontal) / 2, (height + surfaceInsetsVertical) / 2);
+        int fromX = mNextAppTransitionStartX + mNextAppTransitionStartWidth / 2
+                - (containingFrame.left + containingFrame.width() / 2);
+        int fromY = mNextAppTransitionStartY + mNextAppTransitionStartHeight / 2
+                - (containingFrame.top + containingFrame.height() / 2);
+        TranslateAnimation translation = new TranslateAnimation(fromX, 0, fromY, 0);
+        set.addAnimation(scale);
+        set.addAnimation(translation);
+        return set;
+    }
+
     /**
      * This animation runs for the thumbnail that gets cross faded with the enter/exit activity
      * when a thumbnail is specified with the activity options.
@@ -881,7 +911,7 @@
      * leaving, and the activity that is entering.
      */
     Animation createThumbnailEnterExitAnimationLocked(int thumbTransitState, int appWidth,
-                                                    int appHeight, int transit) {
+            int appHeight, int transit) {
         Animation a;
         final int thumbWidthI = mNextAppTransitionThumbnail.getWidth();
         final float thumbWidth = thumbWidthI > 0 ? thumbWidthI : 1;
@@ -954,7 +984,8 @@
 
     Animation loadAnimation(WindowManager.LayoutParams lp, int transit, boolean enter,
             int appWidth, int appHeight, int orientation, Rect containingFrame, Rect contentInsets,
-            Rect appFrame, boolean isVoiceInteraction) {
+            @Nullable Rect surfaceInsets, Rect appFrame, boolean isVoiceInteraction,
+            boolean resizedWindow) {
         Animation a;
         if (isVoiceInteraction && (transit == TRANSIT_ACTIVITY_OPEN
                 || transit == TRANSIT_TASK_OPEN
@@ -1023,8 +1054,8 @@
             mNextAppTransitionScaleUp =
                     (mNextAppTransitionType == NEXT_TRANSIT_TYPE_THUMBNAIL_ASPECT_SCALE_UP);
             a = createAspectScaledThumbnailEnterExitAnimationLocked(
-                    getThumbnailTransitionState(enter), appWidth, appHeight, orientation,
-                    transit, containingFrame, contentInsets);
+                    getThumbnailTransitionState(enter), appWidth, appHeight, orientation, transit,
+                    containingFrame, contentInsets, surfaceInsets, resizedWindow);
             if (DEBUG_APP_TRANSITIONS || DEBUG_ANIM) {
                 String animName = mNextAppTransitionScaleUp ?
                         "ANIM_THUMBNAIL_ASPECT_SCALE_UP" : "ANIM_THUMBNAIL_ASPECT_SCALE_DOWN";
diff --git a/services/core/java/com/android/server/wm/DisplayContent.java b/services/core/java/com/android/server/wm/DisplayContent.java
index fcf743e..2b26b42 100644
--- a/services/core/java/com/android/server/wm/DisplayContent.java
+++ b/services/core/java/com/android/server/wm/DisplayContent.java
@@ -208,7 +208,9 @@
     }
 
     void moveStack(TaskStack stack, boolean toTop) {
-        mStacks.remove(stack);
+        if (!mStacks.remove(stack)) {
+            Slog.wtf(TAG, "moving stack that was not added: " + stack, new Throwable());
+        }
         mStacks.add(toTop ? mStacks.size() : 0, stack);
     }
 
diff --git a/services/core/java/com/android/server/wm/Task.java b/services/core/java/com/android/server/wm/Task.java
index 3ff5be1..1eddb04 100644
--- a/services/core/java/com/android/server/wm/Task.java
+++ b/services/core/java/com/android/server/wm/Task.java
@@ -19,6 +19,7 @@
 import static com.android.server.wm.WindowManagerService.TAG;
 import static com.android.server.wm.WindowManagerService.DEBUG_RESIZE;
 import static com.android.server.wm.WindowManagerService.DEBUG_STACK;
+import static android.app.ActivityManager.FREEFORM_WORKSPACE_STACK_ID;
 
 import android.content.res.Configuration;
 import android.graphics.Rect;
@@ -176,10 +177,12 @@
                 bounds = mTmpRect;
                 mFullscreen = true;
             } else {
-                // ensure bounds are entirely within the display rect
-                if (!bounds.intersect(mTmpRect)) {
-                    // Can't set bounds outside the containing display...Sorry!
-                    return false;
+                if (mStack.mStackId != FREEFORM_WORKSPACE_STACK_ID || bounds.isEmpty()) {
+                    // ensure bounds are entirely within the display rect
+                    if (!bounds.intersect(mTmpRect)) {
+                        // Can't set bounds outside the containing display...Sorry!
+                        return false;
+                    }
                 }
                 mFullscreen = mTmpRect.equals(bounds);
             }
diff --git a/services/core/java/com/android/server/wm/TaskStack.java b/services/core/java/com/android/server/wm/TaskStack.java
index 90d2593..1c65c27 100644
--- a/services/core/java/com/android/server/wm/TaskStack.java
+++ b/services/core/java/com/android/server/wm/TaskStack.java
@@ -318,8 +318,6 @@
         }
 
         close();
-
-        mDisplayContent = null;
     }
 
     void resetAnimationBackgroundAnimator() {
@@ -358,6 +356,7 @@
         for (int taskNdx = mTasks.size() - 1; taskNdx >= 0; --taskNdx) {
             mTasks.get(taskNdx).close();
         }
+        mDisplayContent = null;
     }
 
     public void dump(String prefix, PrintWriter pw) {
diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java
index 9af5e14..5ec2137 100644
--- a/services/core/java/com/android/server/wm/WindowManagerService.java
+++ b/services/core/java/com/android/server/wm/WindowManagerService.java
@@ -3448,8 +3448,8 @@
         }
     }
 
-    private boolean applyAnimationLocked(AppWindowToken atoken,
-            WindowManager.LayoutParams lp, int transit, boolean enter, boolean isVoiceInteraction) {
+    private boolean applyAnimationLocked(AppWindowToken atoken, WindowManager.LayoutParams lp,
+            int transit, boolean enter, boolean isVoiceInteraction) {
         // Only apply an animation if the display isn't frozen.  If it is
         // frozen, there is no reason to animate and it can cause strange
         // artifacts when we unfreeze the display if some different animation
@@ -3466,24 +3466,36 @@
             Rect containingFrame = new Rect(0, 0, width, height);
             Rect contentInsets = new Rect();
             Rect appFrame = new Rect(0, 0, width, height);
-            if (win != null && win.isFullscreen(width, height)) {
-                // For fullscreen windows use the window frames and insets to set the thumbnail
-                // clip. For none-fullscreen windows we use the app display region so the clip
-                // isn't affected by the window insets.
+            Rect surfaceInsets = null;
+            final boolean fullscreen = win != null && win.isFullscreen(width, height);
+            // Dialog activities have windows with containing frame being very large, but not
+            // exactly fullscreen and much smaller mFrame. We use this distinction to identify
+            // dialog activities.
+            final boolean dialogWindow = win != null && !win.mContainingFrame.equals(win.mFrame);
+            if (win != null) {
                 containingFrame.set(win.mContainingFrame);
-                contentInsets.set(win.mContentInsets);
-                appFrame.set(win.mFrame);
+                surfaceInsets = win.getAttrs().surfaceInsets;
+                if (fullscreen) {
+                    // For fullscreen windows use the window frames and insets to set the thumbnail
+                    // clip. For none-fullscreen windows we use the app display region so the clip
+                    // isn't affected by the window insets.
+                    contentInsets.set(win.mContentInsets);
+                    appFrame.set(win.mFrame);
+                }
             }
 
+            final int containingWidth = containingFrame.width();
+            final int containingHeight = containingFrame.height();
             if (atoken.mLaunchTaskBehind) {
                 // Differentiate the two animations. This one which is briefly on the screen
                 // gets the !enter animation, and the other activity which remains on the
                 // screen gets the enter animation. Both appear in the mOpeningApps set.
                 enter = false;
             }
-            Animation a = mAppTransition.loadAnimation(lp, transit, enter, width, height,
-                    mCurConfiguration.orientation, containingFrame, contentInsets, appFrame,
-                    isVoiceInteraction);
+            final boolean resizedWindow = !fullscreen && !dialogWindow;
+            Animation a = mAppTransition.loadAnimation(lp, transit, enter, containingWidth,
+                    containingHeight, mCurConfiguration.orientation, containingFrame, contentInsets,
+                    surfaceInsets, appFrame, isVoiceInteraction, resizedWindow);
             if (a != null) {
                 if (DEBUG_ANIM) {
                     RuntimeException e = null;
@@ -3493,7 +3505,7 @@
                     }
                     Slog.v(TAG, "Loaded animation " + a + " for " + atoken, e);
                 }
-                atoken.mAppAnimator.setAnimation(a, width, height,
+                atoken.mAppAnimator.setAnimation(a, containingWidth, containingHeight,
                         mAppTransition.canSkipFirstFrame());
             }
         } else {
@@ -9533,7 +9545,7 @@
                         // open/close animation (only on the way down)
                         anim = mAppTransition.createThumbnailAspectScaleAnimationLocked(
                                 displayInfo.appWidth, displayInfo.appHeight,
-                                displayInfo.logicalWidth, transit);
+                                displayInfo.logicalWidth);
                         openingAppAnimator.thumbnailForceAboveLayer = Math.max(topOpeningLayer,
                                 topClosingLayer);
                         openingAppAnimator.deferThumbnailDestruction =
diff --git a/services/core/java/com/android/server/wm/WindowStateAnimator.java b/services/core/java/com/android/server/wm/WindowStateAnimator.java
index 48f2a9d..5d33cbd 100644
--- a/services/core/java/com/android/server/wm/WindowStateAnimator.java
+++ b/services/core/java/com/android/server/wm/WindowStateAnimator.java
@@ -1090,7 +1090,6 @@
             if (selfTransformation) {
                 tmpMatrix.postConcat(mTransformation.getMatrix());
             }
-            tmpMatrix.postTranslate(frame.left + mWin.mXOffset, frame.top + mWin.mYOffset);
             if (attachedTransformation != null) {
                 tmpMatrix.postConcat(attachedTransformation.getMatrix());
             }
@@ -1100,6 +1099,10 @@
             if (screenAnimation) {
                 tmpMatrix.postConcat(screenRotationAnimation.getEnterTransformation().getMatrix());
             }
+            // The translation that applies the position of the window needs to be applied at the
+            // end in case that other translations include scaling. Otherwise the scaling will
+            // affect this translation.
+            tmpMatrix.postTranslate(frame.left + mWin.mXOffset, frame.top + mWin.mYOffset);
 
             //TODO (multidisplay): Magnification is supported only for the default display.
             if (mService.mAccessibilityController != null && displayId == Display.DEFAULT_DISPLAY) {
diff --git a/services/java/com/android/server/SystemServer.java b/services/java/com/android/server/SystemServer.java
index 6e6c71f..ed32c76 100644
--- a/services/java/com/android/server/SystemServer.java
+++ b/services/java/com/android/server/SystemServer.java
@@ -96,6 +96,7 @@
 import dalvik.system.VMRuntime;
 
 import java.io.File;
+import java.util.Locale;
 import java.util.Timer;
 import java.util.TimerTask;
 
@@ -183,6 +184,23 @@
             SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
         }
 
+        // If the system has "persist.sys.language" and friends set, replace them with
+        // "persist.sys.locale". Note that the default locale at this point is calculated
+        // using the "-Duser.locale" command line flag. That flag is usually populated by
+        // AndroidRuntime using the same set of system properties, but only the system_server
+        // and system apps are allowed to set them.
+        //
+        // NOTE: Most changes made here will need an equivalent change to
+        // core/jni/AndroidRuntime.cpp
+        if (!SystemProperties.get("persist.sys.language").isEmpty()) {
+            final String languageTag = Locale.getDefault().toLanguageTag();
+
+            SystemProperties.set("persist.sys.locale", languageTag);
+            SystemProperties.set("persist.sys.language", "");
+            SystemProperties.set("persist.sys.country", "");
+            SystemProperties.set("persist.sys.localevar", "");
+        }
+
         // Here we go!
         Slog.i(TAG, "Entered the Android system server!");
         EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, SystemClock.uptimeMillis());
diff --git a/services/net/java/android/net/dhcp/DhcpClient.java b/services/net/java/android/net/dhcp/DhcpClient.java
index 2d40291..9ee9cf4 100644
--- a/services/net/java/android/net/dhcp/DhcpClient.java
+++ b/services/net/java/android/net/dhcp/DhcpClient.java
@@ -603,7 +603,10 @@
         @Override
         public void exit() {
             cancelOneshotTimeout();
-            mReceiveThread.halt();  // Also closes sockets.
+            if (mReceiveThread != null) {
+                mReceiveThread.halt();  // Also closes sockets.
+                mReceiveThread = null;
+            }
             clearDhcpState();
         }
 
diff --git a/telecomm/java/android/telecom/DefaultDialerManager.java b/telecomm/java/android/telecom/DefaultDialerManager.java
index 3d49308..5852b8e 100644
--- a/telecomm/java/android/telecom/DefaultDialerManager.java
+++ b/telecomm/java/android/telecom/DefaultDialerManager.java
@@ -97,7 +97,7 @@
      * @hide
      * */
     public static String getDefaultDialerApplication(Context context) {
-        return getDefaultDialerApplication(context, ActivityManager.getCurrentUser());
+        return getDefaultDialerApplication(context, context.getUserId());
     }
 
     /**
diff --git a/telephony/java/android/telephony/CarrierConfigManager.java b/telephony/java/android/telephony/CarrierConfigManager.java
index b5e4342..3054422 100644
--- a/telephony/java/android/telephony/CarrierConfigManager.java
+++ b/telephony/java/android/telephony/CarrierConfigManager.java
@@ -342,6 +342,14 @@
             "ci_action_on_sys_update_extra_val_string";
 
     /**
+     * Specifies the amount of gap to be added in millis between DTMF tones. When a non-zero value
+     * is specified, the UE shall wait for the specified amount of time before it sends out
+     * successive DTMF tones on the network.
+     * @hide
+     */
+    public static final String KEY_IMS_DTMF_TONE_DELAY_INT = "ims_dtmf_tone_delay_int";
+
+    /**
      * If this is true, the SIM card (through Customer Service Profile EF file) will be able to
      * prevent manual operator selection. If false, this SIM setting will be ignored and manual
      * operator selection will always be available. See CPHS4_2.WW6, CPHS B.4.7.1 for more
@@ -439,6 +447,7 @@
         sDefaults.putStringArray(KEY_CDMA_ROAMING_NETWORKS_STRING_ARRAY, null);
         sDefaults.putStringArray(KEY_CDMA_NONROAMING_NETWORKS_STRING_ARRAY, null);
         sDefaults.putBoolean(KEY_FORCE_HOME_NETWORK_BOOL, false);
+        sDefaults.putInt(KEY_IMS_DTMF_TONE_DELAY_INT, 0);
 
         // MMS defaults
         sDefaults.putBoolean(KEY_MMS_ALIAS_ENABLED_BOOL, false);
diff --git a/telephony/java/android/telephony/ServiceState.java b/telephony/java/android/telephony/ServiceState.java
index 303a492..80515cf 100644
--- a/telephony/java/android/telephony/ServiceState.java
+++ b/telephony/java/android/telephony/ServiceState.java
@@ -220,6 +220,8 @@
     private int mCdmaEriIconIndex;
     private int mCdmaEriIconMode;
 
+    private boolean mIsDataRoamingFromRegistration;
+
     /**
      * get String description of roaming type
      * @hide
@@ -297,6 +299,7 @@
         mCdmaEriIconIndex = s.mCdmaEriIconIndex;
         mCdmaEriIconMode = s.mCdmaEriIconMode;
         mIsEmergencyOnly = s.mIsEmergencyOnly;
+        mIsDataRoamingFromRegistration = s.mIsDataRoamingFromRegistration;
     }
 
     /**
@@ -324,6 +327,7 @@
         mCdmaEriIconIndex = in.readInt();
         mCdmaEriIconMode = in.readInt();
         mIsEmergencyOnly = in.readInt() != 0;
+        mIsDataRoamingFromRegistration = in.readInt() != 0;
     }
 
     public void writeToParcel(Parcel out, int flags) {
@@ -348,6 +352,7 @@
         out.writeInt(mCdmaEriIconIndex);
         out.writeInt(mCdmaEriIconMode);
         out.writeInt(mIsEmergencyOnly ? 1 : 0);
+        out.writeInt(mIsDataRoamingFromRegistration ? 1 : 0);
     }
 
     public int describeContents() {
@@ -439,6 +444,26 @@
     }
 
     /**
+     * Set whether data network registration state is roaming
+     *
+     * This should only be set to the roaming value received
+     * once the data registration phase has completed.
+     * @hide
+     */
+    public void setDataRoamingFromRegistration(boolean dataRoaming) {
+        mIsDataRoamingFromRegistration = dataRoaming;
+    }
+
+    /**
+     * Get whether data network registration state is roaming
+     * @return true if registration indicates roaming, false otherwise
+     * @hide
+     */
+    public boolean getDataRoamingFromRegistration() {
+        return mIsDataRoamingFromRegistration;
+    }
+
+    /**
      * Get current data network roaming type
      * @return roaming type
      * @hide
@@ -599,7 +624,8 @@
                 + ((null == mDataOperatorNumeric) ? 0 : mDataOperatorNumeric.hashCode())
                 + mCdmaRoamingIndicator
                 + mCdmaDefaultRoamingIndicator
-                + (mIsEmergencyOnly ? 1 : 0));
+                + (mIsEmergencyOnly ? 1 : 0)
+                + (mIsDataRoamingFromRegistration ? 1 : 0));
     }
 
     @Override
@@ -635,7 +661,8 @@
                 && equalsHandlesNulls(mCdmaRoamingIndicator, s.mCdmaRoamingIndicator)
                 && equalsHandlesNulls(mCdmaDefaultRoamingIndicator,
                         s.mCdmaDefaultRoamingIndicator)
-                && mIsEmergencyOnly == s.mIsEmergencyOnly);
+                && mIsEmergencyOnly == s.mIsEmergencyOnly
+                && mIsDataRoamingFromRegistration == s.mIsDataRoamingFromRegistration);
     }
 
     /**
@@ -736,7 +763,8 @@
                 + " " + mSystemId
                 + " RoamInd=" + mCdmaRoamingIndicator
                 + " DefRoamInd=" + mCdmaDefaultRoamingIndicator
-                + " EmergOnly=" + mIsEmergencyOnly);
+                + " EmergOnly=" + mIsEmergencyOnly
+                + " IsDataRoamingFromRegistration=" + mIsDataRoamingFromRegistration);
     }
 
     private void setNullState(int state) {
@@ -762,6 +790,7 @@
         mCdmaEriIconIndex = -1;
         mCdmaEriIconMode = -1;
         mIsEmergencyOnly = false;
+        mIsDataRoamingFromRegistration = false;
     }
 
     public void setStateOutOfService() {
@@ -934,6 +963,7 @@
         mCdmaRoamingIndicator = m.getInt("cdmaRoamingIndicator");
         mCdmaDefaultRoamingIndicator = m.getInt("cdmaDefaultRoamingIndicator");
         mIsEmergencyOnly = m.getBoolean("emergencyOnly");
+        mIsDataRoamingFromRegistration = m.getBoolean("isDataRoamingFromRegistration");
     }
 
     /**
@@ -962,6 +992,7 @@
         m.putInt("cdmaRoamingIndicator", mCdmaRoamingIndicator);
         m.putInt("cdmaDefaultRoamingIndicator", mCdmaDefaultRoamingIndicator);
         m.putBoolean("emergencyOnly", Boolean.valueOf(mIsEmergencyOnly));
+        m.putBoolean("isDataRoamingFromRegistration", Boolean.valueOf(mIsDataRoamingFromRegistration));
     }
 
     /** @hide */
diff --git a/telephony/java/android/telephony/TelephonyManager.java b/telephony/java/android/telephony/TelephonyManager.java
index 88612e9..e104b38 100644
--- a/telephony/java/android/telephony/TelephonyManager.java
+++ b/telephony/java/android/telephony/TelephonyManager.java
@@ -602,6 +602,46 @@
     public static final String EXTRA_DATA_FAILURE_CAUSE = PhoneConstants.DATA_FAILURE_CAUSE_KEY;
 
     /**
+     * Broadcast intent action for letting custom component know to show voicemail notification.
+     * @hide
+     */
+    @SystemApi
+    public static final String ACTION_SHOW_VOICEMAIL_NOTIFICATION =
+            "android.telephony.action.SHOW_VOICEMAIL_NOTIFICATION";
+
+    /**
+     * The number of voice messages associated with the notification.
+     * @hide
+     */
+    @SystemApi
+    public static final String EXTRA_NOTIFICATION_COUNT =
+            "android.telephony.extra.NOTIFICATION_COUNT";
+
+    /**
+     * The voicemail number.
+     * @hide
+     */
+    @SystemApi
+    public static final String EXTRA_VOICEMAIL_NUMBER =
+            "android.telephony.extra.VOICEMAIL_NUMBER";
+
+    /**
+     * The intent to call voicemail.
+     * @hide
+     */
+    @SystemApi
+    public static final String EXTRA_CALL_VOICEMAIL_INTENT =
+            "android.telephony.extra.CALL_VOICEMAIL_INTENT";
+
+    /**
+     * The intent to launch voicemail settings.
+     * @hide
+     */
+    @SystemApi
+    public static final String EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT =
+            "android.telephony.extra.LAUNCH_VOICEMAIL_SETTINGS_INTENT";
+
+    /**
      * Response codes for sim activation. Activation completed successfully.
      * @hide
      */
diff --git a/tests/VoiceInteraction/AndroidManifest.xml b/tests/VoiceInteraction/AndroidManifest.xml
index 36d5d98..fe17c6e 100644
--- a/tests/VoiceInteraction/AndroidManifest.xml
+++ b/tests/VoiceInteraction/AndroidManifest.xml
@@ -2,6 +2,7 @@
         package="com.android.test.voiceinteraction">
 
     <uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" />
+    <uses-permission android:name="android.permission.READ_LOGS" />
 
     <application>
         <activity android:name="VoiceInteractionMain" android:label="Voice Interaction"
diff --git a/tools/aapt/Command.cpp b/tools/aapt/Command.cpp
index 8a0a39c..d12ab3b 100644
--- a/tools/aapt/Command.cpp
+++ b/tools/aapt/Command.cpp
@@ -215,7 +215,7 @@
             goto bail;
         }
 
-#ifdef HAVE_ANDROID_OS
+#ifdef __ANDROID__
         static const bool kHaveAndroidOs = true;
 #else
         static const bool kHaveAndroidOs = false;
@@ -633,7 +633,7 @@
     Asset* asset = NULL;
 
     if (strcmp("resources", option) == 0) {
-#ifndef HAVE_ANDROID_OS
+#ifndef __ANDROID__
         res.print(bundle->getValues());
 #endif
 
diff --git a/tools/aapt2/XmlDom.cpp b/tools/aapt2/XmlDom.cpp
index 763029f..b8b2d12 100644
--- a/tools/aapt2/XmlDom.cpp
+++ b/tools/aapt2/XmlDom.cpp
@@ -312,7 +312,7 @@
             }
         }
     }
-    return std::move(root);
+    return root;
 }
 
 Node::Node(NodeType type) : type(type), parent(nullptr), lineNumber(0), columnNumber(0) {
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/DelegateManager.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/DelegateManager.java
index 47258b6..baf2e2e 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/DelegateManager.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/DelegateManager.java
@@ -97,13 +97,13 @@
      * @return the delegate or null if not found.
      */
     @Nullable
-    public T getDelegate(long native_object) {
+    public synchronized T getDelegate(long native_object) {
         if (native_object > 0) {
-            T delegate =  mDelegates.get(native_object);
+            T delegate = mDelegates.get(native_object);
 
             if (Debug.DEBUG) {
                 if (delegate == null) {
-                    System.out.println("Unknown " + mClass.getSimpleName() + " with int " +
+                    System.err.println("Unknown " + mClass.getSimpleName() + " with int " +
                             native_object);
                 }
             }
@@ -119,14 +119,18 @@
      * @param newDelegate the delegate to add
      * @return a unique native int to identify the delegate
      */
-    public long addNewDelegate(T newDelegate) {
+    public synchronized long addNewDelegate(T newDelegate) {
         long native_object = ++mDelegateCounter;
+
         mDelegates.put(native_object, newDelegate);
         assert !mJavaReferences.contains(newDelegate);
         mJavaReferences.add(newDelegate);
 
         if (Debug.DEBUG) {
-            System.out.println("New " + mClass.getSimpleName() + " with int " + native_object);
+            System.out.println(
+                    "New " + mClass.getSimpleName() + " " +
+                            "with int " +
+                            native_object);
         }
 
         return native_object;
@@ -136,7 +140,7 @@
      * Removes the main reference on the given delegate.
      * @param native_object the native integer representing the delegate.
      */
-    public void removeJavaReferenceFor(long native_object) {
+    public synchronized void removeJavaReferenceFor(long native_object) {
         T delegate = getDelegate(native_object);
 
         if (Debug.DEBUG) {