Merge "Trigger power hints for activity launch" into nyc-mr1-dev
diff --git a/api/current.txt b/api/current.txt
index 35514f2..01aa843 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -1107,6 +1107,15 @@
     field public static final int shareInterpolator = 16843195; // 0x10101bb
     field public static final int sharedUserId = 16842763; // 0x101000b
     field public static final int sharedUserLabel = 16843361; // 0x1010261
+    field public static final int shortcutCategories = 16844081; // 0x1010531
+    field public static final int shortcutDisabledMessage = 16844080; // 0x1010530
+    field public static final int shortcutIcon = 16844077; // 0x101052d
+    field public static final int shortcutId = 16844075; // 0x101052b
+    field public static final int shortcutIntentAction = 16844082; // 0x1010532
+    field public static final int shortcutIntentData = 16844083; // 0x1010533
+    field public static final int shortcutRank = 16844076; // 0x101052c
+    field public static final int shortcutText = 16844079; // 0x101052f
+    field public static final int shortcutTitle = 16844078; // 0x101052e
     field public static final int shouldDisableView = 16843246; // 0x10101ee
     field public static final int showAsAction = 16843481; // 0x10102d9
     field public static final int showDefault = 16843258; // 0x10101fa
@@ -9502,8 +9511,8 @@
 
   public class LauncherApps {
     method public java.util.List<android.content.pm.LauncherActivityInfo> getActivityList(java.lang.String, android.os.UserHandle);
-    method public android.graphics.drawable.Drawable getShortcutBadgedIconDrawable(int);
-    method public android.graphics.drawable.Drawable getShortcutIconDrawable(int);
+    method public android.graphics.drawable.Drawable getShortcutBadgedIconDrawable(android.content.pm.ShortcutInfo, int);
+    method public android.graphics.drawable.Drawable getShortcutIconDrawable(android.content.pm.ShortcutInfo, int);
     method public android.os.ParcelFileDescriptor getShortcutIconFd(android.content.pm.ShortcutInfo);
     method public android.os.ParcelFileDescriptor getShortcutIconFd(java.lang.String, java.lang.String, android.os.UserHandle);
     method public java.util.List<android.content.pm.ShortcutInfo> getShortcuts(android.content.pm.LauncherApps.ShortcutQuery, android.os.UserHandle);
@@ -9535,13 +9544,14 @@
 
   public static class LauncherApps.ShortcutQuery {
     ctor public LauncherApps.ShortcutQuery();
-    method public void setActivity(android.content.ComponentName);
-    method public void setChangedSince(long);
-    method public void setPackage(java.lang.String);
-    method public void setQueryFlags(int);
-    method public void setShortcutIds(java.util.List<java.lang.String>);
+    method public android.content.pm.LauncherApps.ShortcutQuery setActivity(android.content.ComponentName);
+    method public android.content.pm.LauncherApps.ShortcutQuery setChangedSince(long);
+    method public android.content.pm.LauncherApps.ShortcutQuery setPackage(java.lang.String);
+    method public android.content.pm.LauncherApps.ShortcutQuery setQueryFlags(int);
+    method public android.content.pm.LauncherApps.ShortcutQuery setShortcutIds(java.util.List<java.lang.String>);
     field public static final int FLAG_GET_DYNAMIC = 1; // 0x1
     field public static final int FLAG_GET_KEY_FIELDS_ONLY = 4; // 0x4
+    field public static final int FLAG_GET_MANIFEST = 8; // 0x8
     field public static final int FLAG_GET_PINNED = 2; // 0x2
   }
 
@@ -10045,29 +10055,30 @@
 
   public final class ShortcutInfo implements android.os.Parcelable {
     method public int describeContents();
-    method public android.content.ComponentName getActivityComponent();
+    method public android.content.ComponentName getActivity();
     method public java.util.Set<java.lang.String> getCategories();
-    method public java.lang.String getDisabledMessage();
+    method public java.lang.CharSequence getDisabledMessage();
     method public int getDisabledMessageResId();
     method public android.os.PersistableBundle getExtras();
     method public int getIconResourceId();
     method public java.lang.String getId();
     method public android.content.Intent getIntent();
     method public long getLastChangedTimestamp();
-    method public java.lang.String getPackageName();
+    method public java.lang.String getPackage();
     method public int getRank();
-    method public java.lang.String getText();
+    method public java.lang.CharSequence getText();
     method public int getTextResId();
-    method public java.lang.String getTitle();
+    method public java.lang.CharSequence getTitle();
     method public int getTitleResId();
     method public android.os.UserHandle getUserHandle();
     method public boolean hasIconFile();
     method public boolean hasIconResource();
     method public boolean hasKeyFieldsOnly();
     method public boolean hasStringResourcesResolved();
-    method public boolean isDisabled();
     method public boolean isDynamic();
-    method public boolean isFromManifest();
+    method public boolean isEnabled();
+    method public boolean isImmutable();
+    method public boolean isManifestShortcut();
     method public boolean isPinned();
     method public void writeToParcel(android.os.Parcel, int);
     field public static final int CLONE_REMOVE_FOR_CREATOR = 1; // 0x1
@@ -10076,10 +10087,11 @@
     field public static final android.os.Parcelable.Creator<android.content.pm.ShortcutInfo> CREATOR;
     field public static final int FLAG_DISABLED = 64; // 0x40
     field public static final int FLAG_DYNAMIC = 1; // 0x1
-    field public static final int FLAG_FROM_MANIFEST = 32; // 0x20
     field public static final int FLAG_HAS_ICON_FILE = 8; // 0x8
     field public static final int FLAG_HAS_ICON_RES = 4; // 0x4
+    field public static final int FLAG_IMMUTABLE = 256; // 0x100
     field public static final int FLAG_KEY_FIELDS_ONLY = 16; // 0x10
+    field public static final int FLAG_MANIFEST = 32; // 0x20
     field public static final int FLAG_PINNED = 2; // 0x2
     field public static final int FLAG_STRINGS_RESOLVED = 128; // 0x80
     field public static final java.lang.String SHORTCUT_CATEGORY_CONVERSATION = "android.shortcut.conversation";
@@ -10088,19 +10100,16 @@
   public static class ShortcutInfo.Builder {
     ctor public ShortcutInfo.Builder(android.content.Context);
     method public android.content.pm.ShortcutInfo build();
-    method public android.content.pm.ShortcutInfo.Builder setActivityComponent(android.content.ComponentName);
+    method public android.content.pm.ShortcutInfo.Builder setActivity(android.content.ComponentName);
     method public android.content.pm.ShortcutInfo.Builder setCategories(java.util.Set<java.lang.String>);
     method public android.content.pm.ShortcutInfo.Builder setDisabledMessage(java.lang.String);
-    method public android.content.pm.ShortcutInfo.Builder setDisabledMessageResId(int);
     method public android.content.pm.ShortcutInfo.Builder setExtras(android.os.PersistableBundle);
     method public android.content.pm.ShortcutInfo.Builder setIcon(android.graphics.drawable.Icon);
     method public android.content.pm.ShortcutInfo.Builder setId(java.lang.String);
     method public android.content.pm.ShortcutInfo.Builder setIntent(android.content.Intent);
     method public android.content.pm.ShortcutInfo.Builder setRank(int);
     method public android.content.pm.ShortcutInfo.Builder setText(java.lang.String);
-    method public android.content.pm.ShortcutInfo.Builder setTextResId(int);
     method public android.content.pm.ShortcutInfo.Builder setTitle(java.lang.String);
-    method public android.content.pm.ShortcutInfo.Builder setTitleResId(int);
   }
 
   public class ShortcutManager {
@@ -10108,9 +10117,12 @@
     method public void disableShortcuts(java.util.List<java.lang.String>);
     method public void disableShortcuts(java.util.List<java.lang.String>, int);
     method public void disableShortcuts(java.util.List<java.lang.String>, java.lang.String);
+    method public void enableShortcuts(java.util.List<java.lang.String>);
     method public java.util.List<android.content.pm.ShortcutInfo> getDynamicShortcuts();
-    method public int getIconMaxDimensions();
-    method public int getMaxDynamicShortcutCount();
+    method public int getIconMaxHeight();
+    method public int getIconMaxWidth();
+    method public java.util.List<android.content.pm.ShortcutInfo> getManifestShortcuts();
+    method public int getMaxShortcutCountForActivity();
     method public java.util.List<android.content.pm.ShortcutInfo> getPinnedShortcuts();
     method public long getRateLimitResetTime();
     method public int getRemainingCallCount();
@@ -37365,70 +37377,48 @@
 
   public class TelephonyManager {
     method public boolean canChangeDtmfToneLength();
+    method public android.telephony.TelephonyManager createForSubscriptionId(int);
     method public java.util.List<android.telephony.CellInfo> getAllCellInfo();
     method public int getCallState();
-    method public int getCallState(int);
     method public android.telephony.CellLocation getCellLocation();
     method public int getDataActivity();
-    method public int getDataNetworkType(int);
+    method public int getDataNetworkType();
     method public int getDataState();
     method public java.lang.String getDeviceId();
     method public java.lang.String getDeviceId(int);
     method public java.lang.String getDeviceSoftwareVersion();
     method public java.lang.String getGroupIdLevel1();
-    method public java.lang.String getGroupIdLevel1(int);
     method public java.lang.String getIccAuthentication(int, int, java.lang.String);
-    method public java.lang.String getIccAuthentication(int, int, int, java.lang.String);
-    method public java.lang.String getLine1AlphaTag(int);
     method public java.lang.String getLine1Number();
-    method public java.lang.String getLine1Number(int);
     method public java.lang.String getMmsUAProfUrl();
     method public java.lang.String getMmsUserAgent();
     method public deprecated java.util.List<android.telephony.NeighboringCellInfo> getNeighboringCellInfo();
     method public java.lang.String getNetworkCountryIso();
-    method public java.lang.String getNetworkCountryIso(int);
     method public java.lang.String getNetworkOperator();
-    method public java.lang.String getNetworkOperator(int);
     method public java.lang.String getNetworkOperatorName();
-    method public java.lang.String getNetworkOperatorName(int);
     method public int getNetworkType();
-    method public int getNetworkType(int);
     method public int getPhoneCount();
     method public int getPhoneType();
     method public java.lang.String getSimCountryIso();
-    method public java.lang.String getSimCountryIso(int);
     method public java.lang.String getSimOperator();
-    method public java.lang.String getSimOperator(int);
     method public java.lang.String getSimOperatorName();
-    method public java.lang.String getSimOperatorName(int);
     method public java.lang.String getSimSerialNumber();
-    method public java.lang.String getSimSerialNumber(int);
     method public int getSimState();
     method public java.lang.String getSubscriberId();
-    method public java.lang.String getSubscriberId(int);
     method public java.util.List<android.telephony.TelephonyHistogram> getTelephonyHistograms();
     method public java.lang.String getVoiceMailAlphaTag();
-    method public java.lang.String getVoiceMailAlphaTag(int);
     method public java.lang.String getVoiceMailNumber();
-    method public java.lang.String getVoiceMailNumber(int);
-    method public int getVoiceNetworkType(int);
+    method public int getVoiceNetworkType();
     method public android.net.Uri getVoicemailRingtoneUri(android.telecom.PhoneAccountHandle);
     method public boolean hasCarrierPrivileges();
-    method public boolean hasCarrierPrivileges(int);
     method public boolean hasIccCard();
     method public boolean iccCloseLogicalChannel(int);
-    method public boolean iccCloseLogicalChannel(int, int);
     method public byte[] iccExchangeSimIO(int, int, int, int, int, java.lang.String);
-    method public byte[] iccExchangeSimIO(int, int, int, int, int, int, java.lang.String);
     method public android.telephony.IccOpenLogicalChannelResponse iccOpenLogicalChannel(java.lang.String);
-    method public android.telephony.IccOpenLogicalChannelResponse iccOpenLogicalChannel(int, java.lang.String);
     method public java.lang.String iccTransmitApduBasicChannel(int, int, int, int, int, java.lang.String);
-    method public java.lang.String iccTransmitApduBasicChannel(int, int, int, int, int, int, java.lang.String);
     method public java.lang.String iccTransmitApduLogicalChannel(int, int, int, int, int, int, java.lang.String);
-    method public java.lang.String iccTransmitApduLogicalChannel(int, int, int, int, int, int, int, java.lang.String);
     method public boolean isHearingAidCompatibilitySupported();
     method public boolean isNetworkRoaming();
-    method public boolean isNetworkRoaming(int);
     method public boolean isSmsCapable();
     method public boolean isTtyModeSupported();
     method public boolean isVoiceCapable();
@@ -37436,15 +37426,10 @@
     method public boolean isWorldPhone();
     method public void listen(android.telephony.PhoneStateListener, int);
     method public java.lang.String sendEnvelopeWithStatus(java.lang.String);
-    method public java.lang.String sendEnvelopeWithStatus(int, java.lang.String);
     method public boolean setLine1NumberForDisplay(java.lang.String, java.lang.String);
-    method public boolean setLine1NumberForDisplay(int, java.lang.String, java.lang.String);
     method public boolean setOperatorBrandOverride(java.lang.String);
-    method public boolean setOperatorBrandOverride(int, java.lang.String);
     method public boolean setPreferredNetworkTypeToGlobal();
-    method public boolean setPreferredNetworkTypeToGlobal(int);
     method public boolean setVoiceMailNumber(java.lang.String, java.lang.String);
-    method public boolean setVoiceMailNumber(int, java.lang.String, java.lang.String);
     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";
diff --git a/api/system-current.txt b/api/system-current.txt
index 1e4722d..c18b916 100644
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -1217,6 +1217,15 @@
     field public static final int shareInterpolator = 16843195; // 0x10101bb
     field public static final int sharedUserId = 16842763; // 0x101000b
     field public static final int sharedUserLabel = 16843361; // 0x1010261
+    field public static final int shortcutCategories = 16844081; // 0x1010531
+    field public static final int shortcutDisabledMessage = 16844080; // 0x1010530
+    field public static final int shortcutIcon = 16844077; // 0x101052d
+    field public static final int shortcutId = 16844075; // 0x101052b
+    field public static final int shortcutIntentAction = 16844082; // 0x1010532
+    field public static final int shortcutIntentData = 16844083; // 0x1010533
+    field public static final int shortcutRank = 16844076; // 0x101052c
+    field public static final int shortcutText = 16844079; // 0x101052f
+    field public static final int shortcutTitle = 16844078; // 0x101052e
     field public static final int shouldDisableView = 16843246; // 0x10101ee
     field public static final int showAsAction = 16843481; // 0x10102d9
     field public static final int showDefault = 16843258; // 0x10101fa
@@ -9855,8 +9864,8 @@
 
   public class LauncherApps {
     method public java.util.List<android.content.pm.LauncherActivityInfo> getActivityList(java.lang.String, android.os.UserHandle);
-    method public android.graphics.drawable.Drawable getShortcutBadgedIconDrawable(int);
-    method public android.graphics.drawable.Drawable getShortcutIconDrawable(int);
+    method public android.graphics.drawable.Drawable getShortcutBadgedIconDrawable(android.content.pm.ShortcutInfo, int);
+    method public android.graphics.drawable.Drawable getShortcutIconDrawable(android.content.pm.ShortcutInfo, int);
     method public android.os.ParcelFileDescriptor getShortcutIconFd(android.content.pm.ShortcutInfo);
     method public android.os.ParcelFileDescriptor getShortcutIconFd(java.lang.String, java.lang.String, android.os.UserHandle);
     method public java.util.List<android.content.pm.ShortcutInfo> getShortcuts(android.content.pm.LauncherApps.ShortcutQuery, android.os.UserHandle);
@@ -9888,13 +9897,14 @@
 
   public static class LauncherApps.ShortcutQuery {
     ctor public LauncherApps.ShortcutQuery();
-    method public void setActivity(android.content.ComponentName);
-    method public void setChangedSince(long);
-    method public void setPackage(java.lang.String);
-    method public void setQueryFlags(int);
-    method public void setShortcutIds(java.util.List<java.lang.String>);
+    method public android.content.pm.LauncherApps.ShortcutQuery setActivity(android.content.ComponentName);
+    method public android.content.pm.LauncherApps.ShortcutQuery setChangedSince(long);
+    method public android.content.pm.LauncherApps.ShortcutQuery setPackage(java.lang.String);
+    method public android.content.pm.LauncherApps.ShortcutQuery setQueryFlags(int);
+    method public android.content.pm.LauncherApps.ShortcutQuery setShortcutIds(java.util.List<java.lang.String>);
     field public static final int FLAG_GET_DYNAMIC = 1; // 0x1
     field public static final int FLAG_GET_KEY_FIELDS_ONLY = 4; // 0x4
+    field public static final int FLAG_GET_MANIFEST = 8; // 0x8
     field public static final int FLAG_GET_PINNED = 2; // 0x2
   }
 
@@ -10468,29 +10478,30 @@
 
   public final class ShortcutInfo implements android.os.Parcelable {
     method public int describeContents();
-    method public android.content.ComponentName getActivityComponent();
+    method public android.content.ComponentName getActivity();
     method public java.util.Set<java.lang.String> getCategories();
-    method public java.lang.String getDisabledMessage();
+    method public java.lang.CharSequence getDisabledMessage();
     method public int getDisabledMessageResId();
     method public android.os.PersistableBundle getExtras();
     method public int getIconResourceId();
     method public java.lang.String getId();
     method public android.content.Intent getIntent();
     method public long getLastChangedTimestamp();
-    method public java.lang.String getPackageName();
+    method public java.lang.String getPackage();
     method public int getRank();
-    method public java.lang.String getText();
+    method public java.lang.CharSequence getText();
     method public int getTextResId();
-    method public java.lang.String getTitle();
+    method public java.lang.CharSequence getTitle();
     method public int getTitleResId();
     method public android.os.UserHandle getUserHandle();
     method public boolean hasIconFile();
     method public boolean hasIconResource();
     method public boolean hasKeyFieldsOnly();
     method public boolean hasStringResourcesResolved();
-    method public boolean isDisabled();
     method public boolean isDynamic();
-    method public boolean isFromManifest();
+    method public boolean isEnabled();
+    method public boolean isImmutable();
+    method public boolean isManifestShortcut();
     method public boolean isPinned();
     method public void writeToParcel(android.os.Parcel, int);
     field public static final int CLONE_REMOVE_FOR_CREATOR = 1; // 0x1
@@ -10499,10 +10510,11 @@
     field public static final android.os.Parcelable.Creator<android.content.pm.ShortcutInfo> CREATOR;
     field public static final int FLAG_DISABLED = 64; // 0x40
     field public static final int FLAG_DYNAMIC = 1; // 0x1
-    field public static final int FLAG_FROM_MANIFEST = 32; // 0x20
     field public static final int FLAG_HAS_ICON_FILE = 8; // 0x8
     field public static final int FLAG_HAS_ICON_RES = 4; // 0x4
+    field public static final int FLAG_IMMUTABLE = 256; // 0x100
     field public static final int FLAG_KEY_FIELDS_ONLY = 16; // 0x10
+    field public static final int FLAG_MANIFEST = 32; // 0x20
     field public static final int FLAG_PINNED = 2; // 0x2
     field public static final int FLAG_STRINGS_RESOLVED = 128; // 0x80
     field public static final java.lang.String SHORTCUT_CATEGORY_CONVERSATION = "android.shortcut.conversation";
@@ -10511,19 +10523,16 @@
   public static class ShortcutInfo.Builder {
     ctor public ShortcutInfo.Builder(android.content.Context);
     method public android.content.pm.ShortcutInfo build();
-    method public android.content.pm.ShortcutInfo.Builder setActivityComponent(android.content.ComponentName);
+    method public android.content.pm.ShortcutInfo.Builder setActivity(android.content.ComponentName);
     method public android.content.pm.ShortcutInfo.Builder setCategories(java.util.Set<java.lang.String>);
     method public android.content.pm.ShortcutInfo.Builder setDisabledMessage(java.lang.String);
-    method public android.content.pm.ShortcutInfo.Builder setDisabledMessageResId(int);
     method public android.content.pm.ShortcutInfo.Builder setExtras(android.os.PersistableBundle);
     method public android.content.pm.ShortcutInfo.Builder setIcon(android.graphics.drawable.Icon);
     method public android.content.pm.ShortcutInfo.Builder setId(java.lang.String);
     method public android.content.pm.ShortcutInfo.Builder setIntent(android.content.Intent);
     method public android.content.pm.ShortcutInfo.Builder setRank(int);
     method public android.content.pm.ShortcutInfo.Builder setText(java.lang.String);
-    method public android.content.pm.ShortcutInfo.Builder setTextResId(int);
     method public android.content.pm.ShortcutInfo.Builder setTitle(java.lang.String);
-    method public android.content.pm.ShortcutInfo.Builder setTitleResId(int);
   }
 
   public class ShortcutManager {
@@ -10531,9 +10540,12 @@
     method public void disableShortcuts(java.util.List<java.lang.String>);
     method public void disableShortcuts(java.util.List<java.lang.String>, int);
     method public void disableShortcuts(java.util.List<java.lang.String>, java.lang.String);
+    method public void enableShortcuts(java.util.List<java.lang.String>);
     method public java.util.List<android.content.pm.ShortcutInfo> getDynamicShortcuts();
-    method public int getIconMaxDimensions();
-    method public int getMaxDynamicShortcutCount();
+    method public int getIconMaxHeight();
+    method public int getIconMaxWidth();
+    method public java.util.List<android.content.pm.ShortcutInfo> getManifestShortcuts();
+    method public int getMaxShortcutCountForActivity();
     method public java.util.List<android.content.pm.ShortcutInfo> getPinnedShortcuts();
     method public long getRateLimitResetTime();
     method public int getRemainingCallCount();
@@ -40302,6 +40314,7 @@
     method public boolean canChangeDtmfToneLength();
     method public int checkCarrierPrivilegesForPackage(java.lang.String);
     method public int checkCarrierPrivilegesForPackageAnyPhone(java.lang.String);
+    method public android.telephony.TelephonyManager createForSubscriptionId(int);
     method public void dial(java.lang.String);
     method public boolean disableDataConnectivity();
     method public boolean enableDataConnectivity();
@@ -40309,7 +40322,6 @@
     method public boolean endCall();
     method public java.util.List<android.telephony.CellInfo> getAllCellInfo();
     method public int getCallState();
-    method public int getCallState(int);
     method public java.util.List<java.lang.String> getCarrierPackageNamesForIntent(android.content.Intent);
     method public java.util.List<java.lang.String> getCarrierPackageNamesForIntentAndPhone(android.content.Intent, int);
     method public java.lang.String getCdmaMdn();
@@ -40322,69 +40334,47 @@
     method public int getDataActivity();
     method public boolean getDataEnabled();
     method public boolean getDataEnabled(int);
-    method public int getDataNetworkType(int);
+    method public int getDataNetworkType();
     method public int getDataState();
     method public java.lang.String getDeviceId();
     method public java.lang.String getDeviceId(int);
     method public java.lang.String getDeviceSoftwareVersion();
     method public java.lang.String getGroupIdLevel1();
-    method public java.lang.String getGroupIdLevel1(int);
     method public java.lang.String getIccAuthentication(int, int, java.lang.String);
-    method public java.lang.String getIccAuthentication(int, int, int, java.lang.String);
-    method public java.lang.String getLine1AlphaTag(int);
     method public java.lang.String getLine1Number();
-    method public java.lang.String getLine1Number(int);
     method public java.lang.String getMmsUAProfUrl();
     method public java.lang.String getMmsUserAgent();
     method public deprecated java.util.List<android.telephony.NeighboringCellInfo> getNeighboringCellInfo();
     method public java.lang.String getNetworkCountryIso();
-    method public java.lang.String getNetworkCountryIso(int);
     method public java.lang.String getNetworkOperator();
-    method public java.lang.String getNetworkOperator(int);
     method public java.lang.String getNetworkOperatorName();
-    method public java.lang.String getNetworkOperatorName(int);
     method public int getNetworkType();
-    method public int getNetworkType(int);
     method public int getPhoneCount();
     method public int getPhoneType();
     method public java.lang.String getSimCountryIso();
-    method public java.lang.String getSimCountryIso(int);
     method public java.lang.String getSimOperator();
-    method public java.lang.String getSimOperator(int);
     method public java.lang.String getSimOperatorName();
-    method public java.lang.String getSimOperatorName(int);
     method public java.lang.String getSimSerialNumber();
-    method public java.lang.String getSimSerialNumber(int);
     method public int getSimState();
     method public java.lang.String getSubscriberId();
-    method public java.lang.String getSubscriberId(int);
     method public java.util.List<android.telephony.TelephonyHistogram> getTelephonyHistograms();
     method public java.lang.String getVoiceMailAlphaTag();
-    method public java.lang.String getVoiceMailAlphaTag(int);
     method public java.lang.String getVoiceMailNumber();
-    method public java.lang.String getVoiceMailNumber(int);
-    method public int getVoiceNetworkType(int);
+    method public int getVoiceNetworkType();
     method public android.net.Uri getVoicemailRingtoneUri(android.telecom.PhoneAccountHandle);
     method public boolean handlePinMmi(java.lang.String);
     method public boolean handlePinMmiForSubscriber(int, java.lang.String);
     method public boolean hasCarrierPrivileges();
-    method public boolean hasCarrierPrivileges(int);
     method public boolean hasIccCard();
     method public boolean iccCloseLogicalChannel(int);
-    method public boolean iccCloseLogicalChannel(int, int);
     method public byte[] iccExchangeSimIO(int, int, int, int, int, java.lang.String);
-    method public byte[] iccExchangeSimIO(int, int, int, int, int, int, java.lang.String);
     method public android.telephony.IccOpenLogicalChannelResponse iccOpenLogicalChannel(java.lang.String);
-    method public android.telephony.IccOpenLogicalChannelResponse iccOpenLogicalChannel(int, java.lang.String);
     method public java.lang.String iccTransmitApduBasicChannel(int, int, int, int, int, java.lang.String);
-    method public java.lang.String iccTransmitApduBasicChannel(int, int, int, int, int, int, java.lang.String);
     method public java.lang.String iccTransmitApduLogicalChannel(int, int, int, int, int, int, java.lang.String);
-    method public java.lang.String iccTransmitApduLogicalChannel(int, int, int, int, int, int, int, java.lang.String);
     method public boolean isDataConnectivityPossible();
     method public boolean isHearingAidCompatibilitySupported();
     method public boolean isIdle();
     method public boolean isNetworkRoaming();
-    method public boolean isNetworkRoaming(int);
     method public boolean isOffhook();
     method public boolean isRadioOn();
     method public boolean isRinging();
@@ -40397,19 +40387,14 @@
     method public void listen(android.telephony.PhoneStateListener, int);
     method public boolean needsOtaServiceProvisioning();
     method public java.lang.String sendEnvelopeWithStatus(java.lang.String);
-    method public java.lang.String sendEnvelopeWithStatus(int, java.lang.String);
     method public void setDataEnabled(boolean);
     method public void setDataEnabled(int, boolean);
     method public boolean setLine1NumberForDisplay(java.lang.String, java.lang.String);
-    method public boolean setLine1NumberForDisplay(int, java.lang.String, java.lang.String);
     method public boolean setOperatorBrandOverride(java.lang.String);
-    method public boolean setOperatorBrandOverride(int, java.lang.String);
     method public boolean setPreferredNetworkTypeToGlobal();
-    method public boolean setPreferredNetworkTypeToGlobal(int);
     method public boolean setRadio(boolean);
     method public boolean setRadioPower(boolean);
     method public boolean setVoiceMailNumber(java.lang.String, java.lang.String);
-    method public boolean setVoiceMailNumber(int, java.lang.String, java.lang.String);
     method public void silenceRinger();
     method public boolean supplyPin(java.lang.String);
     method public int[] supplyPinReportResult(java.lang.String);
diff --git a/api/test-current.txt b/api/test-current.txt
index 6dc2e48..7de82b3 100644
--- a/api/test-current.txt
+++ b/api/test-current.txt
@@ -1107,6 +1107,15 @@
     field public static final int shareInterpolator = 16843195; // 0x10101bb
     field public static final int sharedUserId = 16842763; // 0x101000b
     field public static final int sharedUserLabel = 16843361; // 0x1010261
+    field public static final int shortcutCategories = 16844081; // 0x1010531
+    field public static final int shortcutDisabledMessage = 16844080; // 0x1010530
+    field public static final int shortcutIcon = 16844077; // 0x101052d
+    field public static final int shortcutId = 16844075; // 0x101052b
+    field public static final int shortcutIntentAction = 16844082; // 0x1010532
+    field public static final int shortcutIntentData = 16844083; // 0x1010533
+    field public static final int shortcutRank = 16844076; // 0x101052c
+    field public static final int shortcutText = 16844079; // 0x101052f
+    field public static final int shortcutTitle = 16844078; // 0x101052e
     field public static final int shouldDisableView = 16843246; // 0x10101ee
     field public static final int showAsAction = 16843481; // 0x10102d9
     field public static final int showDefault = 16843258; // 0x10101fa
@@ -9514,8 +9523,8 @@
   public class LauncherApps {
     ctor public LauncherApps(android.content.Context);
     method public java.util.List<android.content.pm.LauncherActivityInfo> getActivityList(java.lang.String, android.os.UserHandle);
-    method public android.graphics.drawable.Drawable getShortcutBadgedIconDrawable(int);
-    method public android.graphics.drawable.Drawable getShortcutIconDrawable(int);
+    method public android.graphics.drawable.Drawable getShortcutBadgedIconDrawable(android.content.pm.ShortcutInfo, int);
+    method public android.graphics.drawable.Drawable getShortcutIconDrawable(android.content.pm.ShortcutInfo, int);
     method public android.os.ParcelFileDescriptor getShortcutIconFd(android.content.pm.ShortcutInfo);
     method public android.os.ParcelFileDescriptor getShortcutIconFd(java.lang.String, java.lang.String, android.os.UserHandle);
     method public java.util.List<android.content.pm.ShortcutInfo> getShortcuts(android.content.pm.LauncherApps.ShortcutQuery, android.os.UserHandle);
@@ -9547,13 +9556,14 @@
 
   public static class LauncherApps.ShortcutQuery {
     ctor public LauncherApps.ShortcutQuery();
-    method public void setActivity(android.content.ComponentName);
-    method public void setChangedSince(long);
-    method public void setPackage(java.lang.String);
-    method public void setQueryFlags(int);
-    method public void setShortcutIds(java.util.List<java.lang.String>);
+    method public android.content.pm.LauncherApps.ShortcutQuery setActivity(android.content.ComponentName);
+    method public android.content.pm.LauncherApps.ShortcutQuery setChangedSince(long);
+    method public android.content.pm.LauncherApps.ShortcutQuery setPackage(java.lang.String);
+    method public android.content.pm.LauncherApps.ShortcutQuery setQueryFlags(int);
+    method public android.content.pm.LauncherApps.ShortcutQuery setShortcutIds(java.util.List<java.lang.String>);
     field public static final int FLAG_GET_DYNAMIC = 1; // 0x1
     field public static final int FLAG_GET_KEY_FIELDS_ONLY = 4; // 0x4
+    field public static final int FLAG_GET_MANIFEST = 8; // 0x8
     field public static final int FLAG_GET_PINNED = 2; // 0x2
   }
 
@@ -10058,29 +10068,30 @@
 
   public final class ShortcutInfo implements android.os.Parcelable {
     method public int describeContents();
-    method public android.content.ComponentName getActivityComponent();
+    method public android.content.ComponentName getActivity();
     method public java.util.Set<java.lang.String> getCategories();
-    method public java.lang.String getDisabledMessage();
+    method public java.lang.CharSequence getDisabledMessage();
     method public int getDisabledMessageResId();
     method public android.os.PersistableBundle getExtras();
     method public int getIconResourceId();
     method public java.lang.String getId();
     method public android.content.Intent getIntent();
     method public long getLastChangedTimestamp();
-    method public java.lang.String getPackageName();
+    method public java.lang.String getPackage();
     method public int getRank();
-    method public java.lang.String getText();
+    method public java.lang.CharSequence getText();
     method public int getTextResId();
-    method public java.lang.String getTitle();
+    method public java.lang.CharSequence getTitle();
     method public int getTitleResId();
     method public android.os.UserHandle getUserHandle();
     method public boolean hasIconFile();
     method public boolean hasIconResource();
     method public boolean hasKeyFieldsOnly();
     method public boolean hasStringResourcesResolved();
-    method public boolean isDisabled();
     method public boolean isDynamic();
-    method public boolean isFromManifest();
+    method public boolean isEnabled();
+    method public boolean isImmutable();
+    method public boolean isManifestShortcut();
     method public boolean isPinned();
     method public void writeToParcel(android.os.Parcel, int);
     field public static final int CLONE_REMOVE_FOR_CREATOR = 1; // 0x1
@@ -10089,10 +10100,11 @@
     field public static final android.os.Parcelable.Creator<android.content.pm.ShortcutInfo> CREATOR;
     field public static final int FLAG_DISABLED = 64; // 0x40
     field public static final int FLAG_DYNAMIC = 1; // 0x1
-    field public static final int FLAG_FROM_MANIFEST = 32; // 0x20
     field public static final int FLAG_HAS_ICON_FILE = 8; // 0x8
     field public static final int FLAG_HAS_ICON_RES = 4; // 0x4
+    field public static final int FLAG_IMMUTABLE = 256; // 0x100
     field public static final int FLAG_KEY_FIELDS_ONLY = 16; // 0x10
+    field public static final int FLAG_MANIFEST = 32; // 0x20
     field public static final int FLAG_PINNED = 2; // 0x2
     field public static final int FLAG_STRINGS_RESOLVED = 128; // 0x80
     field public static final java.lang.String SHORTCUT_CATEGORY_CONVERSATION = "android.shortcut.conversation";
@@ -10101,19 +10113,16 @@
   public static class ShortcutInfo.Builder {
     ctor public ShortcutInfo.Builder(android.content.Context);
     method public android.content.pm.ShortcutInfo build();
-    method public android.content.pm.ShortcutInfo.Builder setActivityComponent(android.content.ComponentName);
+    method public android.content.pm.ShortcutInfo.Builder setActivity(android.content.ComponentName);
     method public android.content.pm.ShortcutInfo.Builder setCategories(java.util.Set<java.lang.String>);
     method public android.content.pm.ShortcutInfo.Builder setDisabledMessage(java.lang.String);
-    method public android.content.pm.ShortcutInfo.Builder setDisabledMessageResId(int);
     method public android.content.pm.ShortcutInfo.Builder setExtras(android.os.PersistableBundle);
     method public android.content.pm.ShortcutInfo.Builder setIcon(android.graphics.drawable.Icon);
     method public android.content.pm.ShortcutInfo.Builder setId(java.lang.String);
     method public android.content.pm.ShortcutInfo.Builder setIntent(android.content.Intent);
     method public android.content.pm.ShortcutInfo.Builder setRank(int);
     method public android.content.pm.ShortcutInfo.Builder setText(java.lang.String);
-    method public android.content.pm.ShortcutInfo.Builder setTextResId(int);
     method public android.content.pm.ShortcutInfo.Builder setTitle(java.lang.String);
-    method public android.content.pm.ShortcutInfo.Builder setTitleResId(int);
   }
 
   public class ShortcutManager {
@@ -10122,9 +10131,12 @@
     method public void disableShortcuts(java.util.List<java.lang.String>);
     method public void disableShortcuts(java.util.List<java.lang.String>, int);
     method public void disableShortcuts(java.util.List<java.lang.String>, java.lang.String);
+    method public void enableShortcuts(java.util.List<java.lang.String>);
     method public java.util.List<android.content.pm.ShortcutInfo> getDynamicShortcuts();
-    method public int getIconMaxDimensions();
-    method public int getMaxDynamicShortcutCount();
+    method public int getIconMaxHeight();
+    method public int getIconMaxWidth();
+    method public java.util.List<android.content.pm.ShortcutInfo> getManifestShortcuts();
+    method public int getMaxShortcutCountForActivity();
     method public java.util.List<android.content.pm.ShortcutInfo> getPinnedShortcuts();
     method public long getRateLimitResetTime();
     method public int getRemainingCallCount();
@@ -37443,70 +37455,48 @@
 
   public class TelephonyManager {
     method public boolean canChangeDtmfToneLength();
+    method public android.telephony.TelephonyManager createForSubscriptionId(int);
     method public java.util.List<android.telephony.CellInfo> getAllCellInfo();
     method public int getCallState();
-    method public int getCallState(int);
     method public android.telephony.CellLocation getCellLocation();
     method public int getDataActivity();
-    method public int getDataNetworkType(int);
+    method public int getDataNetworkType();
     method public int getDataState();
     method public java.lang.String getDeviceId();
     method public java.lang.String getDeviceId(int);
     method public java.lang.String getDeviceSoftwareVersion();
     method public java.lang.String getGroupIdLevel1();
-    method public java.lang.String getGroupIdLevel1(int);
     method public java.lang.String getIccAuthentication(int, int, java.lang.String);
-    method public java.lang.String getIccAuthentication(int, int, int, java.lang.String);
-    method public java.lang.String getLine1AlphaTag(int);
     method public java.lang.String getLine1Number();
-    method public java.lang.String getLine1Number(int);
     method public java.lang.String getMmsUAProfUrl();
     method public java.lang.String getMmsUserAgent();
     method public deprecated java.util.List<android.telephony.NeighboringCellInfo> getNeighboringCellInfo();
     method public java.lang.String getNetworkCountryIso();
-    method public java.lang.String getNetworkCountryIso(int);
     method public java.lang.String getNetworkOperator();
-    method public java.lang.String getNetworkOperator(int);
     method public java.lang.String getNetworkOperatorName();
-    method public java.lang.String getNetworkOperatorName(int);
     method public int getNetworkType();
-    method public int getNetworkType(int);
     method public int getPhoneCount();
     method public int getPhoneType();
     method public java.lang.String getSimCountryIso();
-    method public java.lang.String getSimCountryIso(int);
     method public java.lang.String getSimOperator();
-    method public java.lang.String getSimOperator(int);
     method public java.lang.String getSimOperatorName();
-    method public java.lang.String getSimOperatorName(int);
     method public java.lang.String getSimSerialNumber();
-    method public java.lang.String getSimSerialNumber(int);
     method public int getSimState();
     method public java.lang.String getSubscriberId();
-    method public java.lang.String getSubscriberId(int);
     method public java.util.List<android.telephony.TelephonyHistogram> getTelephonyHistograms();
     method public java.lang.String getVoiceMailAlphaTag();
-    method public java.lang.String getVoiceMailAlphaTag(int);
     method public java.lang.String getVoiceMailNumber();
-    method public java.lang.String getVoiceMailNumber(int);
-    method public int getVoiceNetworkType(int);
+    method public int getVoiceNetworkType();
     method public android.net.Uri getVoicemailRingtoneUri(android.telecom.PhoneAccountHandle);
     method public boolean hasCarrierPrivileges();
-    method public boolean hasCarrierPrivileges(int);
     method public boolean hasIccCard();
     method public boolean iccCloseLogicalChannel(int);
-    method public boolean iccCloseLogicalChannel(int, int);
     method public byte[] iccExchangeSimIO(int, int, int, int, int, java.lang.String);
-    method public byte[] iccExchangeSimIO(int, int, int, int, int, int, java.lang.String);
     method public android.telephony.IccOpenLogicalChannelResponse iccOpenLogicalChannel(java.lang.String);
-    method public android.telephony.IccOpenLogicalChannelResponse iccOpenLogicalChannel(int, java.lang.String);
     method public java.lang.String iccTransmitApduBasicChannel(int, int, int, int, int, java.lang.String);
-    method public java.lang.String iccTransmitApduBasicChannel(int, int, int, int, int, int, java.lang.String);
     method public java.lang.String iccTransmitApduLogicalChannel(int, int, int, int, int, int, java.lang.String);
-    method public java.lang.String iccTransmitApduLogicalChannel(int, int, int, int, int, int, int, java.lang.String);
     method public boolean isHearingAidCompatibilitySupported();
     method public boolean isNetworkRoaming();
-    method public boolean isNetworkRoaming(int);
     method public boolean isSmsCapable();
     method public boolean isTtyModeSupported();
     method public boolean isVoiceCapable();
@@ -37514,15 +37504,10 @@
     method public boolean isWorldPhone();
     method public void listen(android.telephony.PhoneStateListener, int);
     method public java.lang.String sendEnvelopeWithStatus(java.lang.String);
-    method public java.lang.String sendEnvelopeWithStatus(int, java.lang.String);
     method public boolean setLine1NumberForDisplay(java.lang.String, java.lang.String);
-    method public boolean setLine1NumberForDisplay(int, java.lang.String, java.lang.String);
     method public boolean setOperatorBrandOverride(java.lang.String);
-    method public boolean setOperatorBrandOverride(int, java.lang.String);
     method public boolean setPreferredNetworkTypeToGlobal();
-    method public boolean setPreferredNetworkTypeToGlobal(int);
     method public boolean setVoiceMailNumber(java.lang.String, java.lang.String);
-    method public boolean setVoiceMailNumber(int, java.lang.String, java.lang.String);
     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";
diff --git a/core/java/android/animation/ObjectAnimator.java b/core/java/android/animation/ObjectAnimator.java
index 1d10860..5c4b979 100644
--- a/core/java/android/animation/ObjectAnimator.java
+++ b/core/java/android/animation/ObjectAnimator.java
@@ -227,10 +227,11 @@
 
     /**
      * Constructs and returns an ObjectAnimator that animates between int values. A single
-     * value implies that that value is the one being animated to. Two values imply starting
-     * and ending values. More than two values imply a starting value, values to animate through
-     * along the way, and an ending value (these values will be distributed evenly across
-     * the duration of the animation).
+     * value implies that that value is the one being animated to, in which case the start value
+     * will be derived from the property being animated and the target object when {@link #start()}
+     * is called for the first time. Two values imply starting and ending values. More than two
+     * values imply a starting value, values to animate through along the way, and an ending value
+     * (these values will be distributed evenly across the duration of the animation).
      *
      * @param target The object whose property is to be animated. This object should
      * have a public method on it called <code>setName()</code>, where <code>name</code> is
@@ -274,10 +275,11 @@
 
     /**
      * Constructs and returns an ObjectAnimator that animates between int values. A single
-     * value implies that that value is the one being animated to. Two values imply starting
-     * and ending values. More than two values imply a starting value, values to animate through
-     * along the way, and an ending value (these values will be distributed evenly across
-     * the duration of the animation).
+     * value implies that that value is the one being animated to, in which case the start value
+     * will be derived from the property being animated and the target object when {@link #start()}
+     * is called for the first time. Two values imply starting and ending values. More than two
+     * values imply a starting value, values to animate through along the way, and an ending value
+     * (these values will be distributed evenly across the duration of the animation).
      *
      * @param target The object whose property is to be animated.
      * @param property The property being animated.
@@ -383,10 +385,11 @@
 
     /**
      * Constructs and returns an ObjectAnimator that animates between color values. A single
-     * value implies that that value is the one being animated to. Two values imply starting
-     * and ending values. More than two values imply a starting value, values to animate through
-     * along the way, and an ending value (these values will be distributed evenly across
-     * the duration of the animation).
+     * value implies that that value is the one being animated to, in which case the start value
+     * will be derived from the property being animated and the target object when {@link #start()}
+     * is called for the first time. Two values imply starting and ending values. More than two
+     * values imply a starting value, values to animate through along the way, and an ending value
+     * (these values will be distributed evenly across the duration of the animation).
      *
      * @param target The object whose property is to be animated. This object should
      * have a public method on it called <code>setName()</code>, where <code>name</code> is
@@ -403,10 +406,11 @@
 
     /**
      * Constructs and returns an ObjectAnimator that animates between color values. A single
-     * value implies that that value is the one being animated to. Two values imply starting
-     * and ending values. More than two values imply a starting value, values to animate through
-     * along the way, and an ending value (these values will be distributed evenly across
-     * the duration of the animation).
+     * value implies that that value is the one being animated to, in which case the start value
+     * will be derived from the property being animated and the target object when {@link #start()}
+     * is called for the first time. Two values imply starting and ending values. More than two
+     * values imply a starting value, values to animate through along the way, and an ending value
+     * (these values will be distributed evenly across the duration of the animation).
      *
      * @param target The object whose property is to be animated.
      * @param property The property being animated.
@@ -422,10 +426,11 @@
 
     /**
      * Constructs and returns an ObjectAnimator that animates between float values. A single
-     * value implies that that value is the one being animated to. Two values imply starting
-     * and ending values. More than two values imply a starting value, values to animate through
-     * along the way, and an ending value (these values will be distributed evenly across
-     * the duration of the animation).
+     * value implies that that value is the one being animated to, in which case the start value
+     * will be derived from the property being animated and the target object when {@link #start()}
+     * is called for the first time. Two values imply starting and ending values. More than two
+     * values imply a starting value, values to animate through along the way, and an ending value
+     * (these values will be distributed evenly across the duration of the animation).
      *
      * @param target The object whose property is to be animated. This object should
      * have a public method on it called <code>setName()</code>, where <code>name</code> is
@@ -469,10 +474,11 @@
 
     /**
      * Constructs and returns an ObjectAnimator that animates between float values. A single
-     * value implies that that value is the one being animated to. Two values imply starting
-     * and ending values. More than two values imply a starting value, values to animate through
-     * along the way, and an ending value (these values will be distributed evenly across
-     * the duration of the animation).
+     * value implies that that value is the one being animated to, in which case the start value
+     * will be derived from the property being animated and the target object when {@link #start()}
+     * is called for the first time. Two values imply starting and ending values. More than two
+     * values imply a starting value, values to animate through along the way, and an ending value
+     * (these values will be distributed evenly across the duration of the animation).
      *
      * @param target The object whose property is to be animated.
      * @param property The property being animated.
@@ -580,10 +586,11 @@
 
     /**
      * Constructs and returns an ObjectAnimator that animates between Object values. A single
-     * value implies that that value is the one being animated to. Two values imply starting
-     * and ending values. More than two values imply a starting value, values to animate through
-     * along the way, and an ending value (these values will be distributed evenly across
-     * the duration of the animation).
+     * value implies that that value is the one being animated to, in which case the start value
+     * will be derived from the property being animated and the target object when {@link #start()}
+     * is called for the first time. Two values imply starting and ending values. More than two
+     * values imply a starting value, values to animate through along the way, and an ending value
+     * (these values will be distributed evenly across the duration of the animation).
      *
      * <p><strong>Note:</strong> The values are stored as references to the original
      * objects, which means that changes to those objects after this method is called will
@@ -635,10 +642,11 @@
 
     /**
      * Constructs and returns an ObjectAnimator that animates between Object values. A single
-     * value implies that that value is the one being animated to. Two values imply starting
-     * and ending values. More than two values imply a starting value, values to animate through
-     * along the way, and an ending value (these values will be distributed evenly across
-     * the duration of the animation).
+     * value implies that that value is the one being animated to, in which case the start value
+     * will be derived from the property being animated and the target object when {@link #start()}
+     * is called for the first time. Two values imply starting and ending values. More than two
+     * values imply a starting value, values to animate through along the way, and an ending value
+     * (these values will be distributed evenly across the duration of the animation).
      *
      * <p><strong>Note:</strong> The values are stored as references to the original
      * objects, which means that changes to those objects after this method is called will
@@ -665,12 +673,13 @@
 
     /**
      * Constructs and returns an ObjectAnimator that animates between Object values. A single
-     * value implies that that value is the one being animated to. Two values imply starting
-     * and ending values. More than two values imply a starting value, values to animate through
-     * along the way, and an ending value (these values will be distributed evenly across
-     * the duration of the animation). This variant supplies a <code>TypeConverter</code> to
-     * convert from the animated values to the type of the property. If only one value is
-     * supplied, the <code>TypeConverter</code> must be a
+     * value implies that that value is the one being animated to, in which case the start value
+     * will be derived from the property being animated and the target object when {@link #start()}
+     * is called for the first time. Two values imply starting and ending values. More than two
+     * values imply a starting value, values to animate through along the way, and an ending value
+     * (these values will be distributed evenly across the duration of the animation).
+     * This variant supplies a <code>TypeConverter</code> to convert from the animated values to the
+     * type of the property. If only one value is supplied, the <code>TypeConverter</code> must be a
      * {@link android.animation.BidirectionalTypeConverter} to retrieve the current value.
      *
      * <p><strong>Note:</strong> The values are stored as references to the original
diff --git a/core/java/android/app/Activity.java b/core/java/android/app/Activity.java
index 6d405f6..ac5f3ef 100644
--- a/core/java/android/app/Activity.java
+++ b/core/java/android/app/Activity.java
@@ -5948,7 +5948,7 @@
      * @return true if this is the topmost, non-finishing activity in its task.
      */
     private boolean isTopOfTask() {
-        if (mToken == null || mWindow == null || !mWindowAdded) {
+        if (mToken == null || mWindow == null) {
             return false;
         }
         try {
diff --git a/core/java/android/app/ActivityManagerInternal.java b/core/java/android/app/ActivityManagerInternal.java
index 4b8d9ee..3a70a4c 100644
--- a/core/java/android/app/ActivityManagerInternal.java
+++ b/core/java/android/app/ActivityManagerInternal.java
@@ -18,6 +18,7 @@
 
 import android.annotation.NonNull;
 import android.content.ComponentName;
+import android.content.IIntentSender;
 import android.os.IBinder;
 import android.service.voice.IVoiceInteractionSession;
 
@@ -144,4 +145,10 @@
      * Kill foreground apps from the specified user.
      */
     public abstract void killForegroundAppsForUser(int userHandle);
+
+    /**
+     *  Sets how long a {@link PendingIntent} can be temporarily whitelist to by bypass restrictions
+     *  such as Power Save mode.
+     */
+    public abstract void setPendingIntentWhitelistDuration(IIntentSender target, long duration);
 }
diff --git a/core/java/android/app/ActivityManagerNative.java b/core/java/android/app/ActivityManagerNative.java
index cd9a05b..f12c284 100644
--- a/core/java/android/app/ActivityManagerNative.java
+++ b/core/java/android/app/ActivityManagerNative.java
@@ -6966,8 +6966,8 @@
         reply.recycle();
     }
 
-    public void notifyLockedProfile(@UserIdInt int userId) throws RemoteException
-    {
+    @Override
+    public void notifyLockedProfile(@UserIdInt int userId) throws RemoteException {
         Parcel data = Parcel.obtain();
         Parcel reply = Parcel.obtain();
         data.writeInterfaceToken(IActivityManager.descriptor);
@@ -6978,6 +6978,7 @@
         reply.recycle();
     }
 
+    @Override
     public void startConfirmDeviceCredentialIntent(Intent intent) throws RemoteException {
         Parcel data = Parcel.obtain();
         Parcel reply = Parcel.obtain();
@@ -6989,6 +6990,7 @@
         reply.recycle();
     }
 
+    @Override
     public int sendIntentSender(IIntentSender target, int code, Intent intent, String resolvedType,
             IIntentReceiver finishedReceiver, String requiredPermission, Bundle options)
             throws RemoteException {
diff --git a/core/java/android/app/ActivityTransitionState.java b/core/java/android/app/ActivityTransitionState.java
index 4a1aff7..02eb4d3 100644
--- a/core/java/android/app/ActivityTransitionState.java
+++ b/core/java/android/app/ActivityTransitionState.java
@@ -284,7 +284,7 @@
     }
 
     public boolean startExitBackTransition(final Activity activity) {
-        if (mEnteringNames == null) {
+        if (mEnteringNames == null || mCalledExitCoordinator != null) {
             return false;
         } else {
             if (!mHasExited) {
diff --git a/core/java/android/app/AlarmManager.java b/core/java/android/app/AlarmManager.java
index 02dcc5c..2ae437e 100644
--- a/core/java/android/app/AlarmManager.java
+++ b/core/java/android/app/AlarmManager.java
@@ -28,12 +28,12 @@
 import android.os.UserHandle;
 import android.os.WorkSource;
 import android.text.TextUtils;
+import android.util.ArrayMap;
 import android.util.Log;
 
 import libcore.util.ZoneInfoDB;
 
 import java.io.IOException;
-import java.util.WeakHashMap;
 
 /**
  * This class provides access to the system alarm services.  These allow you
@@ -244,7 +244,7 @@
 
     // Tracking of the OnAlarmListener -> wrapper mapping, for cancel() support.
     // Access is synchronized on the AlarmManager class object.
-    private static WeakHashMap<OnAlarmListener, ListenerWrapper> sWrappers;
+    private static ArrayMap<OnAlarmListener, ListenerWrapper> sWrappers;
 
     /**
      * package private on purpose
@@ -631,7 +631,7 @@
         if (listener != null) {
             synchronized (AlarmManager.class) {
                 if (sWrappers == null) {
-                    sWrappers = new WeakHashMap<OnAlarmListener, ListenerWrapper>();
+                    sWrappers = new ArrayMap<OnAlarmListener, ListenerWrapper>();
                 }
 
                 recipientWrapper = sWrappers.get(listener);
diff --git a/core/java/android/app/EnterTransitionCoordinator.java b/core/java/android/app/EnterTransitionCoordinator.java
index a599584..8bf1e9a 100644
--- a/core/java/android/app/EnterTransitionCoordinator.java
+++ b/core/java/android/app/EnterTransitionCoordinator.java
@@ -150,6 +150,7 @@
                 }
             };
             decor.getViewTreeObserver().addOnPreDrawListener(mViewsReadyListener);
+            decor.invalidate();
         }
     }
 
diff --git a/core/java/android/app/Notification.java b/core/java/android/app/Notification.java
index 0cc44e7..e108dd6e 100644
--- a/core/java/android/app/Notification.java
+++ b/core/java/android/app/Notification.java
@@ -4323,18 +4323,23 @@
                 // experience
                 bigTextText = mBuilder.processLegacyText(text);
             }
-            contentView.setTextViewText(R.id.big_text, bigTextText);
-            contentView.setViewVisibility(R.id.big_text,
-                    TextUtils.isEmpty(bigTextText) ? View.GONE : View.VISIBLE);
-            contentView.setInt(R.id.big_text, "setMaxLines", calculateMaxLines());
-            contentView.setBoolean(R.id.big_text, "setHasImage", mBuilder.mN.mLargeIcon != null);
+            applyBigTextContentView(mBuilder, contentView, bigTextText);
 
             return contentView;
         }
 
-        private int calculateMaxLines() {
+        static void applyBigTextContentView(Builder builder,
+                RemoteViews contentView, CharSequence bigTextText) {
+            contentView.setTextViewText(R.id.big_text, bigTextText);
+            contentView.setViewVisibility(R.id.big_text,
+                    TextUtils.isEmpty(bigTextText) ? View.GONE : View.VISIBLE);
+            contentView.setInt(R.id.big_text, "setMaxLines", calculateMaxLines(builder));
+            contentView.setBoolean(R.id.big_text, "setHasImage", builder.mN.mLargeIcon != null);
+        }
+
+        private static int calculateMaxLines(Builder builder) {
             int lineCount = MAX_LINES;
-            boolean hasActions = mBuilder.mActions.size() > 0;
+            boolean hasActions = builder.mActions.size() > 0;
             if (hasActions) {
                 lineCount -= LINES_CONSUMED_BY_ACTIONS;
             }
@@ -4532,6 +4537,16 @@
                     : mConversationTitle;
             boolean hasTitle = !TextUtils.isEmpty(title);
 
+            if (!hasTitle && mMessages.size() == 1) {
+                CharSequence sender = mMessages.get(0).mSender;
+                CharSequence text = mMessages.get(0).mText;
+                RemoteViews contentView = mBuilder.applyStandardTemplateWithActions(
+                        mBuilder.getBigTextLayoutResource(),
+                        false /* progress */, sender, null /* text */);
+                BigTextStyle.applyBigTextContentView(mBuilder, contentView, text);
+                return contentView;
+            }
+
             RemoteViews contentView = mBuilder.applyStandardTemplateWithActions(
                     mBuilder.getMessagingLayoutResource(),
                     false /* hasProgress */,
diff --git a/core/java/android/bluetooth/IBluetoothManager.aidl b/core/java/android/bluetooth/IBluetoothManager.aidl
index 0b81ee8..2b853a3 100644
--- a/core/java/android/bluetooth/IBluetoothManager.aidl
+++ b/core/java/android/bluetooth/IBluetoothManager.aidl
@@ -37,6 +37,7 @@
     boolean enable();
     boolean enableNoAutoConnect();
     boolean disable(boolean persist);
+    int getState();
     IBluetoothGatt getBluetoothGatt();
 
     boolean bindBluetoothProfileService(int profile, IBluetoothProfileServiceConnection proxy);
diff --git a/core/java/android/content/Context.java b/core/java/android/content/Context.java
index fc579a9..8b3eac5 100644
--- a/core/java/android/content/Context.java
+++ b/core/java/android/content/Context.java
@@ -285,6 +285,12 @@
     public static final int BIND_ADJUST_WITH_ACTIVITY = 0x0080;
 
     /**
+     * @hide Flag for {@link #bindService}: allows application hosting service to manage whitelists
+     * such as temporary allowing a {@code PendingIntent} to bypass Power Save mode.
+     */
+    public static final int BIND_ALLOW_WHITELIST_MANAGEMENT = 0x01000000;
+
+    /**
      * @hide Flag for {@link #bindService}: Like {@link #BIND_FOREGROUND_SERVICE},
      * but only applies while the device is awake.
      */
diff --git a/core/java/android/content/pm/IPackageManager.aidl b/core/java/android/content/pm/IPackageManager.aidl
index 03f83d6..4bbbdee 100644
--- a/core/java/android/content/pm/IPackageManager.aidl
+++ b/core/java/android/content/pm/IPackageManager.aidl
@@ -459,23 +459,19 @@
 
     /**
      * Ask the package manager to perform dex-opt (if needed) on the given
-     * package and for the given instruction set if it already hasn't done
-     * so.
-     *
-     * If the supplied instructionSet is null, the package manager will use
-     * the packages default instruction set.
+     * package if it already hasn't done so.
      *
      * In most cases, apps are dexopted in advance and this function will
      * be a no-op.
      */
-    boolean performDexOptIfNeeded(String packageName, String instructionSet);
+    boolean performDexOptIfNeeded(String packageName);
 
     /**
      * Ask the package manager to perform a dex-opt for the given reason. The package
      * manager will map the reason to a compiler filter according to the current system
      * configuration.
      */
-    boolean performDexOpt(String packageName, String instructionSet, boolean checkProfiles,
+    boolean performDexOpt(String packageName, boolean checkProfiles,
             int compileReason, boolean force);
     /**
      * Ask the package manager to perform a dex-opt with the given compiler filter.
@@ -483,7 +479,7 @@
      * Note: exposed only for the shell command to allow moving packages explicitly to a
      *       definite state.
      */
-    boolean performDexOptMode(String packageName, String instructionSet, boolean checkProfiles,
+    boolean performDexOptMode(String packageName, boolean checkProfiles,
             String targetCompilerFilter, boolean force);
 
     void forceDexOpt(String packageName);
diff --git a/core/java/android/content/pm/IShortcutService.aidl b/core/java/android/content/pm/IShortcutService.aidl
index 06200bf..1c373f9 100644
--- a/core/java/android/content/pm/IShortcutService.aidl
+++ b/core/java/android/content/pm/IShortcutService.aidl
@@ -28,6 +28,8 @@
 
     ParceledListSlice getDynamicShortcuts(String packageName, int userId);
 
+    ParceledListSlice getManifestShortcuts(String packageName, int userId);
+
     boolean addDynamicShortcuts(String packageName, in ParceledListSlice shortcutInfoList,
             int userId);
 
@@ -42,6 +44,8 @@
     void disableShortcuts(String packageName, in List shortcutIds, String disabledMessage,
             int disabledMessageResId, int userId);
 
+    void enableShortcuts(String packageName, in List shortcutIds, int userId);
+
     int getMaxDynamicShortcutCount(String packageName, int userId);
 
     int getRemainingCallCount(String packageName, int userId);
diff --git a/core/java/android/content/pm/LauncherApps.java b/core/java/android/content/pm/LauncherApps.java
index acd85cb..6cb50fc 100644
--- a/core/java/android/content/pm/LauncherApps.java
+++ b/core/java/android/content/pm/LauncherApps.java
@@ -24,7 +24,12 @@
 import android.content.Context;
 import android.content.Intent;
 import android.content.pm.PackageManager.ApplicationInfoFlags;
+import android.content.pm.PackageManager.NameNotFoundException;
+import android.content.res.Resources;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
 import android.graphics.Rect;
+import android.graphics.drawable.BitmapDrawable;
 import android.graphics.drawable.Drawable;
 import android.os.Bundle;
 import android.os.Handler;
@@ -35,8 +40,10 @@
 import android.os.ServiceManager;
 import android.os.UserHandle;
 import android.os.UserManager;
+import android.util.DisplayMetrics;
 import android.util.Log;
 
+import java.io.IOException;
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
 import java.util.ArrayList;
@@ -188,6 +195,11 @@
         public static final int FLAG_GET_PINNED = 1 << 1;
 
         /**
+         * Include manifest shortcuts in the result.
+         */
+        public static final int FLAG_GET_MANIFEST = 1 << 3;
+
+        /**
          * Requests "key" fields only.  See {@link ShortcutInfo#hasKeyFieldsOnly()} for which
          * fields are available.
          */
@@ -198,6 +210,7 @@
                 value = {
                         FLAG_GET_DYNAMIC,
                         FLAG_GET_PINNED,
+                        FLAG_GET_MANIFEST,
                         FLAG_GET_KEY_FIELDS_ONLY,
                 })
         @Retention(RetentionPolicy.SOURCE)
@@ -224,39 +237,44 @@
          * If non-zero, returns only shortcuts that have been added or updated since the timestamp,
          * which is a milliseconds since the Epoch.
          */
-        public void setChangedSince(long changedSince) {
+        public ShortcutQuery setChangedSince(long changedSince) {
             mChangedSince = changedSince;
+            return this;
         }
 
         /**
          * If non-null, returns only shortcuts from the package.
          */
-        public void setPackage(@Nullable String packageName) {
+        public ShortcutQuery setPackage(@Nullable String packageName) {
             mPackage = packageName;
+            return this;
         }
 
         /**
          * If non-null, return only the specified shortcuts by ID.  When setting this field,
          * a packange name must also be set with {@link #setPackage}.
          */
-        public void setShortcutIds(@Nullable List<String> shortcutIds) {
+        public ShortcutQuery setShortcutIds(@Nullable List<String> shortcutIds) {
             mShortcutIds = shortcutIds;
+            return this;
         }
 
         /**
-         * If non-null, returns only shortcuts associated with the activity, which are
-         * {@link ShortcutInfo}s that have null {@link ShortcutInfo#getActivityComponent()}, or
-         * {@link ShortcutInfo#getActivityComponent()} equals to {@code activity}.
+         * If non-null, returns only shortcuts associated with the activity; i.e.
+         * {@link ShortcutInfo}s whose {@link ShortcutInfo#getActivity()} are equal
+         * to {@code activity}.
          */
-        public void setActivity(@Nullable ComponentName activity) {
+        public ShortcutQuery setActivity(@Nullable ComponentName activity) {
             mActivity = activity;
+            return this;
         }
 
         /**
          * Set query options.
          */
-        public void setQueryFlags(@QueryFlags int queryFlags) {
+        public ShortcutQuery setQueryFlags(@QueryFlags int queryFlags) {
             mQueryFlags = queryFlags;
+            return this;
         }
     }
 
@@ -525,7 +543,7 @@
      */
     public ParcelFileDescriptor getShortcutIconFd(
             @NonNull ShortcutInfo shortcut) {
-        return getShortcutIconFd(shortcut.getPackageName(), shortcut.getId(),
+        return getShortcutIconFd(shortcut.getPackage(), shortcut.getId(),
                 shortcut.getUserId());
     }
 
@@ -555,14 +573,61 @@
         }
     }
 
-    /** TODO Javadoc */
-    public Drawable getShortcutIconDrawable(int density) {
-        throw new RuntimeException("TODO implement it");
+    /**
+     * Returns the icon for this shortcut, without any badging for the profile.
+     *
+     * @param density The preferred density of the icon, zero for default density. Use
+     * density DPI values from {@link DisplayMetrics}.
+     * @see #getShortcutBadgedIconDrawable(ShortcutInfo, int)
+     * @see DisplayMetrics
+     * @return The drawable associated with the shortcut.
+     */
+    public Drawable getShortcutIconDrawable(@NonNull ShortcutInfo shortcut, int density) {
+        if (shortcut.hasIconFile()) {
+            final ParcelFileDescriptor pfd = getShortcutIconFd(shortcut);
+            if (pfd == null) {
+                return null;
+            }
+            try {
+                final Bitmap bmp = BitmapFactory.decodeFileDescriptor(pfd.getFileDescriptor());
+                return (bmp == null) ? null : new BitmapDrawable(mContext.getResources(), bmp);
+            } finally {
+                try {
+                    pfd.close();
+                } catch (IOException ignore) {
+                }
+            }
+        } else if (shortcut.hasIconResource()) {
+            try {
+                final int resId = shortcut.getIconResourceId();
+                if (resId == 0) {
+                    return null; // Shouldn't happen but just in case.
+                }
+                final ApplicationInfo ai = getApplicationInfo(shortcut.getPackage(),
+                        /* flags =*/ 0, shortcut.getUserHandle());
+                final Resources res = mContext.getPackageManager().getResourcesForApplication(ai);
+                return res.getDrawableForDensity(resId, density);
+            } catch (NameNotFoundException | Resources.NotFoundException e) {
+                return null;
+            }
+        } else {
+            return null; // Has no icon.
+        }
     }
 
-    /** TODO Javadoc */
-    public Drawable getShortcutBadgedIconDrawable(int density) {
-        throw new RuntimeException("TODO implement it");
+    /**
+     * Returns the shortcut icon with badging appropriate for the profile.
+     *
+     * @param density Optional density for the icon, or 0 to use the default density. Use
+     * {@link DisplayMetrics} for DPI values.
+     * @see DisplayMetrics
+     * @return A badged icon for the shortcut.
+     */
+    public Drawable getShortcutBadgedIconDrawable(ShortcutInfo shortcut, int density) {
+        final Drawable originalIcon = getShortcutIconDrawable(shortcut, density);
+
+        return (originalIcon == null) ? null : mContext.getPackageManager().getUserBadgedIcon(
+                originalIcon, shortcut.getUserHandle());
     }
 
     /**
@@ -600,7 +665,7 @@
      */
     public boolean startShortcut(@NonNull ShortcutInfo shortcut,
             @Nullable Rect sourceBounds, @Nullable Bundle startActivityOptions) {
-        return startShortcut(shortcut.getPackageName(), shortcut.getId(),
+        return startShortcut(shortcut.getPackage(), shortcut.getId(),
                 sourceBounds, startActivityOptions,
                 shortcut.getUserId());
     }
diff --git a/core/java/android/content/pm/ShortcutInfo.java b/core/java/android/content/pm/ShortcutInfo.java
index 3648d9e..c83aa22 100644
--- a/core/java/android/content/pm/ShortcutInfo.java
+++ b/core/java/android/content/pm/ShortcutInfo.java
@@ -70,7 +70,7 @@
     public static final int FLAG_KEY_FIELDS_ONLY = 1 << 4;
 
     /* @hide */
-    public static final int FLAG_FROM_MANIFEST = 1 << 5;
+    public static final int FLAG_MANIFEST = 1 << 5;
 
     /* @hide */
     public static final int FLAG_DISABLED = 1 << 6;
@@ -78,6 +78,9 @@
     /* @hide */
     public static final int FLAG_STRINGS_RESOLVED = 1 << 7;
 
+    /* @hide */
+    public static final int FLAG_IMMUTABLE = 1 << 8;
+
     /** @hide */
     @IntDef(flag = true,
             value = {
@@ -86,9 +89,10 @@
             FLAG_HAS_ICON_RES,
             FLAG_HAS_ICON_FILE,
             FLAG_KEY_FIELDS_ONLY,
-            FLAG_FROM_MANIFEST,
+            FLAG_MANIFEST,
             FLAG_DISABLED,
             FLAG_STRINGS_RESOLVED,
+            FLAG_IMMUTABLE,
     })
     @Retention(RetentionPolicy.SOURCE)
     public @interface ShortcutFlags {}
@@ -133,7 +137,7 @@
     private final String mPackageName;
 
     @Nullable
-    private ComponentName mActivityComponent;
+    private ComponentName mActivity;
 
     @Nullable
     private Icon mIcon;
@@ -141,17 +145,17 @@
     private int mTitleResId;
 
     @Nullable
-    private String mTitle;
+    private CharSequence mTitle;
 
     private int mTextResId;
 
     @Nullable
-    private String mText;
+    private CharSequence mText;
 
     private int mDisabledMessageResId;
 
     @Nullable
-    private String mDisabledMessage;
+    private CharSequence mDisabledMessage;
 
     @Nullable
     private ArraySet<String> mCategories;
@@ -196,7 +200,7 @@
         // Note we can't do other null checks here because SM.updateShortcuts() takes partial
         // information.
         mPackageName = b.mContext.getPackageName();
-        mActivityComponent = b.mActivityComponent;
+        mActivity = b.mActivity;
         mIcon = b.mIcon;
         mTitle = b.mTitle;
         mTitleResId = b.mTitleResId;
@@ -229,7 +233,7 @@
      */
     public void enforceMandatoryFields() {
         Preconditions.checkStringNotEmpty(mId, "Shortcut ID must be provided");
-        Preconditions.checkNotNull(mActivityComponent, "activityComponent must be provided");
+        Preconditions.checkNotNull(mActivity, "activity must be provided");
         if (mTitle == null && mTitleResId == 0) {
             throw new IllegalArgumentException("Shortcut title must be provided");
         }
@@ -250,7 +254,7 @@
         mIconResourceId = source.mIconResourceId;
 
         if ((cloneFlags & CLONE_REMOVE_NON_KEY_INFO) == 0) {
-            mActivityComponent = source.mActivityComponent;
+            mActivity = source.mActivity;
 
             if ((cloneFlags & CLONE_REMOVE_ICON) == 0) {
                 mIcon = source.mIcon;
@@ -309,6 +313,17 @@
     }
 
     /**
+     * @hide
+     */
+    public void ensureUpdatableWith(ShortcutInfo source) {
+        Preconditions.checkState(mUserId == source.mUserId, "Owner User ID must match");
+        Preconditions.checkState(mId.equals(source.mId), "ID must match");
+        Preconditions.checkState(mPackageName.equals(source.mPackageName),
+                "Package name must match");
+        Preconditions.checkState(!isImmutable(), "Target ShortcutInfo is immutable");
+    }
+
+    /**
      * Copy non-null/zero fields from another {@link ShortcutInfo}.  Only "public" information
      * will be overwritten.  The timestamp will be updated.
      *
@@ -316,16 +331,15 @@
      * - mBitmapPath will not change
      * - Current time will be set to timestamp
      *
+     * @throws IllegalStateException if source is not compatible.
+     *
      * @hide
      */
     public void copyNonNullFieldsFrom(ShortcutInfo source) {
-        Preconditions.checkState(mUserId == source.mUserId, "Owner User ID must match");
-        Preconditions.checkState(mId.equals(source.mId), "ID must match");
-        Preconditions.checkState(mPackageName.equals(source.mPackageName),
-                "Package name must match");
+        ensureUpdatableWith(source);
 
-        if (source.mActivityComponent != null) {
-            mActivityComponent = source.mActivityComponent;
+        if (source.mActivity != null) {
+            mActivity = source.mActivity;
         }
 
         if (source.mIcon != null) {
@@ -401,21 +415,21 @@
 
         private String mId;
 
-        private ComponentName mActivityComponent;
+        private ComponentName mActivity;
 
         private Icon mIcon;
 
         private int mTitleResId;
 
-        private String mTitle;
+        private CharSequence mTitle;
 
         private int mTextResId;
 
-        private String mText;
+        private CharSequence mText;
 
         private int mDisabledMessageResId;
 
-        private String mDisabledMessage;
+        private CharSequence mDisabledMessage;
 
         private Set<String> mCategories;
 
@@ -451,8 +465,8 @@
          * a hint to the launcher app about which launcher icon to associate this shortcut with.
          */
         @NonNull
-        public Builder setActivityComponent(@NonNull ComponentName activityComponent) {
-            mActivityComponent = Preconditions.checkNotNull(activityComponent, "activityComponent");
+        public Builder setActivity(@NonNull ComponentName activity) {
+            mActivity = Preconditions.checkNotNull(activity, "activity");
             return this;
         }
 
@@ -476,7 +490,7 @@
             return this;
         }
 
-        /** TODO Javadoc */
+        /** @hide */
         public Builder setTitleResId(int titleResId) {
             Preconditions.checkState(mTitle == null, "title already set");
             mTitleResId = titleResId;
@@ -496,7 +510,7 @@
             return this;
         }
 
-        /** TODO Javadoc */
+        /** @hide */
         public Builder setTextResId(int textResId) {
             Preconditions.checkState(mText == null, "text already set");
             mTextResId = textResId;
@@ -516,7 +530,7 @@
             return this;
         }
 
-        /** TODO Javadoc */
+        /** @hide */
         public Builder setDisabledMessageResId(int disabledMessageResId) {
             Preconditions.checkState(mDisabledMessage == null, "disabledMessage already set");
             mDisabledMessageResId = disabledMessageResId;
@@ -595,7 +609,7 @@
      * Return the package name of the creator application.
      */
     @NonNull
-    public String getPackageName() {
+    public String getPackage() {
         return mPackageName;
     }
 
@@ -606,11 +620,11 @@
      * <p>This has nothing to do with the activity that this shortcut will launch.  This is
      * a hint to the launcher app that on which launcher icon this shortcut should be shown.
      *
-     * @see Builder#setActivityComponent
+     * @see Builder#setActivity
      */
     @Nullable
-    public ComponentName getActivityComponent() {
-        return mActivityComponent;
+    public ComponentName getActivity() {
+        return mActivity;
     }
 
     /**
@@ -634,7 +648,7 @@
      * {@link #hasKeyFieldsOnly()} is true.
      */
     @Nullable
-    public String getTitle() {
+    public CharSequence getTitle() {
         return mTitle;
     }
 
@@ -647,7 +661,7 @@
      * Return the shortcut text.
      */
     @Nullable
-    public String getText() {
+    public CharSequence getText() {
         return mText;
     }
 
@@ -660,7 +674,7 @@
      * Return the message that should be shown when a shortcut in disabled state is launched.
      */
     @Nullable
-    public String getDisabledMessage() {
+    public CharSequence getDisabledMessage() {
         return mDisabledMessage;
     }
 
@@ -788,18 +802,67 @@
     }
 
     /**
-     * Return whether a shortcut is published via manifest or not.  If true, the shortcut is
-     * immutable.
+     * Return whether a shortcut is published via AndroidManifest.xml or not.  If {@code true},
+     * it's also {@link #isImmutable()}.
+     *
+     * <p>When an app is upgraded and a shortcut is no longer published from AndroidManifest.xml,
+     * this will be set to {@code false}.  If the shortcut is not pinned, then it'll just disappear.
+     * However, if it's pinned, it will still be alive, and {@link #isEnabled()} will be
+     * {@code false} and {@link #isImmutable()} will be {@code true}.
+     *
+     * <p>NOTE this is whether a shortcut is published from the <b>current version's</b>
+     * AndroidManifest.xml.
      */
-    public boolean isFromManifest() {
-        return hasFlags(FLAG_FROM_MANIFEST);
+    public boolean isManifestShortcut() {
+        return hasFlags(FLAG_MANIFEST);
     }
 
-    /** Return whether a shortcut is disabled by publisher or not. */
-    public boolean isDisabled() {
+    /**
+     * @return true if pinned but neither dynamic nor manifest.
+     * @hide
+     */
+    public boolean isFloating() {
+        return isPinned() && !(isDynamic() || isManifestShortcut());
+    }
+
+    /** @hide */
+    public boolean isOriginallyFromManifest() {
+        return hasFlags(FLAG_IMMUTABLE);
+    }
+
+    /**
+     * Return if a shortcut is immutable, in which case it cannot be modified with any of
+     * {@link ShortcutManager} APIs.
+     *
+     * <p>All manifest shortcuts are immutable.  When a manifest shortcut is pinned and then
+     * disabled because the app is upgraded and its AndroidManifest.xml no longer publishes it,
+     * {@link #isManifestShortcut} returns {@code false}, but it is still immutable.
+     *
+     * <p>All shortcuts originally published via the {@link ShortcutManager} APIs
+     * are all mutable.
+     */
+    public boolean isImmutable() {
+        return hasFlags(FLAG_IMMUTABLE);
+    }
+
+    /**
+     * Returns {@code false} if a shortcut is disabled with
+     * {@link ShortcutManager#disableShortcuts}.
+     */
+    public boolean isEnabled() {
         return !hasFlags(FLAG_DISABLED);
     }
 
+    /** @hide */
+    public boolean isAlive() {
+        return hasFlags(FLAG_PINNED) || hasFlags(FLAG_DYNAMIC) || hasFlags(FLAG_MANIFEST);
+    }
+
+    /** @hide */
+    public boolean usesQuota() {
+        return hasFlags(FLAG_DYNAMIC) || hasFlags(FLAG_MANIFEST);
+    }
+
     /**
      * Return whether a shortcut's icon is a resource in the owning package.
      *
@@ -833,7 +896,7 @@
      * following fields are available.
      * <ul>
      *     <li>{@link #getId()}
-     *     <li>{@link #getPackageName()}
+     *     <li>{@link #getPackage()}
      *     <li>{@link #getLastChangedTimestamp()}
      *     <li>{@link #isDynamic()}
      *     <li>{@link #isPinned()}
@@ -888,19 +951,31 @@
         mBitmapPath = bitmapPath;
     }
 
+    /** @hide */
+    public void setDisabledMessageResId(int disabledMessageResId) {
+        mDisabledMessageResId = disabledMessageResId;
+        mDisabledMessage = null;
+    }
+
+    /** @hide */
+    public void setDisabledMessage(String disabledMessage) {
+        mDisabledMessage = disabledMessage;
+        mDisabledMessageResId = 0;
+    }
+
     private ShortcutInfo(Parcel source) {
         final ClassLoader cl = getClass().getClassLoader();
 
         mUserId = source.readInt();
         mId = source.readString();
         mPackageName = source.readString();
-        mActivityComponent = source.readParcelable(cl);
+        mActivity = source.readParcelable(cl);
         mIcon = source.readParcelable(cl);
-        mTitle = source.readString();
+        mTitle = source.readCharSequence();
         mTitleResId = source.readInt();
-        mText = source.readString();
+        mText = source.readCharSequence();
         mTextResId = source.readInt();
-        mDisabledMessage = source.readString();
+        mDisabledMessage = source.readCharSequence();
         mDisabledMessageResId = source.readInt();
         mIntent = source.readParcelable(cl);
         mIntentPersistableExtras = source.readParcelable(cl);
@@ -927,13 +1002,13 @@
         dest.writeInt(mUserId);
         dest.writeString(mId);
         dest.writeString(mPackageName);
-        dest.writeParcelable(mActivityComponent, flags);
+        dest.writeParcelable(mActivity, flags);
         dest.writeParcelable(mIcon, flags);
-        dest.writeString(mTitle);
+        dest.writeCharSequence(mTitle);
         dest.writeInt(mTitleResId);
-        dest.writeString(mText);
+        dest.writeCharSequence(mText);
         dest.writeInt(mTextResId);
-        dest.writeString(mDisabledMessage);
+        dest.writeCharSequence(mDisabledMessage);
         dest.writeInt(mDisabledMessageResId);
 
         dest.writeParcelable(mIntent, flags);
@@ -991,18 +1066,43 @@
         sb.append("id=");
         sb.append(secure ? "***" : mId);
 
+        sb.append(", flags=0x");
+        sb.append(Integer.toHexString(mFlags));
+        sb.append(" [");
+        if (!isEnabled()) {
+            sb.append("X");
+        }
+        if (isImmutable()) {
+            sb.append("Im");
+        }
+        if (isManifestShortcut()) {
+            sb.append("M");
+        }
+        if (isDynamic()) {
+            sb.append("D");
+        }
+        if (isPinned()) {
+            sb.append("P");
+        }
+        if (hasIconFile()) {
+            sb.append("If");
+        }
+        if (hasIconResource()) {
+            sb.append("Ir");
+        }
+        if (hasKeyFieldsOnly()) {
+            sb.append("K");
+        }
+        if (hasStringResourcesResolved()) {
+            sb.append("Sr");
+        }
+        sb.append("]");
+
         sb.append(", packageName=");
         sb.append(mPackageName);
 
-        if (isDynamic()) {
-            sb.append(", dynamic");
-        }
-        if (isPinned()) {
-            sb.append(", pinned");
-        }
-
         sb.append(", activity=");
-        sb.append(mActivityComponent);
+        sb.append(mActivity);
 
         sb.append(", title=");
         sb.append(secure ? "***" : mTitle);
@@ -1040,35 +1140,6 @@
         sb.append(", extras=");
         sb.append(mExtras);
 
-        sb.append(", flags=");
-        sb.append(mFlags);
-        sb.append(" [");
-        if (hasFlags(FLAG_DISABLED)) {
-            sb.append("X");
-        }
-        if (hasFlags(FLAG_FROM_MANIFEST)) {
-            sb.append("M");
-        }
-        if (hasFlags(FLAG_DYNAMIC)) {
-            sb.append("D");
-        }
-        if (hasFlags(FLAG_PINNED)) {
-            sb.append("P");
-        }
-        if (hasFlags(FLAG_HAS_ICON_FILE)) {
-            sb.append("If");
-        }
-        if (hasFlags(FLAG_HAS_ICON_RES)) {
-            sb.append("Ir");
-        }
-        if (hasFlags(FLAG_KEY_FIELDS_ONLY)) {
-            sb.append("K");
-        }
-        if (hasFlags(FLAG_STRINGS_RESOLVED)) {
-            sb.append("S");
-        }
-        sb.append("]");
-
         if (includeInternalData) {
 
             sb.append(", iconRes=");
@@ -1084,16 +1155,16 @@
 
     /** @hide */
     public ShortcutInfo(
-            @UserIdInt int userId, String id, String packageName, ComponentName activityComponent,
-            Icon icon, String title, int titleResId, String text, int textResId,
-            String disabledMessage, int disabledMessageResId, Set<String> categories, Intent intent,
-            PersistableBundle intentPersistableExtras,
+            @UserIdInt int userId, String id, String packageName, ComponentName activity,
+            Icon icon, CharSequence title, int titleResId, CharSequence text, int textResId,
+            CharSequence disabledMessage, int disabledMessageResId, Set<String> categories,
+            Intent intent, PersistableBundle intentPersistableExtras,
             int rank, PersistableBundle extras, long lastChangedTimestamp,
             int flags, int iconResId, String bitmapPath) {
         mUserId = userId;
         mId = id;
         mPackageName = packageName;
-        mActivityComponent = activityComponent;
+        mActivity = activity;
         mIcon = icon;
         mTitle = title;
         mTitleResId = titleResId;
diff --git a/core/java/android/content/pm/ShortcutManager.java b/core/java/android/content/pm/ShortcutManager.java
index 44fa98d..3d214a84 100644
--- a/core/java/android/content/pm/ShortcutManager.java
+++ b/core/java/android/content/pm/ShortcutManager.java
@@ -28,7 +28,7 @@
 
 // TODO Enhance javadoc
 /**
- * <b>TODO: Update to reflect DR changes.</b><br>
+ * <b>TODO: Update to reflect DR changes, such as manifest shortcuts.</b><br>
  *
  * {@link ShortcutManager} manages shortcuts created by applications.
  *
@@ -36,8 +36,8 @@
  *
  * An application can publish shortcuts with {@link #setDynamicShortcuts(List)} and
  * {@link #addDynamicShortcuts(List)}.  There can be at most
- * {@link #getMaxDynamicShortcutCount()} number of dynamic shortcuts at a time from the same
- * application.
+ * {@link #getMaxShortcutCountForActivity()} number of dynamic shortcuts at a time from the
+ * same application.
  * A dynamic shortcut can be deleted with {@link #removeDynamicShortcuts(List)}, and apps
  * can also use {@link #removeAllDynamicShortcuts()} to delete all dynamic shortcuts.
  *
@@ -51,7 +51,8 @@
  * <p>The number of pinned shortcuts does not affect the number of dynamic shortcuts that can be
  * published by an application at a time.
  * No matter how many pinned shortcuts that Launcher has for an application, the
- * application can still always publish {@link #getMaxDynamicShortcutCount()} number of dynamic
+ * application can still always publish {@link #getMaxShortcutCountForActivity()} number of
+ * dynamic
  * shortcuts.
  *
  * <h3>Shortcut IDs</h3>
@@ -132,7 +133,7 @@
      * @return {@code true} if the call has succeeded. {@code false} if the call is rate-limited.
      *
      * @throws IllegalArgumentException if {@code shortcutInfoList} contains more than
-     * {@link #getMaxDynamicShortcutCount()} shortcuts.
+     * {@link #getMaxShortcutCountForActivity()} shortcuts.
      */
     public boolean setDynamicShortcuts(@NonNull List<ShortcutInfo> shortcutInfoList) {
         try {
@@ -145,7 +146,7 @@
 
     /**
      * Return all dynamic shortcuts from the caller application.  The number of result items
-     * will not exceed the value returned by {@link #getMaxDynamicShortcutCount()}.
+     * will not exceed the value returned by {@link #getMaxShortcutCountForActivity()}.
      */
     @NonNull
     public List<ShortcutInfo> getDynamicShortcuts() {
@@ -158,6 +159,19 @@
     }
 
     /**
+     * TODO Javadoc
+     */
+    @NonNull
+    public List<ShortcutInfo> getManifestShortcuts() {
+        try {
+            return mService.getManifestShortcuts(mContext.getPackageName(), injectMyUserId())
+                    .getList();
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
      * Publish list of dynamic shortcuts.  If there's already dynamic or pinned shortcuts with
      * the same IDs, they will all be updated.
      *
@@ -269,9 +283,21 @@
     }
 
     /**
-     * Return the max number of dynamic shortcuts that each application can have at a time.
+     * TODO Javadoc
      */
-    public int getMaxDynamicShortcutCount() {
+    public void enableShortcuts(@NonNull List<String> shortcutIds) {
+        try {
+            mService.enableShortcuts(mContext.getPackageName(), shortcutIds, injectMyUserId());
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Return the max number of dynamic shortcuts + manifest shortcuts that each launcehr icon
+     * can have at a time.
+     */
+    public int getMaxShortcutCountForActivity() {
         try {
             return mService.getMaxDynamicShortcutCount(mContext.getPackageName(), injectMyUserId());
         } catch (RemoteException e) {
@@ -308,10 +334,23 @@
     }
 
     /**
-     * Return the max width and height for icons, in pixels.
+     * Return the max width for icons, in pixels.
      */
-    public int getIconMaxDimensions() {
+    public int getIconMaxWidth() {
         try {
+            // TODO Implement it properly using xdpi.
+            return mService.getIconMaxDimensions(mContext.getPackageName(), injectMyUserId());
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Return the max height for icons, in pixels.
+     */
+    public int getIconMaxHeight() {
+        try {
+            // TODO Implement it properly using ydpi.
             return mService.getIconMaxDimensions(mContext.getPackageName(), injectMyUserId());
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
diff --git a/core/java/android/content/res/Configuration.java b/core/java/android/content/res/Configuration.java
index f6445e6..6f43d99 100644
--- a/core/java/android/content/res/Configuration.java
+++ b/core/java/android/content/res/Configuration.java
@@ -207,7 +207,7 @@
     public static final int SCREENLAYOUT_COMPAT_NEEDED = 0x10000000;
 
     /**
-     * Bit mask of overall layout of the screen.  Currently there are two
+     * Bit mask of overall layout of the screen.  Currently there are four
      * fields:
      * <p>The {@link #SCREENLAYOUT_SIZE_MASK} bits define the overall size
      * of the screen.  They may be one of
diff --git a/core/java/android/content/res/ResourcesImpl.java b/core/java/android/content/res/ResourcesImpl.java
index 32a2795..000751e 100644
--- a/core/java/android/content/res/ResourcesImpl.java
+++ b/core/java/android/content/res/ResourcesImpl.java
@@ -292,8 +292,10 @@
             return mAssets.openNonAsset(value.assetCookie, value.string.toString(),
                     AssetManager.ACCESS_STREAMING);
         } catch (Exception e) {
-            NotFoundException rnf = new NotFoundException("File " + value.string.toString() +
-                    " from drawable resource ID #0x" + Integer.toHexString(id));
+            // Note: value.string might be null
+            NotFoundException rnf = new NotFoundException("File "
+                    + (value.string == null ? "(null)" : value.string.toString())
+                    + " from drawable resource ID #0x" + Integer.toHexString(id));
             rnf.initCause(e);
             throw rnf;
         }
diff --git a/core/java/android/net/PacProxySelector.java b/core/java/android/net/PacProxySelector.java
index 9bdf4f6..85bf79a 100644
--- a/core/java/android/net/PacProxySelector.java
+++ b/core/java/android/net/PacProxySelector.java
@@ -30,6 +30,7 @@
 import java.net.ProxySelector;
 import java.net.SocketAddress;
 import java.net.URI;
+import java.net.URISyntaxException;
 import java.util.List;
 
 /**
@@ -67,7 +68,15 @@
         String response = null;
         String urlString;
         try {
+            // Strip path and username/password from URI so it's not visible to PAC script. The
+            // path often contains credentials the app does not want exposed to a potentially
+            // malicious PAC script.
+            if (!"http".equalsIgnoreCase(uri.getScheme())) {
+                uri = new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), "/", null, null);
+            }
             urlString = uri.toURL().toString();
+        } catch (URISyntaxException e) {
+            urlString = uri.getHost();
         } catch (MalformedURLException e) {
             urlString = uri.getHost();
         }
diff --git a/core/java/android/os/Environment.java b/core/java/android/os/Environment.java
index f6e8940..6af0678 100644
--- a/core/java/android/os/Environment.java
+++ b/core/java/android/os/Environment.java
@@ -324,6 +324,33 @@
     }
 
     /**
+     * Return preloads directory.
+     * <p>This directory may contain pre-loaded content such as
+     * {@link #getDataPreloadsDemoDirectory() demo videos} and
+     * {@link #getDataPreloadsAppsDirectory() APK files} .
+     * {@hide}
+     */
+    public static File getDataPreloadsDirectory() {
+        return new File(getDataDirectory(), "preloads");
+    }
+
+    /**
+     * @see #getDataPreloadsDirectory()
+     * {@hide}
+     */
+    public static File getDataPreloadsDemoDirectory() {
+        return new File(getDataPreloadsDirectory(), "demo");
+    }
+
+    /**
+     * @see #getDataPreloadsDirectory()
+     * {@hide}
+     */
+    public static File getDataPreloadsAppsDirectory() {
+        return new File(getDataPreloadsDirectory(), "apps");
+    }
+
+    /**
      * Return the primary shared/external storage directory. This directory may
      * not currently be accessible if it has been mounted by the user on their
      * computer, has been removed from the device, or some other problem has
diff --git a/core/java/android/os/PowerManager.java b/core/java/android/os/PowerManager.java
index c285acb..ce7a124 100644
--- a/core/java/android/os/PowerManager.java
+++ b/core/java/android/os/PowerManager.java
@@ -1021,9 +1021,19 @@
     }
 
     /**
-     * Returns True if the device supports Sustained Performance Mode.
-     * Applications Should check if the device supports this mode, before
-     * using {@link android.view.Window#setSustainedPerformanceMode}.
+     * This function checks if the device has implemented Sustained Performance
+     * Mode. This needs to be checked only once and is constant for a particular
+     * device/release.
+     *
+     * Sustained Performance Mode is intended to provide a consistent level of
+     * performance for prolonged amount of time.
+     *
+     * Applications should check if the device supports this mode, before using
+     * {@link android.view.Window#setSustainedPerformanceMode}.
+     *
+     * @return Returns True if the device supports it, false otherwise.
+     *
+     * @see android.view.Window#setSustainedPerformanceMode
      */
     public boolean isSustainedPerformanceModeSupported() {
         return mContext.getResources().getBoolean(
diff --git a/core/java/android/os/UserManager.java b/core/java/android/os/UserManager.java
index 2613994..4b0cb09 100644
--- a/core/java/android/os/UserManager.java
+++ b/core/java/android/os/UserManager.java
@@ -789,7 +789,7 @@
      */
     public boolean isPrimaryUser() {
         UserInfo user = getUserInfo(UserHandle.myUserId());
-        return user != null ? user.isPrimary() : false;
+        return user != null && user.isPrimary();
     }
 
     /**
@@ -855,7 +855,19 @@
      */
     public boolean isGuestUser() {
         UserInfo user = getUserInfo(UserHandle.myUserId());
-        return user != null ? user.isGuest() : false;
+        return user != null && user.isGuest();
+    }
+
+    /**
+     * Checks if the calling app is running in a demo user.
+     * <p>
+     * Caller must hold the MANAGE_USERS permission.
+     * @return whether the caller is a demo user.
+     * @hide
+     */
+    public boolean isDemoUser() {
+        UserInfo user = getUserInfo(UserHandle.myUserId());
+        return user != null && user.isDemo();
     }
 
     /**
@@ -924,6 +936,7 @@
 
     /** {@hide} */
     public boolean isUserRunning(int userId) {
+        // TODO Switch to using UMS internal isUserRunning
         try {
             return ActivityManagerNative.getDefault().isUserRunning(userId, 0);
         } catch (RemoteException re) {
diff --git a/core/java/android/os/UserManagerInternal.java b/core/java/android/os/UserManagerInternal.java
index 551ea6b..93afb43 100644
--- a/core/java/android/os/UserManagerInternal.java
+++ b/core/java/android/os/UserManagerInternal.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2015 The Android Open Source Project
+ * Copyright (C) 2016 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.
@@ -11,7 +11,7 @@
  * 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.
+ * limitations under the License
  */
 package android.os;
 
@@ -129,15 +129,23 @@
 
     /**
      * Return whether the given user is running in an
-     * {@link com.android.server.am.UserState#STATE_RUNNING_UNLOCKING "unlocking"} or
-     * {@link com.android.server.am.UserState#STATE_RUNNING_UNLOCKED "unlocked"} state.
+     * {@code UserState.STATE_RUNNING_UNLOCKING} or
+     * {@code UserState.STATE_RUNNING_UNLOCKED} state.
      */
     public abstract boolean isUserUnlockingOrUnlocked(int userId);
 
     /**
-     * Sets whether the given user is running in an
-     * {@link com.android.server.am.UserState#STATE_RUNNING_UNLOCKING "unlocking"} or
-     * {@link com.android.server.am.UserState#STATE_RUNNING_UNLOCKED "unlocked"} state.
+     * Return whether the given user is running
      */
-    public abstract void setUserUnlockingOrUnlocked(int userId, boolean unlockingOrUnlocked);
+    public abstract boolean isUserRunning(int userId);
+
+    /**
+     * Set user's running state
+     */
+    public abstract void setUserState(int userId, int userState);
+
+    /**
+     * Remove user's running state
+     */
+    public abstract void removeUserState(int userId);
 }
diff --git a/core/java/android/os/storage/StorageManager.java b/core/java/android/os/storage/StorageManager.java
index fbf7b26..485bbd1 100644
--- a/core/java/android/os/storage/StorageManager.java
+++ b/core/java/android/os/storage/StorageManager.java
@@ -114,6 +114,8 @@
     /** {@hide} */
     public static final int FLAG_INCLUDE_INVISIBLE = 1 << 10;
 
+    private static volatile IMountService sMountService = null;
+
     private final Context mContext;
     private final ContentResolver mResolver;
 
@@ -1064,15 +1066,17 @@
 
     /** {@hide} */
     public static boolean isUserKeyUnlocked(int userId) {
-        final IMountService mount = IMountService.Stub
-                .asInterface(ServiceManager.getService("mount"));
-        if (mount == null) {
+        if (sMountService == null) {
+            sMountService = IMountService.Stub
+                    .asInterface(ServiceManager.getService("mount"));
+        }
+        if (sMountService == null) {
             Slog.w(TAG, "Early during boot, assuming locked");
             return false;
         }
         final long token = Binder.clearCallingIdentity();
         try {
-            return mount.isUserKeyUnlocked(userId);
+            return sMountService.isUserKeyUnlocked(userId);
         } catch (RemoteException e) {
             throw e.rethrowAsRuntimeException();
         } finally {
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index 9e8e5ef..1b4c15d 100755
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -60,8 +60,8 @@
 import android.util.ArrayMap;
 import android.util.ArraySet;
 import android.util.Log;
-
 import android.util.MemoryIntArray;
+
 import com.android.internal.annotations.GuardedBy;
 import com.android.internal.util.ArrayUtils;
 import com.android.internal.widget.ILockSettings;
@@ -7969,6 +7969,7 @@
          * idle_factor                      (float)
          * min_time_to_alarm                (long)
          * max_temp_app_whitelist_duration  (long)
+         * notification_whitelist_duration  (long)
          * </pre>
          *
          * <p>
diff --git a/core/java/android/text/TextUtils.java b/core/java/android/text/TextUtils.java
index 1c13962..b8fd2ff 100644
--- a/core/java/android/text/TextUtils.java
+++ b/core/java/android/text/TextUtils.java
@@ -67,7 +67,8 @@
     private static final String TAG = "TextUtils";
 
     /* package */ static final char[] ELLIPSIS_NORMAL = { '\u2026' }; // this is "..."
-    private static final String ELLIPSIS_STRING = new String(ELLIPSIS_NORMAL);
+    /** {@hide} */
+    public static final String ELLIPSIS_STRING = new String(ELLIPSIS_NORMAL);
 
     /* package */ static final char[] ELLIPSIS_TWO_DOTS = { '\u2025' }; // this is ".."
     private static final String ELLIPSIS_TWO_DOTS_STRING = new String(ELLIPSIS_TWO_DOTS);
diff --git a/core/java/android/view/NotificationHeaderView.java b/core/java/android/view/NotificationHeaderView.java
index 6e6baea..3069e5a 100644
--- a/core/java/android/view/NotificationHeaderView.java
+++ b/core/java/android/view/NotificationHeaderView.java
@@ -21,9 +21,9 @@
 import android.graphics.Canvas;
 import android.graphics.Outline;
 import android.graphics.Rect;
-import android.graphics.drawable.ColorDrawable;
 import android.graphics.drawable.Drawable;
 import android.util.AttributeSet;
+import android.view.accessibility.AccessibilityNodeInfo;
 import android.widget.ImageView;
 import android.widget.RemoteViews;
 
@@ -230,6 +230,7 @@
     public void setOnClickListener(@Nullable OnClickListener l) {
         mExpandClickListener = l;
         setOnTouchListener(mExpandClickListener != null ? mTouchListener : null);
+        setFocusable(l != null);
         updateTouchListener();
     }
 
@@ -379,6 +380,19 @@
         return this;
     }
 
+    @Override
+    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
+        super.onInitializeAccessibilityNodeInfo(info);
+        if (mExpandClickListener != null) {
+            AccessibilityNodeInfo.AccessibilityAction expand
+                    = new AccessibilityNodeInfo.AccessibilityAction(
+                    AccessibilityNodeInfo.ACTION_CLICK,
+                    getContext().getString(
+                            com.android.internal.R.string.expand_action_accessibility));
+            info.addAction(expand);
+        }
+    }
+
     public ImageView getExpandButton() {
         return mExpandButton;
     }
diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java
index 414882a..88605db 100644
--- a/core/java/android/view/View.java
+++ b/core/java/android/view/View.java
@@ -22812,6 +22812,11 @@
         boolean mKeepScreenOn;
 
         /**
+         * Set during a traveral if the light center needs to be updated.
+         */
+        boolean mNeedsUpdateLightCenter;
+
+        /**
          * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
          */
         int mSystemUiVisibility;
diff --git a/core/java/android/view/ViewRootImpl.java b/core/java/android/view/ViewRootImpl.java
index d812cb4..0d648c1 100644
--- a/core/java/android/view/ViewRootImpl.java
+++ b/core/java/android/view/ViewRootImpl.java
@@ -80,7 +80,6 @@
 import android.view.accessibility.IAccessibilityInteractionConnectionCallback;
 import android.view.animation.AccelerateDecelerateInterpolator;
 import android.view.animation.Interpolator;
-import android.view.inputmethod.InputConnection;
 import android.view.inputmethod.InputMethodManager;
 import android.widget.Scroller;
 
@@ -920,6 +919,11 @@
                 // Recompute system ui visibility.
                 mAttachInfo.mRecomputeGlobalAttributes = true;
             }
+            if ((mWindowAttributesChangesFlag
+                    & WindowManager.LayoutParams.LAYOUT_CHANGED) != 0) {
+                // Request to update light center.
+                mAttachInfo.mNeedsUpdateLightCenter = true;
+            }
             if (mWindowAttributes.packageName == null) {
                 mWindowAttributes.packageName = mBasePackageName;
             }
@@ -2226,13 +2230,16 @@
             }
             mAttachInfo.mWindowLeft = frame.left;
             mAttachInfo.mWindowTop = frame.top;
-
-            // Update the light position for the new window offsets.
+        }
+        if (windowMoved || mAttachInfo.mNeedsUpdateLightCenter) {
+            // Update the light position for the new offsets.
             if (mAttachInfo.mHardwareRenderer != null) {
                 mAttachInfo.mHardwareRenderer.setLightCenter(mAttachInfo);
             }
+            mAttachInfo.mNeedsUpdateLightCenter = false;
         }
     }
+
     private void handleOutOfResourcesException(Surface.OutOfResourcesException e) {
         Log.e(mTag, "OutOfResourcesException initializing HW surface", e);
         try {
diff --git a/core/java/android/view/inputmethod/InputMethodManagerInternal.java b/core/java/android/view/inputmethod/InputMethodManagerInternal.java
index ce9908c..77df4e3 100644
--- a/core/java/android/view/inputmethod/InputMethodManagerInternal.java
+++ b/core/java/android/view/inputmethod/InputMethodManagerInternal.java
@@ -32,4 +32,9 @@
      * Called by the window manager to let the input method manager rotate the input method.
      */
     void switchInputMethod(boolean forwardDirection);
+
+    /**
+     * Hides the current input method, if visible.
+     */
+    void hideCurrentInputMethod();
 }
diff --git a/core/java/android/widget/AbsListView.java b/core/java/android/widget/AbsListView.java
index 28ade80..b331be7 100644
--- a/core/java/android/widget/AbsListView.java
+++ b/core/java/android/widget/AbsListView.java
@@ -2675,19 +2675,49 @@
         return (mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK ? 0 : mPaddingBottom;
     }
 
+    /**
+     * @hide
+     */
+    @Override
+    protected void internalSetPadding(int left, int top, int right, int bottom) {
+        super.internalSetPadding(left, top, right, bottom);
+        if (isLayoutRequested()) {
+            handleBoundsChange();
+        }
+    }
+
     @Override
     protected void onSizeChanged(int w, int h, int oldw, int oldh) {
-        if (getChildCount() > 0) {
-            mDataChanged = true;
-            rememberSyncState();
-        }
-
+        handleBoundsChange();
         if (mFastScroll != null) {
             mFastScroll.onSizeChanged(w, h, oldw, oldh);
         }
     }
 
     /**
+     * Called when bounds of the AbsListView are changed. AbsListView marks data set as changed
+     * and force layouts all children that don't have exact measure specs.
+     * <p>
+     * This invalidation is necessary, otherwise, AbsListView may think the children are valid and
+     * fail to relayout them properly to accommodate for new bounds.
+     */
+    void handleBoundsChange() {
+        final int childCount = getChildCount();
+        if (childCount > 0) {
+            mDataChanged = true;
+            rememberSyncState();
+            for (int i = 0; i < childCount; i++) {
+                final View child = getChildAt(i);
+                final ViewGroup.LayoutParams lp = child.getLayoutParams();
+                // force layout child unless it has exact specs
+                if (lp == null || lp.width < 1 || lp.height < 1) {
+                    child.forceLayout();
+                }
+            }
+        }
+    }
+
+    /**
      * @return True if the current touch mode requires that we draw the selector in the pressed
      *         state.
      */
diff --git a/core/java/android/widget/DateTimeView.java b/core/java/android/widget/DateTimeView.java
index d2ee866..e172044 100644
--- a/core/java/android/widget/DateTimeView.java
+++ b/core/java/android/widget/DateTimeView.java
@@ -34,6 +34,7 @@
 import android.os.Handler;
 import android.text.format.Time;
 import android.util.AttributeSet;
+import android.view.accessibility.AccessibilityNodeInfo;
 import android.widget.RemoteViews.RemoteView;
 
 import com.android.internal.R;
@@ -118,7 +119,6 @@
     public void setTime(long time) {
         Time t = new Time();
         t.set(time);
-        t.second = 0;
         mTimeMillis = t.toMillis(false);
         mTime = new Date(t.year-1900, t.month, t.monthDay, t.hour, t.minute, 0);
         update();
@@ -333,6 +333,63 @@
         update();
     }
 
+    @Override
+    public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
+        super.onInitializeAccessibilityNodeInfoInternal(info);
+        if (mShowRelativeTime) {
+            // The short version of the time might not be completely understandable and for
+            // accessibility we rather have a longer version.
+            long now = System.currentTimeMillis();
+            long duration = Math.abs(now - mTimeMillis);
+            int count;
+            boolean past = (now >= mTimeMillis);
+            String result;
+            if (duration < MINUTE_IN_MILLIS) {
+                result = mNowText;
+            } else if (duration < HOUR_IN_MILLIS) {
+                count = (int)(duration / MINUTE_IN_MILLIS);
+                result = String.format(getContext().getResources().getQuantityString(past
+                                ? com.android.internal.
+                                        R.plurals.duration_minutes_relative
+                                : com.android.internal.
+                                        R.plurals.duration_minutes_relative_future,
+                        count),
+                        count);
+            } else if (duration < DAY_IN_MILLIS) {
+                count = (int)(duration / HOUR_IN_MILLIS);
+                result = String.format(getContext().getResources().getQuantityString(past
+                                ? com.android.internal.
+                                        R.plurals.duration_hours_relative
+                                : com.android.internal.
+                                        R.plurals.duration_hours_relative_future,
+                        count),
+                        count);
+            } else if (duration < YEAR_IN_MILLIS) {
+                // In weird cases it can become 0 because of daylight savings
+                TimeZone timeZone = TimeZone.getDefault();
+                count = Math.max(Math.abs(dayDistance(timeZone, mTimeMillis, now)), 1);
+                result = String.format(getContext().getResources().getQuantityString(past
+                                ? com.android.internal.
+                                        R.plurals.duration_days_relative
+                                : com.android.internal.
+                                        R.plurals.duration_days_relative_future,
+                        count),
+                        count);
+
+            } else {
+                count = (int)(duration / YEAR_IN_MILLIS);
+                result = String.format(getContext().getResources().getQuantityString(past
+                                ? com.android.internal.
+                                        R.plurals.duration_years_relative
+                                : com.android.internal.
+                                        R.plurals.duration_years_relative_future,
+                        count),
+                        count);
+            }
+            info.setText(result);
+        }
+    }
+
     private static class ReceiverInfo {
         private final ArrayList<DateTimeView> mAttachedViews = new ArrayList<DateTimeView>();
         private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java
index 3711b94..5cbd284 100644
--- a/core/java/android/widget/TextView.java
+++ b/core/java/android/widget/TextView.java
@@ -6857,11 +6857,11 @@
                         .setLineSpacing(mSpacingAdd, mSpacingMult)
                         .setIncludePad(mIncludePad)
                         .setBreakStrategy(mBreakStrategy)
-                        .setHyphenationFrequency(mHyphenationFrequency)
-                        .setMaxLines(mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE);
+                        .setHyphenationFrequency(mHyphenationFrequency);
                 if (shouldEllipsize) {
                     builder.setEllipsize(mEllipsize)
-                            .setEllipsizedWidth(ellipsisWidth);
+                            .setEllipsizedWidth(ellipsisWidth)
+                            .setMaxLines(mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE);
                 }
                 mHintLayout = builder.build();
             }
@@ -6948,12 +6948,11 @@
                     .setLineSpacing(mSpacingAdd, mSpacingMult)
                     .setIncludePad(mIncludePad)
                     .setBreakStrategy(mBreakStrategy)
-                    .setHyphenationFrequency(mHyphenationFrequency)
-                    .setMaxLines(mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE);
+                    .setHyphenationFrequency(mHyphenationFrequency);
             if (shouldEllipsize) {
                 builder.setEllipsize(effectiveEllipsize)
-                        .setEllipsizedWidth(ellipsisWidth);
-
+                        .setEllipsizedWidth(ellipsisWidth)
+                        .setMaxLines(mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE);
             }
             // TODO: explore always setting maxLines
             result = builder.build();
@@ -6983,19 +6982,14 @@
         return false;
     }
 
-    private static int desired(Layout layout, int maxLines) {
+    private static int desired(Layout layout) {
         int n = layout.getLineCount();
         CharSequence text = layout.getText();
         float max = 0;
 
-        // if maxLines is set, and the text length is greater that the length of the text in the
-        // layout, it means that there is a cut-off and we cannot use it.
-        if (maxLines != -1 && text.length() > layout.getLineEnd(n - 1)) {
-            return -1;
-        }
-
         // if any line was wrapped, we can't use it.
         // but it's ok for the last line not to have a newline
+
         for (int i = 0; i < n - 1; i++) {
             if (text.charAt(layout.getLineEnd(i) - 1) != '\n')
                 return -1;
@@ -7068,7 +7062,7 @@
             width = widthSize;
         } else {
             if (mLayout != null && mEllipsize == null) {
-                des = desired(mLayout, getMaxLines());
+                des = desired(mLayout);
             }
 
             if (des < 0) {
@@ -7100,7 +7094,7 @@
                 int hintWidth;
 
                 if (mHintLayout != null && mEllipsize == null) {
-                    hintDes = desired(mHintLayout, getMaxLines());
+                    hintDes = desired(mHintLayout);
                 }
 
                 if (hintDes < 0) {
diff --git a/core/java/com/android/internal/app/LocaleHelper.java b/core/java/com/android/internal/app/LocaleHelper.java
index 106999b..d26be91 100644
--- a/core/java/com/android/internal/app/LocaleHelper.java
+++ b/core/java/com/android/internal/app/LocaleHelper.java
@@ -16,9 +16,11 @@
 
 package com.android.internal.app;
 
+import android.annotation.IntRange;
 import android.icu.text.ListFormatter;
 import android.icu.util.ULocale;
 import android.os.LocaleList;
+import android.text.TextUtils;
 
 import java.text.Collator;
 import java.util.Comparator;
@@ -153,16 +155,34 @@
      * @param locales the list of locales whose names is to be displayed.
      * @param displayLocale the locale in which to display the names.
      *                      If this is null, it will use the default locale.
+     * @param maxLocales maximum number of locales to display. Generates ellipsis after that.
      * @return the locale aware list of locale names
      */
-    public static String getDisplayLocaleList(LocaleList locales, Locale displayLocale) {
+    public static String getDisplayLocaleList(
+            LocaleList locales, Locale displayLocale, @IntRange(from=1) int maxLocales) {
+
         final Locale dispLocale = displayLocale == null ? Locale.getDefault() : displayLocale;
 
-        int localeCount = locales.size();
-        final String[] localeNames = new String[localeCount];
+        final boolean ellipsisNeeded = locales.size() > maxLocales;
+        final int localeCount, listCount;
+        if (ellipsisNeeded) {
+            localeCount = maxLocales;
+            listCount = maxLocales + 1;  // One extra slot for the ellipsis
+        } else {
+            listCount = localeCount = locales.size();
+        }
+        final String[] localeNames = new String[listCount];
         for (int i = 0; i < localeCount; i++) {
             localeNames[i] = LocaleHelper.getDisplayName(locales.get(i), dispLocale, false);
         }
+        if (ellipsisNeeded) {
+            // Theoretically, we want to extract this from ICU's Resource Bundle for
+            // "Ellipsis/final", which seems to have different strings than the normal ellipsis for
+            // Hong Kong Traditional Chinese (zh_Hant_HK) and Dzongkha (dz). But that has two
+            // problems: it's expensive to extract it, and in case the output string becomes
+            // automatically ellipsized, it can result in weird output.
+            localeNames[maxLocales] = TextUtils.ELLIPSIS_STRING;
+        }
 
         ListFormatter lfn = ListFormatter.getInstance(dispLocale);
         return lfn.format((Object[]) localeNames);
diff --git a/core/java/com/android/internal/app/PlatLogoActivity.java b/core/java/com/android/internal/app/PlatLogoActivity.java
index 5944568..ef2fd0d 100644
--- a/core/java/com/android/internal/app/PlatLogoActivity.java
+++ b/core/java/com/android/internal/app/PlatLogoActivity.java
@@ -53,6 +53,8 @@
 import android.widget.ImageView;
 
 public class PlatLogoActivity extends Activity {
+    public static final boolean REVEAL_THE_NAME = true;
+
     FrameLayout mLayout;
     int mTapCount;
     int mKeyCount;
@@ -100,6 +102,19 @@
                     public boolean onLongClick(View v) {
                         if (mTapCount < 5) return false;
 
+                        if (REVEAL_THE_NAME) {
+                            final Drawable overlay = getDrawable(
+                                com.android.internal.R.drawable.platlogo_m);
+                            overlay.setBounds(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
+                            im.getOverlay().clear();
+                            im.getOverlay().add(overlay);
+                            overlay.setAlpha(0);
+                            ObjectAnimator.ofInt(overlay, "alpha", 0, 255)
+                                .setDuration(500)
+                                .start();
+                            return true;
+                        }
+
                         final ContentResolver cr = getContentResolver();
                         if (Settings.System.getLong(cr, Settings.System.EGG_MODE, 0)
                                 == 0) {
diff --git a/core/java/com/android/internal/os/BatteryStatsImpl.java b/core/java/com/android/internal/os/BatteryStatsImpl.java
index 93dc625..8b02352 100644
--- a/core/java/com/android/internal/os/BatteryStatsImpl.java
+++ b/core/java/com/android/internal/os/BatteryStatsImpl.java
@@ -8153,14 +8153,17 @@
     }
 
     private void resetAllStatsLocked() {
+        final long uptimeMillis = mClocks.uptimeMillis();
+        final long elapsedRealtimeMillis = mClocks.elapsedRealtime();
         mStartCount = 0;
-        initTimes(mClocks.uptimeMillis() * 1000, mClocks.elapsedRealtime() * 1000);
+        initTimes(uptimeMillis * 1000, elapsedRealtimeMillis * 1000);
         mScreenOnTimer.reset(false);
         for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
             mScreenBrightnessTimer[i].reset(false);
         }
         mInteractiveTimer.reset(false);
         mPowerSaveModeEnabledTimer.reset(false);
+        mLastIdleTimeStart = elapsedRealtimeMillis;
         mLongestLightIdleTime = 0;
         mLongestFullIdleTime = 0;
         mDeviceIdleModeLightTimer.reset(false);
diff --git a/core/java/com/android/internal/policy/DecorView.java b/core/java/com/android/internal/policy/DecorView.java
index f596636..a065219 100644
--- a/core/java/com/android/internal/policy/DecorView.java
+++ b/core/java/com/android/internal/policy/DecorView.java
@@ -45,6 +45,7 @@
 import android.graphics.Rect;
 import android.graphics.Region;
 import android.graphics.Shader;
+import android.graphics.drawable.ColorDrawable;
 import android.graphics.drawable.Drawable;
 import android.os.RemoteException;
 import android.util.DisplayMetrics;
@@ -907,10 +908,12 @@
         if (getBackground() != drawable) {
             setBackgroundDrawable(drawable);
             if (drawable != null) {
-                mResizingBackgroundDrawable = drawable;
+                mResizingBackgroundDrawable = enforceNonTranslucentBackground(drawable,
+                        mWindow.isTranslucent() || mWindow.isShowingWallpaper());
             } else {
                 mResizingBackgroundDrawable = getResizingBackgroundDrawable(
-                        getContext(), 0, mWindow.mBackgroundFallbackResource);
+                        getContext(), 0, mWindow.mBackgroundFallbackResource,
+                        mWindow.isTranslucent() || mWindow.isShowingWallpaper());
             }
             if (mResizingBackgroundDrawable != null) {
                 mResizingBackgroundDrawable.getPadding(mBackgroundPadding);
@@ -1785,7 +1788,8 @@
     private void loadBackgroundDrawablesIfNeeded() {
         if (mResizingBackgroundDrawable == null) {
             mResizingBackgroundDrawable = getResizingBackgroundDrawable(getContext(),
-                    mWindow.mBackgroundResource, mWindow.mBackgroundFallbackResource);
+                    mWindow.mBackgroundResource, mWindow.mBackgroundFallbackResource,
+                    mWindow.isTranslucent() || mWindow.isShowingWallpaper());
             if (mResizingBackgroundDrawable == null) {
                 // We shouldn't really get here as the background fallback should be always
                 // available since it is defaulted by the system.
@@ -1893,21 +1897,41 @@
      * user is resizing the window of an activity in multi-window mode.
      */
     public static Drawable getResizingBackgroundDrawable(Context context, int backgroundRes,
-            int backgroundFallbackRes) {
+            int backgroundFallbackRes, boolean windowTranslucent) {
         if (backgroundRes != 0) {
             final Drawable drawable = context.getDrawable(backgroundRes);
             if (drawable != null) {
-                return drawable;
+                return enforceNonTranslucentBackground(drawable, windowTranslucent);
             }
         }
 
         if (backgroundFallbackRes != 0) {
             final Drawable fallbackDrawable = context.getDrawable(backgroundFallbackRes);
             if (fallbackDrawable != null) {
-                return fallbackDrawable;
+                return enforceNonTranslucentBackground(fallbackDrawable, windowTranslucent);
             }
         }
-        return null;
+        return new ColorDrawable(Color.BLACK);
+    }
+
+    /**
+     * Enforces a drawable to be non-translucent to act as a background if needed, i.e. if the
+     * window is not translucent.
+     */
+    private static Drawable enforceNonTranslucentBackground(Drawable drawable,
+            boolean windowTranslucent) {
+        if (!windowTranslucent && drawable instanceof ColorDrawable) {
+            ColorDrawable colorDrawable = (ColorDrawable) drawable;
+            int color = colorDrawable.getColor();
+            if (Color.alpha(color) != 255) {
+                ColorDrawable copy = (ColorDrawable) colorDrawable.getConstantState().newDrawable()
+                        .mutate();
+                copy.setColor(
+                        Color.argb(255, Color.red(color), Color.green(color), Color.blue(color)));
+                return copy;
+            }
+        }
+        return drawable;
     }
 
     /**
@@ -2037,7 +2061,7 @@
     private void drawResizingShadowIfNeeded(DisplayListCanvas canvas) {
         if (mResizeMode != RESIZE_MODE_DOCKED_DIVIDER || mWindow.mIsFloating
                 || mWindow.isTranslucent()
-                || (mWindow.getAttributes().flags & FLAG_SHOW_WALLPAPER) != 0) {
+                || mWindow.isShowingWallpaper()) {
             return;
         }
         canvas.save();
diff --git a/core/java/com/android/internal/policy/PhoneWindow.java b/core/java/com/android/internal/policy/PhoneWindow.java
index 4f15ece..9ad750d 100644
--- a/core/java/com/android/internal/policy/PhoneWindow.java
+++ b/core/java/com/android/internal/policy/PhoneWindow.java
@@ -509,6 +509,13 @@
     }
 
     /**
+     * @return Whether the window is currently showing the wallpaper.
+     */
+    boolean isShowingWallpaper() {
+        return (getAttributes().flags & FLAG_SHOW_WALLPAPER) != 0;
+    }
+
+    /**
      * Return a LayoutInflater instance that can be used to inflate XML view layout
      * resources for use in this Window.
      *
diff --git a/core/jni/android_graphics_drawable_VectorDrawable.cpp b/core/jni/android_graphics_drawable_VectorDrawable.cpp
index 9e69f79..045f127 100644
--- a/core/jni/android_graphics_drawable_VectorDrawable.cpp
+++ b/core/jni/android_graphics_drawable_VectorDrawable.cpp
@@ -36,6 +36,13 @@
     return reinterpret_cast<jlong>(tree);
 }
 
+static jlong createTreeFromCopy(JNIEnv*, jobject, jlong treePtr, jlong groupPtr) {
+    VectorDrawable::Group* rootGroup = reinterpret_cast<VectorDrawable::Group*>(groupPtr);
+    VectorDrawable::Tree* treeToCopy = reinterpret_cast<VectorDrawable::Tree*>(treePtr);
+    VectorDrawable::Tree* tree = new VectorDrawable::Tree(treeToCopy, rootGroup);
+    return reinterpret_cast<jlong>(tree);
+}
+
 static jlong createEmptyFullPath(JNIEnv*, jobject) {
     VectorDrawable::FullPath* newPath = new VectorDrawable::FullPath();
     return reinterpret_cast<jlong>(newPath);
@@ -344,6 +351,7 @@
 
 static const JNINativeMethod gMethods[] = {
         {"nCreateTree", "!(J)J", (void*)createTree},
+        {"nCreateTreeFromCopy", "!(JJ)J", (void*)createTreeFromCopy},
         {"nSetRendererViewportSize", "!(JFF)V", (void*)setTreeViewportSize},
         {"nSetRootAlpha", "!(JF)Z", (void*)setRootAlpha},
         {"nGetRootAlpha", "!(J)F", (void*)getRootAlpha},
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index 6c289dc..b2028a7 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -481,6 +481,8 @@
     <protected-broadcast android:name="android.intent.action.MANAGED_PROFILE_AVAILABLE" />
     <protected-broadcast android:name="android.intent.action.MANAGED_PROFILE_UNAVAILABLE" />
 
+    <protected-broadcast android:name="com.android.server.am.ACTION_RESET_DEMO" />
+
     <!-- ====================================================================== -->
     <!--                          RUNTIME PERMISSIONS                           -->
     <!-- ====================================================================== -->
diff --git a/core/res/res/drawable-nodpi/default_wallpaper.png b/core/res/res/drawable-nodpi/default_wallpaper.png
index 91ad252..ce546f0 100644
--- a/core/res/res/drawable-nodpi/default_wallpaper.png
+++ b/core/res/res/drawable-nodpi/default_wallpaper.png
Binary files differ
diff --git a/core/res/res/drawable-nodpi/platlogo_m.xml b/core/res/res/drawable-nodpi/platlogo_m.xml
index f19e045..d9a558d 100644
--- a/core/res/res/drawable-nodpi/platlogo_m.xml
+++ b/core/res/res/drawable-nodpi/platlogo_m.xml
@@ -1,5 +1,5 @@
 <!--
-Copyright (C) 2015 The Android Open Source Project
+Copyright (C) 2016 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.
@@ -19,19 +19,54 @@
         android:viewportWidth="48.0"
         android:viewportHeight="48.0">
     <path
-        android:fillColor="#08000000"
-        android:pathData="M13.5,34.5l13.3,13.3c11,-1.3,19.7,-10,21,-21L34.5,13.5L13.5,34.5z"
-        />
+        android:fillColor="#FFFFFFFF"
+        android:pathData="M33.8,38l-25.5,-25.5l-1.7000003,0.6999998l25.499998,25.5z"/>
     <path
-        android:pathData="M24,24c0,0,0,2.4,0,5.2s0,5.2,0,5.2L34.5,24V13.5L24,24z"
-        android:fillColor="#FFFFFF"/>
+        android:fillColor="#FFFFFFFF"
+        android:pathData="M40.8,34.8l-25.4,-25.5l-1.6999998,0.6999998l25.5,25.5z"/>
     <path
-        android:pathData="M24,24L13.5,13.5V24L24,34.5c0,0,0,-2.4,0,-5.2S24,24,24,24z"
-        android:fillColor="#EEEEEE"/>
+        android:fillColor="#FFFFFFFF"
+        android:pathData="M11.1,13.1l-0.3,-0.4l1.1,-1.3l0,0l-1.6,0.8l-0.4,-0.4l2.6,-1.2l0.4,0.4l-1.1,1.3l0,0l1.6,-0.8l0.3,0.4L11.1,13.1z"/>
     <path
-        android:pathData="M13.5,34.5l10.5,0.0l-10.5,-10.5z"
-        android:fillColor="#DDDDDD"/>
+        android:fillColor="#FFFFFFFF"
+        android:pathData="M13,14.2l-0.5,-0.5l-0.6,0.2l-0.4,-0.4l3.1,-0.7l0.4,0.4l-2.1,1.7l-0.4,-0.4L13,14.2z M13,13.6l0.3,0.3l0.8,-0.6   l0,0L13,13.6z"/>
     <path
-        android:pathData="M34.5,34.5l0.0,-10.5l-10.5,10.5z"
-        android:fillColor="#DDDDDD"/>
+        android:fillColor="#FFFFFFFF"
+        android:pathData="M16.3,14.6l-1.6,1.2l0,0l2.2,-0.6l0.5,0.5l-2.6,1.2l-0.3,-0.4l0.7,-0.3l1,-0.4l0,0l-2.1,0.5L13.9,16l1.4,-1.1l0,0   l-0.9,0.5l-0.7,0.3l-0.3,-0.4l2.6,-1.2L16.3,14.6z"/>
+    <path
+        android:fillColor="#FFFFFFFF"
+        android:pathData="M17.4,17.8l-0.6,-0.6l-0.7,0.3l0.7,0.7l-0.4,0.2l-1,-1l2.6,-1.2l1,1l-0.4,0.2l-0.7,-0.7L17.2,17l0.6,0.6L17.4,17.8   z"/>
+    <path
+        android:fillColor="#FFFFFFFF"
+        android:pathData="M18.8,18.7L18.8,18.7l1.3,-0.2l0.4,0.4l-2.1,0.3l-0.9,0.4l-0.3,-0.4l1,-0.4l1.2,-1.2l0.4,0.4L18.8,18.7z"/>
+    <path
+        android:fillColor="#FFFFFFFF"
+        android:pathData="M22.2,20.5l-1.6,1.2l0,0l2.2,-0.6l0.5,0.5l-2.6,1.2l-0.3,-0.4l0.7,-0.3l1,-0.4l0,0L20,22.1l-0.2,-0.2l1.4,-1.1l0,0   l-0.9,0.5l-0.7,0.3l-0.3,-0.4l2.6,-1.2L22.2,20.5z"/>
+    <path
+        android:fillColor="#FFFFFFFF"
+        android:pathData="M22,23.6c0,0,0.1,0.1,0.2,0.1c0.1,0,0.2,0,0.3,-0.1l0.3,0.3c-0.2,0.1,-0.4,0.1,-0.6,0.1c-0.2,0,-0.4,-0.1,-0.5,-0.2   c-0.2,-0.2,-0.2,-0.3,-0.1,-0.5c0.1,-0.2,0.2,-0.3,0.5,-0.4l0.2,-0.1c0.3,-0.1,0.5,-0.2,0.8,-0.2c0.2,0,0.5,0.1,0.6,0.3   c0.1,0.1,0.2,0.3,0.1,0.4c0,0.1,-0.2,0.3,-0.4,0.4L23,23.4c0.1,0,0.2,-0.1,0.2,-0.2c0,-0.1,0,-0.1,0,-0.2C23.1,23,23,22.9,22.9,23   c-0.1,0,-0.2,0.1,-0.4,0.1l-0.2,0.1c-0.2,0.1,-0.3,0.1,-0.3,0.2C21.9,23.5,21.9,23.5,22,23.6z"/>
+    <path
+        android:fillColor="#FFFFFFFF"
+        android:pathData="M23.8,25.9l-0.3,-0.4l1.1,-1.3l0,0L22.9,25l-0.4,-0.4l2.6,-1.2l0.4,0.4l-1.1,1.3l0,0l1.6,-0.8l0.3,0.4L23.8,25.9z"/>
+    <path
+        android:fillColor="#FFFFFFFF"
+        android:pathData="M25.7,27l-0.5,-0.5l-0.6,0.2l-0.4,-0.4l3.1,-0.7l0.4,0.4l-2.1,1.7l-0.4,-0.4L25.7,27z M25.7,26.4l0.3,0.3l0.8,-0.6   l0,0L25.7,26.4z"/>
+    <path
+        android:fillColor="#FFFFFFFF"
+        android:pathData="M29,27.4l-1.6,1.2l0,0l2.2,-0.6l0.5,0.5l-2.6,1.2l-0.3,-0.4l0.8,-0.3l1,-0.4l0,0L26.8,29l-0.2,-0.2l1.4,-1.1l0,0   L27,28.1l-0.8,0.3l-0.3,-0.4l2.6,-1.2L29,27.4z"/>
+    <path
+        android:fillColor="#FFFFFFFF"
+        android:pathData="M30,30.6L29.5,30l-0.7,0.3l0.7,0.7L29,31.2l-1,-1l2.6,-1.2l1,1l-0.4,0.2l-0.7,-0.7l-0.6,0.3l0.6,0.6L30,30.6z"/>
+    <path
+        android:fillColor="#FFFFFFFF"
+        android:pathData="M31.5,32.1l-0.6,-0.6L29.8,32l-0.4,-0.4l2.6,-1.2l1,1l-0.4,0.2L32,31l-0.7,0.3l0.6,0.6L31.5,32.1z"/>
+    <path
+        android:fillColor="#FFFFFFFF"
+        android:pathData="M32,33.5L31.6,33L31,33.2l-0.4,-0.4l3.1,-0.7l0.4,0.4l-2.1,1.7l-0.4,-0.4L32,33.5z M32.1,32.9l0.3,0.3l0.8,-0.6   l0,0L32.1,32.9z"/>
+    <path
+        android:fillColor="#FFFFFFFF"
+        android:pathData="M34.3,35.3c-0.3,0.1,-0.5,0.2,-0.8,0.1c-0.2,0,-0.5,-0.1,-0.6,-0.3c-0.2,-0.2,-0.2,-0.4,-0.2,-0.5   c0.1,-0.2,0.2,-0.3,0.6,-0.5l0.8,-0.4c0.3,-0.1,0.6,-0.2,0.9,-0.2c0.3,0,0.5,0.1,0.7,0.3c0.2,0.2,0.3,0.4,0.2,0.5c0,0.2,-0.2,0.3,-0.5,0.5   l-0.3,-0.4c0.2,-0.1,0.3,-0.1,0.3,-0.2c0,-0.1,0,-0.1,-0.1,-0.2C35,34,34.9,34,34.8,34c-0.1,0,-0.3,0,-0.5,0.1l-0.8,0.4   c-0.2,0.1,-0.3,0.2,-0.4,0.2c0,0.1,0,0.1,0,0.2c0.1,0.1,0.2,0.1,0.3,0.1c0.1,0,0.2,0,0.4,-0.1L34.3,35.3z"/>
+    <path
+        android:fillColor="#FFFFFFFF"
+        android:pathData="M36,36.6L35.4,36l-0.7,0.3l0.7,0.7l-0.4,0.2l-1,-1l2.6,-1.2l1,1l-0.4,0.2l-0.7,-0.7l-0.6,0.3l0.6,0.6L36,36.6z"/>
 </vector>
diff --git a/core/res/res/layout/app_error_dialog.xml b/core/res/res/layout/app_error_dialog.xml
index 7147ea2..9a5bbd4 100644
--- a/core/res/res/layout/app_error_dialog.xml
+++ b/core/res/res/layout/app_error_dialog.xml
@@ -35,11 +35,11 @@
     />
 
     <Button
-            android:id="@+id/aerr_reset"
+            android:id="@+id/aerr_close"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
-            android:text="@string/aerr_reset"
-            android:drawableStart="@drawable/ic_refresh"
+            android:text="@string/aerr_close"
+            android:drawableStart="@drawable/ic_close"
             style="@style/aerr_list_item"
     />
 
@@ -53,15 +53,6 @@
     />
 
     <Button
-            android:id="@+id/aerr_close"
-            android:layout_width="match_parent"
-            android:layout_height="wrap_content"
-            android:text="@string/aerr_close"
-            android:drawableStart="@drawable/ic_close"
-            style="@style/aerr_list_item"
-    />
-
-    <Button
             android:id="@+id/aerr_mute"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
diff --git a/core/res/res/layout/notification_template_header.xml b/core/res/res/layout/notification_template_header.xml
index d16dcc6..38ea92a 100644
--- a/core/res/res/layout/notification_template_header.xml
+++ b/core/res/res/layout/notification_template_header.xml
@@ -96,6 +96,7 @@
         android:layout_height="wrap_content"
         android:paddingTop="1dp"
         android:visibility="gone"
+        android:contentDescription="@string/expand_button_content_description"
         />
     <ImageView android:id="@+id/profile_badge"
         android:layout_width="@dimen/notification_badge_size"
diff --git a/core/res/res/layout/preference_list_fragment.xml b/core/res/res/layout/preference_list_fragment.xml
index fc53a1a..c43975e 100644
--- a/core/res/res/layout/preference_list_fragment.xml
+++ b/core/res/res/layout/preference_list_fragment.xml
@@ -33,8 +33,6 @@
             style="?attr/preferenceFragmentListStyle"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
-            android:paddingTop="0dip"
-            android:paddingBottom="@dimen/preference_fragment_padding_bottom"
             android:scrollbarStyle="@integer/preference_fragment_scrollbarStyle"
             android:clipToPadding="false"
             android:drawSelectorOnTop="false"
diff --git a/core/res/res/layout/preference_list_fragment_material.xml b/core/res/res/layout/preference_list_fragment_material.xml
index e411c0e..db2fe7d 100644
--- a/core/res/res/layout/preference_list_fragment_material.xml
+++ b/core/res/res/layout/preference_list_fragment_material.xml
@@ -32,8 +32,6 @@
         <ListView android:id="@android:id/list"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
-            android:paddingTop="0dip"
-            android:paddingBottom="@dimen/preference_fragment_padding_bottom"
             style="?attr/preferenceFragmentListStyle"
             android:scrollbarStyle="@integer/preference_fragment_scrollbarStyle"
             android:clipToPadding="false"
diff --git a/core/res/res/layout/preference_material.xml b/core/res/res/layout/preference_material.xml
index bf0fda9..871b99c 100644
--- a/core/res/res/layout/preference_material.xml
+++ b/core/res/res/layout/preference_material.xml
@@ -67,7 +67,8 @@
             android:layout_alignStart="@id/title"
             android:textAppearance="?attr/textAppearanceListItemSecondary"
             android:textColor="?attr/textColorSecondary"
-            android:maxLines="10" />
+            android:maxLines="10"
+            android:ellipsize="end" />
 
     </RelativeLayout>
 
diff --git a/core/res/res/values-notround/styles_micro.xml b/core/res/res/values-notround/styles_micro.xml
index c45e36459..1294660 100644
--- a/core/res/res/values-notround/styles_micro.xml
+++ b/core/res/res/values-notround/styles_micro.xml
@@ -17,4 +17,6 @@
     <style name="TextAppearance.Micro.AlertDialog.Message" parent="TextAppearance.Micro.Small">
         <item name="textAlignment">viewStart</item>
     </style>
+    <style name="PreferenceFragment.Micro" parent="PreferenceFragment.Material"/>
+    <style name="PreferenceFragmentList.Micro" parent="PreferenceFragmentList.Material"/>
 </resources>
diff --git a/core/res/res/values-round/styles_micro.xml b/core/res/res/values-round/styles_micro.xml
index 7a1e511..f19adde 100644
--- a/core/res/res/values-round/styles_micro.xml
+++ b/core/res/res/values-round/styles_micro.xml
@@ -17,4 +17,13 @@
     <style name="TextAppearance.Micro.AlertDialog.Message" parent="TextAppearance.Micro.Small">
         <item name="textAlignment">center</item>
     </style>
+    <style name="PreferenceFragment.Micro" parent="PreferenceFragment.Material">
+        <item name="paddingTop">22dp</item>
+        <item name="paddingBottom">22dp</item>
+        <item name="clipToPadding">false</item>
+    </style>
+    <style name="PreferenceFragmentList.Micro" parent="PreferenceFragmentList.Material">
+        <item name="paddingTop">22dp</item>
+        <item name="paddingBottom">22dp</item>
+    </style>
 </resources>
diff --git a/core/res/res/values/attrs.xml b/core/res/res/values/attrs.xml
index 69b91ef..88c5629 100644
--- a/core/res/res/values/attrs.xml
+++ b/core/res/res/values/attrs.xml
@@ -8244,4 +8244,17 @@
                    color. -->
         <attr name="colorBackground" />
     </declare-styleable>
+
+    <declare-styleable name="Shortcut">
+        <attr name="shortcutId" format="string" />
+        <attr name="enabled" />
+        <attr name="shortcutRank" format="integer" />
+        <attr name="shortcutIcon" format="reference" />
+        <attr name="shortcutTitle" format="reference" />
+        <attr name="shortcutText" format="reference" />
+        <attr name="shortcutDisabledMessage" format="reference" />
+        <attr name="shortcutCategories" format="string" />
+        <attr name="shortcutIntentAction" format="string" />
+        <attr name="shortcutIntentData" format="string" />
+    </declare-styleable>
 </resources>
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index f528999..be2cc23 100644
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -2477,7 +2477,9 @@
          remote provider -->
     <string name="config_tvRemoteServicePackage" translatable="false"></string>
 
-    <!-- True if the device supports persisting security logs across reboots. -->
+    <!-- True if the device supports persisting security logs across reboots.
+         This requires the device's kernel to have pstore and pmsg enabled,
+         and DRAM to be powered and refreshed through all stages of reboot. -->
     <bool name="config_supportPreRebootSecurityLogs">false</bool>
 
     <!-- Default files to pin via Pinner Service -->
diff --git a/core/res/res/values/public.xml b/core/res/res/values/public.xml
index fee2469..421bc2a 100644
--- a/core/res/res/values/public.xml
+++ b/core/res/res/values/public.xml
@@ -2734,4 +2734,17 @@
     <public type="id" name="list_container" />
     <public type="id" name="switch_widget" />
 
+  <!-- ===============================================================
+       Resources added in version N MR1 of the platform
+       =============================================================== -->
+    <eat-comment />
+    <public type="attr" name="shortcutId" />
+    <public type="attr" name="shortcutRank" />
+    <public type="attr" name="shortcutIcon" />
+    <public type="attr" name="shortcutTitle" />
+    <public type="attr" name="shortcutText" />
+    <public type="attr" name="shortcutDisabledMessage" />
+    <public type="attr" name="shortcutCategories" />
+    <public type="attr" name="shortcutIntentAction" />
+    <public type="attr" name="shortcutIntentData" />
 </resources>
diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml
index 2232942..3b3fc43 100644
--- a/core/res/res/values/strings.xml
+++ b/core/res/res/values/strings.xml
@@ -2474,6 +2474,54 @@
         <item quantity="other">in <xliff:g example="2" id="count">%d</xliff:g>y</item>
     </plurals>
 
+    <!-- Phrase describing a relative time using minutes in the past that is not shown on the screen but used for accessibility. [CHAR LIMIT=NONE] -->
+    <plurals name="duration_minutes_relative">
+        <item quantity="one"><xliff:g example="1" id="count">%d</xliff:g> minute ago</item>
+        <item quantity="other"><xliff:g example="2" id="count">%d</xliff:g> minutes ago</item>
+    </plurals>
+
+    <!-- Phrase describing a relative time using hours in the past that is not shown on the screen but used for accessibility. [CHAR LIMIT=NONE] -->
+    <plurals name="duration_hours_relative">
+        <item quantity="one"><xliff:g example="1" id="count">%d</xliff:g> hour ago</item>
+        <item quantity="other"><xliff:g example="2" id="count">%d</xliff:g> hours ago</item>
+    </plurals>
+
+    <!-- Phrase describing a relative time using days in the past that is not shown on the screen but used for accessibility. [CHAR LIMIT=NONE] -->
+    <plurals name="duration_days_relative">
+        <item quantity="one"><xliff:g example="1" id="count">%d</xliff:g> day ago</item>
+        <item quantity="other"><xliff:g example="2" id="count">%d</xliff:g> days ago</item>
+    </plurals>
+
+    <!-- Phrase describing a relative time using years in the past that is not shown on the screen but used for accessibility. [CHAR LIMIT=NONE] -->
+    <plurals name="duration_years_relative">
+        <item quantity="one"><xliff:g example="1" id="count">%d</xliff:g> year ago</item>
+        <item quantity="other"><xliff:g example="2" id="count">%d</xliff:g> years ago</item>
+    </plurals>
+
+    <!-- Phrase describing a relative time using minutes that is not shown on the screen but used for accessibility. This version should be a future point in time. [CHAR LIMIT=NONE] -->
+    <plurals name="duration_minutes_relative_future">
+        <item quantity="one">in <xliff:g example="1" id="count">%d</xliff:g> minute</item>
+        <item quantity="other">in <xliff:g example="2" id="count">%d</xliff:g> minutes</item>
+    </plurals>
+
+    <!-- Phrase describing a relative time using hours that is not shown on the screen but used for accessibility. This version should be a future point in time. [CHAR LIMIT=NONE] -->
+    <plurals name="duration_hours_relative_future">
+        <item quantity="one">in <xliff:g example="1" id="count">%d</xliff:g> hour</item>
+        <item quantity="other">in <xliff:g example="2" id="count">%d</xliff:g> hours</item>
+    </plurals>
+
+    <!-- Phrase describing a relative time using days that is not shown on the screen but used for accessibility. This version should be a future point in time. [CHAR LIMIT=NONE] -->
+    <plurals name="duration_days_relative_future">
+        <item quantity="one">in <xliff:g example="1" id="count">%d</xliff:g> day</item>
+        <item quantity="other">in <xliff:g example="2" id="count">%d</xliff:g> days</item>
+    </plurals>
+
+    <!-- Phrase describing a relative time using years that is not shown on the screen but used for accessibility. This version should be a future point in time. [CHAR LIMIT=NONE] -->
+    <plurals name="duration_years_relative_future">
+        <item quantity="one">in <xliff:g example="1" id="count">%d</xliff:g> year</item>
+        <item quantity="other">in <xliff:g example="2" id="count">%d</xliff:g> years</item>
+    </plurals>
+
     <!-- Title for error alert when a video cannot be played.  it can be used by any app. -->
     <string name="VideoView_error_title">Video problem</string>
     <!-- Text for error alert when a video container is not valid for progressive download/playback. -->
@@ -2677,9 +2725,7 @@
     <!-- Text of the alert that is displayed when a process has crashed repeatedly. -->
     <string name="aerr_process_repeated"><xliff:g id="process">%1$s</xliff:g> keeps stopping</string>
     <!-- Button that restarts a crashed application -->
-    <string name="aerr_restart">Restart app</string>
-    <!-- Button that clears cache and restarts a crashed application -->
-    <string name="aerr_reset">Reset and restart app</string>
+    <string name="aerr_restart">Open app again</string>
     <!-- Button that sends feedback about a crashed application -->
     <string name="aerr_report">Send feedback</string>
     <!-- Button that closes a crashed application -->
@@ -4081,8 +4127,6 @@
 
     <!-- Notify use that they are in Lock-to-app -->
     <string name="lock_to_app_toast">To unpin this screen, touch &amp; hold Back.</string>
-    <!-- Notify use that they are in Lock-to-app in accessibility mode -->
-    <string name="lock_to_app_toast_accessible">To unpin this screen, touch &amp; hold Overview.</string>
     <!-- Notify user that they are locked in lock-to-app mode -->
     <string name="lock_to_app_toast_locked">App is pinned: Unpinning isn\'t allowed on this device.</string>
     <!-- Starting lock-to-app indication. -->
@@ -4215,6 +4259,12 @@
     <!-- Content description of the work profile icon in the notification. -->
     <string name="notification_work_profile_content_description">Work profile</string>
 
+    <!-- Content description of the expand button icon in the notification.-->
+    <string name="expand_button_content_description">Expand button</string>
+
+    <!-- Accessibility action description on the expand button. -->
+    <string name="expand_action_accessibility">toggle expansion</string>
+
     <!-- User visible name for USB MIDI Peripheral port -->
     <string name="usb_midi_peripheral_name">Android USB Peripheral Port</string>
     <!-- Manufacturer name for USB MIDI Peripheral port -->
@@ -4312,6 +4362,11 @@
     <!-- The representation of a time duration when negative. An example is -1:14. This can be used with a countdown timer for example.-->
     <string name="negative_duration">\u2212<xliff:g id="time" example="1:14">%1$s</xliff:g></string>
 
+    <!-- Title of notification to start a new demo session when device is in retail mode [CHAR LIMIT=NONE] -->
+    <string name="reset_retail_demo_mode_title">Restart Session</string>
+    <!-- Text of notification to start a new demo session when device is in retail mode [CHAR LIMIT=NONE] -->
+    <string name="reset_retail_demo_mode_text">Tap to start a new demo session</string>
+
     <!-- Title of notification shown when device has been forced to safe mode after a security compromise. -->
     <string name="audit_safemode_notification">Factory reset to use this device without restrictions</string>
     <!-- Description of notification shown when device has been forced to safe mode after a security compromise. -->
diff --git a/core/res/res/values/styles.xml b/core/res/res/values/styles.xml
index 790dcfa..273086d 100644
--- a/core/res/res/values/styles.xml
+++ b/core/res/res/values/styles.xml
@@ -1122,6 +1122,8 @@
     <style name="PreferenceFragmentList">
         <item name="paddingStart">@dimen/preference_fragment_padding_side</item>
         <item name="paddingEnd">@dimen/preference_fragment_padding_side</item>
+        <item name="paddingTop">0dp</item>
+        <item name="paddingBottom">@dimen/preference_fragment_padding_bottom</item>
     </style>
 
     <!-- Other Misc Styles -->
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index ba58f15..2de5006 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -698,7 +698,6 @@
   <java-symbol type="string" name="last_month" />
   <java-symbol type="string" name="launchBrowserDefault" />
   <java-symbol type="string" name="lock_to_app_toast" />
-  <java-symbol type="string" name="lock_to_app_toast_accessible" />
   <java-symbol type="string" name="lock_to_app_toast_locked" />
   <java-symbol type="string" name="lock_to_app_start" />
   <java-symbol type="string" name="lock_to_app_exit" />
@@ -1889,6 +1888,8 @@
   <java-symbol type="string" name="config_persistentDataPackageName" />
   <java-symbol type="string" name="audit_safemode_notification" />
   <java-symbol type="string" name="audit_safemode_notification_details" />
+  <java-symbol type="string" name="reset_retail_demo_mode_title" />
+  <java-symbol type="string" name="reset_retail_demo_mode_text" />
 
   <java-symbol type="layout" name="resolver_list" />
   <java-symbol type="id" name="resolver_list" />
@@ -2447,7 +2448,6 @@
   <java-symbol type="id" name="work_widget_badge_icon" />
 
   <java-symbol type="id" name="aerr_report" />
-  <java-symbol type="id" name="aerr_reset" />
   <java-symbol type="id" name="aerr_restart" />
   <java-symbol type="id" name="aerr_close" />
   <java-symbol type="id" name="aerr_mute" />
@@ -2523,6 +2523,15 @@
   <java-symbol type="plurals" name="duration_days_shortest_future" />
   <java-symbol type="plurals" name="duration_years_shortest_future" />
 
+  <java-symbol type="plurals" name="duration_minutes_relative" />
+  <java-symbol type="plurals" name="duration_hours_relative" />
+  <java-symbol type="plurals" name="duration_days_relative" />
+  <java-symbol type="plurals" name="duration_years_relative" />
+  <java-symbol type="plurals" name="duration_minutes_relative_future" />
+  <java-symbol type="plurals" name="duration_hours_relative_future" />
+  <java-symbol type="plurals" name="duration_days_relative_future" />
+  <java-symbol type="plurals" name="duration_years_relative_future" />
+
   <java-symbol type="string" name="now_string_shortest" />
 
   <!-- Encryption notification while accounts are locked by credential encryption -->
@@ -2560,6 +2569,7 @@
 
   <!-- WallpaperManager config -->
   <java-symbol type="string" name="config_wallpaperCropperPackage" />
+  <java-symbol type="string" name="expand_action_accessibility" />
 
   <java-symbol type="id" name="textSpacerNoTitle" />
   <java-symbol type="id" name="titleDividerNoCustom" />
diff --git a/core/res/res/values/themes.xml b/core/res/res/values/themes.xml
index 998eea5..aecda44 100644
--- a/core/res/res/values/themes.xml
+++ b/core/res/res/values/themes.xml
@@ -174,7 +174,6 @@
 
         <!-- Window attributes -->
         <item name="windowBackground">@drawable/screen_background_selector_dark</item>
-        <item name="windowBackgroundFallback">?attr/colorBackground</item>
         <item name="windowClipToOutline">false</item>
         <item name="windowFrame">@null</item>
         <item name="windowNoTitle">false</item>
diff --git a/core/res/res/values/themes_micro.xml b/core/res/res/values/themes_micro.xml
index 89c33b2..63a6a484 100644
--- a/core/res/res/values/themes_micro.xml
+++ b/core/res/res/values/themes_micro.xml
@@ -52,6 +52,10 @@
         <item name="colorPrimary">@color/primary_micro_dark</item>
         <item name="colorAccent">@color/accent_micro_dark</item>
         <item name="colorEdgeEffect">?attr/colorPrimary</item>
+
+        <!-- Preference styles -->
+        <item name="preferenceFragmentStyle">@style/PreferenceFragment.Micro</item>
+        <item name="preferenceFragmentListStyle">@style/PreferenceFragmentList.Micro</item>
     </style>
 
     <style name="Theme.Micro" parent="Theme.MicroBase">
diff --git a/core/tests/bluetoothtests/src/android/bluetooth/BluetoothStressTest.java b/core/tests/bluetoothtests/src/android/bluetooth/BluetoothStressTest.java
index 755e7c4..31ce95e 100644
--- a/core/tests/bluetoothtests/src/android/bluetooth/BluetoothStressTest.java
+++ b/core/tests/bluetoothtests/src/android/bluetooth/BluetoothStressTest.java
@@ -35,6 +35,7 @@
     /** The amount of time to sleep between issuing start/stop SCO in ms. */
     private static final long SCO_SLEEP_TIME = 2 * 1000;
 
+    private BluetoothAdapter mAdapter;
     private BluetoothTestUtils mTestUtils;
 
     @Override
@@ -42,13 +43,18 @@
         super.setUp();
 
         Context context = getInstrumentation().getTargetContext();
+        mAdapter = BluetoothAdapter.getDefaultAdapter();
         mTestUtils = new BluetoothTestUtils(context, TAG, OUTPUT_FILE);
+
+        // Start all tests in a disabled state.
+        if (mAdapter.isEnabled()) {
+            mTestUtils.disable(mAdapter);
+        }
     }
 
     @Override
     protected void tearDown() throws Exception {
         super.tearDown();
-
         mTestUtils.close();
     }
 
@@ -61,13 +67,10 @@
             return;
         }
 
-        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
-        mTestUtils.disable(adapter);
-
         for (int i = 0; i < iterations; i++) {
             mTestUtils.writeOutput("enable iteration " + (i + 1) + " of " + iterations);
-            mTestUtils.enable(adapter);
-            mTestUtils.disable(adapter);
+            mTestUtils.enable(mAdapter);
+            mTestUtils.disable(mAdapter);
         }
     }
 
@@ -80,18 +83,14 @@
             return;
         }
 
-        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
-        mTestUtils.disable(adapter);
-        mTestUtils.enable(adapter);
-        mTestUtils.undiscoverable(adapter);
+        mTestUtils.enable(mAdapter);
+        mTestUtils.undiscoverable(mAdapter);
 
         for (int i = 0; i < iterations; i++) {
             mTestUtils.writeOutput("discoverable iteration " + (i + 1) + " of " + iterations);
-            mTestUtils.discoverable(adapter);
-            mTestUtils.undiscoverable(adapter);
+            mTestUtils.discoverable(mAdapter);
+            mTestUtils.undiscoverable(mAdapter);
         }
-
-        mTestUtils.disable(adapter);
     }
 
     /**
@@ -103,18 +102,14 @@
             return;
         }
 
-        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
-        mTestUtils.disable(adapter);
-        mTestUtils.enable(adapter);
-        mTestUtils.stopScan(adapter);
+        mTestUtils.enable(mAdapter);
+        mTestUtils.stopScan(mAdapter);
 
         for (int i = 0; i < iterations; i++) {
             mTestUtils.writeOutput("scan iteration " + (i + 1) + " of " + iterations);
-            mTestUtils.startScan(adapter);
-            mTestUtils.stopScan(adapter);
+            mTestUtils.startScan(mAdapter);
+            mTestUtils.stopScan(mAdapter);
         }
-
-        mTestUtils.disable(adapter);
     }
 
     /**
@@ -125,19 +120,16 @@
         if (iterations == 0) {
             return;
         }
-        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
-        mTestUtils.disable(adapter);
-        mTestUtils.enable(adapter);
-        mTestUtils.disablePan(adapter);
+
+        mTestUtils.enable(mAdapter);
+        mTestUtils.disablePan(mAdapter);
 
         for (int i = 0; i < iterations; i++) {
             mTestUtils.writeOutput("testEnablePan iteration " + (i + 1) + " of "
                     + iterations);
-            mTestUtils.enablePan(adapter);
-            mTestUtils.disablePan(adapter);
+            mTestUtils.enablePan(mAdapter);
+            mTestUtils.disablePan(mAdapter);
         }
-
-        mTestUtils.disable(adapter);
     }
 
     /**
@@ -152,19 +144,16 @@
             return;
         }
 
-        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
-        BluetoothDevice device = adapter.getRemoteDevice(BluetoothTestRunner.sDeviceAddress);
-        mTestUtils.disable(adapter);
-        mTestUtils.enable(adapter);
-        mTestUtils.unpair(adapter, device);
+        BluetoothDevice device = mAdapter.getRemoteDevice(BluetoothTestRunner.sDeviceAddress);
+        mTestUtils.enable(mAdapter);
+        mTestUtils.unpair(mAdapter, device);
 
         for (int i = 0; i < iterations; i++) {
             mTestUtils.writeOutput("pair iteration " + (i + 1) + " of " + iterations);
-            mTestUtils.pair(adapter, device, BluetoothTestRunner.sDevicePairPasskey,
+            mTestUtils.pair(mAdapter, device, BluetoothTestRunner.sDevicePairPasskey,
                     BluetoothTestRunner.sDevicePairPin);
-            mTestUtils.unpair(adapter, device);
+            mTestUtils.unpair(mAdapter, device);
         }
-        mTestUtils.disable(adapter);
     }
 
     /**
@@ -178,19 +167,16 @@
         if (iterations == 0) {
             return;
         }
-        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
-        BluetoothDevice device = adapter.getRemoteDevice(BluetoothTestRunner.sDeviceAddress);
-        mTestUtils.disable(adapter);
-        mTestUtils.enable(adapter);
-        mTestUtils.unpair(adapter, device);
+        BluetoothDevice device = mAdapter.getRemoteDevice(BluetoothTestRunner.sDeviceAddress);
+        mTestUtils.enable(mAdapter);
+        mTestUtils.unpair(mAdapter, device);
 
         for (int i = 0; i < iterations; i++) {
             mTestUtils.writeOutput("acceptPair iteration " + (i + 1) + " of " + iterations);
-            mTestUtils.acceptPair(adapter, device, BluetoothTestRunner.sDevicePairPasskey,
+            mTestUtils.acceptPair(mAdapter, device, BluetoothTestRunner.sDevicePairPasskey,
                     BluetoothTestRunner.sDevicePairPin);
-            mTestUtils.unpair(adapter, device);
+            mTestUtils.unpair(mAdapter, device);
         }
-        mTestUtils.disable(adapter);
     }
 
     /**
@@ -205,25 +191,22 @@
             return;
         }
 
-        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
-        BluetoothDevice device = adapter.getRemoteDevice(BluetoothTestRunner.sDeviceAddress);
-        mTestUtils.disable(adapter);
-        mTestUtils.enable(adapter);
-        mTestUtils.unpair(adapter, device);
-        mTestUtils.pair(adapter, device, BluetoothTestRunner.sDevicePairPasskey,
+        BluetoothDevice device = mAdapter.getRemoteDevice(BluetoothTestRunner.sDeviceAddress);
+        mTestUtils.enable(mAdapter);
+        mTestUtils.unpair(mAdapter, device);
+        mTestUtils.pair(mAdapter, device, BluetoothTestRunner.sDevicePairPasskey,
                 BluetoothTestRunner.sDevicePairPin);
-        mTestUtils.disconnectProfile(adapter, device, BluetoothProfile.A2DP, null);
+        mTestUtils.disconnectProfile(mAdapter, device, BluetoothProfile.A2DP, null);
 
         for (int i = 0; i < iterations; i++) {
             mTestUtils.writeOutput("connectA2dp iteration " + (i + 1) + " of " + iterations);
-            mTestUtils.connectProfile(adapter, device, BluetoothProfile.A2DP,
+            mTestUtils.connectProfile(mAdapter, device, BluetoothProfile.A2DP,
                     String.format("connectA2dp(device=%s)", device));
-            mTestUtils.disconnectProfile(adapter, device, BluetoothProfile.A2DP,
+            mTestUtils.disconnectProfile(mAdapter, device, BluetoothProfile.A2DP,
                     String.format("disconnectA2dp(device=%s)", device));
         }
 
-        mTestUtils.unpair(adapter, device);
-        mTestUtils.disable(adapter);
+        mTestUtils.unpair(mAdapter, device);
     }
 
     /**
@@ -238,25 +221,22 @@
             return;
         }
 
-        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
-        BluetoothDevice device = adapter.getRemoteDevice(BluetoothTestRunner.sDeviceAddress);
-        mTestUtils.disable(adapter);
-        mTestUtils.enable(adapter);
-        mTestUtils.unpair(adapter, device);
-        mTestUtils.pair(adapter, device, BluetoothTestRunner.sDevicePairPasskey,
+        BluetoothDevice device = mAdapter.getRemoteDevice(BluetoothTestRunner.sDeviceAddress);
+        mTestUtils.enable(mAdapter);
+        mTestUtils.unpair(mAdapter, device);
+        mTestUtils.pair(mAdapter, device, BluetoothTestRunner.sDevicePairPasskey,
                 BluetoothTestRunner.sDevicePairPin);
-        mTestUtils.disconnectProfile(adapter, device, BluetoothProfile.HEADSET, null);
+        mTestUtils.disconnectProfile(mAdapter, device, BluetoothProfile.HEADSET, null);
 
         for (int i = 0; i < iterations; i++) {
             mTestUtils.writeOutput("connectHeadset iteration " + (i + 1) + " of " + iterations);
-            mTestUtils.connectProfile(adapter, device, BluetoothProfile.HEADSET,
+            mTestUtils.connectProfile(mAdapter, device, BluetoothProfile.HEADSET,
                     String.format("connectHeadset(device=%s)", device));
-            mTestUtils.disconnectProfile(adapter, device, BluetoothProfile.HEADSET,
+            mTestUtils.disconnectProfile(mAdapter, device, BluetoothProfile.HEADSET,
                     String.format("disconnectHeadset(device=%s)", device));
         }
 
-        mTestUtils.unpair(adapter, device);
-        mTestUtils.disable(adapter);
+        mTestUtils.unpair(mAdapter, device);
     }
 
     /**
@@ -271,25 +251,22 @@
             return;
         }
 
-        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
-        BluetoothDevice device = adapter.getRemoteDevice(BluetoothTestRunner.sDeviceAddress);
-        mTestUtils.disable(adapter);
-        mTestUtils.enable(adapter);
-        mTestUtils.unpair(adapter, device);
-        mTestUtils.pair(adapter, device, BluetoothTestRunner.sDevicePairPasskey,
+        BluetoothDevice device = mAdapter.getRemoteDevice(BluetoothTestRunner.sDeviceAddress);
+        mTestUtils.enable(mAdapter);
+        mTestUtils.unpair(mAdapter, device);
+        mTestUtils.pair(mAdapter, device, BluetoothTestRunner.sDevicePairPasskey,
                 BluetoothTestRunner.sDevicePairPin);
-        mTestUtils.disconnectProfile(adapter, device, BluetoothProfile.INPUT_DEVICE, null);
+        mTestUtils.disconnectProfile(mAdapter, device, BluetoothProfile.INPUT_DEVICE, null);
 
         for (int i = 0; i < iterations; i++) {
             mTestUtils.writeOutput("connectInput iteration " + (i + 1) + " of " + iterations);
-            mTestUtils.connectProfile(adapter, device, BluetoothProfile.INPUT_DEVICE,
+            mTestUtils.connectProfile(mAdapter, device, BluetoothProfile.INPUT_DEVICE,
                     String.format("connectInput(device=%s)", device));
-            mTestUtils.disconnectProfile(adapter, device, BluetoothProfile.INPUT_DEVICE,
+            mTestUtils.disconnectProfile(mAdapter, device, BluetoothProfile.INPUT_DEVICE,
                     String.format("disconnectInput(device=%s)", device));
         }
 
-        mTestUtils.unpair(adapter, device);
-        mTestUtils.disable(adapter);
+        mTestUtils.unpair(mAdapter, device);
     }
 
     /**
@@ -304,22 +281,19 @@
             return;
         }
 
-        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
-        BluetoothDevice device = adapter.getRemoteDevice(BluetoothTestRunner.sDeviceAddress);
-        mTestUtils.disable(adapter);
-        mTestUtils.enable(adapter);
-        mTestUtils.unpair(adapter, device);
-        mTestUtils.pair(adapter, device, BluetoothTestRunner.sDevicePairPasskey,
+        BluetoothDevice device = mAdapter.getRemoteDevice(BluetoothTestRunner.sDeviceAddress);
+        mTestUtils.enable(mAdapter);
+        mTestUtils.unpair(mAdapter, device);
+        mTestUtils.pair(mAdapter, device, BluetoothTestRunner.sDevicePairPasskey,
                 BluetoothTestRunner.sDevicePairPin);
 
         for (int i = 0; i < iterations; i++) {
             mTestUtils.writeOutput("connectPan iteration " + (i + 1) + " of " + iterations);
-            mTestUtils.connectPan(adapter, device);
-            mTestUtils.disconnectPan(adapter, device);
+            mTestUtils.connectPan(mAdapter, device);
+            mTestUtils.disconnectPan(mAdapter, device);
         }
 
-        mTestUtils.unpair(adapter, device);
-        mTestUtils.disable(adapter);
+        mTestUtils.unpair(mAdapter, device);
     }
 
     /**
@@ -334,26 +308,23 @@
             return;
         }
 
-        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
-        BluetoothDevice device = adapter.getRemoteDevice(BluetoothTestRunner.sDeviceAddress);
-        mTestUtils.disable(adapter);
-        mTestUtils.enable(adapter);
-        mTestUtils.disablePan(adapter);
-        mTestUtils.enablePan(adapter);
-        mTestUtils.unpair(adapter, device);
-        mTestUtils.acceptPair(adapter, device, BluetoothTestRunner.sDevicePairPasskey,
+        BluetoothDevice device = mAdapter.getRemoteDevice(BluetoothTestRunner.sDeviceAddress);
+        mTestUtils.enable(mAdapter);
+        mTestUtils.disablePan(mAdapter);
+        mTestUtils.enablePan(mAdapter);
+        mTestUtils.unpair(mAdapter, device);
+        mTestUtils.acceptPair(mAdapter, device, BluetoothTestRunner.sDevicePairPasskey,
                 BluetoothTestRunner.sDevicePairPin);
 
         for (int i = 0; i < iterations; i++) {
             mTestUtils.writeOutput("incomingPanConnection iteration " + (i + 1) + " of "
                     + iterations);
-            mTestUtils.incomingPanConnection(adapter, device);
-            mTestUtils.incomingPanDisconnection(adapter, device);
+            mTestUtils.incomingPanConnection(mAdapter, device);
+            mTestUtils.incomingPanDisconnection(mAdapter, device);
         }
 
-        mTestUtils.unpair(adapter, device);
-        mTestUtils.disablePan(adapter);
-        mTestUtils.disable(adapter);
+        mTestUtils.unpair(mAdapter, device);
+        mTestUtils.disablePan(mAdapter);
     }
 
     /**
@@ -368,28 +339,25 @@
             return;
         }
 
-        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
-        BluetoothDevice device = adapter.getRemoteDevice(BluetoothTestRunner.sDeviceAddress);
-        mTestUtils.disable(adapter);
-        mTestUtils.enable(adapter);
-        mTestUtils.unpair(adapter, device);
-        mTestUtils.pair(adapter, device, BluetoothTestRunner.sDevicePairPasskey,
+        BluetoothDevice device = mAdapter.getRemoteDevice(BluetoothTestRunner.sDeviceAddress);
+        mTestUtils.enable(mAdapter);
+        mTestUtils.unpair(mAdapter, device);
+        mTestUtils.pair(mAdapter, device, BluetoothTestRunner.sDevicePairPasskey,
                 BluetoothTestRunner.sDevicePairPin);
-        mTestUtils.disconnectProfile(adapter, device, BluetoothProfile.HEADSET, null);
-        mTestUtils.connectProfile(adapter, device, BluetoothProfile.HEADSET, null);
-        mTestUtils.stopSco(adapter, device);
+        mTestUtils.disconnectProfile(mAdapter, device, BluetoothProfile.HEADSET, null);
+        mTestUtils.connectProfile(mAdapter, device, BluetoothProfile.HEADSET, null);
+        mTestUtils.stopSco(mAdapter, device);
 
         for (int i = 0; i < iterations; i++) {
             mTestUtils.writeOutput("startStopSco iteration " + (i + 1) + " of " + iterations);
-            mTestUtils.startSco(adapter, device);
+            mTestUtils.startSco(mAdapter, device);
             sleep(SCO_SLEEP_TIME);
-            mTestUtils.stopSco(adapter, device);
+            mTestUtils.stopSco(mAdapter, device);
             sleep(SCO_SLEEP_TIME);
         }
 
-        mTestUtils.disconnectProfile(adapter, device, BluetoothProfile.HEADSET, null);
-        mTestUtils.unpair(adapter, device);
-        mTestUtils.disable(adapter);
+        mTestUtils.disconnectProfile(mAdapter, device, BluetoothProfile.HEADSET, null);
+        mTestUtils.unpair(mAdapter, device);
     }
 
     private void sleep(long time) {
diff --git a/core/tests/bluetoothtests/src/android/bluetooth/BluetoothTestUtils.java b/core/tests/bluetoothtests/src/android/bluetooth/BluetoothTestUtils.java
index 0d9980a..0815172 100644
--- a/core/tests/bluetoothtests/src/android/bluetooth/BluetoothTestUtils.java
+++ b/core/tests/bluetoothtests/src/android/bluetooth/BluetoothTestUtils.java
@@ -425,33 +425,14 @@
     public void enable(BluetoothAdapter adapter) {
         int mask = (BluetoothReceiver.STATE_TURNING_ON_FLAG | BluetoothReceiver.STATE_ON_FLAG
                 | BluetoothReceiver.SCAN_MODE_CONNECTABLE_FLAG);
-        long start = -1;
+        long start = System.currentTimeMillis();
         BluetoothReceiver receiver = getBluetoothReceiver(mask);
 
-        int state = adapter.getState();
-        switch (state) {
-            case BluetoothAdapter.STATE_ON:
-                assertTrue(adapter.isEnabled());
-                removeReceiver(receiver);
-                return;
-            case BluetoothAdapter.STATE_TURNING_ON:
-                assertFalse(adapter.isEnabled());
-                mask = 0; // Don't check for received intents since we might have missed them.
-                break;
-            case BluetoothAdapter.STATE_OFF:
-                assertFalse(adapter.isEnabled());
-                start = System.currentTimeMillis();
-                assertTrue(adapter.enable());
-                break;
-            case BluetoothAdapter.STATE_TURNING_OFF:
-                start = System.currentTimeMillis();
-                assertTrue(adapter.enable());
-                break;
-            default:
-                removeReceiver(receiver);
-                fail(String.format("enable() invalid state: state=%d", state));
-        }
+        writeOutput("Enabling Bluetooth adapter.");
+        assertFalse(adapter.isEnabled());
+        assertTrue(adapter.enable());
 
+        int state = BluetoothAdapter.STATE_OFF;
         long s = System.currentTimeMillis();
         while (System.currentTimeMillis() - s < ENABLE_DISABLE_TIMEOUT) {
             state = adapter.getState();
@@ -485,33 +466,14 @@
     public void disable(BluetoothAdapter adapter) {
         int mask = (BluetoothReceiver.STATE_TURNING_OFF_FLAG | BluetoothReceiver.STATE_OFF_FLAG
                 | BluetoothReceiver.SCAN_MODE_NONE_FLAG);
-        long start = -1;
+        long start = System.currentTimeMillis();
         BluetoothReceiver receiver = getBluetoothReceiver(mask);
 
-        int state = adapter.getState();
-        switch (state) {
-            case BluetoothAdapter.STATE_OFF:
-                assertFalse(adapter.isEnabled());
-                removeReceiver(receiver);
-                return;
-            case BluetoothAdapter.STATE_TURNING_ON:
-                assertFalse(adapter.isEnabled());
-                start = System.currentTimeMillis();
-                break;
-            case BluetoothAdapter.STATE_ON:
-                assertTrue(adapter.isEnabled());
-                start = System.currentTimeMillis();
-                assertTrue(adapter.disable());
-                break;
-            case BluetoothAdapter.STATE_TURNING_OFF:
-                assertFalse(adapter.isEnabled());
-                mask = 0; // Don't check for received intents since we might have missed them.
-                break;
-            default:
-                removeReceiver(receiver);
-                fail(String.format("disable() invalid state: state=%d", state));
-        }
+        writeOutput("Disabling Bluetooth adapter.");
+        assertTrue(adapter.isEnabled());
+        assertTrue(adapter.disable());
 
+        int state = BluetoothAdapter.STATE_OFF;
         long s = System.currentTimeMillis();
         while (System.currentTimeMillis() - s < ENABLE_DISABLE_TIMEOUT) {
             state = adapter.getState();
diff --git a/docs/html/_redirects.yaml b/docs/html/_redirects.yaml
index 42c8889..2464e9e 100644
--- a/docs/html/_redirects.yaml
+++ b/docs/html/_redirects.yaml
@@ -50,25 +50,25 @@
 - from: /tools/sdk/installing.html
   to: /studio/index.html
 - from: /tools/eclipse/installing-adt.html
-  to: /studio/tools/help/adt.html
+  to: /studio/tools/sdk/eclipse-adt.html
 - from: /sdk/requirements.html
   to: /studio/index.html
 - from: /sdk/installing/next.html
   to: /training/basics/firstapp/index.html
 - from: /sdk/installing/installing-adt.html
-  to: /studio/tools/help/adt.html
+  to: /studio/tools/sdk/eclipse-adt.html
 - from: /tools/projects/projects-eclipse.html
-  to: /studio/tools/help/adt.html
+  to: /studio/tools/sdk/eclipse-adt.html
 - from: /tools/building/building-eclipse.html
-  to: /studio/tools/help/adt.html
+  to: /studio/tools/sdk/eclipse-adt.html
 - from: /tools/building/building-cmdline-ant.html
-  to: /studio/tools/help/adt.html
+  to: /studio/tools/sdk/eclipse-adt.html
 - from: /tools/testing/testing_eclipse.html
-  to: /studio/tools/help/adt.html
+  to: /studio/tools/sdk/eclipse-adt.html
 - from: /tools/debugging/debugging-projects.html
-  to: /studio/tools/help/adt.html
+  to: /studio/tools/sdk/eclipse-adt.html
 - from: /tools/publishing/app-signing-eclipse.html
-  to: /studio/tools/help/adt.html
+  to: /studio/tools/sdk/eclipse-adt.html
 - from: /tools/testing/testing_ui.html
   to: /training/testing/ui-testing/index.html
 - from: /tools/testing/activity_test.html
@@ -99,10 +99,6 @@
   to: /training/testing/ui-testing/index.html
 - from: /guide/market/
   to: /google/play/
-- from: /guide/google/gcm/client-javadoc/...
-  to: /reference/com/google/android/gms/gcm/package-summary.html
-- from: /guide/google/gcm/server-javadoc/...
-  to: /reference/com/google/android/gms/gcm/package-summary.html
 - from: /guide/google/play/services.html
   to: https://developers.google.com/android/guides/overview
 - from: /guide/google/
@@ -771,10 +767,6 @@
   to: https://developers.google.com/android/guides/api-client
 - from: /google/auth/http-auth.html
   to: https://developers.google.com/android/guides/http-auth
-- from: /reference/gms-packages.html
-  to: https://developers.google.com/android/reference/packages
-- from: /reference/com/google/android/gms/
-  to: https://developers.google.com/android/reference/com/google/android/gms/
 - from: /preview/features/runtime-permissions.html
   to: /training/permissions/index.html
 - from: /preview/features/app-linking.html
@@ -845,6 +837,8 @@
   to: /studio/run/emulator.html
 - from: /r/studio-ui/instant-run.html
   to: /studio/run/index.html#instant-run
+- from: /r/studio-ui/test-recorder.html
+  to: http://tools.android.com/tech-docs/test-recorder
 - from: /reference/org/apache/http/...
   to: /about/versions/marshmallow/android-6.0-changes.html#behavior-apache-http-client
 - from: /shareables/...
@@ -863,11 +857,18 @@
 - from: /tools/testing-support-library/...
   to: /topic/libraries/testing-support-library/...
 
-# GCM redirects
+# GMS and GCM reference redirects
+- from: /reference/gms-packages.html
+  to: https://developers.google.com/android/reference/packages
+- from: /guide/google/gcm/client-javadoc/...
+  to: https://developers.google.com/android/reference/com/google/android/gms/gcm/package-summary
+- from: /guide/google/gcm/server-javadoc/...
+  to: https://developers.google.com/android/reference/com/google/android/gms/gcm/package-summary
+- from: /reference/com/google/android/gcm/...
+  to: https://developers.google.com/android/reference/com/google/android/gms/gcm/package-summary
 - from: /reference/com/google/...
   to: https://developers.google.com/android/reference/com/google/...
 
-
 # Files moved during the /studio restructure
 - from: /sdk/index.html
   to: /studio/index.html
@@ -1145,6 +1146,8 @@
   to: /studio/profile/ddms.html
 - from: /tools/revisions/index.html
   to: /studio/releases/index.html
+- from: /tools/help/adt.html
+  to: /studio/tools/sdk/eclipse-adt.html
 
 # Just incase something was missed, go to intro page
 - from: /tools/...
diff --git a/docs/html/about/dashboards/index.jd b/docs/html/about/dashboards/index.jd
index f4a03db..fff2608 100644
--- a/docs/html/about/dashboards/index.jd
+++ b/docs/html/about/dashboards/index.jd
@@ -63,19 +63,10 @@
 <br/>Any versions with less than 0.1% distribution are not shown.</em>
 </p>
 
-<p class="note"><strong>Note:</strong> This data is gathered from the new Google Play
-Store app, which supports Android 2.2 and above, so devices running older versions are not included.
-However, in August, 2013, versions older than Android 2.2 accounted for about 1% of devices that
-<em>checked in</em> to Google servers (not those that actually visited Google Play Store).
-</p>
-
-
-
 
 
 <h2 id="Screens">Screen Sizes and Densities</h2>
 
-
 <p>This section provides data about the relative number of devices that have a particular
 screen configuration, defined by a combination of screen size and density. To simplify the way that
 you design your user interfaces for different screen configurations, Android divides the range of
diff --git a/docs/html/guide/topics/manifest/uses-feature-element.jd b/docs/html/guide/topics/manifest/uses-feature-element.jd
index b9d0082..5d163c0 100755
--- a/docs/html/guide/topics/manifest/uses-feature-element.jd
+++ b/docs/html/guide/topics/manifest/uses-feature-element.jd
@@ -77,7 +77,7 @@
 <p>The set of available features that your application declares corresponds to
 the set of feature constants made available by the Android {@link
 android.content.pm.PackageManager}, which are listed for
-convenience in the <a href="#features-reference">Features Reference</a> tables
+convenience in the <a href="#features-reference">Features Reference</a> sections
 at the bottom of this document.
 
 <p>You must specify each feature in a separate <code>&lt;uses-feature&gt;</code>
@@ -131,17 +131,27 @@
 
 <dd>
 <dl class="attr">
+  <dt>
+    <a name="name"></a><code>android:name</code>
+  </dt>
 
-  <dt><a name="name"></a><code>android:name</code></dt>
-  <dd>Specifies a single hardware or software feature used by the application,
-as a descriptor string. Valid descriptor values are listed in the <a
-href="#hw-features">Hardware features</a> and <a href="#sw-features">Software
-features</a> tables, below. Descriptor string values are case-sensitive.</dd>
+  <dd>
+    Specifies a single hardware or software feature used by the application, as
+    a descriptor string. Valid attribute values are listed in the <a href=
+    "#hw-features">Hardware features</a> and <a href="#sw-features">Software
+    features</a> sections. These attribute values are case-sensitive.
+  </dd>
 
-  <dt><a name="required"></a><code>android:required</code></dt>  <!-- added in api level 5 -->
-  <dd>Boolean value that indicates whether the application requires
-  the feature specified in <code>android:name</code>.
+  <dt>
+    <a name="required"></a><code>android:required</code>
+  </dt>
+  <!-- added in api level 5 -->
 
+  <dd>
+    Boolean value that indicates whether the application requires the feature
+    specified in <code>android:name</code>.
+  </dd>
+</dl>
 <ul>
 <li>When you declare <code>android:required="true"</code> for a feature,
 you are specifying that the application <em>cannot function, or is not
@@ -163,7 +173,7 @@
   <dd>The OpenGL ES version required by the application. The higher 16 bits
 represent the major number and the lower 16 bits represent the minor number. For
 example, to specify OpenGL ES version 2.0, you would set the value as
-"0x00020000", or to specify OpenGL ES 3.0, you would set the value as "0x00030000".
+"0x00020000", or to specify OpenGL ES 3.2, you would set the value as "0x00030002".
 
   <p>An application should specify at most one <code>android:glEsVersion</code>
 attribute in its manifest. If it specifies more than one, the
@@ -184,8 +194,8 @@
 can check at run-time whether a higher level of OpenGL ES is available.)</p>
 
   <p>For more information about using OpenGL ES, including how to check the supported OpenGL ES
-version at runtime, see the <a href="{@docRoot}guide/topics/graphics/opengl.html">OpenGL ES</a>
-API guide.</p>
+version at runtime, see the <a href="{@docRoot}guide/topics/graphics/opengl.html">OpenGL ES
+API guide</a>.</p>
   </dd>
 
 </dl>
@@ -229,7 +239,7 @@
 <p>To ensure an accurate comparison of features, the Android Package Manager
 provides a shared set of feature constants that both applications and devices
 use to declare feature requirements and support. The available feature constants
-are listed in the <a href="#features-reference">Features Reference</a> tables at
+are listed in the <a href="#features-reference">Features Reference</a> sections at
 the bottom of this document, and in the class documentation for {@link
 android.content.pm.PackageManager}.</p>
 
@@ -362,8 +372,8 @@
 <p class="caution">It's important to understand that the permissions that you
 request in <code>&lt;uses-permission&gt;</code> elements can directly affect how
 Google Play filters your application. The reference section <a
-href="#permissions">Permissions that Imply Feature Requirements</a>,
-below, lists the full set of permissions that imply feature requirements and
+href="#permissions">Permissions that Imply Feature Requirements</a> lists the
+full set of permissions that imply feature requirements and
 therefore trigger filtering.</p>
 
 <h3 id="bt-permission-handling">Special handling for Bluetooth feature</h3>
@@ -532,493 +542,1159 @@
 densities: '160'
 </pre>
 
+<h2 id="features-reference">
+  Features Reference
+</h2>
 
-<h2 id=features-reference>Features Reference</h2>
+<p>
+  The following sections provide reference information about hardware features,
+  software features, and sets of permissions that imply specific feature
+  requirements.
+</p>
 
-<p>The tables below provide reference information about hardware and software
-features and the permissions that can imply them on Google Play. </p>
+<h3 id="hw-features">
+  Hardware features
+</h3>
 
-<h3 id="hw-features">Hardware features</h3>
+<p>
+  This section presents the hardware features supported by the most current
+  platform release. To indicate that your app uses or requires a hardware
+  feature, declare the corresponding value (beginning with
+  <code>"android.hardware"</code>) in an <code>android:name</code> attribute.
+  Each time you declare a hardware feature, use a separate
+  <code>&lt;uses-feature&gt;</code> element.
+</p>
 
-<p>The table below describes the hardware feature descriptors supported by the
-most current platform release. To signal that your application uses or requires
-a hardware feature, declare each value in a <code>android:name</code> attribute
-in a separate <code>&lt;uses-feature&gt;</code> element. </p>
+<h4 id="audio-hw-features">
+  Audio hardware features
+</h4>
 
-  <table>
-    <tr>
-       <th>Feature Type</th>
-       <th>Feature Descriptor</th>
-       <th style="min-width:170px">Description</th>
-       <th>Comments</th>
-    </tr>
-    <tr>
-       <td rowspan="4">Audio</td>
-       <td><code>android.hardware.audio.low_latency</code></td>
-       <td>The application uses a low-latency audio pipeline on the device and
-           is sensitive to delays or lag in sound input or output.</td>
-       <td></td>
-    </tr>
-    <tr>
-       <td><code>android.hardware.audio.pro</code></td>
-       <td>The application uses high-end audio functionality and performance.</td>
-       <td></td>
-    </tr>
-    <tr>
-       <td><code>android.hardware.microphone</code></td>
-       <td>The application records audio via a microphone.</td>
-       <td></td>
-    </tr>
-    </tr>
-       <td><code>android.hardware.output</code></td>
-       <td>The application produces at least one form of audio output, such as speakers, audio jack
-           or streaming over bluetooth.</td>
-       <td></td>
-    </tr>
-    <tr>
-       <td rowspan="2">Bluetooth</td>
-       <td><code>android.hardware.bluetooth</code></td>
-       <td>The application uses Bluetooth radio features in the device.</td>
-       <td></td>
-    </tr>
-    <tr>
-       <td><code>android.hardware.bluetooth_le</code></td>
-       <td>The application uses Bluetooth Low Energy radio features in the device.</td>
-       <td></td>
-    </tr>
-    <tr>
-       <td rowspan="6">Camera</td>
-       <td><code>android.hardware.camera</code></td>
-       <td>The application uses the device's back-facing (main) camera.</td>
-       <td>Devices with only a front-facing camera do not list this feature, so
-           the <code>android.hardware.camera.any</code> feature should be used
-           instead if a camera facing any direction is acceptable for the
-           application.</td>
-    </tr>
-<tr>
-  <td><code>android.hardware.camera.autofocus</code></td>
-  <td>Subfeature. The application uses the device camera's autofocus capability.</td>
-  <td rowspan="3">These subfeatures implicitly declare the
-<code>android.hardware.camera</code> parent feature, unless declared with
-<code>android:required="false"</code>.</td>
-</tr>
-<tr>
-  <td><code>android.hardware.camera.flash</code></td>
-  <td>Subfeature. The application uses the device camera's flash.</td>
-</tr>
-<tr>
-  <td><code>android.hardware.camera.front</code></td>
-  <td>Subfeature. The application uses a front-facing camera on the device.</td>
-</tr>
-<tr>
-  <td><code>android.hardware.camera.any</code></td>
-  <td>The application uses at least one camera facing in any direction, or an
-external camera device if one is connected. Use this in preference to
-<code>android.hardware.camera</code> if a back-facing camera is not required.
-  </td>
-</tr>
-<tr>
-  <td><code>android.hardware.camera.external</code></td>
-  <td>The application uses an external camera device if one is connected.</td>
-</tr>
-<tr>
-  <td><code>android.hardware.camera.level.full</code></td>
-  <td>The application uses a camera device with <code>FULL</code>-level support.</td>
-</tr>
-<tr>
-  <td><code>android.hardware.camera.capability.manual_sensor</code></td>
-  <td>The application uses a a camera device with the <code>MANUAL_SENSOR</code> capability.</td>
-</tr>
-<tr>
-  <td><code>android.hardware.camera.capability.manual_post_processing</code></td>
-  <td>The application uses a a camera device with the <code>MANUAL_POST_PROCESSING</code> capability.</td>
-</tr>
-<tr>
-  <td><code>android.hardware.camera.capability.raw</code></td>
-  <td>The application uses a a camera device with the <code>RAW</code> capability.</td>
-</tr>
+<dl>
+  <dt>
+    <code>android.hardware.audio.low_latency</code>
+  </dt>
 
-<tr>
-  <td>Infrared</td>
-  <td><code>android.hardware.consumerir</code></td>
-  <td>The application uses the consumer IR capabilities on the device.</td>
-  <td></td>
-</tr>
+  <dd>
+    The app uses the device's low-latency audio pipeline, which reduces lag and
+    delays when processing sound input or output.
+  </dd>
 
-<tr>
-  <td rowspan="3">Location</td>
-  <td><code>android.hardware.location</code></td>
-  <td>The application uses one or more features on the device for determining
-location, such as GPS location, network location, or cell location.</td>
-  <td></td>
-</tr>
-<tr>
-  <td><code>android.hardware.location.network</code></td>
-  <td>Subfeature. The application uses coarse location coordinates obtained from
-a network-based geolocation system supported on the device.</td>
-  <td rowspan="2">These subfeatures implicitly declare the
-<code>android.hardware.location</code> parent feature, unless declared with
-<code>android:required="false"</code>. </td>
-</tr>
-<tr>
-  <td><code>android.hardware.location.gps</code></td>
-  <td>Subfeature. The application uses precise location coordinates obtained
-from a Global Positioning System receiver on the device. </td>
-</tr>
-<tr>
-  <td>Microphone</td>
-  <td><code>android.hardware.microphone</code></td>
-  <td>The application uses a microphone on the device.
-  </td>
-  <td></td>
-</tr>
-<tr>
-  <td rowspan="2">NFC</td>
-  <td><code>android.hardware.nfc</td>
-  <td>The application uses Near Field Communications radio features in the device.</td>
-  <td></td>
-</tr>
-<tr>
-  <td><code>android.hardware.nfc.hce</code></td>
-  <td>The application uses the NFC card emulation feature in the device.</td>
-  <td></td>
-</tr>
-<tr>
-  <td rowspan="8">Sensors</td>
-  <td><code>android.hardware.sensor.accelerometer</code></td>
-  <td>The application uses motion readings from an accelerometer on the
-device.</td>
-  <td></td>
-</tr>
-<tr>
-  <td><code>android.hardware.sensor.barometer</code></td>
-  <td>The application uses the device's barometer.</td>
-  <td></td>
-</tr>
-<tr>
-  <td><code>android.hardware.sensor.compass</code></td>
-  <td>The application uses directional readings from a magnetometer (compass) on
-the device.</td>
-  <td></td>
-</tr>
-<tr>
-  <td><code>android.hardware.sensor.gyroscope</code></td>
-  <td>The application uses the device's gyroscope sensor.</td>
-  <td></td>
-</tr>
-<tr>
-  <td><code>android.hardware.sensor.light</code></td>
-  <td>The application uses the device's light sensor.</td>
-  <td></td>
-</tr>
-<tr>
-  <td><code>android.hardware.sensor.proximity</code></td>
-  <td>The application uses the device's proximity sensor.</td>
-  <td></td>
-</tr>
-<tr>
-  <td><code>android.hardware.sensor.stepcounter</code></td>
-  <td>The application uses the device's step counter.</td>
-  <td></td>
-</tr>
-<tr>
-  <td><code>android.hardware.sensor.stepdetector</code></td>
-  <td>The application uses the device's step detector.</td>
-  <td></td>
-</tr>
+  <dt>
+    <code>android.hardware.audio.output</code>
+  </dt>
 
-<tr>
-  <td rowspan="2">Screen</td>
-  <td><code>android.hardware.screen.landscape</code></td>
-  <td>The application requires landscape orientation.</td>
-  <td rowspan="2">
-     <p>For example, if your app requires portrait orientation, you should declare
-<code>&lt;uses-feature android:name="android.hardware.screen.portrait"/&gt;</code> so that only devices
-that support portrait orientation (whether always or by user choice) can install your app. If your
-application <em>supports</em> both orientations, then you don't need to declare either.</p>
-    <p>Both orientations are assumed <em>not required</em>, by default, so your app may be installed
-on devices that support one or both orientations. However, if any of your activities request that
-they run in a specific orientation, using the <a
-href="{@docRoot}guide/topics/manifest/activity-element.html#screen">{@code
-android:screenOrientation}</a> attribute, then this also declares that the application requires that
-orientation. For example, if you declare <a
-href="{@docRoot}guide/topics/manifest/activity-element.html#screen">{@code
-android:screenOrientation}</a> with either {@code "landscape"}, {@code "reverseLandscape"}, or
-{@code "sensorLandscape"}, then your application will be available only to devices that support
-landscape orientation. As a best practice, you should still declare your requirement for this
-orientation using a {@code <uses-feature>} element. If you declare an orientation for your
-activity using <a href="{@docRoot}guide/topics/manifest/activity-element.html#screen">{@code
-android:screenOrientation}</a>, but don't actually <em>require</em> it, you can disable the
-requirement by declaring the orientation with a {@code <uses-feature>} element and include
-{@code android:required="false"}.</p>
-    <p>For backwards compatibility, any device running a platform version that supports only API
-level 12 or lower is assumed to support both landscape and portrait.</p>
-  </td>
-</tr>
-<tr>
-  <td><code>android.hardware.screen.portrait</code></td>
-  <td>The application requires portrait orientation.</td>
-</tr>
+  <dd>
+    The app transmits sound using the device's speakers, audio jack, Bluetooth
+    streaming capabilities, or a similar mechanism.
+  </dd>
 
-<tr>
-  <td rowspan="3">Telephony</td>
-  <td><code>android.hardware.telephony</code></td>
-  <td>The application uses telephony features on the device, such as telephony
-radio with data communication services.</td>
-  <td></td>
-</tr>
-<tr>
-  <td><code>android.hardware.telephony.cdma</code></td>
-  <td>Subfeature. The application uses CDMA telephony radio features on the
-device. </td>
-  <td rowspan="2">These subfeatures implicitly declare the
-<code>android.hardware.telephony</code> parent feature, unless declared with
-<code>android:required="false"</code>. </td>
-</tr>
-<tr>
-  <td><code>android.hardware.telephony.gsm</code></td>
-  <td>Subfeature. The application uses GSM telephony radio features on the
-device.</td>
-</tr>
+  <dt>
+    <code>android.hardware.audio.pro</code>
+  </dt>
 
-<tr>
-  <td>Television</td>
-  <td><code>android.hardware.type.television</code></td>
-  <td>The application is designed for a television user experience.</td>
-  <td>This feature defines "television" to be a typical living room television experience:
-  displayed on a big screen, where the user is sitting far away and the dominant form of
-  input is something like a d-pad, and generally not through touch or a
-  mouse/pointer-device.</td>
-</tr>
+  <dd>
+    The app uses the device's high-end audio functionality and performance
+    capabilities.
+  </dd>
 
-<tr>
-  <td rowspan="7">Touchscreen</td>
-  <td><code>android.hardware.faketouch</code></td>
-  <td>The application uses basic touch interaction events, such as "click down", "click
-up", and drag.</td>
-  <td><p>When declared as required, this indicates that the application is compatible with a device
-only if it offers an emulated touchscreen ("fake touch" interface), or better. A device that offers
-a fake touch interface provides a user input system that emulates a subset of touchscreen
-capabilities. For example, a mouse or remote control that drives an on-screen cursor provides a fake
-touch interface. If your application requires basic point and click interaction (in other
-words, it won't work with <em>only</em> a d-pad controller), you should declare this feature.
-Because this is the minimum level of touch interaction, your app will also be compatible with
-devices that offer more complex touch interfaces.</p>
-  <p class="note"><strong>Note:</strong> Because applications require the {@code
-android.hardware.touchscreen} feature by default, if you want your application to be available to
-devices that provide a fake touch interface, you must also explicitly declare that a touch screen is
-<em>not</em> required by declaring <code>&lt;uses-feature
-android:name="android.hardware.touchscreen" <strong>android:required="false"</strong>
-/&gt;</code></p></td>
-</tr>
+  <dt>
+    <code>android.hardware.microphone</code>
+  </dt>
 
-<tr>
-  <td><code>android.hardware.faketouch.multitouch.distinct</code></td>
-  <td>The application performs distinct tracking of two or more "fingers" on a fake touch
-interface. This is a superset of the faketouch feature.</td>
-  <td><p>When declared as required, this indicates that the application is compatible with a device
-only if it supports touch emulation for events that supports distinct tracking of two or more
-fingers, or better.</p>
-  <p>Unlike the distinct multitouch defined by {@code
-android.hardware.touchscreen.multitouch.distinct}, input devices that support distinct multi-touch
-with a fake touch interface will not support all two-finger gestures, because the input is
-being transformed to cursor movement on the screen. That is, single finger gestures on such a device
-move a cursor; two-finger swipes will result in single-finger touch events; other two-finger
-gestures will result in the corresponding two-finger touch event. An example device that supports
-distinct multi-touch with a fake touch interface is one that provides a trackpad for cursor movement
-which also supports two or more fingers.</p></td>
-</tr>
+  <dd>
+    The app records audio using the device's microphone.
+  </dd>
+</dl>
 
-<tr>
-  <td><code>android.hardware.faketouch.multitouch.jazzhand</code></td>
-  <td>The application performs distinct tracking of five or more "fingers" on a fake touch
-interface. This is a superset of the faketouch feature.</td>
-  <td><p>When declared as required, this indicates that the application is compatible with a device
-only if it supports touch emulation for events that supports distinct tracking of five or more
-fingers.</p>
-  <p>Unlike the distinct multitouch defined by {@code
-android.hardware.touchscreen.multitouch.jazzhand}, input devices that support jazzhand multi-touch
-with a fake touch interface will not support all five-finger gestures, because the input is being
-transformed to cursor movement on the screen. That is, single finger gestures on such a device move
-a cursor; multi-finger gestures will result in single-finger touch events; other multi-finger
-gestures will result in the corresponding multi-finger touch event. An example device that supports
-distinct multi-touch with a fake touch interface is one that provides a trackpad for cursor movement
-which also supports five or more fingers.</p></td>
-</tr>
+<h4 id="bluetooth-hw-features">
+  Bluetooth hardware features
+</h4>
 
-<tr>
-  <td><code>android.hardware.touchscreen</code></td>
-  <td>The application uses touchscreen capabilities for gestures that are more interactive
-than basic touch events, such as a fling. This is a superset of the basic faketouch feature.</td>
-  <td><p>By default, your application requires this. As such, your application is <em>not</em>
-available to devices that provide only an emulated touch interface ("fake touch"), by default. If
-you want your application available to devices that provide a fake touch interface (or even devices
-that provide only a d-pad controller), you must explicitly declare that a touch screen is not
-required, by declaring {@code android.hardware.touchscreen} with {@code android:required="false"}.
-You should do so even if your application uses&mdash;but does not <em>require</em>&mdash;a real
-touch screen interface.</p>
-<p>If your application <em>does require</em> a touch interface (in order to perform touch
-gestures such as a fling), then you don't need to do anything, because this is required by default.
-However, it's best if you explicitly declare all features used by your application, so you should
-still declare this if your app uses it.</p>
-  <p>If you require more complex touch interaction, such as multi-finger gestures, you
-should declare the advanced touch screen features below.</p></td>
-</tr>
-<tr>
-  <td><code>android.hardware.touchscreen.multitouch</code></td>
-  <td>The application uses basic two-point multitouch capabilities on the device
-screen, such as for pinch gestures, but does not need to track touches independently. This
-is a superset of touchscreen feature.</td>
-  <td>This implicitly declares the <code>android.hardware.touchscreen</code> parent feature, unless
-declared with <code>android:required="false"</code>. </td>
-</tr>
-<tr>
-  <td><code>android.hardware.touchscreen.multitouch.distinct</code></td>
-  <td>Subfeature. The application uses advanced multipoint multitouch
-capabilities on the device screen, such as for tracking two or more points fully
-independently. This is a superset of multitouch feature.</td>
-  <td rowspan="2">This implicitly declares the <code>android.hardware.touchscreen.multitouch</code>
-parent feature, unless declared with <code>android:required="false"</code>. </td>
-</tr>
-<tr>
-  <td><code>android.hardware.touchscreen.multitouch.jazzhand</code></td>
-  <td>The application uses advanced multipoint multitouch
-capabilities on the device screen, for tracking up to five points fully
-independently. This is a superset of distinct multitouch feature.</td>
-</tr>
+<dl>
+  <dt>
+    <code>android.hardware.bluetooth</code>
+  </dt>
 
-<tr>
-  <td rowspan="2">USB</td>
-  <td><code>android.hardware.usb.host</code></td>
-  <td>The application uses USB host mode features (behaves as the host and connects to USB
-devices).</td>
-  <td></td>
-</tr>
+  <dd>
+    The app uses the device's Bluetooth features, usually to communicate with
+    other Bluetooth-enabled devices.
+  </dd>
 
-<tr>
-  <td><code>android.hardware.usb.accessory</code></td>
-  <td>The application uses USB accessory features (behaves as the USB device and connects to USB
-hosts).</td>
-  <td></td>
-</tr>
+  <dt>
+    <code>android.hardware.bluetooth_le</code>
+  </dt>
 
-<tr>
-  <td rowspan="2">Wi-Fi</td>
-  <td><code>android.hardware.wifi</code></td>
-  <td>The application uses 802.11 networking (Wi-Fi) features on the device.</td>
-  <td></td>
-</tr>
-<tr>
-  <td><code>android.hardware.wifi.direct</code></td>
-  <td>The application uses the Wi-Fi Direct networking features on the device.</td>
-</tr>
+  <dd>
+    The app uses the device's Bluetooth Low Energy radio features.
+  </dd>
+</dl>
 
-  </table>
+<h4 id="camera-hw-features">
+  Camera hardware features
+</h4>
 
-<h3 id="sw-features">Software features</h3>
+<dl>
+  <dt>
+    <code>android.hardware.camera</code>
+  </dt>
 
-<p>The table below describes the software feature descriptors supported by the
-most current platform release. To signal that your application uses or requires
-a software feature, declare each value in a <code>android:name</code> attribute
-in a separate <code>&lt;uses-feature&gt;</code> element. </p>
+  <dd>
+    The app uses the device's back-facing camera. Devices with only a
+    front-facing camera do not list this feature, so use the
+    <code>android.hardware.camera.any</code> feature instead if your app can
+    communicate with any camera, regardless of which direction the camera
+    faces.
+  </dd>
 
+  <dt>
+    <code>android.hardware.camera.any</code>
+  </dt>
 
-  <table>
-<tr>
-  <th>Feature</th>
-  <th>Attribute Value</th>
-  <th>Description</th>
-</tr>
-<tr>
-  <td>App Widgets</td>
-  <td><code>android.software.app_widgets</code></td>
-  <td>The application uses or provides App Widgets and should be installed only on devices
-  that include a Home screen or similar location where users can embed App Widgets.</td>
-</tr>
-<tr>
-  <td>Device Management</td>
-  <td><code>android.software.device_admin</code></td>
-  <td>The application uses device policy enforcement via device administrators.</td>
-</tr>
-<tr>
-  <td>Home Screen</td>
-  <td><code>android.software.home_screen</code></td>
-  <td>The application behaves as a Home screen replacement and should be installed only on
-  devices that support third-party Home screen apps.</td>
-</tr>
-<tr>
-  <td>Input Method</td>
-  <td><code>android.software.input_methods</code></td>
-  <td>The application provides a custom input method and should be installed only on devices that
-  support third-party input methods.</td>
-</tr>
-<tr>
-  <td>Live Wallpaper</td>
-  <td><code>android.software.live_wallpaper</code></td>
-  <td>The application uses or provides Live Wallpapers and should be installed only on devices that
-  support Live Wallpapers.</td>
-</tr>
-<tr>
-  <td>MIDI</td>
-  <td><code>android.software.midi</code></td>
-  <td>The application connects to musical instruments or outputs sound
-  using the Musical Instrument Digital Interface (MIDI) protocol.</td>
-</tr>
-<tr>
-  <td rowspan="2">SIP/VOIP</td>
-  <td><code>android.software.sip</code></td>
-  <td>The application uses SIP service on the device and should be installed only on devices that
-  support SIP.
-  </td>
-</tr>
-<tr>
-  <td><code>android.software.sip.voip</code></td>
-  <td><p>Subfeature. The application uses SIP-based VOIP service on the device.
-  <p>This subfeature implicitly declares the <code>android.software.sip</code> parent feature,
-unless declared with <code>android:required="false"</code>.</td>
-</tr>
-  </table>
+  <dd>
+    The app uses one of the device's cameras, or an external camera that the
+    user connects to the device. Use this value instead of
+    <code>android.hardware.camera</code> if your app does not require the
+    camera to be a back-facing one.
+  </dd>
 
+  <dt>
+    <code>android.hardware.camera.autofocus</code>
+  </dt>
 
-<h3 id="permissions">Permissions that Imply Feature Requirements</h3>
+  <dd>
+    <p>
+      The app uses the autofocus feature that the device's camera supports.
+    </p>
 
-<p>Some feature constants listed in the tables above were made available to
-applications <em>after</em> the corresponding API; for example, the
-<code>android.hardware.bluetooth</code> feature was added in Android 2.2 (API
-level 8), but the bluetooth API that it refers to was added in Android 2.0 (API
-level 5). Because of this, some apps were able to use the API before they had
-the ability to declare that they require the API via the
-<code>&lt;uses-feature&gt;</code> system. </p>
+    <p>
+      By using this feature, an app implies that it also uses the
+      <code>android.hardware.camera</code> feature, unless this parent feature
+      is declared with <code>android:required="false"</code>.
+    </p>
+  </dd>
 
-<p>To prevent those apps from being made available unintentionally,  Google
-Play assumes that certain hardware-related permissions indicate that the
-underlying hardware features are required by default. For instance, applications
-that use Bluetooth must request the <code>BLUETOOTH</code> permission in a
-<code>&lt;uses-permission&gt;</code> element &mdash; for legacy apps, Google
-Play assumes that the permission declaration means that the underlying
-<code>android.hardware.bluetooth</code> feature is required by the application
-and sets up filtering based on that feature. </p>
+  <dt>
+    <code>android.hardware.camera.capability.manual_post_processing</code>
+  </dt>
 
-<p>The table below lists permissions that imply feature requirements
-equivalent to those declared in <code>&lt;uses-feature&gt;</code> elements. Note
-that <code>&lt;uses-feature&gt;</code> declarations, including any declared
-<code>android:required</code> attribute, always take precedence over features
-implied by the permissions below. </p>
+  <dd>
+    <p>
+      The app uses the <code>MANUAL_POST_PROCESSING</code> feature that the
+      device's camera supports.
+    </p>
 
-<p>For any of the permissions below, you can disable filtering based on the
-implied feature by explicitly declaring the implied feature explicitly, in a
-<code>&lt;uses-feature&gt;</code> element, with an
-<code>android:required="false"</code> attribute. For example, to disable any
-filtering based on the <code>CAMERA</code> permission, you would add this
-<code>&lt;uses-feature&gt;</code> declaration to the manifest file:</p>
+    <p>
+      This feature allows your app to override the camera's auto white balance
+      functionality. Use <code>android.colorCorrection.transform</code>,
+      <code>android.colorCorrection.gains</code>, and an
+      <code>android.colorCorrection.mode</code> of
+      <code>TRANSFORM_MATRIX</code>.
+    </p>
+  </dd>
+
+  <dt>
+    <code>android.hardware.camera.capability.manual_sensor</code>
+  </dt>
+
+  <dd>
+    <p>
+      The app uses the <code>MANUAL_SENSOR</code> feature that the device's
+      camera supports.
+    </p>
+
+    <p>
+      This feature implies support for auto-exposure locking
+      (<code>android.control.aeLock</code>), which allows the camera's exposure
+      time and sensitivity to remain fixed at specific values.
+    </p>
+  </dd>
+
+  <dt>
+    <code>android.hardware.camera.capability.raw</code>
+  </dt>
+
+  <dd>
+    <p>
+      The app uses the <code>RAW</code> feature that the device's camera
+      supports.
+    </p>
+
+    <p>
+      This feature implies that the device can save DNG (raw) files and that
+      the device's camera provides the DNG-related metadata necessary for your
+      app to process these raw images directly.
+    </p>
+  </dd>
+
+  <dt>
+    <code>android.hardware.camera.external</code>
+  </dt>
+
+  <dd>
+    The app communicates with an external camera that the user connects to the
+    device. This feature does not guarantee, however, that the external camera
+    is available for your app to use.
+  </dd>
+
+  <dt>
+    <code>android.hardware.camera.flash</code>
+  </dt>
+
+  <dd>
+    <p>
+      The app uses the flash feature that the device's camera supports.
+    </p>
+
+    <p>
+      By using this feature, an app implies that it also uses the
+      <code>android.hardware.camera</code> feature, unless this parent feature
+      is declared with <code>android:required="false"</code>.
+    </p>
+  </dd>
+
+  <dt>
+    <code>android.hardware.camera.front</code>
+  </dt>
+
+  <dd>
+    <p>
+      The app uses the device's front-facing camera.
+    </p>
+
+    <p>
+      By using this feature, an app implies that it also uses the
+      <code>android.hardware.camera</code> feature, unless this parent feature
+      is declared with <code>android:required="false"</code>.
+    </p>
+  </dd>
+
+  <dt>
+    <code>android.hardware.camera.level.full</code>
+  </dt>
+
+  <dd>
+    The app uses the <code>FULL</code>-level image-capturing support that at
+    least one of the device's cameras provides. Cameras with <code>FULL</code>
+    support provide burst-capture capabilities, per-frame control, and manual
+    post-processing control.
+  </dd>
+</dl>
+
+<h4 id="device-ui-hw-features">
+  Device UI hardware features
+</h4>
+
+<dl>
+  <dt>
+    <code>android.hardware.type.automotive</code>
+  </dt>
+
+  <dd>
+    <p>
+      The app is designed to show its UI on a set of screens inside a vehicle.
+      The user interacts with the app using hard buttons, touch, rotary
+      controllers, and mouse-like interfaces. The vehicle's screens usually
+      appear in the center console or the instrument cluster of a vehicle. These
+      screens usually have limited size and resolution.
+    </p>
+
+    <p class="note">
+      <strong>Note: </strong>It's important to keep in mind that, since the user
+      is driving while using this type of app UI, the app must minimize driver
+      distraction.
+    </p>
+  </dd>
+
+  <dt>
+    <code>android.hardware.type.television</code>
+  </dt>
+
+  <dd>
+    <p>
+      (Deprecated; use <a href="#media-sw-features">
+      <code>android.software.leanback</code></a> instead.)
+    </p>
+
+    <p>
+      The app is designed to show its UI on a television. This feature defines
+      "television" to be a typical living room television experience: displayed
+      on a big screen, where the user is sitting far away and the dominant form
+      of input is something like a d-pad, and generally not using a mouse,
+      pointer, or touch device.
+    </p>
+  </dd>
+
+  <dt>
+    <code>android.hardware.type.watch</code>
+  </dt>
+
+  <dd>
+    The app is designed to show its UI on a watch. A watch is worn on the body,
+    such as on the wrist. The user is very close to the device while
+    interacting with it.
+  </dd>
+</dl>
+
+<h4 id="fingerprint-hw-features">
+  Fingerprint hardware features
+</h4>
+
+<dl>
+  <dt>
+    <code>android.hardware.fingerprint</code>
+  </dt>
+
+  <dd>
+    The app reads fingerprints using the device's biometric hardware.
+  </dd>
+</dl>
+
+<h4 id="gamepad-hw-features">
+  Gamepad hardware features
+</h4>
+
+<dl>
+  <dt>
+    <code>android.hardware.gamepad</code>
+  </dt>
+
+  <dd>
+    The app captures game controller input, either from the device itself or
+    from a connected gamepad.
+  </dd>
+</dl>
+
+<h4 id="infrared-hw-features">
+  Infrared hardware features
+</h4>
+
+<dl>
+  <dt>
+    <code>android.hardware.consumerir</code>
+  </dt>
+
+  <dd>
+    The app uses the device's infrared (IR) capabilities, usually to
+    communicate with other consumer IR devices.
+  </dd>
+</dl>
+
+<h4 id="location-hw-features">
+  Location hardware features
+</h4>
+
+<dl>
+  <dt>
+    <code>android.hardware.location</code>
+  </dt>
+
+  <dd>
+    The app uses one or more features on the device for determining location,
+    such as GPS location, network location, or cell location.
+  </dd>
+
+  <dt>
+    <code>android.hardware.location.gps</code>
+  </dt>
+
+  <dd>
+    <p>
+      The app uses precise location coordinates obtained from a Global
+      Positioning System (GPS) receiver on the device.
+    </p>
+
+    <p>
+      By using this feature, an app implies that it also uses the
+      <code>android.hardware.location</code> feature, unless this parent
+      feature is declared with the attribute
+      <code>android:required="false"</code>.
+    </p>
+  </dd>
+
+  <dt>
+    <code>android.hardware.location.network</code>
+  </dt>
+
+  <dd>
+    <p>
+      The app uses coarse location coordinates obtained from a network-based
+      geolocation system supported on the device.
+    </p>
+
+    <p>
+      By using this feature, an app implies that it also uses the
+      <code>android.hardware.location</code> feature, unless this parent
+      feature is declared with the attribute
+      <code>android:required="false"</code>.
+    </p>
+  </dd>
+</dl>
+
+<h4 id="nfc-hw-features">
+  NFC hardware features
+</h4>
+
+<dl>
+  <dt>
+    <code>android.hardware.nfc</code>
+  </dt>
+
+  <dd>
+    The app uses the device's Near-Field Communication (NFC) radio features.
+  </dd>
+
+  <dt>
+    <code>android.hardware.nfc.hce</code>
+  </dt>
+
+  <dd>
+    <p>
+      (Deprecated.)
+    </p>
+
+    <p>
+      The app uses NFC card emulation that is hosted on the device.
+    </p>
+  </dd>
+</dl>
+
+<h4 id="opengl-es-hw-features">
+  OpenGL ES hardware features
+</h4>
+
+<dl>
+  <dt>
+    <code>android.hardware.opengles.aep</code>
+  </dt>
+
+  <dd>
+    The app uses the <a href=
+    "http://www.khronos.org/registry/gles/extensions/ANDROID/ANDROID_extension_pack_es31a.txt"
+    class="external-link">OpenGL ES Android Extension Pack</a>that is installed
+    on the device.
+  </dd>
+</dl>
+
+<h4 id="sensor-hw-features">
+  Sensor hardware features
+</h4>
+
+<dl>
+  <dt>
+    <code>android.hardware.sensor.accelerometer</code>
+  </dt>
+
+  <dd>
+    The app uses motion readings from the device's accelerometer to detect
+    the device's current orientation. For example, an app could use
+    accelerometer readings to determine when to switch between portrait and
+    landscape orientations.
+  </dd>
+
+  <dt>
+    <code>android.hardware.sensor.ambient_temperature</code>
+  </dt>
+
+  <dd>
+    The app uses the device's ambient (environmental) temperature sensor. For
+    example, a weather app could report indoor or outdoor temperature.
+  </dd>
+
+  <dt>
+    <code>android.hardware.sensor.barometer</code>
+  </dt>
+
+  <dd>
+    The app uses the device's barometer. For example, a weather app could
+    report air pressure.
+  </dd>
+
+  <dt>
+    <code>android.hardware.sensor.compass</code>
+  </dt>
+
+  <dd>
+    The app uses the device's magnetometer (compass). For example, a navigation
+    app could show the current direction a user faces.
+  </dd>
+
+  <dt>
+    <code>android.hardware.sensor.gyroscope</code>
+  </dt>
+
+  <dd>
+    The app uses the device's gyroscope to detect rotation and twist, creating
+    a six-axis orientation system. By using this sensor, an app can detect more
+    smoothly whether it needs to switch between portrait and landscape
+    orientations.
+  </dd>
+
+  <dt>
+    <code>android.hardware.sensor.hifi_sensors</code>
+  </dt>
+
+  <dd>
+    The app uses the device's high fidelity (Hi-Fi) sensors. For example, a
+    gaming app could detect the user's high-precision movements.
+  </dd>
+
+  <dt>
+    <code>android.hardware.sensor.heartrate</code>
+  </dt>
+
+  <dd>
+    The app uses the device's heart rate monitor. For example, a fitness app
+    could report trends in a user's heart rate over time.
+  </dd>
+
+  <dt>
+    <code>android.hardware.sensor.heartrate.ecg</code>
+  </dt>
+
+  <dd>
+    The app uses the device's elcardiogram (ECG) heart rate sensor. For
+    example, a fitness app could report more detailed information about a
+    user's heart rate.
+  </dd>
+
+  <dt>
+    <code>android.hardware.sensor.light</code>
+  </dt>
+
+  <dd>
+    The app uses the device's light sensor. For example, an app could display
+    one of two different color schemes based on the ambient lighting
+    conditions.
+  </dd>
+
+  <dt>
+    <code>android.hardware.sensor.proximity</code>
+  </dt>
+
+  <dd>
+    The app uses the device's proximity sensor. For example, a telephony app
+    could turn off the device's screen when the app detects that the user is
+    holding the device close to their body.
+  </dd>
+
+  <dt>
+    <code>android.hardware.sensor.relative_humidity</code>
+  </dt>
+
+  <dd>
+    The app uses the device's relative humidity sensor. For example, a weather
+    app could use the humidity to calculate and report the current dewpoint.
+  </dd>
+
+  <dt>
+    <code>android.hardware.sensor.stepcounter</code>
+  </dt>
+
+  <dd>
+    The app uses the device's step counter. For example, a fitness app could
+    report the number of steps a user needs to take to achieve their daily step
+    count goal.
+  </dd>
+
+  <dt>
+    <code>android.hardware.sensor.stepdetector</code>
+  </dt>
+
+  <dd>
+    The app uses the device's step detector. For example, a fitness app could
+    use the time interval between steps to infer the type of exercise that the
+    user is doing.
+  </dd>
+</dl>
+
+<h4 id="screen-hw-features">
+  Screen hardware features
+</h4>
+
+<dl>
+  <dt>
+    <code>android.hardware.screen.landscape</code>
+  </dt>
+
+  <dt>
+    <code>android.hardware.screen.portrait</code>
+  </dt>
+
+  <dd>
+    <p>
+      The app requires the device to use the portrait or landscape orientation.
+      If your app supports both orientations, then you don't need to declare
+      either feature.
+    </p>
+
+    <p>
+      For example, if your app requires portrait orientation, you should
+      declare the following feature so that only the devices that support
+      portrait orientation (always or by user choice) can run your app:
+    </p>
+    <pre>&lt;uses-feature android:name="android.hardware.screen.portrait" /&gt;</pre>
+
+    <p>
+      Both orientations are assumed not required by default, so your app may be
+      installed on devices that support one or both orientations. However, if
+      any of your activities request that they run in a specific orientation,
+      using the <a href=
+      "{@docRoot}guide/topics/manifest/activity-element.html#screen">{@code
+      android:screenOrientation}</a> attribute, then this declaration implies
+      that your app requires that orientation. For example, if you declare
+      <a href=
+      "{@docRoot}guide/topics/manifest/activity-element.html#screen">{@code
+      android:screenOrientation}</a> with either {@code "landscape"}, {@code
+      "reverseLandscape"}, or {@code "sensorLandscape"}, then your app will be
+      available only on devices that support landscape orientation.
+    </p>
+
+    <p>
+      As a best practice, you should still declare your requirement for this
+      orientation using a {@code &lt;uses-feature&gt;} element. If you declare
+      an orientation for your activity using <a href=
+      "{@docRoot}guide/topics/manifest/activity-element.html#screen">{@code
+      android:screenOrientation}</a>, but don't actually require it, you can
+      disable the requirement by declaring the orientation with a {@code
+      &lt;uses-feature&gt;} element and include {@code
+      android:required="false"}.
+    </p>
+
+    <p>
+      For backward compatibility, any device running Android 3.1 (API level 12)
+      or lower supports both landscape and portrait orientations.
+    </p>
+  </dd>
+</dl>
+
+<h4 id="telephony-hw-features">
+  Telephony hardware features
+</h4>
+
+<dl>
+  <dt>
+    <code>android.hardware.telephony</code>
+  </dt>
+
+  <dd>
+    The app uses the device's telephony features, such as telephony radio with
+    data communication services.
+  </dd>
+
+  <dt>
+    <code>android.hardware.telephony.cdma</code>
+  </dt>
+
+  <dd>
+    <p>
+      The app uses the Code Division Multiple Access (CDMA) telephony radio
+      system.
+    </p>
+
+    <p>
+      By using this feature, an app implies that it also uses the
+      <code>android.hardware.telephony</code> feature, unless this parent
+      feature is declared with <code>android:required="false"</code>.
+    </p>
+  </dd>
+
+  <dt>
+    <code>android.hardware.telephony.gsm</code>
+  </dt>
+
+  <dd>
+    <p>
+      The app uses the Global System for Mobile Communications (GSM) telephony
+      radio system.
+    </p>
+
+    <p>
+      By using this feature, an app implies that it also uses the
+      <code>android.hardware.telephony</code> feature, unless this parent
+      feature is declared with <code>android:required="false"</code>.
+    </p>
+  </dd>
+</dl>
+
+<h4 id="touchscreen-hw-features">
+  Touchscreen hardware features
+</h4>
+
+<dl>
+  <dt>
+    <code>android.hardware.faketouch</code>
+  </dt>
+
+  <dd>
+    <p>
+      The app uses basic touch interaction events, such as tapping and
+      dragging.
+    </p>
+
+    <p>
+      When declared as required, this feature indicates that the app is
+      compatible with a device only if that device emulates a touchscreen
+      ("fake touch" interface) or has an actual touchscreen.
+    </p>
+
+    <p>
+      A device that offers a fake touch interface provides a user input system
+      that emulates a subset of a touchscreen's capabilities. For example, a
+      mouse or remote control could drive an on-screen cursor. If your app
+      requires basic point and click interaction (in other words, it won't work
+      with only a d-pad controller), you should declare this feature. Because
+      this is the minimum level of touch interaction, you can also use an app
+      that declares this feature on devices that offer more complex touch
+      interfaces.
+    </p>
+
+    <p class="note">
+      <strong>Note:</strong> Apps require the {@code android.hardware.touchscreen}
+      feature by default. If you want your app to be available to devices that
+      provide a fake touch interface, you must also explicitly declare that a
+      touchscreen is not required as follows:
+    </p>
+    <pre>&lt;uses-feature android:name="android.hardware.touchscreen" <strong>android:required="false"</strong> /&gt;</pre>
+  </dd>
+
+  <dt>
+    <code>android.hardware.faketouch.multitouch.distinct</code>
+  </dt>
+
+  <dd>
+    <p>
+      The app tracks two or more distinct "fingers" on a fake touch interface.
+      This is a superset of the <code>android.hardware.faketouch</code>
+      feature. When declared as required, this feature indicates that the app
+      is compatible with a device only if that device emulates distinct
+      tracking of two or more fingers or has an actual touchscreen.
+    </p>
+
+    <p>
+      Unlike the distinct multitouch defined by {@code
+      android.hardware.touchscreen.multitouch.distinct}, input devices that
+      support distinct multitouch with a fake touch interface don't support all
+      two-finger gestures because the input in transformed to cursor movement
+      on the screen. That is, single-finger gestures on such a device move a
+      cursor, two-finger swipes cause single-finger touch events to occur, and
+      other two-finger gestures trigger the corresponding two-finger touch
+      events.
+    </p>
+
+    <p>
+      A device that provides a two-finger touch trackpad for cursor movement
+      can support this feature.
+    </p>
+  </dd>
+
+  <dt>
+    <code>android.hardware.faketouch.multitouch.jazzhand</code>
+  </dt>
+
+  <dd>
+    <p>
+      The app tracks five or more distinct "fingers" on a fake touch interface.
+      This is a superset of the <code>android.hardware.faketouch</code>
+      feature. When declared as required, this feature indicates that the app
+      is compatible with a device only if that device emulates distinct
+      tracking of five or more fingers or has an actual touchscreen.
+    </p>
+
+    <p>
+      Unlike the distinct multitouch defined by {@code
+      android.hardware.touchscreen.multitouch.jazzhand}, input devices that
+      support jazzhand multitouch with a fake touch interface don't support all
+      five-finger gestures because the input in transformed to cursor movement
+      on the screen. That is, single-finger gestures on such a device move a
+      cursor, multi-finger gestures cause single-finger touch events to occur,
+      and other multi-finger gestures trigger the corresponding multi-finger
+      touch events.
+    </p>
+
+    <p>
+      A device that provides a five-finger touch trackpad for cursor movement
+      can support this feature.
+    </p>
+  </dd>
+
+  <dt>
+    <code>android.hardware.touchscreen</code>
+  </dt>
+
+  <dd>
+    <p>
+      The app uses the device's touchscreen capabilities for gestures that are
+      more interactive than basic touch events, such as a fling. This is a
+      superset of the <code>android.hardware.faketouch</code> feature.
+    </p>
+
+    <p>
+      By default, your app requires this feature. As such, your app is not
+      available to devices that provide only an emulated touch interface ("fake
+      touch") by default. If you want to make your app available on devices
+      that provide a fake touch interface (or even on devices that provide only
+      a d-pad controller), you must explicitly declare that a touchscreen is
+      not required by declaring {@code android.hardware.touchscreen} with
+      {@code android:required="false"}. You should add this declaration if your
+      app uses—but does not require—a real touchscreen interface.
+    </p>
+
+    <p>
+      If your app in fact requires a touch interface (to perform more advanced
+      touch gestures such as fling), then you don't need to declare any touch
+      interface features because they're required by default. However, it's
+      best if you explicitly declare all features that your app uses.
+    </p>
+
+    <p>
+      If you require more complex touch interaction, such as multi-finger
+      gestures, you should declare that your app uses advanced touchscreen
+      features.
+    </p>
+  </dd>
+
+  <dt>
+    <code>android.hardware.touchscreen.multitouch</code>
+  </dt>
+
+  <dd>
+    <p>
+      The app uses the device's basic two-point multitouch capabilities, such
+      as for pinch gestures, but the app does not need to track touches
+      independently. This is a superset of the
+      <code>android.hardware.touchscreen</code> feature.
+    </p>
+
+    <p>
+      By using this feature, an app implies that it also uses the
+      <code>android.hardware.touchscreen</code> feature, unless this parent
+      feature is declared with <code>android:required="false"</code>.
+    </p>
+  </dd>
+
+  <dt>
+    <code>android.hardware.touchscreen.multitouch.distinct</code>
+  </dt>
+
+  <dd>
+    <p>
+      The app uses the device's advanced multitouch capabilities for tracking
+      two or more points independently. This feature is a superset of the
+      <code>android.hardware.touchscreen.multitouch</code> feature.
+    </p>
+
+    <p>
+      By using this feature, an app implies that it also uses the
+      <code>android.hardware.touchscreen.multitouch</code> feature, unless this
+      parent feature is declared with <code>android:required="false"</code>.
+    </p>
+  </dd>
+
+  <dt>
+    <code>android.hardware.touchscreen.multitouch.jazzhand</code>
+  </dt>
+
+  <dd>
+    <p>
+      The app uses the device's advanced multitouch capabilities for tracking
+      five or more points independently. This feature is a superset of the
+      <code>android.hardware.touchscreen.multitouch</code> feature.
+    </p>
+
+    <p>
+      By using this feature, an app implies that it also uses the
+      <code>android.hardware.touchscreen.multitouch</code> feature, unless this
+      parent feature is declared with <code>android:required="false"</code>.
+    </p>
+  </dd>
+</dl>
+
+<h4 id="usb-hw-features">
+  USB hardware features
+</h4>
+
+<dl>
+  <dt>
+    <code>android.hardware.usb.accessory</code>
+  </dt>
+
+  <dd>
+    The app behaves as the USB device and connects to USB hosts.
+  </dd>
+
+  <dt>
+    <code>android.hardware.usb.host</code>
+  </dt>
+
+  <dd>
+    The app uses the USB accessories that are connected to the device. The
+    device serves as the USB host.
+  </dd>
+</dl>
+
+<h4 id="wi-fi-hw-features">
+  Wi-Fi hardware features
+</h4>
+
+<dl>
+  <dt>
+    <code>android.hardware.wifi</code>
+  </dt>
+
+  <dd>
+    The app uses 802.11 networking (Wi-Fi) features on the device.
+  </dd>
+
+  <dt>
+    <code>android.hardware.wifi.direct</code>
+  </dt>
+
+  <dd>
+    The app uses the Wi-Fi Direct networking features on the device.
+  </dd>
+</dl>
+
+<h3 id="sw-features">
+  Software features
+</h3>
+
+<p>
+  This section presents the software features supported by the most current
+  platform release. To indicate that your app uses or requires a software
+  feature, declare the corresponding value (beginning with
+  <code>"android.software"</code>) in an <code>android:name</code> attribute.
+  Each time you declare a software feature, use a separate
+  <code>&lt;uses-feature&gt;</code> element.
+</p>
+
+<h4 id="communication-sw-features">
+  Communication software features
+</h4>
+
+<dl>
+  <dt>
+    <code>android.software.sip</code>
+  </dt>
+
+  <dd>
+    The app uses Session Initiation Protocol (SIP) services. By using SIP, the
+    app can support internet telephony operations, such as video conferencing
+    and instant messaging.
+  </dd>
+
+  <dt>
+    <code>android.software.sip.voip</code>
+  </dt>
+
+  <dd>
+    <p>
+      The app uses SIP-based Voice Over Internet Protocol (VoIP) services. By
+      using VoIP, the app can support real-time internet telephony operations,
+      such as two-way video conferencing.
+    </p>
+
+    <p>
+      By using this feature, an app implies that it also uses the
+      <code>android.software.sip</code> feature, unless this parent feature is
+      declared with <code>android:required="false"</code>.
+    </p>
+  </dd>
+
+  <dt>
+    <code>android.software.webview</code>
+  </dt>
+
+  <dd>
+    The app displays content from the internet.
+  </dd>
+</dl>
+
+<h4 id="custom-input-sw-features">
+  Custom input software features
+</h4>
+
+<dl>
+  <dt>
+    <code>android.software.input_methods</code>
+  </dt>
+
+  <dd>
+    The app uses a new input method, which the developer defines in an <a href=
+    "{@docRoot}reference/android/inputmethodservice/InputMethodService.html">{@code
+    InputMethodService}</a>.
+  </dd>
+</dl>
+
+<h4 id="device-management-sw-features">
+  Device management software features
+</h4>
+
+<dl>
+  <dt>
+    <code>android.software.backup</code>
+  </dt>
+
+  <dd>
+    The app includes logic to handle a backup and restore operation.
+  </dd>
+
+  <dt>
+    <code>android.software.device_admin</code>
+  </dt>
+
+  <dd>
+    The app uses device administrators to enforce a device policy.
+  </dd>
+
+  <dt>
+    <code>android.software.managed_users</code>
+  </dt>
+
+  <dd>
+    The app supports secondary users and managed profiles.
+  </dd>
+
+  <dt>
+    <code>android.software.securely_removes_users</code>
+  </dt>
+
+  <dd>
+    The app can <strong>permanently</strong> remove users and their associated
+    data.
+  </dd>
+
+  <dt>
+    <code>android.software.verified_boot</code>
+  </dt>
+
+  <dd>
+    The app includes logic to handle results from the device's verified boot
+    feature, which detects whether the device's configuration changes during a
+    restart operation.
+  </dd>
+</dl>
+
+<h4 id="media-sw-features">
+  Media software features
+</h4>
+
+<dl>
+  <dt>
+    <code>android.software.midi</code>
+  </dt>
+
+  <dd>
+    The app connects to musical instruments or outputs sound using the Musical
+    Instrument Digital Interface (MIDI) protocol.
+  </dd>
+
+  <dt>
+    <code>android.software.print</code>
+  </dt>
+
+  <dd>
+    The app includes commands for printing documents displayed on the device.
+  </dd>
+
+  <dt>
+    <code>android.software.leanback</code>
+  </dt>
+
+  <dd>
+    The app presents a UI that is designed for viewing on a large screen, such
+    as a television.
+  </dd>
+
+  <dt>
+    <code>android.software.live_tv</code>
+  </dt>
+
+  <dd>
+    The app streams live television programs.
+  </dd>
+</dl>
+
+<h4 id="screen-interface-sw-features">
+  Screen interface software features
+</h4>
+
+<dl>
+  <dt>
+    <code>android.software.app_widgets</code>
+  </dt>
+
+  <dd>
+    The app uses or provides App Widgets and should be installed only on
+    devices that include a Home screen or similar location where users can
+    embed App Widgets.
+  </dd>
+
+  <dt>
+    <code>android.software.home_screen</code>
+  </dt>
+
+  <dd>
+    The app behaves as a replacement to the device's Home screen.
+  </dd>
+
+  <dt>
+    <code>android.software.live_wallpaper</code>
+  </dt>
+
+  <dd>
+    The app uses or provides wallpapers that include animation.
+  </dd>
+</dl>
+
+<h3 id="permissions">
+  Permissions that Imply Feature Requirements
+</h3>
+
+<p>
+  Some of the hardware and software feature constants were made available to
+  applications after the corresponding API; for example, the
+  <code>android.hardware.bluetooth</code> feature was added in Android 2.2 (API
+  level 8), but the Bluetooth API that it refers to was added in Android 2.0
+  (API level 5). Because of this, some apps were able to use the API before
+  they had the ability to declare that they require the API using the
+  <code>&lt;uses-feature&gt;</code> system.
+</p>
+
+<p>
+  To prevent those apps from being made available unintentionally, Google Play
+  assumes that certain hardware-related permissions indicate that the
+  underlying hardware features are required by default. For instance,
+  applications that use Bluetooth must request the <code>BLUETOOTH</code>
+  permission in a <code>&lt;uses-permission&gt;</code> element — for legacy
+  apps, Google Play assumes that the permission declaration means that the
+  underlying <code>android.hardware.bluetooth</code> feature is required by the
+  application and sets up filtering based on that feature. Table 2 lists
+  permissions that imply feature requirements equivalent to those declared in
+  <code>&lt;uses-feature&gt;</code> elements.
+</p>
+
+<p>
+  Note that <code>&lt;uses-feature&gt;</code> declarations, including any
+  declared <code>android:required</code> attribute, always take precedence over
+  features implied by the permissions in table 2. For any of these permissions,
+  you can disable filtering based on the implied feature by explicitly
+  declaring the implied feature explicitly, in a
+  <code>&lt;uses-feature&gt;</code> element, with an
+  <code>android:required="false"</code> attribute. For example, to disable any
+  filtering based on the <code>CAMERA</code> permission, you would add this
+  <code>&lt;uses-feature&gt;</code> declaration to the manifest file:
+</p>
 
 <pre>&lt;uses-feature android:name="android.hardware.camera" android:required="false" /&gt;</pre>
 
-<table id="permissions-features" >
+<p class="table-caption" id="permissions-features">
+  <strong>Table 2. </strong>Device permissions that imply device hardware use.
+</p>
+<table>
   <tr>
     <th>Category</th>
     <th>This Permission...</th>
-    <th>Implies This Feature Requirement</th>
+    <th>...Implies This Feature Requirement</th>
     <!-- <th>Comments</th> -->
   </tr>
 
diff --git a/docs/html/guide/topics/providers/content-provider-creating.jd b/docs/html/guide/topics/providers/content-provider-creating.jd
index 7cd3d69..baa92e1 100755
--- a/docs/html/guide/topics/providers/content-provider-creating.jd
+++ b/docs/html/guide/topics/providers/content-provider-creating.jd
@@ -409,25 +409,27 @@
 public class ExampleProvider extends ContentProvider {
 ...
     // Creates a UriMatcher object.
-    private static final UriMatcher sUriMatcher;
-...
-    /*
-     * The calls to addURI() go here, for all of the content URI patterns that the provider
-     * should recognize. For this snippet, only the calls for table 3 are shown.
-     */
-...
-    /*
-     * Sets the integer value for multiple rows in table 3 to 1. Notice that no wildcard is used
-     * in the path
-     */
-    sUriMatcher.addURI("com.example.app.provider", "table3", 1);
+    private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
 
-    /*
-     * Sets the code for a single row to 2. In this case, the "#" wildcard is
-     * used. "content://com.example.app.provider/table3/3" matches, but
-     * "content://com.example.app.provider/table3 doesn't.
-     */
-    sUriMatcher.addURI("com.example.app.provider", "table3/#", 2);
+    static {
+        /*
+         * The calls to addURI() go here, for all of the content URI patterns that the provider
+         * should recognize. For this snippet, only the calls for table 3 are shown.
+         */
+
+        /*
+         * Sets the integer value for multiple rows in table 3 to 1. Notice that no wildcard is used
+         * in the path
+         */
+        sUriMatcher.addURI("com.example.app.provider", "table3", 1);
+    
+        /*
+         * Sets the code for a single row to 2. In this case, the "#" wildcard is
+         * used. "content://com.example.app.provider/table3/3" matches, but
+         * "content://com.example.app.provider/table3 doesn't.
+         */
+        sUriMatcher.addURI("com.example.app.provider", "table3/#", 2);
+    }
 ...
     // Implements ContentProvider.query()
     public Cursor query(
diff --git a/docs/html/images/training/tv/playback/guided-step-buttonaction-2x.png b/docs/html/images/training/tv/playback/guided-step-buttonaction-2x.png
new file mode 100644
index 0000000..059cf0a
--- /dev/null
+++ b/docs/html/images/training/tv/playback/guided-step-buttonaction-2x.png
Binary files differ
diff --git a/docs/html/images/training/tv/playback/guided-step-buttonaction.png b/docs/html/images/training/tv/playback/guided-step-buttonaction.png
new file mode 100644
index 0000000..aacb844
--- /dev/null
+++ b/docs/html/images/training/tv/playback/guided-step-buttonaction.png
Binary files differ
diff --git a/docs/html/images/training/tv/playback/guided-step-subaction-2x.png b/docs/html/images/training/tv/playback/guided-step-subaction-2x.png
new file mode 100644
index 0000000..411bee4
--- /dev/null
+++ b/docs/html/images/training/tv/playback/guided-step-subaction-2x.png
Binary files differ
diff --git a/docs/html/images/training/tv/playback/guided-step-subaction.png b/docs/html/images/training/tv/playback/guided-step-subaction.png
new file mode 100644
index 0000000..5b004d5
--- /dev/null
+++ b/docs/html/images/training/tv/playback/guided-step-subaction.png
Binary files differ
diff --git a/docs/html/ndk/guides/audio/opensl-prog-notes.jd b/docs/html/ndk/guides/audio/opensl-prog-notes.jd
index 3263145..e70aa08 100644
--- a/docs/html/ndk/guides/audio/opensl-prog-notes.jd
+++ b/docs/html/ndk/guides/audio/opensl-prog-notes.jd
@@ -61,8 +61,8 @@
  create array and can be added
 later after the object is created. The Android implementation provides
  a convenience feature to
-avoid this complexity; see the
- <a href="#dynamic-interfaces">Dynamic interfaces at object creation</a> section above.
+avoid this complexity, which is described in
+ <a href="{@docRoot}ndk/guides/audio/opensl-for-android.html#dynamic-interfaces">Dynamic interfaces at object creation</a>.
 </p>
 
 <p>
diff --git a/docs/html/samples/index.jd b/docs/html/samples/index.jd
index 76ea573..5885086 100644
--- a/docs/html/samples/index.jd
+++ b/docs/html/samples/index.jd
@@ -35,9 +35,8 @@
   from GitHub as a new project.
 </p>
 
-<p>For more information about importing samples, see
-<a href="{@docRoot}tools/studio/index.html#git-samples">Easy access to Android code samples on
-GitHub</a>.</p>
+<p>To view the Android code samples that you can import, see the 
+<a class="external-link" href="https://github.com/googlesamples/">Google Samples page</a> on GitHub.</p>
 
 <h2>Download Samples</h2>
 
diff --git a/docs/html/training/basics/firstapp/building-ui.jd b/docs/html/training/basics/firstapp/building-ui.jd
index 402396e..275500c 100644
--- a/docs/html/training/basics/firstapp/building-ui.jd
+++ b/docs/html/training/basics/firstapp/building-ui.jd
@@ -396,20 +396,13 @@
 <h2>Run Your App</h2>
 
 <p>This layout is applied by the default {@link android.app.Activity} class
-that the SDK tools generated when you created the project. Run the app to see the
-results:</p>
+that the SDK tools generated when you created the project.</p>
 
-<ul>
-  <li>In Android Studio, from the toolbar, click <strong>Run</strong>
+<p>To run the app and see the results,
+  click <strong>Run 'app'</strong>
     <img src="{@docRoot}images/tools/as-run.png"
-    style="vertical-align:baseline;margin:0; max-height:1em" />.</li>
-  <li>Or from a command line, change directories to the root of your Android project and
-execute:
-<pre class="no-pretty-print">
-$ ant debug
-adb install -r app/build/outputs/apk/app-debug.apk
-</pre></li>
-</ul>
+    style="vertical-align:baseline;margin:0; max-height:1em" /> in the
+    toolbar.</p>
 
 <p>Continue to the <a href="starting-activity.html">next
 lesson</a> to learn how to respond to button presses, read content
diff --git a/docs/html/training/basics/firstapp/running-app.jd b/docs/html/training/basics/firstapp/running-app.jd
index 99b38bf..21fb64d 100755
--- a/docs/html/training/basics/firstapp/running-app.jd
+++ b/docs/html/training/basics/firstapp/running-app.jd
@@ -76,46 +76,6 @@
 <p>Android Studio installs the app on your connected device and starts it.</p>
 
 
-<h3>Run the app from a command line</h3>
-
-<p>Open a command-line and navigate to the root of your project directory.
-  Use Gradle to build your project in debug mode, invoke the <code>assembleDebug</code> build task
-  using the Gradle wrapper script (<code>gradlew assembleRelease</code>).
-
-  <p>This creates your debug <code>.apk</code> file inside the module <code>build/</code>
-  directory, named <code>app-debug.apk</code>.  </p>
-
-  <p>On Windows platforms, type this command:</p>
-
-<pre>
-> gradlew.bat assembleDebug
-</pre>
-
-<p>On Mac OS and Linux platforms, type these commands:</p>
-
-<pre>
-$ chmod +x gradlew
-$ ./gradlew assembleDebug
-</pre>
-
-  <p>After you build the project, the output APK for the app module is located in
-  <code>app/build/outputs/apk/</code>
-
-  <p class="note"><strong>Note:</strong> The first command (<code>chmod</code>) adds the execution
-  permission to the Gradle wrapper script and is only necessary the first time you build this
-  project from the command line.</p>
-
-  <p>Make sure the Android SDK <code>platform-tools/</code> directory is included in your
-  <code>PATH</code> environment variable, then execute:
-  <pre class="no-pretty-print">$ adb install app/build/outputs/apk/app-debug.apk</pre><p>
-  <p>On your device, locate <em>MyFirstApp</em> and open it.</p>
-
-<p>That's how you build and run your Android app on a device!
-  To start developing, continue to the <a href="building-ui.html">next
-lesson</a>.</p>
-
-
-
 <h2 id="Emulator">Run on the Emulator</h2>
 
 <p>Whether you're using Android Studio or the command line, to run your app on the emulator you need
@@ -168,23 +128,8 @@
 When you do, <em>My First App</em> appears on the emulator screen.</p>
 
 
-<h3>Run your app from the command line</h3>
- <ol>
-  <li>Build the project from the command line. The output APK for the app module is located in
-  <code>app/build/outputs/apk/</code>.</li>
-  <li>Make sure the Android SDK <code>platform-tools/</code> directory is included in your
-  <code>PATH</code> environment variable.</li>
-  <li>Execute this command:
-   <p>
-   <pre class="no-pretty-print">$ adb install app/build/outputs/apk/apk-debug.apk</pre>
-   </p>
-  </li>
-  <li>On the emulator, locate <em>MyFirstApp</em> and open it.</li>
- </ol>
-
-
-  <p>That's how you build and run your Android app on the emulator!
-  To start developing, continue to the <a href="building-ui.html">next
-  lesson</a>.</p>
+<p>That's how you build and run your Android app on the emulator!
+To start developing, continue to the <a href="building-ui.html">next
+lesson</a>.</p>
 
 
diff --git a/docs/html/training/sync-adapters/running-sync-adapter.jd b/docs/html/training/sync-adapters/running-sync-adapter.jd
index 033450f..a640aa6 100644
--- a/docs/html/training/sync-adapters/running-sync-adapter.jd
+++ b/docs/html/training/sync-adapters/running-sync-adapter.jd
@@ -240,6 +240,7 @@
              * Ask the framework to run your sync adapter.
              * To maintain backward compatibility, assume that
              * changeUri is null.
+             */
             ContentResolver.requestSync(ACCOUNT, AUTHORITY, null);
         }
         ...
diff --git a/docs/html/training/tv/playback/guided-step.jd b/docs/html/training/tv/playback/guided-step.jd
index 121961f..99e5c08 100644
--- a/docs/html/training/tv/playback/guided-step.jd
+++ b/docs/html/training/tv/playback/guided-step.jd
@@ -1,5 +1,6 @@
 page.title=Adding a Guided Step
-page.tags=tv, guided step
+page.tags=tv,guided step,GuidedStepFragment,GuidedAction
+page.keywords=tv,GuidedStepFragment,GuidedAction
 helpoutsWidget=true
 
 trainingnavtop=true
@@ -12,7 +13,7 @@
   <ol>
     <li><a href="#details">Provide Details for a Step</a></li>
     <li><a href="#actions">Create and Handle User Actions</a></li>
-    <li><a href="#sequence">Group Guided Steps Into a Sequence</a></li>
+    <li><a href="#sequence">Group Guided Steps Into a Guided Sequence</a></li>
     <li><a href="#presentation">Customize Step Presentation</a></li>
   </ol>
   <h2>Try it out</h2>
@@ -107,7 +108,7 @@
 
 <pre>
 &#64;Override
-public void onCreateActions(List<GuidedAction> actions, Bundle savedInstanceState) {
+public void onCreateActions(List&lt;GuidedAction&gt; actions, Bundle savedInstanceState) {
     // Add "Continue" user action for this step
     actions.add(new GuidedAction.Builder()
            .id(CONTINUE)
@@ -119,39 +120,60 @@
 </pre>
 
 <p>
-Actions aren’t limited to single-line selections. Use
-{@link android.support.v17.leanback.widget.GuidedAction} attributes
-to add the following additional types of actions:
+Actions aren't limited to single-line selections. Here are additional types of
+actions you can create:
 </p>
 
 <ul>
 <li>
-Add a information label action by setting
+Add an information label action by setting
 {@link android.support.v17.leanback.widget.GuidedAction.Builder#infoOnly infoOnly(true)}.
-If <code>infoOnly</code> is set to true, the action can't be selected by the user. Use label
-actions to provide additional information about user choices.
+If you set <code>infoOnly</code> to true, the user can't select the action. To
+provide additional information about user choices, use label actions.
 </li>
 <li>
 Add an editable text action by setting
 {@link android.support.v17.leanback.widget.GuidedAction.Builder#editable editable(true)}. If
 <code>editable</code> is true, when the action is selected the user can enter text using the
-remote or a connected keyboard.
+remote or a connected keyboard. Override
+{@link android.support.v17.leanback.app.GuidedStepFragment#onGuidedActionEdited
+onGuidedActionEdited()} or
+{@code onGuidedActionEditedAndProceed()} to get the modified text the user entered.
 </li>
 <li>
 Add a set of actions that behave as checkable radio buttons by using
 {@link android.support.v17.leanback.widget.GuidedAction.Builder#checkSetId checkSetId()}
 with a common ID value to group actions into a set. All actions in the same list with the same
-check-set ID are considered linked. When one of the actions within that set is selected, that
+check-set ID are considered linked. When the user selects one of the actions within that set, that
 action becomes checked, while all other actions become unchecked.
 </li>
+<li>
+Add a date-picker action by using
+{@code GuidedDatePickerAction.Builder}
+instead of
+{@link android.support.v17.leanback.widget.GuidedAction.Builder} in
+{@link android.support.v17.leanback.app.GuidedStepFragment#onCreateActions
+onCreateActions()}. Override
+{@link android.support.v17.leanback.app.GuidedStepFragment#onGuidedActionEdited
+onGuidedActionEdited()} or
+{@code onGuidedActionEditedAndProceed()} to get the modified date value the user entered.
+</li>
+<li>
+Add an action that uses subactions to let the user pick from an extended list of
+choices. Subactions are described in <a href="#subactions">Add subactions</a>.
+</li>
+<li>
+Add a button action that appears to the right of the actions list and is easily
+accessible. Button actions are described in <a href="#buttonactions">Add button
+actions</a>.</li>
 </ul>
 
 <p>
-You can also add a visual indicator that indicates selecting the action leads to a new step by
-setting
+You can also add a visual indicator&mdash;to indicate that selecting the action
+leads to a new step&mdash;by setting
 {@link android.support.v17.leanback.widget.GuidedAction#hasNext hasNext(true)}.
-See {@link android.support.v17.leanback.widget.GuidedAction} for all the different attributes
-you can set.
+For all the different attributes that you can set, see
+{@link android.support.v17.leanback.widget.GuidedAction}.
 </p>
 
 <p>
@@ -162,6 +184,111 @@
 examining {@link android.support.v17.leanback.widget.GuidedAction#getId GuidedAction.getId()}.
 </p>
 
+<h3 id="subactions">Add subactions</h3>
+
+<p>
+Some actions might require giving the user an additional set of choices. A
+{@link android.support.v17.leanback.widget.GuidedAction} can specify a list of
+subactions that get displayed as a drop-down list of child actions.
+</p>
+
+<img src="{@docRoot}images/training/tv/playback/guided-step-subaction.png"
+srcset="{@docRoot}images/training/tv/playback/guided-step-subaction.png 1x,
+{@docRoot}images/training/tv/playback/guided-step-subaction-2x.png 2x" />
+<p class="img-caption"><strong>Figure 2.</strong> Guided step subactions.</p>
+
+<p>
+The subaction list can contain regular actions or radio button actions, but
+not date-picker or editable text actions. Also, a subaction cannot have its own
+set of subactions as the system does not support more than one level of subactions.
+Deeply nested sets of actions create a poor user experience.
+</p>
+
+<p>
+To add subactions, first create and populate a list of
+{@link android.support.v17.leanback.widget.GuidedAction GuidedActions} that will
+act as subactions:
+</p>
+
+<pre>
+List&lt;GuidedAction&gt; subActions = new ArrayList&lt;GuidedAction&gt;();
+subActions.add(new GuidedAction.Builder()
+       .id(SUBACTION1)
+       .title(getString(R.string.guidedstep_subaction1_title))
+       .description(getString(R.string.guidedstep_subaction1_desc))
+       .build());
+...
+</pre>
+
+<p>
+In {@link android.support.v17.leanback.app.GuidedStepFragment#onCreateActions
+onCreateActions()}, create a top-level
+{@link android.support.v17.leanback.widget.GuidedAction} that will display the
+list of subactions when selected:
+</p>
+
+<pre>
+&#64;Override
+public void onCreateActions(List&lt;GuidedAction&gt; actions, Bundle savedInstanceState) {
+...
+    actions.add(new GuidedAction.Builder()
+           .id(SUBACTIONS)
+           .title(getString(R.string.guidedstep_subactions_title))
+           .description(getString(R.string.guidedstep_subactions_desc))
+           <b>.subActions(subActions)</b>
+           .build());
+...
+}
+</pre>
+
+<p>
+Finally, respond to subaction selections by overriding
+{@code onSubGuidedActionClicked()}:
+</p>
+
+<pre>
+&#64;Override
+public boolean onSubGuidedActionClicked(GuidedAction action) {
+   // Check for which action was clicked, and handle as needed
+   if (action.getId() == SUBACTION1) {
+       // Subaction 1 selected
+   }
+   // Return true to collapse the subactions drop-down list, or
+   // false to keep the drop-down list expanded.
+   return true;
+}
+</pre>
+
+<h3 id="buttonactions">Add button actions</h3>
+
+<p>
+If your guided step has a large list of actions, users may have to scroll through the list
+to access the most commonly used actions. Use button actions to separate
+commonly used actions from the action list. Button actions appear to the right
+of the action list and are easy to navigate to.
+</p>
+
+<img src="{@docRoot}images/training/tv/playback/guided-step-buttonaction.png"
+srcset="{@docRoot}images/training/tv/playback/guided-step-buttonaction.png 1x,
+{@docRoot}images/training/tv/playback/guided-step-buttonaction-2x.png 2x" />
+<p class="img-caption"><strong>Figure 3.</strong> Guided step button actions.</p>
+
+<p>
+Button actions are created and handled just like regular actions, but you create
+button actions in
+{@code onCreateButtonActions()} instead of
+{@link android.support.v17.leanback.app.GuidedStepFragment#onCreateActions
+onCreateActions()}. Respond to button actions in
+{@link android.support.v17.leanback.app.GuidedStepFragment#onGuidedActionClicked
+onGuidedActionClicked()}.
+</p>
+
+<p>
+Use button actions for simple actions, such as navigation actions between steps.
+Don't use the date-picker action or other editable actions as button actions.
+Also, button actions cannot have subactions.
+</p>
+
 <h2 id="sequence">Group Guided Steps Into a Guided Sequence</h2>
 
 <p>
@@ -188,6 +315,20 @@
 decide to provide your own {@link android.support.v17.leanback.widget.GuidedAction} that
 returns to the previous step, you can implement the Back behavior by calling
 {@link android.app.FragmentManager#popBackStack getFragmentManager().popBackStack()}.
+If you need to return the user to an even earlier step in the sequence, use
+{@code popBackStackToGuidedStepFragment()} to return to a specific
+{@link android.support.v17.leanback.app.GuidedStepFragment} in the fragment stack.
+</p>
+
+<p>
+When the user has finished the last step in the sequence, use
+{@code finishGuidedStepFragments()} to remove all
+{@link android.support.v17.leanback.app.GuidedStepFragment GuidedStepFragments}
+from the current stack and return to the original parent activity. If the
+first {@link android.support.v17.leanback.app.GuidedStepFragment} was added
+using {@link android.support.v17.leanback.app.GuidedStepFragment#addAsRoot
+addAsRoot()}, calling
+{@code finishGuidedStepFragments()} will also close the parent activity.
 </p>
 
 <h2 id="presentation">Customize Step Presentation</h2>
@@ -220,11 +361,11 @@
 {@link android.support.v17.leanback.R.styleable#LeanbackGuidedStepTheme_guidedStepTheme}
 attribute to your existing custom activity theme. This attribute points to the custom theme that
 only the {@link android.support.v17.leanback.app.GuidedStepFragment} objects in your
-activity will use.
+activity use.
 </li>
 <li>
 If you use {@link android.support.v17.leanback.app.GuidedStepFragment} objects in different
-activities that are part of the same overall multi-step task, and want to use a consistent
+activities that are part of the same overall multi-step task and want to use a consistent
 visual theme across all steps, override
 {@link android.support.v17.leanback.app.GuidedStepFragment#onProvideTheme
 GuidedStepFragment.onProvideTheme()} and return your custom theme.
diff --git a/docs/html/wear/preview/api-overview.jd b/docs/html/wear/preview/api-overview.jd
index 384cb0a..543313a 100644
--- a/docs/html/wear/preview/api-overview.jd
+++ b/docs/html/wear/preview/api-overview.jd
@@ -147,7 +147,7 @@
 <p> If you have a chat messaging app, your notifications should use
 {@code Notification.MessagingStyle}, which is new in Android 6.0. Wear 2.0 uses
 the chat messages included in a
-<a href="{docRoot}preview/features/notification-updates.html#style">{@code MessagingStyle}</a>
+<a href="{@docRoot}preview/features/notification-updates.html#style">{@code MessagingStyle}</a>
  notification
 (see {@code addMessage()}) to provide a rich chat app-like experience in the
 expanded notification.
diff --git a/docs/html/wear/preview/downloads.jd b/docs/html/wear/preview/downloads.jd
index b119d57..8689504 100644
--- a/docs/html/wear/preview/downloads.jd
+++ b/docs/html/wear/preview/downloads.jd
@@ -418,13 +418,15 @@
       devices, <code>fastboot oem unlock</code>
       </li>
 
-      <li>Navigate to the directory where you unzipped the system image in Step
-      1.
+      <li>On the watch, select the <strong>Unlock</strong> option.
       </li>
 
-      <li>Execute the <code>flash-all</code> script by typing
+      <li>Navigate to the directory where you unzipped the system image in Step
+      1. At the top level of that directory,
+      execute the <code>flash-all</code> script by typing
       <code>flash-all.sh</code> or, in the case of Windows,
-      <code>flash-all.bat</code>.
+      <code>flash-all.bat</code>. The following may need to
+      precede the command: <code>./</code>
       </li>
     </ol>
 
@@ -434,40 +436,10 @@
     </h4>
 
       <p>
-        After the <code>flash-all</code> script finishes, your watch reboots
-        and soon will be ready for testing with the preview image.
-      </p>
-
-    <ol>
-      <li>Attach the watch charger to the watch and plug the USB cord
-      into your computer, if it is not already plugged in.
-      </li>
-
-      <li>Use the following <a href="{@docRoot}tools/help/adb.html">adb
-      command</a> to confirm that the watch is available:
-      <code>adb devices</code>
-      </li>
-
-      <li>Use the following adb command to start the device in fastboot mode:
-      <code>adb reboot bootloader</code>
-      </li>
-
-      <li>Use the following command to
-      lock the device's bootloader: <code>fastboot flashing lock</code> or, for some
-      devices, <code>fastboot oem lock</code>
-      </li>
-
-      <li>On the watch, continue the boot by touching <strong>'0'</strong>.
-      </li>
-
-    </ol>
-
-
-    <p>
-      Pair the watch with a
-      phone or tablet. The preview now is available for testing on the watch.
-      Before installing an app, enable the Developer Options menu, and ADB
-      debugging, on the watch as follows:
+        After the <code>flash-all</code> script finishes, your watch reboots.
+        Pair the watch with a phone or tablet. The preview now is available
+        for testing on the watch. Before installing an app, perform the
+        following steps on the watch to re-secure the watch's bootloader:
     </p>
 
     <ol>
@@ -490,6 +462,19 @@
       <li>Connect the watch to your computer and tap <strong>Always allow from
       this computer</strong>.
       </li>
+
+      <li>Use the following adb command to start the device in fastboot mode:
+      <code>adb reboot bootloader</code>
+      </li>
+
+      <li>Use the following command to
+      lock the device's bootloader: <code>fastboot flashing lock</code> or, for some
+      devices, <code>fastboot oem lock</code>
+      </li>
+
+      <li>On the watch, continue the boot by choosing
+      <strong>Start</strong> and touching <strong>'0'</strong>.
+      </li>
     </ol>
 
     <p>
@@ -502,8 +487,8 @@
       <li>Open your app in Android Studio.
       </li>
 
-      <li>Select <strong>wear</strong> from the Run/Debug configuration
-      drop-down menu.
+      <li>Select your Wear app module name from the Run/Debug configuration
+      drop-down menu (typically <strong>wear</strong>).
       </li>
 
       <li>Click the Play button.
@@ -514,8 +499,7 @@
     </ol>
 
     <p>
-      After your app is installed on the watch, you are prompted to start the
-      app on the watch.
+      After your app is installed on the watch, the app should run.
     </p>
 
     <p>
@@ -567,10 +551,12 @@
       <li>Click <strong>Create Virtual Device</strong>.
       </li>
 
-      <li>In the <strong>Category</strong> pane, select Wear, choose a hardware profile,
-       and click <strong>Next</strong>. The Android Wear 2.0 Developer Preview
+      <li>In the <strong>Category</strong> pane, select Wear and
+       choose a hardware profile.
+       The Android Wear 2.0 Developer Preview
        is only optimized for round devices currently, so we recommend not
        using the square or chin profiles for now.
+       Click <strong>Next</strong>.
       </li>
 
       <li>Select an <strong>N</strong> image to download. The images may be on
@@ -588,7 +574,8 @@
     </ol>
 
     <p>
-      You can now test an application in the <a href=
+      You can now test an application with a virtual preview device
+      in the <a href=
       "{@docRoot}tools/devices/emulator.html">Android Emulator</a>. For more
       information about using virtual devices, see <a href=
       "{@docRoot}tools/devices/managing-avds.html">Managing AVDs with the AVD
diff --git a/docs/html/wear/preview/features/notifications.jd b/docs/html/wear/preview/features/notifications.jd
index 0962eb4..75f9fee 100644
--- a/docs/html/wear/preview/features/notifications.jd
+++ b/docs/html/wear/preview/features/notifications.jd
@@ -41,7 +41,7 @@
 </p>
 
 <p><img src="{@docRoot}wear/preview/images/comparison_diagram.png" /> </p>
-<p><b>Figure 1.</b> Comparison of the same notification in Android Wear 1.x and 2.0.</p> 
+<p><b>Figure 1.</b> Comparison of the same notification in Android Wear 1.x and 2.0.</p>
 
 <p>Some of the visual updates include:</p>
 <ul>
@@ -73,7 +73,7 @@
 
 <li><strong>Updated horizontal swipe gesture on a notification</strong>:
   To dismiss a notification in Wear 2.0, the user swipes horizontally in either
-  direction. So if your notification instructs the user to swipe left or right, 
+  direction. So if your notification instructs the user to swipe left or right,
   you must update the text of your notification.
 </li>
 </ul>
@@ -82,13 +82,14 @@
   substantial additional content and actions for each notification.
 </p>
 <p>When you <a href="{@docRoot}training/wearables/notifications/pages.html">specify additional content pages</a>
- and actions for a notification, those are available to the user within the 
- expanded notification. Each expanded notification follows 
+ and actions for a notification, those are available to the user within the
+ expanded notification. Each expanded notification follows
  <a href="http://www.google.com/design/spec-wear">Material Design for Android Wear</a>,
   so the user gets an app-like experience.
 </p>
-<p><img src="{@docRoot}wear/preview/images/expanded_diagram.png" /> </p>
-<p><b>Figure 2</b>. An expanded notification with content and actions.</p>
+
+
+<h3 id="expanded">Expanded notifications</h3>
 <p>If the first action in the expanded notification has a
 <a href=" {@docRoot}reference/android/support/v4/app/RemoteInput.html">{@code RemoteInput}</a>
   (e.g., a Reply action), then the choices you set with <a href="http://developer.android.com/reference/android/support/v4/app/RemoteInput.Builder.html#setChoices(java.lang.CharSequence[])">{@code setChoices()}</a>
@@ -102,7 +103,7 @@
   <li>The notification is generated by an app on the paired phone and
     bridged to Wear.
   </li>
-  <li>The notification does not have a 
+  <li>The notification does not have a
   <a href="http://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html#setContentIntent(android.app.PendingIntent)">{@code contentIntent}</a>.
   </li>
 </ul>
@@ -126,9 +127,11 @@
 <p>
  Expanded Notifications allow you to include additional content and actions
    for a notification. You choose the level of detail that your app's notifications
-    will provide; however be judicious with the amount of detail you include in a 
-    notification. 
+    will provide; however be judicious with the amount of detail you include in a
+    notification.
 </p>
+<img src="{@docRoot}wear/preview/images/expanded_diagram.png" height="340"
+  style="float:left;margin:10px 20px 0 0" />
 <h4>Adding additional content</h4>
 To show additional content in your expanded notification, see <a href="{@docRoot}training/wearables/notifications/pages.html">Adding Pages to a Notification</a>.</p>
 <p>Additional content pages are stacked vertically in the expanded notification
@@ -151,34 +154,36 @@
 
 <p>If you have a chat messaging app, your notifications should use
 <a href="{@docRoot}preview/features/notification-updates.html#style">{@code Notification.MessagingStyle}</a>,
- which is new in Android 6.0. Wear 2.0 uses the chat messages included
+ which is new in Android N. Wear 2.0 uses the chat messages included
   in a <a href="{@docRoot}preview/features/notification-updates.html#style">{@code MessagingStyle}</a> notification 
+
   (see <a href="{@docRoot}preview/features/notification-updates.html#style">{@code addMessage()}</a>) to provide
   a rich chat app-like experience in the expanded notification.
 </p>
-<p class="note">Note: <a href="{@docRoot}preview/features/notification-updates.html#style">{@code MessagingStyle}</a> 
+
+<p class="note">Note: <a href="{@docRoot}preview/features/notification-updates.html#style">{@code MessagingStyle}</a>
 expanded notifications require that you have at least version 1.5.0.2861804 of the
   <a href="https://play.google.com/store/apps/details?id=com.google.android.wearable.app">Android Wear app</a>
   on your paired Android phone. That version will be available within the next
   few weeks in the Play Store.
 </p>
+
 <h3 id="smart-reply">Smart Reply</h3>
-<p>Wear 2.0 also introduces <i>Smart Reply</i> for <a href="{@docRoot}preview/features/notification-updates.html#style">{@code MessagingStyle}</a> notifications.
+<img src="{@docRoot}wear/preview/images/messaging_style.png" height="420"
+  style="float:right;margin:10px 20px 0 0" />
+<p>Wear 2.0 also introduces <i>Smart Reply</i>
+for <a href="{@docRoot}preview/features/notification-updates.html#style">{@code MessagingStyle}</a> notifications.
   Smart Reply provides the user with contextually relevant, touchable choices in
   the expanded notification and in {@code RemoteInput}. These augment the fixed
-  list of choices that the developer provides in 
+  list of choices that the developer provides in
    <a href="http://developer.android.com/reference/android/support/v4/app/RemoteInput.html">{@code RemoteInput}</a>
-    using the 
+    using the
     <a href="{@docRoot}reference/android/support/v4/app/RemoteInput.Builder.html#setChoices(java.lang.CharSequence[])">{@code setChoices()}</a> method.
 </p>
 <p>By enabling Smart Reply for your MessagingStyle notifications,
   you provide users with a fast (single tap), discreet (no speaking aloud), and
   reliable way to respond to chat messages.
 </p>
-<p><img src="{@docRoot}wear/preview/images/messaging_style.png" /></p>
-<p><b>Figure 3</b>. The expanded notification includes contextually relevant
-  Smart Reply responses below the primary action.
-</p>
 
 <p>Responses generated by Smart Reply are shown in addition to those set using the
   <a href="{@docRoot}reference/android/support/v4/app/RemoteInput.Builder.html#setChoices(java.lang.CharSequence[])">{@code setChoices()}</a> method.
@@ -189,7 +194,7 @@
 <ol>
   <li>Use <a href="{@docRoot}preview/features/notification-updates.html#style">{@code Notification.MessagingStyle}</a>.
   </li>
-  <li>Call the method 
+  <li>Call the method
   <a href="{@docRoot}wear/preview/start.html#get_the_preview_reference_documentation">{@code setAllowGeneratedReplies()}</a>
    for the notification action.</li>
   <li>Ensure that the notification action has a
@@ -222,8 +227,9 @@
  .setSmallIcon(R.drawable.new_message)
  .setLargeIcon(aBitmap)
  // 2) set the style to MessagingStyle
- .setStyle(new NotificationCompat.MessagingStyle(resources.getString(R.string.reply_name)).addMessage(messages[0].getText(), messages[0].getTime(), messages[0].getSender())
-  .addMessage(messages[1].getText(), messages[1].getTime(), messages[1].getSender()))
+ .setStyle(new NotificationCompat.MessagingStyle(resources.getString(R.string.reply_name))
+ .addMessage(messages[0].getText(), messages[0].getTime(), messages[0].getSender())
+ .addMessage(messages[1].getText(), messages[1].getTime(), messages[1].getSender()))
 
 
 // 3) add an action with RemoteInput
diff --git a/docs/html/wear/preview/features/ui-nav-actions.jd b/docs/html/wear/preview/features/ui-nav-actions.jd
index 800fc8e..1ba275f 100644
--- a/docs/html/wear/preview/features/ui-nav-actions.jd
+++ b/docs/html/wear/preview/features/ui-nav-actions.jd
@@ -19,10 +19,10 @@
 
    <h2>You should also read</h2>
    <ul>
-   <li><a href="http://www.google.com/design/wear-spec/components/navigation-drawer.html">
+   <li><a href="http://www.google.com/design/spec-wear/components/navigation-drawer.html">
    Navigation Drawer Design</a> </li>
    <li>
-   <a href="http://www.google.com/design/wear-spec/components/action-drawer.html">
+   <a href="http://www.google.com/design/spec-wear/components/action-drawer.html">
    Action Drawer Design</a>
    </ul>
 
@@ -76,6 +76,7 @@
 &lt;android.support.wearable.view.drawer.WearableDrawerLayout
     android:id="@+id/drawer_layout"
     xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     tools:deviceIds="wear">
diff --git a/docs/html/wear/preview/images/comparison_diagram.png b/docs/html/wear/preview/images/comparison_diagram.png
index 7dbf65f2..4bcf10e 100644
--- a/docs/html/wear/preview/images/comparison_diagram.png
+++ b/docs/html/wear/preview/images/comparison_diagram.png
Binary files differ
diff --git a/docs/html/wear/preview/images/messaging_style.png b/docs/html/wear/preview/images/messaging_style.png
index 966e524..a3bf109 100644
--- a/docs/html/wear/preview/images/messaging_style.png
+++ b/docs/html/wear/preview/images/messaging_style.png
Binary files differ
diff --git a/docs/html/wear/preview/images/messaging_style_diagram.png b/docs/html/wear/preview/images/messaging_style_diagram.png
deleted file mode 100644
index 3b21c7973..0000000
--- a/docs/html/wear/preview/images/messaging_style_diagram.png
+++ /dev/null
Binary files differ
diff --git a/graphics/java/android/graphics/drawable/DrawableContainer.java b/graphics/java/android/graphics/drawable/DrawableContainer.java
index 8971004..c6977746 100644
--- a/graphics/java/android/graphics/drawable/DrawableContainer.java
+++ b/graphics/java/android/graphics/drawable/DrawableContainer.java
@@ -500,34 +500,44 @@
      * @param d The drawable to initialize.
      */
     private void initializeDrawableForDisplay(Drawable d) {
-        if (mDrawableContainerState.mEnterFadeDuration <= 0 && mHasAlpha) {
-            d.setAlpha(mAlpha);
-        }
+        // Temporary fix for suspending callbacks during initialization. We
+        // don't want any of these setters causing an invalidate() since that
+        // may call back into DrawableContainer.
+        final Callback cb = d.getCallback();
+        d.setCallback(null);
 
-        if (mDrawableContainerState.mHasColorFilter) {
-            // Color filter always overrides tint.
-            d.setColorFilter(mDrawableContainerState.mColorFilter);
-        } else {
-            if (mDrawableContainerState.mHasTintList) {
-                d.setTintList(mDrawableContainerState.mTintList);
+        try {
+            if (mDrawableContainerState.mEnterFadeDuration <= 0 && mHasAlpha) {
+                d.setAlpha(mAlpha);
             }
-            if (mDrawableContainerState.mHasTintMode) {
-                d.setTintMode(mDrawableContainerState.mTintMode);
+
+            if (mDrawableContainerState.mHasColorFilter) {
+                // Color filter always overrides tint.
+                d.setColorFilter(mDrawableContainerState.mColorFilter);
+            } else {
+                if (mDrawableContainerState.mHasTintList) {
+                    d.setTintList(mDrawableContainerState.mTintList);
+                }
+                if (mDrawableContainerState.mHasTintMode) {
+                    d.setTintMode(mDrawableContainerState.mTintMode);
+                }
             }
-        }
 
-        d.setVisible(isVisible(), true);
-        d.setDither(mDrawableContainerState.mDither);
-        d.setState(getState());
-        d.setLevel(getLevel());
-        d.setBounds(getBounds());
-        d.setLayoutDirection(getLayoutDirection());
-        d.setAutoMirrored(mDrawableContainerState.mAutoMirrored);
+            d.setVisible(isVisible(), true);
+            d.setDither(mDrawableContainerState.mDither);
+            d.setState(getState());
+            d.setLevel(getLevel());
+            d.setBounds(getBounds());
+            d.setLayoutDirection(getLayoutDirection());
+            d.setAutoMirrored(mDrawableContainerState.mAutoMirrored);
 
-        final Rect hotspotBounds = mHotspotBounds;
-        if (hotspotBounds != null) {
-            d.setHotspotBounds(hotspotBounds.left, hotspotBounds.top,
-                    hotspotBounds.right, hotspotBounds.bottom);
+            final Rect hotspotBounds = mHotspotBounds;
+            if (hotspotBounds != null) {
+                d.setHotspotBounds(hotspotBounds.left, hotspotBounds.top,
+                        hotspotBounds.right, hotspotBounds.bottom);
+            }
+        } finally {
+            d.setCallback(cb);
         }
     }
 
diff --git a/graphics/java/android/graphics/drawable/VectorDrawable.java b/graphics/java/android/graphics/drawable/VectorDrawable.java
index dd33e98..f5592fa 100644
--- a/graphics/java/android/graphics/drawable/VectorDrawable.java
+++ b/graphics/java/android/graphics/drawable/VectorDrawable.java
@@ -804,7 +804,7 @@
                 mTintMode = copy.mTintMode;
                 mAutoMirrored = copy.mAutoMirrored;
                 mRootGroup = new VGroup(copy.mRootGroup, mVGTargetsMap);
-                createNativeTree(mRootGroup);
+                createNativeTreeFromCopy(copy, mRootGroup);
 
                 mBaseWidth = copy.mBaseWidth;
                 mBaseHeight = copy.mBaseHeight;
@@ -826,6 +826,16 @@
             VMRuntime.getRuntime().registerNativeAllocation(NATIVE_ALLOCATION_SIZE);
         }
 
+        // Create a new native tree with the given root group, and copy the properties from the
+        // given VectorDrawableState's native tree.
+        private void createNativeTreeFromCopy(VectorDrawableState copy, VGroup rootGroup) {
+            mNativeTree = new VirtualRefBasePtr(nCreateTreeFromCopy(
+                    copy.mNativeTree.get(), rootGroup.mNativePtr));
+            // Register tree size
+            VMRuntime.getRuntime().registerNativeAllocation(NATIVE_ALLOCATION_SIZE);
+        }
+
+
         void onTreeConstructionFinished() {
             mRootGroup.setTree(mNativeTree);
             mAllocationOfAllNodes = mRootGroup.getNativeSize();
@@ -1777,6 +1787,7 @@
     }
 
     private static native long nCreateTree(long rootGroupPtr);
+    private static native long nCreateTreeFromCopy(long treeToCopy, long rootGroupPtr);
     private static native void nSetRendererViewportSize(long rendererPtr, float viewportWidth,
             float viewportHeight);
     private static native boolean nSetRootAlpha(long rendererPtr, float alpha);
diff --git a/libs/hwui/BakedOpDispatcher.cpp b/libs/hwui/BakedOpDispatcher.cpp
index 59c1065..8b3f172 100644
--- a/libs/hwui/BakedOpDispatcher.cpp
+++ b/libs/hwui/BakedOpDispatcher.cpp
@@ -805,27 +805,21 @@
     // Note that we don't use op->paint in this function - it's never set on a LayerOp
     OffscreenBuffer* buffer = *op.layerHandle;
 
-    if (CC_UNLIKELY(!buffer)) {
-        // Layer was not allocated, which can occur if there were no draw ops inside. We draw the
-        // equivalent by drawing a rect with the same layer properties (alpha/xfer/filter).
-        int color = SkColorSetA(SK_ColorTRANSPARENT, op.alpha * 255);
-        renderRectForLayer(renderer, op, state,
-                color, op.mode, op.colorFilter);
-    } else {
-        float layerAlpha = op.alpha * state.alpha;
-        Glop glop;
-        GlopBuilder(renderer.renderState(), renderer.caches(), &glop)
-                .setRoundRectClipState(state.roundRectClipState)
-                .setMeshTexturedIndexedVbo(buffer->vbo, buffer->elementCount)
-                .setFillLayer(buffer->texture, op.colorFilter, layerAlpha, op.mode, Blend::ModeOrderSwap::NoSwap)
-                .setTransform(state.computedState.transform, TransformFlags::None)
-                .setModelViewOffsetRectSnap(op.unmappedBounds.left, op.unmappedBounds.top,
-                        Rect(op.unmappedBounds.getWidth(), op.unmappedBounds.getHeight()))
-                .build();
-        renderer.renderGlop(state, glop);
-    }
+    if (CC_UNLIKELY(!buffer)) return;
 
-    if (buffer && !buffer->hasRenderedSinceRepaint) {
+    float layerAlpha = op.alpha * state.alpha;
+    Glop glop;
+    GlopBuilder(renderer.renderState(), renderer.caches(), &glop)
+            .setRoundRectClipState(state.roundRectClipState)
+            .setMeshTexturedIndexedVbo(buffer->vbo, buffer->elementCount)
+            .setFillLayer(buffer->texture, op.colorFilter, layerAlpha, op.mode, Blend::ModeOrderSwap::NoSwap)
+            .setTransform(state.computedState.transform, TransformFlags::None)
+            .setModelViewOffsetRectSnap(op.unmappedBounds.left, op.unmappedBounds.top,
+                    Rect(op.unmappedBounds.getWidth(), op.unmappedBounds.getHeight()))
+            .build();
+    renderer.renderGlop(state, glop);
+
+    if (!buffer->hasRenderedSinceRepaint) {
         buffer->hasRenderedSinceRepaint = true;
         if (CC_UNLIKELY(Properties::debugLayersUpdates)) {
             // render debug layer highlight
diff --git a/libs/hwui/VectorDrawable.cpp b/libs/hwui/VectorDrawable.cpp
index f0348e4..2b79941 100644
--- a/libs/hwui/VectorDrawable.cpp
+++ b/libs/hwui/VectorDrawable.cpp
@@ -530,7 +530,7 @@
     if (prop->getRootAlpha() == 1.0f && prop->getColorFilter() == nullptr) {
         return nullptr;
     } else {
-        outPaint->setColorFilter(mStagingProperties.getColorFilter());
+        outPaint->setColorFilter(prop->getColorFilter());
         outPaint->setFilterQuality(kLow_SkFilterQuality);
         outPaint->setAlpha(prop->getRootAlpha() * 255);
         return outPaint;
diff --git a/libs/hwui/VectorDrawable.h b/libs/hwui/VectorDrawable.h
index b33f26c..a5d1d4b 100644
--- a/libs/hwui/VectorDrawable.h
+++ b/libs/hwui/VectorDrawable.h
@@ -542,6 +542,12 @@
     Tree(Group* rootNode) : mRootNode(rootNode) {
         mRootNode->setPropertyChangedListener(&mPropertyChangedListener);
     }
+
+    // Copy properties from the tree and use the give node as the root node
+    Tree(const Tree* copy, Group* rootNode) : Tree(rootNode) {
+        mStagingProperties.syncAnimatableProperties(*copy->stagingProperties());
+        mStagingProperties.syncNonAnimatableProperties(*copy->stagingProperties());
+    }
     // Draws the VD onto a bitmap cache, then the bitmap cache will be rendered onto the input
     // canvas. Returns the number of pixels needed for the bitmap cache.
     int draw(Canvas* outCanvas, SkColorFilter* colorFilter,
@@ -666,7 +672,7 @@
     };
     void onPropertyChanged(TreeProperties* prop);
     TreeProperties* mutateStagingProperties() { return &mStagingProperties; }
-    const TreeProperties* stagingProperties() { return &mStagingProperties; }
+    const TreeProperties* stagingProperties() const { return &mStagingProperties; }
     PushStagingFunctor* getFunctor() { return &mFunctor;}
 
     // This should only be called from animations on RT
diff --git a/libs/hwui/tests/unit/BakedOpDispatcherTests.cpp b/libs/hwui/tests/unit/BakedOpDispatcherTests.cpp
index 01d3d70..6b7b721 100644
--- a/libs/hwui/tests/unit/BakedOpDispatcherTests.cpp
+++ b/libs/hwui/tests/unit/BakedOpDispatcherTests.cpp
@@ -53,7 +53,7 @@
 typedef void (*TestBakedOpReceiver)(BakedOpRenderer&, const BakedOpState&);
 
 static void testUnmergedGlopDispatch(renderthread::RenderThread& renderThread, RecordedOp* op,
-        std::function<void(const Glop& glop)> glopVerifier) {
+        std::function<void(const Glop& glop)> glopVerifier, int expectedGlopCount = 1) {
     // Create op, and wrap with basic state.
     LinearAllocator allocator;
     auto snapshot = TestUtils::makeSnapshot(Matrix4::identity(), Rect(100, 100));
@@ -61,8 +61,8 @@
     ASSERT_NE(nullptr, state);
 
     int glopCount = 0;
-    auto glopReceiver = [&glopVerifier, &glopCount] (const Glop& glop) {
-        ASSERT_EQ(glopCount++, 0) << "Only one Glop expected";
+    auto glopReceiver = [&glopVerifier, &glopCount, &expectedGlopCount] (const Glop& glop) {
+        ASSERT_LE(glopCount++, expectedGlopCount) << expectedGlopCount << "glop(s) expected";
         glopVerifier(glop);
     };
     ValidatingBakedOpRenderer renderer(renderThread.renderState(), glopReceiver);
@@ -75,7 +75,8 @@
     static TestBakedOpReceiver unmergedReceivers[] = BUILD_RENDERABLE_OP_LUT(X);
 #undef X
     unmergedReceivers[op->opId](renderer, *state);
-    ASSERT_EQ(1, glopCount) << "Exactly one Glop expected";
+    ASSERT_EQ(expectedGlopCount, glopCount) << "Exactly " << expectedGlopCount
+            << "Glop(s) expected";
 }
 
 RENDERTHREAD_TEST(BakedOpDispatcher, pathTexture_positionOvalArc) {
@@ -119,12 +120,8 @@
     OffscreenBuffer* buffer = nullptr; // no providing a buffer, should hit rect fallback case
     LayerOp op(Rect(10, 10), Matrix4::identity(), nullptr, &layerPaint, &buffer);
     testUnmergedGlopDispatch(renderThread, &op, [&renderThread] (const Glop& glop) {
-        // rect glop is dispatched with paint props applied
-        EXPECT_EQ(renderThread.renderState().meshState().getUnitQuadVBO(),
-                glop.mesh.vertices.bufferObject) << "Unit quad should be drawn";
-        EXPECT_EQ(nullptr, glop.fill.texture.texture) << "Should be no texture when layer is null";
-        EXPECT_FLOAT_EQ(128 / 255.0f, glop.fill.color.a) << "Rect quad should use op alpha";
-    });
+        ADD_FAILURE() << "Nothing should happen";
+    }, 0);
 }
 
 static int getGlopTransformFlags(renderthread::RenderThread& renderThread, RecordedOp* op) {
diff --git a/media/java/android/media/AudioAttributes.java b/media/java/android/media/AudioAttributes.java
index a3bbdfc..5286f8f 100644
--- a/media/java/android/media/AudioAttributes.java
+++ b/media/java/android/media/AudioAttributes.java
@@ -225,9 +225,20 @@
     public final static int FLAG_BYPASS_MUTE = 0x1 << 7;
 
     /**
-     * Flag requesting a low latency path.
+     * Flag requesting a low latency path when creating an AudioTrack.
      * When using this flag, the sample rate must match the native sample rate
      * of the device. Effects processing is also unavailable.
+     *
+     * Note that if this flag is used without specifying a bufferSizeInBytes then the
+     * AudioTrack's actual buffer size may be too small. It is recommended that a fairly
+     * large buffer should be specified when the AudioTrack is created.
+     * Then the actual size can be reduced by calling
+     * {@link AudioTrack#setBufferSizeInFrames(int)}. The buffer size can be optimized
+     * by lowering it after each write() call until the audio glitches, which is detected by calling
+     * {@link AudioTrack#getUnderrunCount()}. Then the buffer size can be increased
+     * until there are no glitches.
+     * This tuning step should be done while playing silence.
+     * This technique provides a compromise between latency and glitch rate.
      */
     public final static int FLAG_LOW_LATENCY = 0x1 << 8;
 
diff --git a/media/java/android/media/MediaCodecInfo.java b/media/java/android/media/MediaCodecInfo.java
index 349d67e..72fb1e9 100644
--- a/media/java/android/media/MediaCodecInfo.java
+++ b/media/java/android/media/MediaCodecInfo.java
@@ -591,7 +591,12 @@
                     }
                 }
                 levelCaps = createFromProfileLevel(mMime, profile, maxLevel);
-                if (levelCaps != null && !levelCaps.isFormatSupported(format)) {
+                // remove profile from this format otherwise levelCaps.isFormatSupported will
+                // get into this same conditon and loop forever.
+                Map<String, Object> mapWithoutProfile = new HashMap<>(map);
+                mapWithoutProfile.remove(MediaFormat.KEY_PROFILE);
+                MediaFormat formatWithoutProfile = new MediaFormat(mapWithoutProfile);
+                if (levelCaps != null && !levelCaps.isFormatSupported(formatWithoutProfile)) {
                     return false;
                 }
             }
diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/Camera2SurfaceViewTestCase.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/Camera2SurfaceViewTestCase.java
index 423c3b0..a8b782e8 100644
--- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/Camera2SurfaceViewTestCase.java
+++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/Camera2SurfaceViewTestCase.java
@@ -37,6 +37,7 @@
 import android.hardware.camera2.CameraMetadata;
 import android.hardware.camera2.CaptureRequest;
 import android.hardware.camera2.CaptureResult;
+import android.hardware.camera2.params.StreamConfigurationMap;
 import android.media.ImageReader;
 import android.graphics.SurfaceTexture;
 import android.os.Bundle;
@@ -127,6 +128,7 @@
     protected List<Size> mOrderedRAW10Sizes; // In descending order.
     protected List<Size> mOrderedYUV420888Sizes; // In descending order.
     protected HashMap<Size, Long> mMinPreviewFrameDurationMap;
+    protected boolean mSupportRAW10;
 
     protected WindowManager mWindowManager;
 
@@ -603,16 +605,21 @@
         mCamera = CameraTestUtils.openCamera(
                 mCameraManager, cameraId, mCameraListener, mHandler);
         mCollector.setCameraId(cameraId);
-        mStaticInfo = new StaticMetadata(mCameraManager.getCameraCharacteristics(cameraId),
-                CheckLevel.ASSERT, /*collector*/null);
+        CameraCharacteristics properties = mCameraManager.getCameraCharacteristics(cameraId);
+        mStaticInfo = new StaticMetadata(properties, CheckLevel.ASSERT, /*collector*/null);
+        StreamConfigurationMap configMap =
+                properties.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
+        mSupportRAW10 = configMap.isOutputSupportedFor(ImageFormat.RAW10);
         if (mStaticInfo.isColorOutputSupported()) {
             mOrderedPreviewSizes = getSupportedPreviewSizes(cameraId, mCameraManager,
                     getPreviewSizeBound(mWindowManager, PREVIEW_SIZE_BOUND));
             mOrderedVideoSizes = getSupportedVideoSizes(
                     cameraId, mCameraManager, PREVIEW_SIZE_BOUND);
             mOrderedStillSizes = getSupportedStillSizes(cameraId, mCameraManager, null);
-            mOrderedRAW10Sizes = getSortedSizesForFormat(
-                    cameraId, mCameraManager, ImageFormat.RAW10, null);
+            if (mSupportRAW10) {
+                mOrderedRAW10Sizes = getSortedSizesForFormat(
+                        cameraId, mCameraManager, ImageFormat.RAW10, null);
+            }
             mOrderedYUV420888Sizes = getSortedSizesForFormat(
                     cameraId, mCameraManager, ImageFormat.YUV_420_888, null);
             // Use ImageFormat.YUV_420_888 for now. TODO: need figure out what's format for preview
@@ -636,6 +643,7 @@
             mOrderedPreviewSizes = null;
             mOrderedVideoSizes = null;
             mOrderedStillSizes = null;
+            mSupportRAW10 = false;
         }
     }
 
diff --git a/packages/DocumentsUI/src/com/android/documentsui/FilesActivity.java b/packages/DocumentsUI/src/com/android/documentsui/FilesActivity.java
index 57c14e9..b82f8dd 100644
--- a/packages/DocumentsUI/src/com/android/documentsui/FilesActivity.java
+++ b/packages/DocumentsUI/src/com/android/documentsui/FilesActivity.java
@@ -86,17 +86,26 @@
         if (mState.restored) {
             if (DEBUG) Log.d(TAG, "Stack already resolved for uri: " + intent.getData());
         } else if (!mState.stack.isEmpty()) {
-            // If a non-empty stack is present in our state it was read (presumably)
+            // If a non-empty stack is present in our state, it was read (presumably)
             // from EXTRA_STACK intent extra. In this case, we'll skip other means of
-            // loading or restoring the stack.
+            // loading or restoring the stack (like URI).
             //
-            // When restoring from a stack, if a URI is present, it should only ever
-            // be a launch URI, or a fake Uri from notifications.
-            // Launch URIs support sensible activity management, but don't specify a real
-            // content target.
-            if (DEBUG) Log.d(TAG, "Launching with non-empty stack.");
-            assert(uri == null || uri.getAuthority() == null ||
-                    LauncherActivity.isLaunchUri(uri));
+            // When restoring from a stack, if a URI is present, it should only ever be:
+            // -- a launch URI: Launch URIs support sensible activity management,
+            //    but don't specify a real content target)
+            // -- a fake Uri from notifications. These URIs have no authority (TODO: details).
+            //
+            // Any other URI is *sorta* unexpected...except when browsing an archive
+            // in downloads.
+            if(uri != null
+                    && uri.getAuthority() != null
+                    && !uri.equals(mState.stack.peek())
+                    && !LauncherActivity.isLaunchUri(uri)) {
+                if (DEBUG) Log.w(TAG,
+                        "Launching with non-empty stack. Ignoring unexpected uri: " + uri);
+            } else {
+                if (DEBUG) Log.d(TAG, "Launching with non-empty stack.");
+            }
             refreshCurrentRootAndDirectory(AnimationView.ANIM_NONE);
         } else if (Intent.ACTION_VIEW.equals(intent.getAction())) {
             assert(uri != null);
diff --git a/packages/DocumentsUI/src/com/android/documentsui/services/Job.java b/packages/DocumentsUI/src/com/android/documentsui/services/Job.java
index b4f1299..b8f8fba 100644
--- a/packages/DocumentsUI/src/com/android/documentsui/services/Job.java
+++ b/packages/DocumentsUI/src/com/android/documentsui/services/Job.java
@@ -308,7 +308,9 @@
                 String id, DocumentStack stack, List<DocumentInfo> srcs,
                 DocumentInfo srcParent) {
             assert(!srcs.isEmpty());
-            assert(stack.peek().isDirectory());  // we can't currently delete from archives.
+            // stack is empty if we delete docs from recent.
+            // we can't currently delete from archives.
+            assert(stack.isEmpty() || stack.peek().isDirectory());
             return new DeleteJob(service, appContext, listener, id, stack, srcs, srcParent);
         }
     }
diff --git a/packages/Keyguard/src/com/android/keyguard/EmergencyButton.java b/packages/Keyguard/src/com/android/keyguard/EmergencyButton.java
index 40c11cf..8d41145 100644
--- a/packages/Keyguard/src/com/android/keyguard/EmergencyButton.java
+++ b/packages/Keyguard/src/com/android/keyguard/EmergencyButton.java
@@ -16,15 +16,18 @@
 
 package com.android.keyguard;
 
+import android.app.ActivityManagerNative;
 import android.app.ActivityOptions;
 import android.content.Context;
 import android.content.Intent;
 import android.content.res.Configuration;
 import android.os.PowerManager;
+import android.os.RemoteException;
 import android.os.SystemClock;
 import android.os.UserHandle;
 import android.telecom.TelecomManager;
 import android.util.AttributeSet;
+import android.util.Slog;
 import android.view.View;
 import android.widget.Button;
 
@@ -47,6 +50,8 @@
                     | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
                     | Intent.FLAG_ACTIVITY_CLEAR_TOP);
 
+    private static final String LOG_TAG = "EmergencyButton";
+
     KeyguardUpdateMonitorCallback mInfoCallback = new KeyguardUpdateMonitorCallback() {
 
         @Override
@@ -122,6 +127,11 @@
         // TODO: implement a shorter timeout once new PowerManager API is ready.
         // should be the equivalent to the old userActivity(EMERGENCY_CALL_TIMEOUT)
         mPowerManager.userActivity(SystemClock.uptimeMillis(), true);
+        try {
+            ActivityManagerNative.getDefault().stopSystemLockTaskMode();
+        } catch (RemoteException e) {
+            Slog.w(LOG_TAG, "Failed to stop app pinning");
+        }
         if (isInCall()) {
             resumeCall();
             if (mEmergencyButtonCallback != null) {
diff --git a/packages/PrintSpooler/res/values-my-rMM/strings.xml b/packages/PrintSpooler/res/values-my-rMM/strings.xml
index b51336e..c277c55 100644
--- a/packages/PrintSpooler/res/values-my-rMM/strings.xml
+++ b/packages/PrintSpooler/res/values-my-rMM/strings.xml
@@ -81,7 +81,7 @@
     <string name="cancelling_notification_title_template" msgid="1821759594704703197">"<xliff:g id="PRINT_JOB_NAME">%1$s</xliff:g> ကို ပယ်ဖျက်နေပါသည်"</string>
     <string name="failed_notification_title_template" msgid="2256217208186530973">"စာထုတ်စက်မှ အမှား <xliff:g id="PRINT_JOB_NAME">%1$s</xliff:g>"</string>
     <string name="blocked_notification_title_template" msgid="1175435827331588646">"<xliff:g id="PRINT_JOB_NAME">%1$s</xliff:g>ကိုစာထုတ်စက်ကငြင်းလိုက်သည်"</string>
-    <string name="cancel" msgid="4373674107267141885">"ဖျက်သိမ်းရန်"</string>
+    <string name="cancel" msgid="4373674107267141885">"မလုပ်တော့ပါ"</string>
     <string name="restart" msgid="2472034227037808749">"အစက ပြန်စရန်"</string>
     <string name="no_connection_to_printer" msgid="2159246915977282728">"စာထုတ်စက်နဲ့ ဆက်သွယ်ထားမှု မရှိပါ"</string>
     <string name="reason_unknown" msgid="5507940196503246139">"အကြောင်းအရာ မသိရှိ"</string>
diff --git a/packages/SettingsLib/res/drawable/notification_auto_importance.xml b/packages/SettingsLib/res/drawable/notification_auto_importance.xml
index a63e911b..c946153 100644
--- a/packages/SettingsLib/res/drawable/notification_auto_importance.xml
+++ b/packages/SettingsLib/res/drawable/notification_auto_importance.xml
@@ -20,8 +20,8 @@
         android:viewportHeight="24.0">
     <path
             android:fillColor="#FFFFFFFF"
-            android:pathData="M11.2,13.6l1.6,0l-0.8,-2.6z"/>
+            android:pathData="M10.8,12.7l2.4,0l-1.2,-3.7z"/>
     <path
             android:fillColor="#FF000000"
-            android:pathData="M22.5,9.6L15,9l-3,-7L9,9L1.5,9.6l5.7,5L5.5,22l6.5,-3.9l6.5,3.9l-1.7,-7.4L22.5,9.6zM13.6,16l-0.5,-1.4h-2.3L10.4,16H9l2.3,-6.4h1.4L15,16H13.6z"/>
+            android:pathData="M12,2C6.5,2 2,6.5 2,12s4.5,10 10,10s10,-4.5 10,-10S17.5,2 12,2zM14.3,16l-0.7,-2h-3.2l-0.7,2H7.8L11,7h2l3.2,9H14.3z"/>
 </vector>
\ No newline at end of file
diff --git a/packages/SettingsLib/res/values-hy-rAM/strings.xml b/packages/SettingsLib/res/values-hy-rAM/strings.xml
index 36eafa5..c31ece3 100644
--- a/packages/SettingsLib/res/values-hy-rAM/strings.xml
+++ b/packages/SettingsLib/res/values-hy-rAM/strings.xml
@@ -139,7 +139,7 @@
     <string name="choose_profile" msgid="8229363046053568878">"Ընտրել պրոֆիլ"</string>
     <string name="category_personal" msgid="1299663247844969448">"Անձնական"</string>
     <string name="category_work" msgid="8699184680584175622">"Աշխատանքային"</string>
-    <string name="development_settings_title" msgid="215179176067683667">"Ծրագրավորման ընտրանքներ"</string>
+    <string name="development_settings_title" msgid="215179176067683667">"Ծրագրավորողի ընտրանքներ"</string>
     <string name="development_settings_enable" msgid="542530994778109538">"Միացնել մշակողի ընտրանքները"</string>
     <string name="development_settings_summary" msgid="1815795401632854041">"Կարգավորել ընտրանքները ծրագրի ծրագրավորման համար"</string>
     <string name="development_settings_not_available" msgid="4308569041701535607">"Ծրագրավորման ընտրանքներն այլևս հասանելի չեն այս օգտվողի համար"</string>
diff --git a/packages/SettingsLib/res/values-my-rMM/strings.xml b/packages/SettingsLib/res/values-my-rMM/strings.xml
index 9bb5694..0acc414 100644
--- a/packages/SettingsLib/res/values-my-rMM/strings.xml
+++ b/packages/SettingsLib/res/values-my-rMM/strings.xml
@@ -71,7 +71,7 @@
     <string name="bluetooth_hid_profile_summary_use_for" msgid="232727040453645139">"ထည့်သွင်းရန်အသုံးပြုသည်"</string>
     <string name="bluetooth_pairing_accept" msgid="6163520056536604875">"အတူတွဲပါ"</string>
     <string name="bluetooth_pairing_accept_all_caps" msgid="6061699265220789149">"ချိတ်တွဲရန်"</string>
-    <string name="bluetooth_pairing_decline" msgid="4185420413578948140">"ဖျက်သိမ်းရန်"</string>
+    <string name="bluetooth_pairing_decline" msgid="4185420413578948140">"မလုပ်တော့ပါ"</string>
     <string name="bluetooth_pairing_will_share_phonebook" msgid="4982239145676394429">"ချိတ်တွဲမှုက ချိတ်ဆက်ထားလျှင် သင်၏ အဆက်အသွယ်များ နှင့် ခေါ်ဆိုမှု မှတ်တမ်းကို ရယူခွင့် ပြုသည်။"</string>
     <string name="bluetooth_pairing_error_message" msgid="3748157733635947087">"<xliff:g id="DEVICE_NAME">%1$s</xliff:g>နှင့် တွဲချိတ်မရပါ"</string>
     <string name="bluetooth_pairing_pin_error_message" msgid="8337234855188925274">"ပင်နံပါတ် သို့မဟုတ် ဖြတ်သန်းခွင့်ကီးမမှန်ကန်သောကြောင့်<xliff:g id="DEVICE_NAME">%1$s</xliff:g>နှင့် တွဲချိတ်မရပါ။"</string>
diff --git a/packages/SettingsLib/res/values-uz-rUZ/strings.xml b/packages/SettingsLib/res/values-uz-rUZ/strings.xml
index 015478f..7d41acb 100644
--- a/packages/SettingsLib/res/values-uz-rUZ/strings.xml
+++ b/packages/SettingsLib/res/values-uz-rUZ/strings.xml
@@ -114,7 +114,7 @@
     <string name="tts_engine_security_warning" msgid="8786238102020223650">"Ushbu nutq sintezi mexanizmi barcha yozgan matnlaringizni to‘plab olishi mumkin, jumladan kredit karta raqamlari va parollar kabi shaxsiy ma‘lumotlarni ham. U <xliff:g id="TTS_PLUGIN_ENGINE_NAME">%s</xliff:g> mexanizmi bilan o‘rnatiladi. Ushbu nutq sintezi mexanizmidan foydalanilsinmi?"</string>
     <string name="tts_engine_network_required" msgid="1190837151485314743">"Bu til uchun nutq sintezatorini yoqish uchun Internetga ulaning."</string>
     <string name="tts_default_sample_string" msgid="4040835213373086322">"Bu nutq sintezining misoli"</string>
-    <string name="tts_status_title" msgid="7268566550242584413">"Birlamchi til"</string>
+    <string name="tts_status_title" msgid="7268566550242584413">"Asosiy til"</string>
     <string name="tts_status_ok" msgid="1309762510278029765">"<xliff:g id="LOCALE">%1$s</xliff:g> – to‘liq qo‘llab-quvvatlanadi"</string>
     <string name="tts_status_requires_network" msgid="6042500821503226892">"<xliff:g id="LOCALE">%1$s</xliff:g> tili tarmoqqa ulanishi lozim"</string>
     <string name="tts_status_not_supported" msgid="4491154212762472495">"<xliff:g id="LOCALE">%1$s</xliff:g> – qo‘llab-quvvatlanmaydi"</string>
diff --git a/packages/SettingsLib/res/values-zh-rCN/strings.xml b/packages/SettingsLib/res/values-zh-rCN/strings.xml
index 4eca743..6b4c453 100644
--- a/packages/SettingsLib/res/values-zh-rCN/strings.xml
+++ b/packages/SettingsLib/res/values-zh-rCN/strings.xml
@@ -324,9 +324,11 @@
     <string name="enabled_by_admin" msgid="2386503803463071894">"已被管理员启用"</string>
     <string name="disabled_by_admin" msgid="3669999613095206948">"已被管理员禁用"</string>
     <string name="home" msgid="3256884684164448244">"设置主屏幕"</string>
-    <!-- no translation found for battery_labels:0 (8494684293649631252) -->
-    <!-- no translation found for battery_labels:1 (8934126114226089439) -->
-    <!-- no translation found for battery_labels:2 (1286113608943010849) -->
+  <string-array name="battery_labels">
+    <item msgid="8494684293649631252">"0%"</item>
+    <item msgid="8934126114226089439">"50%"</item>
+    <item msgid="1286113608943010849">"100%"</item>
+  </string-array>
     <string name="charge_length_format" msgid="8978516217024434156">"<xliff:g id="ID_1">%1$s</xliff:g>前"</string>
     <string name="remaining_length_format" msgid="7886337596669190587">"还剩 <xliff:g id="ID_1">%1$s</xliff:g>"</string>
     <string name="screen_zoom_summary_small" msgid="5867245310241621570">"小"</string>
diff --git a/packages/SystemUI/res/anim/tv_pip_controls_text_focus_gain_animation.xml b/packages/SystemUI/res/anim/tv_pip_controls_focus_gain_animation.xml
similarity index 100%
rename from packages/SystemUI/res/anim/tv_pip_controls_text_focus_gain_animation.xml
rename to packages/SystemUI/res/anim/tv_pip_controls_focus_gain_animation.xml
diff --git a/packages/SystemUI/res/anim/tv_pip_controls_text_focus_lose_animation.xml b/packages/SystemUI/res/anim/tv_pip_controls_focus_loss_animation.xml
similarity index 100%
rename from packages/SystemUI/res/anim/tv_pip_controls_text_focus_lose_animation.xml
rename to packages/SystemUI/res/anim/tv_pip_controls_focus_loss_animation.xml
diff --git a/packages/SystemUI/res/anim/tv_pip_controls_in_recents_focus_lose_animation.xml b/packages/SystemUI/res/anim/tv_pip_controls_in_recents_focus_loss_animation.xml
similarity index 100%
rename from packages/SystemUI/res/anim/tv_pip_controls_in_recents_focus_lose_animation.xml
rename to packages/SystemUI/res/anim/tv_pip_controls_in_recents_focus_loss_animation.xml
diff --git a/packages/SystemUI/res/drawable/ic_hotspot_unavailable.xml b/packages/SystemUI/res/drawable/ic_hotspot_unavailable.xml
new file mode 100644
index 0000000..736cfd8
--- /dev/null
+++ b/packages/SystemUI/res/drawable/ic_hotspot_unavailable.xml
@@ -0,0 +1,62 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+     Copyright (C) 2016 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.
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+    android:name="root"
+    android:height="48dp"
+    android:width="48dp"
+    android:viewportHeight="48"
+    android:viewportWidth="48"
+    android:tint="@color/qs_tile_tint_unavailable" >
+    <group
+        android:name="ic_hotspot"
+        android:translateX="23.97354"
+        android:translateY="24.26306" >
+        <group
+            android:name="ic_hotspot_pivot"
+            android:translateX="-23.21545"
+            android:translateY="-18.86649" >
+            <clip-path
+                android:name="mask"
+                android:pathData="M 38.8337860107,-40.3974914551 c 0.0,0.0 -38.4077911377,30.8523712158 -38.4077911377,30.8523712158 c 0.0,0.0 43.1884765625,43.515335083 43.1884765625,43.515335083 c 0.0,0.0 -2.4169921875,2.57838439941 -2.4169921875,2.57838439941 c 0.0,0.0 -42.9885101318,-43.0112609863 -42.9885101318,-43.0112609863 c 0.0,0.0 -32.6199798584,25.1699066162 -32.6199798584,25.1699066162 c 0.0,0.0 55.9664764404,69.742401123 55.9664764404,69.742401123 c 0.0,0.0 27.6589050293,-22.6579437256 27.6589050293,-22.6579437256 c 0.0,0.0 -30.8645172119,-34.00390625 -30.8645172119,-34.00390625 c 0.0,0.0 2.70756530762,-1.99278259277 2.70756530762,-1.99278259277 c 0.0,0.0 1.53030395508,-0.876571655273 1.53030395508,-0.876571655274 c 0.0,0.0 2.85780334473,-3.12069702148 2.85780334473,-3.12069702148 c 0.0,0.0 13.0984039307,13.025604248 13.0984039307,13.025604248 c 0.0,0.0 -3.13299560547,2.82977294922 -3.13299560547,2.82977294922 c 0.0,0.0 16.571762085,22.0471801758 16.571762085,22.0471801758 c 0.0,0.0 42.8175811768,-34.3554534912 42.8175811768,-34.3554534912 c 0.0,0.0 -55.9664916992,-69.7423400879 -55.9664916992,-69.7423400879 Z" />
+            <group
+                android:name="cross" >
+                <path
+                    android:name="cross_1"
+                    android:pathData="M 4.44044494629,2.24310302734 c 0.0,0.0 35.4000396729,35.3999633789 35.4000396729,35.3999633789 "
+                    android:strokeColor="#FFFFFFFF"
+                    android:strokeAlpha="1"
+                    android:strokeWidth="3.5"
+                    android:fillColor="#00000000" />
+            </group>
+            <group
+                android:name="hotspot"
+                android:translateX="23.481"
+                android:translateY="18.71151" >
+                <group
+                    android:name="circles"
+                    android:translateX="-0.23909"
+                    android:translateY="-0.10807" >
+                    <path
+                        android:name="circle_3"
+                        android:pathData="M 0.0843505859375,-2.93901062012 c -2.30102539062,0.0 -4.16702270508,1.86602783203 -4.16702270508,4.16702270508 c 0.0,2.29898071289 1.86599731445,4.16598510742 4.16702270508,4.16598510742 c 2.29998779297,0.0 4.16598510742,-1.86700439453 4.16598510742,-4.16598510742 c 0.0,-2.30099487305 -1.86599731445,-4.16702270508 -4.16598510742,-4.16702270508 Z M 11.1185302734,5.83390808105 c 0.0,0.0 0.0009765625,0.00100708007812 0.0009765625,0.00100708007812 c 0.14501953125,-0.356994628906 0.27099609375,-0.725006103516 0.382995605469,-1.09799194336 c 0.0570068359375,-0.195007324219 0.101013183594,-0.394989013672 0.149017333984,-0.595001220703 c 0.0690002441406,-0.281005859375 0.126983642578,-0.563995361328 0.175994873047,-0.851989746094 c 0.0270080566406,-0.169006347656 0.0559997558594,-0.337005615234 0.0759887695313,-0.509002685547 c 0.0580139160156,-0.468017578125 0.0970153808594,-0.942993164062 0.0970153808593,-1.4280090332 c 0.0,0.0 0.0,-0.00100708007812 0.0,-0.00100708007812 c 0.0,-5.03900146484 -3.11099243164,-9.3450012207 -7.5119934082,-11.1229858398 c -0.00601196289062,-0.00299072265625 -0.0130004882812,-0.0050048828125 -0.0190124511719,-0.00701904296875 c -0.686004638672,-0.275970458984 -1.39999389648,-0.492980957031 -2.14099121094,-0.638977050781 c -0.072998046875,-0.0150146484375 -0.149017333984,-0.02099609375 -0.222991943359,-0.0339965820313 c -0.302001953125,-0.0540161132812 -0.605010986328,-0.106018066406 -0.916015625,-0.136016845703 c -0.389984130859,-0.0390014648438 -0.786987304688,-0.0599975585938 -1.18899536133,-0.0599975585937 c -0.402008056641,0.0 -0.799011230469,0.02099609375 -1.19000244141,0.0599975585937 c -0.304992675781,0.0299987792969 -0.602996826172,0.0809936523438 -0.901000976563,0.132995605469 c -0.0790100097656,0.0150146484375 -0.160003662109,0.02099609375 -0.238006591797,0.0370178222656 c -0.368988037109,0.0719909667969 -0.730987548828,0.164001464844 -1.08700561523,0.269989013672 c -0.00299072265625,0.00100708007812 -0.0059814453125,0.00201416015625 -0.00900268554687,0.0020141601562 c -0.351989746094,0.10498046875 -0.694000244141,0.226989746094 -1.0309753418,0.361999511719 c -0.0110168457031,0.00399780273438 -0.0220031738281,0.00698852539062 -0.0320129394531,0.0119934082031 c -4.40200805664,1.77798461914 -7.51098632812,6.083984375 -7.5119934082,11.1229858398 c 0.0,0.00799560546875 0.00198364257812,0.0160217285156 0.0019836425781,0.0240173339844 c 0.00100708007812,0.475006103516 0.0380249023438,0.940002441406 0.0950012207032,1.39898681641 c 0.02001953125,0.175994873047 0.0490112304688,0.348999023438 0.0780029296875,0.523010253906 c 0.0469970703125,0.281982421875 0.105010986328,0.557983398438 0.171997070312,0.833984375 c 0.0480041503906,0.204010009766 0.093017578125,0.410003662109 0.152008056641,0.610015869141 c 0.110992431641,0.372009277344 0.238006591797,0.736999511719 0.382019042969,1.09298706055 c 0.0,0.0 0.0009765625,0.0 0.0009765625,0.0 c 1.00701904297,2.48400878906 2.81301879883,4.56100463867 5.11001586914,5.89501953125 c 0.0,0.0 2.01599121094,-3.48300170898 2.01599121094,-3.48300170898 c -2.03900146484,-1.18402099609 -3.5119934082,-3.22500610352 -3.89898681641,-5.63900756836 c 0.0,0.0 0.0009765625,-0.00100708007812 0.0009765625,-0.00100708007812 c -0.0220031738281,-0.130981445312 -0.0369873046875,-0.265991210938 -0.052978515625,-0.399993896484 c -0.0290222167969,-0.274993896484 -0.0570068359375,-0.552001953125 -0.0570068359375,-0.834991455078 c 0.0,0.0 0.0,-0.0190124511719 0.0,-0.0190124511719 c 0.0,-3.98999023438 2.92498779297,-7.28900146484 6.74398803711,-7.89199829102 c 0.0,0.0 0.0180053710938,0.0169982910156 0.0180053710938,0.0169982910156 c 0.404998779297,-0.0639953613281 0.81298828125,-0.125 1.23599243164,-0.125 c 0.0,0.0 0.00201416015625,0.0 0.00201416015624,0.0 c 0.0,0.0 0.00299072265625,0.0 0.00299072265626,0.0 c 0.423004150391,0.0 0.830017089844,0.0610046386719 1.23501586914,0.125 c 0.0,0.0 0.0169982910156,-0.0180053710938 0.0169982910156,-0.0180053710938 c 3.81997680664,0.60400390625 6.74499511719,3.90301513672 6.74499511719,7.89199829102 c 0.0,0.292999267578 -0.0280151367188,0.578002929688 -0.0589904785156,0.861999511719 c -0.0150146484375,0.132019042969 -0.0290222167969,0.264007568359 -0.051025390625,0.393005371094 c -0.385986328125,2.41500854492 -1.85897827148,4.45599365234 -3.89797973633,5.64001464844 c 0.0,0.0 2.01599121094,3.48300170898 2.01599121094,3.48300170898 c 2.29699707031,-1.33401489258 4.10299682617,-3.41101074219 5.11001586914,-5.89602661133 Z M 19.9300231934,2.95698547363 c 0.0059814453125,-0.0659790039062 0.0159912109375,-0.130981445312 0.02099609375,-0.196990966797 c 0.031982421875,-0.462005615234 0.0479736328125,-0.928009033203 0.0489807128906,-1.39700317383 c 0,0.0 0,-0.00997924804688 0,-0.00997924804687 c 0,0.0 0,-0.00100708007812 0,-0.00100708007813 c 0,-7.22500610352 -3.84399414062,-13.5360107422 -9.58599853516,-17.0500183105 c -1.06500244141,-0.652984619141 -2.19299316406,-1.20599365234 -3.37799072266,-1.65197753906 c -0.157989501953,-0.0599975585938 -0.317016601562,-0.118011474609 -0.476989746094,-0.174011230469 c -0.317016601562,-0.110992431641 -0.634002685547,-0.218994140625 -0.9580078125,-0.31298828125 c -0.470001220703,-0.139007568359 -0.944000244141,-0.264007568359 -1.4280090332,-0.368011474609 c -0.186004638672,-0.0390014648438 -0.376983642578,-0.0669860839844 -0.565002441406,-0.101013183594 c -0.414001464844,-0.0759887695312 -0.832000732422,-0.140991210938 -1.25500488281,-0.190979003906 c -0.184997558594,-0.0220031738281 -0.369995117188,-0.0429992675781 -0.556976318359,-0.0599975585937 c -0.592010498047,-0.0530090332031 -1.18801879883,-0.0899963378906 -1.79602050781,-0.0899963378907 c -0.605987548828,0.0 -1.20300292969,0.0369873046875 -1.79598999023,0.0899963378907 c -0.186004638672,0.0169982910156 -0.371002197266,0.0379943847656 -0.555999755859,0.0599975585937 c -0.423004150391,0.0499877929688 -0.842010498047,0.114990234375 -1.25601196289,0.190979003906 c -0.18798828125,0.0350036621094 -0.377990722656,0.06201171875 -0.563995361328,0.101013183594 c -0.483001708984,0.10400390625 -0.959991455078,0.22900390625 -1.42999267578,0.368011474609 c -0.321990966797,0.093994140625 -0.638000488281,0.201995849609 -0.953002929688,0.311981201172 c -0.162994384766,0.0570068359375 -0.324005126953,0.115997314453 -0.484985351562,0.177001953125 c -1.18099975586,0.445007324219 -2.30599975586,0.997009277344 -3.36801147461,1.64700317383 c -0.00201416015625,0.00100708007812 -0.00399780273438,0.00201416015625 -0.0060119628907,0.0029907226562 c -5.74099731445,3.51400756836 -9.58499145508,9.82501220703 -9.58599853516,17.0500183105 c 0,0.0 0,0.00100708007812 0,0.00100708007813 c 0,0.0059814453125 0.00100708007812,0.0130004882812 0.0010070800781,0.0199890136719 c 0.0,0.466003417969 0.0169982910156,0.928009033203 0.0490112304688,1.38598632812 c 0.0050048828125,0.0690002441406 0.0159912109375,0.136016845703 0.02099609375,0.206024169922 c 0.031982421875,0.401000976562 0.0719909667969,0.799987792969 0.127990722656,1.19400024414 c 0.00201416015625,0.0189819335938 0.00701904296875,0.0369873046875 0.010009765625,0.0569763183594 c 0.888000488281,6.17202758789 4.59799194336,11.4250183105 9.7799987793,14.4309997559 c 0.0,0.0 2.00198364258,-3.458984375 2.00198364258,-3.458984375 c -2.58599853516,-1.5 -4.708984375,-3.70401000977 -6.11697387695,-6.34399414063 c 0.0,0.0 0.0169982910156,-0.0180053710938 0.0169982910156,-0.0180053710938 c -0.890014648438,-1.67098999023 -1.50601196289,-3.5110168457 -1.76000976562,-5.46499633789 c -0.00698852539062,-0.0500183105469 -0.010009765625,-0.102020263672 -0.0159912109375,-0.152008056641 c -0.0330200195312,-0.273010253906 -0.0610046386719,-0.545989990234 -0.0800170898437,-0.821990966797 c -0.0220031738281,-0.343017578125 -0.0350036621094,-0.68701171875 -0.0350036621094,-1.03500366211 c 0,-6.53701782227 3.92599487305,-12.1480102539 9.54299926758,-14.6310119629 c 0.157012939453,-0.0700073242188 0.313995361328,-0.135986328125 0.472015380859,-0.199981689453 c 0.373992919922,-0.151000976562 0.751983642578,-0.294006347656 1.13900756836,-0.417022705078 c 0.108978271484,-0.0350036621094 0.221984863281,-0.0619812011719 0.332000732422,-0.0950012207031 c 0.349975585938,-0.102996826172 0.705993652344,-0.194976806641 1.06597900391,-0.273986816406 c 0.114013671875,-0.0249938964844 0.227996826172,-0.052001953125 0.342010498047,-0.0750122070313 c 0.440002441406,-0.0869750976562 0.885986328125,-0.154998779297 1.33700561523,-0.203979492188 c 0.10400390625,-0.0120239257812 0.209991455078,-0.02001953125 0.315002441406,-0.0299987792969 c 0.47998046875,-0.0429992675781 0.963989257812,-0.072998046875 1.45397949219,-0.072998046875 c 0.492004394531,0.0 0.975006103516,0.0299987792969 1.45401000977,0.072998046875 c 0.105987548828,0.00997924804688 0.212005615234,0.0179748535156 0.316986083984,0.0299987792969 c 0.450012207031,0.0489807128906 0.89501953125,0.117004394531 1.33502197266,0.203002929688 c 0.115997314453,0.0239868164062 0.22998046875,0.0509948730469 0.345001220703,0.0769958496094 c 0.358001708984,0.0780029296875 0.710998535156,0.169982910156 1.06097412109,0.272003173828 c 0.111022949219,0.0329895019531 0.226013183594,0.0609741210938 0.336029052734,0.0969848632813 c 0.385986328125,0.123016357422 0.761993408203,0.265014648438 1.13497924805,0.415008544922 c 0.160003662109,0.0650024414062 0.319000244141,0.131988525391 0.477020263672,0.201995849609 c 5.61599731445,2.48400878906 9.53997802734,8.09399414062 9.53997802734,14.6310119629 c 0,0.346984863281 -0.0130004882812,0.690979003906 -0.0350036621094,1.03399658203 c -0.0179748535156,0.274993896484 -0.0469970703125,0.548004150391 -0.0789794921875,0.819000244141 c -0.00601196289062,0.052001953125 -0.010009765625,0.10498046875 -0.0160217285156,0.154998779297 c -0.252990722656,1.95498657227 -0.871002197266,3.79400634766 -1.75997924805,5.46499633789 c 0.0,0.0 0.0169982910156,0.0180053710938 0.0169982910156,0.0180053710938 c -1.40802001953,2.63998413086 -3.53100585938,4.84399414062 -6.11700439453,6.34399414063 c 0.0,0.0 2.00198364258,3.458984375 2.00198364258,3.458984375 c 5.18402099609,-3.00698852539 8.89501953125,-8.26300048828 9.78100585938,-14.4379882813 c 0.00201416015625,-0.0169982910156 0.00601196289062,-0.0320129394531 0.0079956054688,-0.0490112304688 c 0.0570068359375,-0.39697265625 0.0970153808594,-0.798980712891 0.129028320312,-1.20300292969 Z"
+                        android:fillColor="#FFFFFFFF"
+                        android:fillAlpha="1" />
+                </group>
+            </group>
+        </group>
+    </group>
+</vector>
diff --git a/packages/SystemUI/res/drawable/ic_mode_edit.xml b/packages/SystemUI/res/drawable/ic_mode_edit.xml
new file mode 100644
index 0000000..8a73686
--- /dev/null
+++ b/packages/SystemUI/res/drawable/ic_mode_edit.xml
@@ -0,0 +1,24 @@
+<!--
+    Copyright (C) 2016 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.
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+        android:width="20.0dp"
+        android:height="20.0dp"
+        android:viewportWidth="24.0"
+        android:viewportHeight="24.0">
+    <path
+        android:fillColor="#FFFFFF"
+        android:pathData="M3.0,17.25L3.0,21.0l3.75,0.0L17.81,9.94l-3.75,-3.75L3.0,17.25zM20.71,7.04c0.39,-0.3 0.39,-1.02 0.0,-1.41l-2.34,-2.34c-0.39,-0.39 -1.02,-0.39 -1.41,0.0l-1.83,1.83 3.75,3.75 1.83,-1.83z"/>
+</vector>
diff --git a/packages/SystemUI/res/drawable/ic_settings_20dp.xml b/packages/SystemUI/res/drawable/ic_settings_20dp.xml
new file mode 100644
index 0000000..3170f86
--- /dev/null
+++ b/packages/SystemUI/res/drawable/ic_settings_20dp.xml
@@ -0,0 +1,24 @@
+<!--
+    Copyright (C) 2016 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.
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+    android:width="20dp"
+    android:height="20dp"
+    android:viewportWidth="24.0"
+    android:viewportHeight="24.0">
+    <path
+        android:pathData="M19.4,13.0c0.0,-0.3 0.1,-0.6 0.1,-1.0s0.0,-0.7 -0.1,-1.0l2.1,-1.7c0.2,-0.2 0.2,-0.4 0.1,-0.6l-2.0,-3.5C19.5,5.1 19.3,5.0 19.0,5.1l-2.5,1.0c-0.5,-0.4 -1.1,-0.7 -1.7,-1.0l-0.4,-2.6C14.5,2.2 14.2,2.0 14.0,2.0l-4.0,0.0C9.8,2.0 9.5,2.2 9.5,2.4L9.1,5.1C8.5,5.3 8.0,5.7 7.4,6.1L5.0,5.1C4.7,5.0 4.5,5.1 4.3,5.3l-2.0,3.5C2.2,8.9 2.3,9.2 2.5,9.4L4.6,11.0c0.0,0.3 -0.1,0.6 -0.1,1.0s0.0,0.7 0.1,1.0l-2.1,1.7c-0.2,0.2 -0.2,0.4 -0.1,0.6l2.0,3.5C4.5,18.9 4.7,19.0 5.0,18.9l2.5,-1.0c0.5,0.4 1.1,0.7 1.7,1.0l0.4,2.6c0.0,0.2 0.2,0.4 0.5,0.4l4.0,0.0c0.2,0.0 0.5,-0.2 0.5,-0.4l0.4,-2.6c0.6,-0.3 1.2,-0.6 1.7,-1.0l2.5,1.0c0.2,0.1 0.5,0.0 0.6,-0.2l2.0,-3.5c0.1,-0.2 0.1,-0.5 -0.1,-0.6L19.4,13.0zM12.0,15.5c-1.9,0.0 -3.5,-1.6 -3.5,-3.5s1.6,-3.5 3.5,-3.5s3.5,1.6 3.5,3.5S13.9,15.5 12.0,15.5z"
+        android:fillColor="#ffffffff" />
+</vector>
diff --git a/packages/SystemUI/res/layout-television/recents_on_tv.xml b/packages/SystemUI/res/layout-television/recents_on_tv.xml
index 82b9f8c..2b78bee 100644
--- a/packages/SystemUI/res/layout-television/recents_on_tv.xml
+++ b/packages/SystemUI/res/layout-television/recents_on_tv.xml
@@ -21,6 +21,7 @@
     android:clipChildren="false"
     android:clipToPadding="false"
     android:background="@drawable/recents_tv_background_gradient">
+
     <com.android.systemui.recents.tv.views.TaskStackHorizontalGridView
         android:id="@+id/task_list"
         android:layout_width="wrap_content"
@@ -32,13 +33,13 @@
         android:focusable="true"
         android:layoutDirection="rtl" />
 
-    <!-- Placeholder view to give focus to the PIP menus. -->
+    <!-- Placeholder view to give focus to the PIP menus in talkback mode -->
     <View
         android:id="@+id/pip"
         android:layout_width="1dp"
         android:layout_height="1dp"
         android:focusable="true"
-        android:visibility="visible" />
+        android:visibility="gone" />
 
     <!-- Placeholder to dismiss during talkback. -->
     <ImageView
diff --git a/packages/SystemUI/res/layout/qs_detail.xml b/packages/SystemUI/res/layout/qs_detail.xml
index 32839d8..63390e2 100644
--- a/packages/SystemUI/res/layout/qs_detail.xml
+++ b/packages/SystemUI/res/layout/qs_detail.xml
@@ -44,7 +44,7 @@
         android:layout_height="wrap_content"
         />
 
-    <ScrollView
+    <com.android.systemui.qs.NonInterceptingScrollView
         android:layout_width="match_parent"
         android:layout_height="0dp"
         android:layout_weight="1">
@@ -52,7 +52,7 @@
             android:id="@android:id/content"
             android:layout_width="match_parent"
             android:layout_height="wrap_content" />
-    </ScrollView>
+    </com.android.systemui.qs.NonInterceptingScrollView>
 
     <include layout="@layout/qs_detail_buttons" />
 
diff --git a/packages/SystemUI/res/layout/qs_paged_tile_layout.xml b/packages/SystemUI/res/layout/qs_paged_tile_layout.xml
index ee55ec2..8b6060f 100644
--- a/packages/SystemUI/res/layout/qs_paged_tile_layout.xml
+++ b/packages/SystemUI/res/layout/qs_paged_tile_layout.xml
@@ -37,19 +37,6 @@
             android:importantForAccessibility="yes"
             android:focusable="true" />
 
-        <TextView
-            android:id="@android:id/edit"
-            style="@style/QSBorderlessButton"
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
-            android:layout_gravity="end"
-            android:minWidth="88dp"
-            android:textAppearance="@style/TextAppearance.QS.DetailButton"
-            android:textColor="#64FFFFFF"
-            android:focusable="true"
-            android:text="@string/qs_edit"
-            android:contentDescription="@string/accessibility_quick_settings_edit"/>
-
     </FrameLayout>
 
 </com.android.systemui.qs.PagedTileLayout>
diff --git a/packages/SystemUI/res/layout/qs_panel.xml b/packages/SystemUI/res/layout/qs_panel.xml
index 751f181..26c7339 100644
--- a/packages/SystemUI/res/layout/qs_panel.xml
+++ b/packages/SystemUI/res/layout/qs_panel.xml
@@ -26,7 +26,7 @@
     <com.android.systemui.qs.QSPanel
             android:id="@+id/quick_settings_panel"
             android:background="#0000"
-            android:layout_marginTop="@dimen/status_bar_header_height"
+            android:layout_marginTop="80dp"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:paddingBottom="8dp" />
diff --git a/packages/SystemUI/res/layout/quick_status_bar_expanded_header.xml b/packages/SystemUI/res/layout/quick_status_bar_expanded_header.xml
index 5d62940..678ec4e 100644
--- a/packages/SystemUI/res/layout/quick_status_bar_expanded_header.xml
+++ b/packages/SystemUI/res/layout/quick_status_bar_expanded_header.xml
@@ -37,7 +37,7 @@
         android:clipToPadding="false"
         android:orientation="horizontal"
         android:layout_alignParentEnd="true"
-        android:layout_marginTop="28dp"
+        android:layout_marginTop="4dp"
         android:layout_marginEnd="12dp">
 
         <com.android.systemui.statusbar.phone.MultiUserSwitch android:id="@+id/multi_user_switch"
@@ -52,6 +52,18 @@
                 android:scaleType="centerInside"/>
         </com.android.systemui.statusbar.phone.MultiUserSwitch>
 
+        <com.android.systemui.statusbar.AlphaOptimizedImageView
+            android:id="@android:id/edit"
+            android:layout_width="48dp"
+            android:layout_height="48dp"
+            android:clipToPadding="false"
+            android:clickable="true"
+            android:focusable="true"
+            android:src="@drawable/ic_mode_edit"
+            android:background="?android:attr/selectableItemBackgroundBorderless"
+            android:contentDescription="@string/accessibility_quick_settings_edit"
+            android:padding="14dp" />
+
         <com.android.systemui.statusbar.AlphaOptimizedFrameLayout
             android:id="@+id/settings_button_container"
             android:layout_width="48dp"
@@ -64,7 +76,7 @@
                 android:layout_width="match_parent"
                 android:layout_height="match_parent"
                 android:background="@drawable/ripple_drawable"
-                android:src="@drawable/ic_settings"
+                android:src="@drawable/ic_settings_20dp"
                 android:contentDescription="@string/accessibility_quick_settings_settings" />
             <com.android.systemui.statusbar.AlphaOptimizedImageView android:id="@+id/tuner_icon"
                 android:layout_width="match_parent"
@@ -98,7 +110,7 @@
         android:layout_alignParentTop="true"
         android:paddingStart="16dp"
         android:paddingEnd="16dp"
-        android:paddingTop="8dp"
+        android:paddingTop="2dp"
         android:visibility="gone"
         android:textAppearance="@style/TextAppearance.StatusBar.Expanded.EmergencyCallsOnly"
         android:text="@*android:string/emergency_calls_only"
@@ -112,7 +124,7 @@
         android:layout_height="wrap_content"
         android:layout_alignParentStart="true"
         android:layout_alignParentTop="true"
-        android:layout_marginTop="8dp"
+        android:layout_marginTop="16dp"
         android:layout_marginStart="16dp"
         android:gravity="start"
         android:orientation="vertical">
@@ -169,7 +181,7 @@
         android:id="@+id/quick_qs_panel"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
-        android:layout_marginTop="28dp"
+        android:layout_marginTop="52dp"
         android:layout_marginStart="12dp"
         android:layout_marginEnd="12dp"
         android:layout_alignParentEnd="true"
diff --git a/packages/SystemUI/res/layout/tv_pip_control_button.xml b/packages/SystemUI/res/layout/tv_pip_control_button.xml
index f18a5da..096dda8 100644
--- a/packages/SystemUI/res/layout/tv_pip_control_button.xml
+++ b/packages/SystemUI/res/layout/tv_pip_control_button.xml
@@ -23,15 +23,25 @@
     <ImageView android:id="@+id/button"
         android:layout_width="34dp"
         android:layout_height="34dp"
-        android:padding="5dp"
+        android:layout_alignParentTop="true"
+        android:layout_centerHorizontal="true"
         android:focusable="true"
-        android:src="@drawable/ic_fullscreen_white_24dp"
-        android:background="@drawable/tv_pip_button_focused"
-        android:layerType="software" />
+        android:src="@drawable/tv_pip_button_focused"
+        android:importantForAccessibility="yes" />
+
+    <ImageView android:id="@+id/icon"
+        android:layout_width="34dp"
+        android:layout_height="34dp"
+        android:layout_alignParentTop="true"
+        android:layout_centerHorizontal="true"
+        android:padding="5dp"
+        android:importantForAccessibility="no" />
 
     <TextView android:id="@+id/desc"
         android:layout_width="100dp"
         android:layout_height="wrap_content"
+        android:layout_below="@id/icon"
+        android:layout_centerHorizontal="true"
         android:layout_marginTop="3dp"
         android:gravity="center"
         android:text="@string/pip_fullscreen"
diff --git a/packages/SystemUI/res/layout/tv_pip_recents_overlay.xml b/packages/SystemUI/res/layout/tv_pip_recents_overlay.xml
index 557bbe6..f157fd5 100644
--- a/packages/SystemUI/res/layout/tv_pip_recents_overlay.xml
+++ b/packages/SystemUI/res/layout/tv_pip_recents_overlay.xml
@@ -15,7 +15,7 @@
 -->
 <LinearLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
-    android:layout_width="match_parent"
+    android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:gravity="top|center_horizontal"
     android:orientation="vertical">
@@ -33,7 +33,8 @@
             android:layout_height="32dp"
             android:translationY="-46dp"
             android:layout_gravity="top|center_horizontal"
-            android:background="@drawable/tv_pip_recents_overlay_scrim" />
+            android:background="@drawable/tv_pip_recents_overlay_scrim"
+            android:alpha="0" />
         <com.android.systemui.tv.pip.PipControlsView
             android:id="@+id/pip_control_contents"
             android:layout_width="wrap_content"
@@ -42,6 +43,8 @@
             android:layout_gravity="top|center_horizontal" />
     </com.android.systemui.tv.pip.PipRecentsControlsView>
 
+    <!-- Placeholder view to handle focus change between Recents row and PIP controls
+        in talkback mode -->
     <View
         android:id="@+id/recents"
         android:layout_width="1dp"
diff --git a/packages/SystemUI/res/values-sw600dp/dimens.xml b/packages/SystemUI/res/values-sw600dp/dimens.xml
index 6c5a313..7e63cbf 100644
--- a/packages/SystemUI/res/values-sw600dp/dimens.xml
+++ b/packages/SystemUI/res/values-sw600dp/dimens.xml
@@ -94,8 +94,6 @@
     <dimen name="navigation_key_width">128dp</dimen>
     <dimen name="navigation_key_padding">25dp</dimen>
 
-    <dimen name="qs_expand_margin">0dp</dimen>
-
     <!-- Keyboard shortcuts helper -->
     <dimen name="ksh_layout_width">488dp</dimen>
 
diff --git a/packages/SystemUI/res/values-w550dp-land/dimens.xml b/packages/SystemUI/res/values-w550dp-land/dimens.xml
index 4160c83..eaca9d7 100644
--- a/packages/SystemUI/res/values-w550dp-land/dimens.xml
+++ b/packages/SystemUI/res/values-w550dp-land/dimens.xml
@@ -18,6 +18,4 @@
 <resources>
     <!-- Standard notification width + gravity -->
     <dimen name="notification_panel_width">544dp</dimen>
-
-    <dimen name="qs_expand_margin">32dp</dimen>
 </resources>
diff --git a/packages/SystemUI/res/values/dimens.xml b/packages/SystemUI/res/values/dimens.xml
index cbb3c0a..677dbe5 100644
--- a/packages/SystemUI/res/values/dimens.xml
+++ b/packages/SystemUI/res/values/dimens.xml
@@ -130,7 +130,7 @@
     <dimen name="close_handle_underlap">32dp</dimen>
 
     <!-- Height of the status bar header bar -->
-    <dimen name="status_bar_header_height">80dp</dimen>
+    <dimen name="status_bar_header_height">104dp</dimen>
 
     <!-- Height of the status bar header bar when expanded -->
     <dimen name="status_bar_header_height_expanded">116dp</dimen>
@@ -169,8 +169,6 @@
     <dimen name="qs_tile_margin_top">16dp</dimen>
     <dimen name="qs_quick_tile_size">48dp</dimen>
     <dimen name="qs_quick_tile_padding">12dp</dimen>
-    <dimen name="qs_date_anim_translation">32dp</dimen>
-    <dimen name="qs_date_alarm_anim_translation">22dp</dimen>
     <dimen name="qs_date_collapsed_text_size">14sp</dimen>
     <dimen name="qs_date_text_size">16sp</dimen>
     <dimen name="qs_header_gear_translation">16dp</dimen>
@@ -199,7 +197,6 @@
     <dimen name="qs_detail_margin_top">28dp</dimen>
     <dimen name="qs_data_usage_text_size">14sp</dimen>
     <dimen name="qs_data_usage_usage_text_size">36sp</dimen>
-    <dimen name="qs_expand_margin">0dp</dimen>
     <dimen name="qs_battery_padding">2dp</dimen>
     <dimen name="qs_detail_items_padding_top">4dp</dimen>
 
diff --git a/packages/SystemUI/res/values/strings.xml b/packages/SystemUI/res/values/strings.xml
index 2758551..f7a169c 100644
--- a/packages/SystemUI/res/values/strings.xml
+++ b/packages/SystemUI/res/values/strings.xml
@@ -594,6 +594,12 @@
     <!-- The overflow indicator shown when a group has more notification inside the group than the visible ones. An example is "+ 3" [CHAR LIMIT=5] -->
     <string name="notification_group_overflow_indicator">+ <xliff:g id="number" example="3">%s</xliff:g></string>
 
+    <!-- Content description describing how many more notifications are in a group [CHAR LIMIT=NONE] -->
+    <plurals name="notification_group_overflow_description">
+        <item quantity="one"><xliff:g id="number" example="1">%s</xliff:g> more notification inside.</item>
+        <item quantity="other"><xliff:g id="number" example="3">%s</xliff:g> more notifications inside.</item>
+    </plurals>
+
     <!-- Content description of button in notification inspector for system settings relating to
          notifications from this application [CHAR LIMIT=NONE] -->
     <string name="status_bar_notification_inspect_item_title">Notification settings</string>
diff --git a/packages/SystemUI/src/com/android/systemui/qs/NonInterceptingScrollView.java b/packages/SystemUI/src/com/android/systemui/qs/NonInterceptingScrollView.java
new file mode 100644
index 0000000..15e1c96
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/qs/NonInterceptingScrollView.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2016 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.systemui.qs;
+
+import android.content.Context;
+import android.util.AttributeSet;
+import android.view.MotionEvent;
+import android.widget.ScrollView;
+
+/**
+ * ScrollView that disallows intercepting for touches that can cause scrolling.
+ */
+public class NonInterceptingScrollView extends ScrollView {
+
+    private float mInitialY;
+
+    public NonInterceptingScrollView(Context context, AttributeSet attrs) {
+        super(context, attrs);
+    }
+
+    @Override
+    public boolean onTouchEvent(MotionEvent ev) {
+        int action = ev.getActionMasked();
+        switch (action) {
+            case MotionEvent.ACTION_DOWN:
+                mInitialY = ev.getY();
+                break;
+            case MotionEvent.ACTION_UP:
+            case MotionEvent.ACTION_CANCEL:
+                requestDisallowInterceptTouchEvent(false);
+                break;
+            default:
+                if (canScrollVertically(ev.getY() > mInitialY ? -1 : 1)) {
+                    requestDisallowInterceptTouchEvent(true);
+                }
+                break;
+        }
+        return super.onTouchEvent(ev);
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSPanel.java b/packages/SystemUI/src/com/android/systemui/qs/QSPanel.java
index 0e8d76a..1211354 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QSPanel.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QSPanel.java
@@ -103,8 +103,6 @@
         mTileLayout = (QSTileLayout) LayoutInflater.from(mContext).inflate(
                 R.layout.qs_paged_tile_layout, this, false);
         addView((View) mTileLayout);
-        findViewById(android.R.id.edit).setOnClickListener(view ->
-                mHost.startRunnableDismissingKeyguard(() -> showEdit(view)));
     }
 
     public boolean isShowingCustomize() {
@@ -354,7 +352,7 @@
     }
 
 
-    private void showEdit(final View v) {
+    public void showEdit(final View v) {
         v.post(new Runnable() {
             @Override
             public void run() {
@@ -362,8 +360,8 @@
                     if (!mCustomizePanel.isCustomizing()) {
                         int[] loc = new int[2];
                         v.getLocationInWindow(loc);
-                        int x = loc[0];
-                        int y = loc[1];
+                        int x = loc[0] + v.getWidth() / 2;
+                        int y = loc[1] + v.getHeight() / 2;
                         mCustomizePanel.show(x, y);
                     }
                 }
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSTileBaseView.java b/packages/SystemUI/src/com/android/systemui/qs/QSTileBaseView.java
index f05aa3c..feacaa0 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QSTileBaseView.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QSTileBaseView.java
@@ -154,9 +154,9 @@
             event.setClassName(mAccessibilityClass);
             if (Switch.class.getName().equals(mAccessibilityClass)) {
                 String label = getResources()
-                        .getString(mTileState ? R.string.switch_bar_on : R.string.switch_bar_off);
+                        .getString(!mTileState ? R.string.switch_bar_on : R.string.switch_bar_off);
                 event.setContentDescription(label);
-                event.setChecked(mTileState);
+                event.setChecked(!mTileState);
             }
         }
     }
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QuickQSPanel.java b/packages/SystemUI/src/com/android/systemui/qs/QuickQSPanel.java
index 4accc8b..9adcfbf 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QuickQSPanel.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QuickQSPanel.java
@@ -140,12 +140,11 @@
     };
 
     public int getNumQuickTiles(Context context) {
-        return TunerService.get(context).getValue(NUM_QUICK_TILES, 5);
+        return TunerService.get(context).getValue(NUM_QUICK_TILES, 6);
     }
 
     private static class HeaderTileLayout extends LinearLayout implements QSTileLayout {
 
-        private final Space mEndSpacer;
         protected final ArrayList<TileRecord> mRecords = new ArrayList<>();
 
         public HeaderTileLayout(Context context) {
@@ -154,34 +153,15 @@
             setClipToPadding(false);
             setGravity(Gravity.CENTER_VERTICAL);
             setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
-
-            mEndSpacer = new Space(context);
-            mEndSpacer.setLayoutParams(generateLayoutParams());
-            updateDownArrowMargin();
-            addView(mEndSpacer);
-            setOrientation(LinearLayout.HORIZONTAL);
-        }
-
-        @Override
-        protected void onConfigurationChanged(Configuration newConfig) {
-            super.onConfigurationChanged(newConfig);
-            updateDownArrowMargin();
-        }
-
-        private void updateDownArrowMargin() {
-            LayoutParams params = (LayoutParams) mEndSpacer.getLayoutParams();
-            params.setMarginStart(mContext.getResources().getDimensionPixelSize(
-                    R.dimen.qs_expand_margin));
-            mEndSpacer.setLayoutParams(params);
         }
 
         @Override
         public void addTile(TileRecord tile) {
-            addView(tile.tileView, getChildCount() - 1 /* Leave icon at end */,
-                    generateLayoutParams());
-            // Add a spacer.
-            addView(new Space(mContext), getChildCount() - 1 /* Leave icon at end */,
-                    generateSpaceParams());
+            if (getChildCount() != 0) {
+                // Add a spacer.
+                addView(new Space(mContext), getChildCount(), generateSpaceParams());
+            }
+            addView(tile.tileView, getChildCount(), generateLayoutParams());
             mRecords.add(tile);
         }
 
@@ -205,8 +185,10 @@
             int childIndex = getChildIndex(tile.tileView);
             // Remove the tile.
             removeViewAt(childIndex);
-            // Remove its spacer as well.
-            removeViewAt(childIndex);
+            if (getChildCount() != 0) {
+                // Remove its spacer as well.
+                removeViewAt(childIndex);
+            }
             mRecords.remove(tile);
         }
 
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/HotspotTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/HotspotTile.java
index 3587262..1c134c1 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/HotspotTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/HotspotTile.java
@@ -16,15 +16,22 @@
 
 package com.android.systemui.qs.tiles;
 
+import android.content.BroadcastReceiver;
+import android.content.Context;
 import android.content.Intent;
+import android.content.IntentFilter;
 import android.os.UserManager;
 
 import android.provider.Settings;
+import android.provider.Settings.Global;
+import android.text.SpannableStringBuilder;
+import android.text.style.ForegroundColorSpan;
 import android.widget.Switch;
 
 import com.android.internal.logging.MetricsLogger;
 import com.android.internal.logging.MetricsProto.MetricsEvent;
 import com.android.systemui.R;
+import com.android.systemui.qs.GlobalSetting;
 import com.android.systemui.qs.QSTile;
 import com.android.systemui.statusbar.policy.HotspotController;
 
@@ -36,12 +43,22 @@
     private final AnimationIcon mDisable =
             new AnimationIcon(R.drawable.ic_hotspot_disable_animation,
                     R.drawable.ic_hotspot_enable);
+    private final Icon mUnavailable =
+            ResourceIcon.get(R.drawable.ic_hotspot_unavailable);
     private final HotspotController mController;
     private final Callback mCallback = new Callback();
+    private final GlobalSetting mAirplaneMode;
+    private boolean mListening;
 
     public HotspotTile(Host host) {
         super(host);
         mController = host.getHotspotController();
+        mAirplaneMode = new GlobalSetting(mContext, mHandler, Global.AIRPLANE_MODE_ON) {
+            @Override
+            protected void handleValueChanged(int value) {
+                refreshState();
+            }
+        };
     }
 
     @Override
@@ -61,11 +78,18 @@
 
     @Override
     public void setListening(boolean listening) {
+        if (mListening == listening) return;
+        mListening = listening;
         if (listening) {
             mController.addCallback(mCallback);
+            final IntentFilter filter = new IntentFilter();
+            filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
+            mContext.registerReceiver(mReceiver, filter);
         } else {
             mController.removeCallback(mCallback);
+            mContext.unregisterReceiver(mReceiver);
         }
+        mAirplaneMode.setListening(listening);
     }
 
     @Override
@@ -76,6 +100,9 @@
     @Override
     protected void handleClick() {
         final boolean isEnabled = (Boolean) mState.value;
+        if (!isEnabled && mAirplaneMode.getValue() != 0) {
+            return;
+        }
         MetricsLogger.action(mContext, getMetricsCategory(), !isEnabled);
         mController.setHotspotEnabled(!isEnabled);
     }
@@ -96,6 +123,13 @@
             state.value = mController.isHotspotEnabled();
         }
         state.icon = state.value ? mEnable : mDisable;
+        if (mAirplaneMode.getValue() != 0) {
+            final int disabledColor = mHost.getContext().getColor(R.color.qs_tile_tint_unavailable);
+            state.label = new SpannableStringBuilder().append(state.label,
+                    new ForegroundColorSpan(disabledColor),
+                    SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE);
+            state.icon = mUnavailable;
+        }
         state.minimalAccessibilityClassName = state.expandedAccessibilityClassName
                 = Switch.class.getName();
         state.contentDescription = state.label;
@@ -121,4 +155,13 @@
             refreshState(enabled);
         }
     };
+
+    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(intent.getAction())) {
+                refreshState();
+            }
+        }
+    };
 }
diff --git a/packages/SystemUI/src/com/android/systemui/recents/RecentsDebugFlags.java b/packages/SystemUI/src/com/android/systemui/recents/RecentsDebugFlags.java
index 1715356..bb8bfee 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/RecentsDebugFlags.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/RecentsDebugFlags.java
@@ -35,7 +35,7 @@
         public static final boolean DisableBackgroundCache = false;
         // Enables the task affiliations
         public static final boolean EnableAffiliatedTaskGroups = false;
-        // TODO: To be repurposed
+        // Enables the button above the stack
         public static final boolean EnableStackActionButton = true;
         // Overrides the Tuner flags and enables the timeout
         private static final boolean EnableFastToggleTimeout = false;
diff --git a/packages/SystemUI/src/com/android/systemui/recents/RecentsImpl.java b/packages/SystemUI/src/com/android/systemui/recents/RecentsImpl.java
index cfc6c52..b20f46f 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/RecentsImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/RecentsImpl.java
@@ -372,7 +372,7 @@
             if (stack.getTaskCount() > 0) {
                 // Only preload the icon (but not the thumbnail since it may not have been taken for
                 // the pausing activity)
-                preloadIcon(runningTask);
+                preloadIcon(runningTask.id);
 
                 // At this point, we don't know anything about the stack state.  So only calculate
                 // the dimensions of the thumbnail that we need for the transition into Recents, but
@@ -664,10 +664,10 @@
     /**
      * Preloads the icon of a task.
      */
-    private void preloadIcon(ActivityManager.RunningTaskInfo task) {
+    private void preloadIcon(int runningTaskId) {
         // Ensure that we load the running task's icon
         RecentsTaskLoadPlan.Options launchOpts = new RecentsTaskLoadPlan.Options();
-        launchOpts.runningTaskId = task.id;
+        launchOpts.runningTaskId = runningTaskId;
         launchOpts.loadThumbnails = false;
         launchOpts.onlyLoadForCache = true;
         Recents.getTaskLoader().loadTasks(mContext, sInstanceLoadPlan, launchOpts);
@@ -699,7 +699,7 @@
     private ActivityOptions getThumbnailTransitionActivityOptions(
             ActivityManager.RunningTaskInfo runningTask, TaskStackView stackView,
                     Rect windowOverrideRect) {
-        if (runningTask.stackId == FREEFORM_WORKSPACE_STACK_ID) {
+        if (runningTask != null && runningTask.stackId == FREEFORM_WORKSPACE_STACK_ID) {
             ArrayList<AppTransitionAnimationSpec> specs = new ArrayList<>();
             ArrayList<Task> tasks = stackView.getStack().getStackTasks();
             TaskStackLayoutAlgorithm stackLayout = stackView.getStackAlgorithm();
@@ -810,6 +810,10 @@
         RecentsTaskLoader loader = Recents.getTaskLoader();
         RecentsActivityLaunchState launchState = Recents.getConfiguration().getLaunchState();
 
+        int runningTaskId = !mLaunchedWhileDocking && (runningTask != null)
+                ? runningTask.id
+                : -1;
+
         // In the case where alt-tab is triggered, we never get a preloadRecents() call, so we
         // should always preload the tasks now. If we are dragging in recents, reload them as
         // the stacks might have changed.
@@ -818,7 +822,7 @@
             sInstanceLoadPlan = loader.createLoadPlan(mContext);
         }
         if (mLaunchedWhileDocking || mTriggeredFromAltTab || !sInstanceLoadPlan.hasTasks()) {
-            loader.preloadTasks(sInstanceLoadPlan, runningTask.id, !isHomeStackVisible);
+            loader.preloadTasks(sInstanceLoadPlan, runningTaskId, !isHomeStackVisible);
         }
 
         TaskStack stack = sInstanceLoadPlan.getTaskStack();
@@ -830,12 +834,12 @@
         launchState.launchedFromApp = useThumbnailTransition || mLaunchedWhileDocking;
         launchState.launchedViaDockGesture = mLaunchedWhileDocking;
         launchState.launchedViaDragGesture = mDraggingInRecents;
-        launchState.launchedToTaskId = (runningTask != null) ? runningTask.id : -1;
+        launchState.launchedToTaskId = runningTaskId;
         launchState.launchedWithAltTab = mTriggeredFromAltTab;
 
         // Preload the icon (this will be a null-op if we have preloaded the icon already in
         // preloadRecents())
-        preloadIcon(runningTask);
+        preloadIcon(runningTaskId);
 
         // Update the header bar if necessary
         Rect windowOverrideRect = getWindowRectOverride(growTarget);
diff --git a/packages/SystemUI/src/com/android/systemui/recents/model/TaskStack.java b/packages/SystemUI/src/com/android/systemui/recents/model/TaskStack.java
index 50e28ca..26200d0 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/model/TaskStack.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/model/TaskStack.java
@@ -228,8 +228,8 @@
         /**
          * Notifies when a task has been removed from the stack.
          */
-        void onStackTaskRemoved(TaskStack stack, Task removedTask, boolean wasFrontMostTask,
-            Task newFrontMostTask, AnimationProps animation, boolean fromDockGesture);
+        void onStackTaskRemoved(TaskStack stack, Task removedTask, Task newFrontMostTask,
+                AnimationProps animation, boolean fromDockGesture);
 
         /**
          * Notifies when all tasks have been removed from the stack.
@@ -609,12 +609,11 @@
      */
     public void removeTask(Task t, AnimationProps animation, boolean fromDockGesture) {
         if (mStackTaskList.contains(t)) {
-            boolean wasFrontMostTask = (getStackFrontMostTask(false /* includeFreeform */) == t);
             removeTaskImpl(mStackTaskList, t);
             Task newFrontMostTask = getStackFrontMostTask(false  /* includeFreeform */);
             if (mCb != null) {
                 // Notify that a task has been removed
-                mCb.onStackTaskRemoved(this, t, wasFrontMostTask, newFrontMostTask, animation,
+                mCb.onStackTaskRemoved(this, t, newFrontMostTask, animation,
                         fromDockGesture);
             }
         }
@@ -648,6 +647,7 @@
         ArrayMap<Task.TaskKey, Task> currentTasksMap = createTaskKeyMapFromList(mRawTaskList);
         ArrayMap<Task.TaskKey, Task> newTasksMap = createTaskKeyMapFromList(tasks);
         ArrayList<Task> addedTasks = new ArrayList<>();
+        ArrayList<Task> removedTasks = new ArrayList<>();
         ArrayList<Task> allTasks = new ArrayList<>();
 
         // Disable notifications if there are no callbacks
@@ -661,11 +661,7 @@
             Task task = mRawTaskList.get(i);
             if (!newTasksMap.containsKey(task.key)) {
                 if (notifyStackChanges) {
-                    // If we are notifying, then remove the task now, otherwise the raw task list
-                    // will be reset at the end of this method
-                    removeTask(task, AnimationProps.IMMEDIATE, false /* fromDockGesture */);
-                    mCb.onStackTaskRemoved(this, task, i == (taskCount - 1), null,
-                            AnimationProps.IMMEDIATE, false /* fromDockGesture */);
+                    removedTasks.add(task);
                 }
             }
             task.setGroup(null);
@@ -699,6 +695,14 @@
         // Update the affiliated groupings
         createAffiliatedGroupings(context);
 
+        // Only callback for the removed tasks after the stack has updated
+        int removedTaskCount = removedTasks.size();
+        Task newFrontMostTask = getStackFrontMostTask(false);
+        for (int i = 0; i < removedTaskCount; i++) {
+            mCb.onStackTaskRemoved(this, removedTasks.get(i), newFrontMostTask,
+                    AnimationProps.IMMEDIATE, false /* fromDockGesture */);
+        }
+
         // Only callback for the newly added tasks after this stack has been updated
         int addedTaskCount = addedTasks.size();
         for (int i = 0; i < addedTaskCount; i++) {
diff --git a/packages/SystemUI/src/com/android/systemui/recents/tv/RecentsTvActivity.java b/packages/SystemUI/src/com/android/systemui/recents/tv/RecentsTvActivity.java
index 1a55958..ecb12d3 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/tv/RecentsTvActivity.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/tv/RecentsTvActivity.java
@@ -81,6 +81,7 @@
     private long mLastTabKeyEventTime;
     private boolean mIgnoreAltTabRelease;
     private boolean mLaunchedFromHome;
+    private boolean mTalkBackEnabled;
 
     private RecentsTvView mRecentsView;
     private View mPipView;
@@ -133,15 +134,22 @@
 
                 @Override
                 public void onRecentsFocused() {
-                    mRecentsView.requestFocus();
-                    mRecentsView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
+                    if (mTalkBackEnabled) {
+                        mTaskStackHorizontalGridView.requestFocus();
+                        mTaskStackHorizontalGridView.sendAccessibilityEvent(
+                                AccessibilityEvent.TYPE_VIEW_FOCUSED);
+                    }
+                    mTaskStackHorizontalGridView.startFocusGainAnimation();
                 }
             };
+
     private final View.OnFocusChangeListener mPipViewFocusChangeListener =
             new View.OnFocusChangeListener() {
                 @Override
                 public void onFocusChange(View v, boolean hasFocus) {
-                    handlePipViewFocusChange(hasFocus);
+                    if (hasFocus) {
+                        requestPipControlsFocus();
+                    }
                 }
             };
 
@@ -194,17 +202,18 @@
         loadOpts.numVisibleTaskThumbnails = numVisibleTasks;
         loader.loadTasks(this, plan, loadOpts);
 
-
-        mRecentsView.setTaskStack(stack);
         List stackTasks = stack.getStackTasks();
         Collections.reverse(stackTasks);
         if (mTaskStackViewAdapter == null) {
             mTaskStackViewAdapter = new TaskStackHorizontalViewAdapter(stackTasks);
             mTaskStackHorizontalGridView = mRecentsView
                     .setTaskStackViewAdapter(mTaskStackViewAdapter);
+            mHomeRecentsEnterExitAnimationHolder = new HomeRecentsEnterExitAnimationHolder(
+                    getApplicationContext(), mTaskStackHorizontalGridView);
         } else {
             mTaskStackViewAdapter.setNewStackTasks(stackTasks);
         }
+        mRecentsView.init(stack);
 
         if (launchState.launchedToTaskId != -1) {
             ArrayList<Task> tasks = stack.getStackTasks();
@@ -305,6 +314,7 @@
                 View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
 
         mPipView = findViewById(R.id.pip);
+        mPipView.setOnFocusChangeListener(mPipViewFocusChangeListener);
         // Place mPipView at the PIP bounds for fine tuned focus handling.
         Rect pipBounds = mPipManager.getRecentsFocusedPipBounds();
         LayoutParams lp = (LayoutParams) mPipView.getLayoutParams();
@@ -342,7 +352,6 @@
         if(mLaunchedFromHome) {
             mHomeRecentsEnterExitAnimationHolder.startEnterAnimation(mPipManager.isPipShown());
         }
-        mTaskStackViewAdapter.setResetAddedCards(true);
         EventBus.getDefault().send(new EnterRecentsWindowAnimationCompletedEvent());
     }
 
@@ -353,19 +362,6 @@
         // Update the recent tasks
         updateRecentsTasks();
 
-        mHomeRecentsEnterExitAnimationHolder = new HomeRecentsEnterExitAnimationHolder(
-                getApplicationContext(), mTaskStackHorizontalGridView);
-        if(mTaskStackHorizontalGridView != null &&
-                mTaskStackHorizontalGridView.getChildCount() > 0) {
-            if(mLaunchedFromHome) {
-                mHomeRecentsEnterExitAnimationHolder.setEnterFromHomeStartingAnimationValues();
-            } else {
-                mHomeRecentsEnterExitAnimationHolder.setEnterFromAppStartingAnimationValues();
-            }
-        } else {
-            mRecentsView.getViewTreeObserver().addOnPreDrawListener(this);
-        }
-
         // If this is a new instance from a configuration change, then we have to manually trigger
         // the enter animation state, or if recents was relaunched by AM, without going through
         // the normal mechanisms
@@ -387,9 +383,11 @@
         } else {
             mTaskStackHorizontalGridView.setSelectedPosition(0);
         }
+        mRecentsView.getViewTreeObserver().addOnPreDrawListener(this);
 
         View dismissPlaceholder = findViewById(R.id.dismiss_placeholder);
-        if (ssp.isTouchExplorationEnabled()) {
+        mTalkBackEnabled = ssp.isTouchExplorationEnabled();
+        if (mTalkBackEnabled) {
             dismissPlaceholder.setAccessibilityTraversalBefore(R.id.task_list);
             dismissPlaceholder.setAccessibilityTraversalAfter(R.id.dismiss_placeholder);
             mTaskStackHorizontalGridView.setAccessibilityTraversalAfter(R.id.dismiss_placeholder);
@@ -408,14 +406,29 @@
                 }
             });
         }
-        updatePipUI();
+
+        // Initialize PIP UI
+        if (mPipManager.isPipShown()) {
+            if (mTalkBackEnabled) {
+                // If talkback is on, use the mPipView to handle focus changes
+                // between recents row and PIP controls.
+                mPipView.setVisibility(View.VISIBLE);
+            } else {
+                mPipView.setVisibility(View.GONE);
+            }
+            // When PIP view has focus, recents overlay view will takes the focus
+            // as if it's the part of the Recents UI.
+            mPipRecentsOverlayManager.requestFocus(mTaskStackViewAdapter.getItemCount() > 0);
+        } else {
+            mPipView.setVisibility(View.GONE);
+            mPipRecentsOverlayManager.removePipRecentsOverlayView();
+        }
     }
 
     @Override
     public void onPause() {
         super.onPause();
         mPipRecentsOverlayManager.onRecentsPaused();
-        mTaskStackViewAdapter.setResetAddedCards(false);
     }
 
     @Override
@@ -534,6 +547,7 @@
     public final void onBusEvent(AllTaskViewsDismissedEvent event) {
         if (mPipManager.isPipShown()) {
             mRecentsView.showEmptyView();
+            mPipRecentsOverlayManager.requestFocus(false);
         } else {
             dismissRecentsToHome(false);
         }
@@ -547,10 +561,14 @@
     @Override
     public boolean onPreDraw() {
         mRecentsView.getViewTreeObserver().removeOnPreDrawListener(this);
-        if(mLaunchedFromHome) {
-            mHomeRecentsEnterExitAnimationHolder.setEnterFromHomeStartingAnimationValues();
+        // Sets the initial values for enter animation.
+        // Animation will be started in {@link #onEnterAnimationComplete()}
+        if (mLaunchedFromHome) {
+            mHomeRecentsEnterExitAnimationHolder
+                    .setEnterFromHomeStartingAnimationValues(mPipManager.isPipShown());
         } else {
-            mHomeRecentsEnterExitAnimationHolder.setEnterFromAppStartingAnimationValues();
+            mHomeRecentsEnterExitAnimationHolder
+                    .setEnterFromAppStartingAnimationValues(mPipManager.isPipShown());
         }
         // We post to make sure that this information is delivered after this traversals is
         // finished.
@@ -564,35 +582,25 @@
     }
 
     private void updatePipUI() {
-        if (mPipManager.isPipShown()) {
-            mPipView.setVisibility(View.VISIBLE);
-            mPipView.setOnFocusChangeListener(mPipViewFocusChangeListener);
-            if (mPipView.hasFocus()) {
-                // This can happen only if the activity is resumed. Ask for reset.
-                handlePipViewFocusChange(true);
-            } else {
-                mPipView.requestFocus();
-            }
-        } else {
-            mPipView.setVisibility(View.GONE);
+        if (!mPipManager.isPipShown()) {
             mPipRecentsOverlayManager.removePipRecentsOverlayView();
+            mTaskStackHorizontalGridView.startFocusLossAnimation();
+        } else {
+            Log.w(TAG, "An activity entered PIP mode while Recents is shown");
         }
     }
 
     /**
-     * Handles the PIP view's focus change.
+     * Requests the focus to the PIP controls.
      * This starts the relevant recents row animation
      * and give focus to the recents overlay if needed.
      */
-    private void handlePipViewFocusChange(boolean hasFocus) {
-        mRecentsView.startRecentsRowFocusAnimation(!hasFocus);
-        if (hasFocus) {
-            // When PIP view has focus, recents overlay view will takes the focus
-            // as if it's the part of the Recents UI.
-            mPipRecentsOverlayManager.requestFocus(
-                    mTaskStackViewAdapter.getItemCount() > 0);
-        } else {
-            mPipRecentsOverlayManager.clearFocus();
+    public void requestPipControlsFocus() {
+        if (!mPipManager.isPipShown()) {
+            return;
         }
+
+        mTaskStackHorizontalGridView.startFocusLossAnimation();
+        mPipRecentsOverlayManager.requestFocus(mTaskStackViewAdapter.getItemCount() > 0);
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/recents/tv/animations/HomeRecentsEnterExitAnimationHolder.java b/packages/SystemUI/src/com/android/systemui/recents/tv/animations/HomeRecentsEnterExitAnimationHolder.java
index 92718a3..9faaa4b 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/tv/animations/HomeRecentsEnterExitAnimationHolder.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/tv/animations/HomeRecentsEnterExitAnimationHolder.java
@@ -74,19 +74,35 @@
         }
     }
 
-    public void setEnterFromHomeStartingAnimationValues() {
+    /**
+     * Sets the initial values Recents enter animation
+     * when Recents is started from the Launcher.
+     */
+    public void setEnterFromHomeStartingAnimationValues(boolean isPipShown) {
         for(int i = 0; i < mGridView.getChildCount(); i++) {
             TaskCardView view = (TaskCardView) mGridView.getChildAt(i);
             view.setTranslationX(0);
             view.setAlpha(0.0f);
+            view.getInfoFieldView().setAlpha(isPipShown ? 0 : 1f);
+            if (isPipShown && view.hasFocus()) {
+                view.getViewFocusAnimator().changeSize(false);
+            }
         }
     }
 
-    public void setEnterFromAppStartingAnimationValues() {
+    /**
+     * Sets the initial values Recents enter animation
+     * when Recents is started from an app.
+     */
+    public void setEnterFromAppStartingAnimationValues(boolean isPipShown) {
         for(int i = 0; i < mGridView.getChildCount(); i++) {
             TaskCardView view = (TaskCardView) mGridView.getChildAt(i);
             view.setTranslationX(0);
-            view.setAlpha(1.0f);
+            view.setAlpha(isPipShown ? mDimAlpha : 1f);
+            view.getInfoFieldView().setAlpha(isPipShown ? 0 : 1f);
+            if (isPipShown && view.hasFocus()) {
+                view.getViewFocusAnimator().changeSize(false);
+            }
         }
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/recents/tv/animations/RecentsRowFocusAnimationHolder.java b/packages/SystemUI/src/com/android/systemui/recents/tv/animations/RecentsRowFocusAnimationHolder.java
index 45c1537..8a4cf399 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/tv/animations/RecentsRowFocusAnimationHolder.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/tv/animations/RecentsRowFocusAnimationHolder.java
@@ -29,11 +29,11 @@
  * Recents row's focus animation with PIP controls.
  */
 public class RecentsRowFocusAnimationHolder {
-    private View mView;
-    private View mTitleView;
+    private final View mView;
+    private final View mTitleView;
 
     private AnimatorSet mFocusGainAnimatorSet;
-    private AnimatorSet mFocusLoseAnimatorSet;
+    private AnimatorSet mFocusLossAnimatorSet;
 
     public RecentsRowFocusAnimationHolder(View view, View titleView) {
         mView = view;
@@ -50,28 +50,45 @@
         mFocusGainAnimatorSet.setDuration(duration);
         mFocusGainAnimatorSet.setInterpolator(Interpolators.FAST_OUT_SLOW_IN);
 
-        mFocusLoseAnimatorSet = new AnimatorSet();
-        mFocusLoseAnimatorSet.playTogether(
+        mFocusLossAnimatorSet = new AnimatorSet();
+        mFocusLossAnimatorSet.playTogether(
                 // Animation doesn't start from the current value (1f) sometimes,
                 // so specify the desired initial value here.
                 ObjectAnimator.ofFloat(mView, "alpha", 1f, dimAlpha),
                 ObjectAnimator.ofFloat(mTitleView, "alpha", 0f));
-        mFocusLoseAnimatorSet.setDuration(duration);
-        mFocusLoseAnimatorSet.setInterpolator(Interpolators.FAST_OUT_SLOW_IN);
+        mFocusLossAnimatorSet.setDuration(duration);
+        mFocusLossAnimatorSet.setInterpolator(Interpolators.FAST_OUT_SLOW_IN);
     }
 
     /**
-     * Returns the Recents row's focus change animation.
+     * Starts the Recents row's focus gain animation.
      */
-    public Animator getFocusChangeAnimator(boolean hasFocus) {
-        return hasFocus ? mFocusGainAnimatorSet : mFocusLoseAnimatorSet;
+    public void startFocusGainAnimation() {
+        cancelAnimator(mFocusLossAnimatorSet);
+        mFocusGainAnimatorSet.start();
     }
 
     /**
-     * Resets the views to the initial state immediately.
+     * Starts the Recents row's focus loss animation.
+     */
+    public void startFocusLossAnimation() {
+        cancelAnimator(mFocusGainAnimatorSet);
+        mFocusLossAnimatorSet.start();
+    }
+
+    /**
+     * Resets the views immediately and ends the animations.
      */
     public void reset() {
+        cancelAnimator(mFocusLossAnimatorSet);
+        cancelAnimator(mFocusGainAnimatorSet);
         mView.setAlpha(1f);
         mTitleView.setAlpha(1f);
     }
+
+    private static void cancelAnimator(Animator animator) {
+        if (animator.isStarted()) {
+            animator.cancel();
+        }
+    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/recents/tv/animations/ViewFocusAnimator.java b/packages/SystemUI/src/com/android/systemui/recents/tv/animations/ViewFocusAnimator.java
index 8218599..72fd7a4 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/tv/animations/ViewFocusAnimator.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/tv/animations/ViewFocusAnimator.java
@@ -89,7 +89,7 @@
         });
     }
 
-    public void setFocusProgress(float level) {
+    private void setFocusProgress(float level) {
         mFocusProgress = level;
 
         float scale = mUnselectedScale + (level * mSelectedScaleDelta);
@@ -107,33 +107,19 @@
         mTargetView.getDismissIconView().setZ(z);
     }
 
-    public float getFocusProgress() {
-        return mFocusProgress;
-    }
-
-    public void animateFocus(boolean focused) {
+    private void animateFocus(boolean focused) {
         if (mFocusAnimation.isStarted()) {
             mFocusAnimation.cancel();
         }
 
         float target = focused ? 1.0f : 0.0f;
 
-        if (getFocusProgress() != target) {
-            mFocusAnimation.setFloatValues(getFocusProgress(), target);
+        if (mFocusProgress != target) {
+            mFocusAnimation.setFloatValues(mFocusProgress, target);
             mFocusAnimation.start();
         }
     }
 
-    public void setFocusImmediate(boolean focused) {
-        if (mFocusAnimation.isStarted()) {
-            mFocusAnimation.cancel();
-        }
-
-        float target = focused ? 1.0f : 0.0f;
-
-        setFocusProgress(target);
-    }
-
     @Override
     public void onFocusChange(View v, boolean hasFocus) {
         if (v != mTargetView) {
@@ -142,21 +128,27 @@
         changeSize(hasFocus);
     }
 
-    protected void changeSize(boolean hasFocus) {
+    /**
+     * Changes the size of the {@link TaskCardView} to show its focused state.
+     */
+    public void changeSize(boolean hasFocus) {
         ViewGroup.LayoutParams lp = mTargetView.getLayoutParams();
         int width = lp.width;
         int height = lp.height;
 
         if (width < 0 && height < 0) {
             mTargetView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
-            height = mTargetView.getMeasuredHeight();
         }
 
         if (mTargetView.isAttachedToWindow() && mTargetView.hasWindowFocus() &&
                 mTargetView.getVisibility() == View.VISIBLE) {
             animateFocus(hasFocus);
         } else {
-            setFocusImmediate(hasFocus);
+            // Set focus immediately.
+            if (mFocusAnimation.isStarted()) {
+                mFocusAnimation.cancel();
+            }
+            setFocusProgress(hasFocus ? 1.0f : 0.0f);
         }
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/recents/tv/views/RecentsTvView.java b/packages/SystemUI/src/com/android/systemui/recents/tv/views/RecentsTvView.java
index 06b24418..318b7f9 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/tv/views/RecentsTvView.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/tv/views/RecentsTvView.java
@@ -59,7 +59,7 @@
     private boolean mAwaitingFirstLayout = true;
     private Rect mSystemInsets = new Rect();
     private RecentsTvTransitionHelper mTransitionHelper;
-    private Handler mHandler;
+    private final Handler mHandler = new Handler();
     private OnScrollListener mScrollListener;
     public RecentsTvView(Context context) {
         this(context, null);
@@ -81,9 +81,7 @@
         LayoutInflater inflater = LayoutInflater.from(context);
         mEmptyView = inflater.inflate(R.layout.recents_tv_empty, this, false);
         addView(mEmptyView);
-        mEmptyViewFocusAnimationHolder = new RecentsRowFocusAnimationHolder(mEmptyView, null);
 
-        mHandler = new Handler();
         mTransitionHelper = new RecentsTvTransitionHelper(mContext, mHandler);
     }
 
@@ -91,20 +89,18 @@
     protected void onFinishInflate() {
         super.onFinishInflate();
         mDismissPlaceholder = findViewById(R.id.dismiss_placeholder);
+        mTaskStackHorizontalView = (TaskStackHorizontalGridView) findViewById(R.id.task_list);
     }
 
-    public void setTaskStack(TaskStack stack) {
+    /**
+     * Initialize the view.
+     */
+    public void init(TaskStack stack) {
         RecentsConfiguration config = Recents.getConfiguration();
         RecentsActivityLaunchState launchState = config.getLaunchState();
         mStack = stack;
 
-        if (mTaskStackHorizontalView != null) {
-            mTaskStackHorizontalView.reset();
-            mTaskStackHorizontalView.setStack(stack);
-        } else {
-            mTaskStackHorizontalView = (TaskStackHorizontalGridView) findViewById(R.id.task_list);
-            mTaskStackHorizontalView.setStack(stack);
-        }
+        mTaskStackHorizontalView.init(stack);
 
         if (stack.getStackTaskCount() > 0) {
             hideEmptyView();
@@ -112,6 +108,7 @@
             showEmptyView();
         }
 
+        // Layout with the new stack
         requestLayout();
     }
 
@@ -189,17 +186,6 @@
     }
 
     /**
-     * Starts the focus change animation.
-     */
-    public void startRecentsRowFocusAnimation(boolean hasFocus) {
-        if (mEmptyView.getVisibility() == View.VISIBLE) {
-            mEmptyViewFocusAnimationHolder.getFocusChangeAnimator(hasFocus).start();
-        } else {
-            mTaskStackHorizontalView.startRecentsRowFocusAnimation(hasFocus);
-        }
-    }
-
-    /**
      * Hides the task stack and shows the empty view.
      */
     public void showEmptyView() {
diff --git a/packages/SystemUI/src/com/android/systemui/recents/tv/views/TaskCardView.java b/packages/SystemUI/src/com/android/systemui/recents/tv/views/TaskCardView.java
index 758f93a..72a589f 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/tv/views/TaskCardView.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/tv/views/TaskCardView.java
@@ -40,16 +40,18 @@
 import com.android.systemui.R;
 import com.android.systemui.recents.Recents;
 import com.android.systemui.recents.misc.SystemServicesProxy;
+import com.android.systemui.recents.model.Task;
+import com.android.systemui.recents.tv.RecentsTvActivity;
 import com.android.systemui.recents.tv.animations.DismissAnimationsHolder;
 import com.android.systemui.recents.tv.animations.RecentsRowFocusAnimationHolder;
 import com.android.systemui.recents.tv.animations.ViewFocusAnimator;
-import com.android.systemui.recents.model.Task;
 
 public class TaskCardView extends LinearLayout {
 
     private static final String TAG = "TaskCardView";
     private View mThumbnailView;
     private View mDismissIconView;
+    private View mInfoFieldView;
     private TextView mTitleTextView;
     private ImageView mBadgeView;
     private Task mTask;
@@ -79,14 +81,14 @@
     protected void onFinishInflate() {
         super.onFinishInflate();
         mThumbnailView = findViewById(R.id.card_view_thumbnail);
+        mInfoFieldView = findViewById(R.id.card_info_field);
         mTitleTextView = (TextView) findViewById(R.id.card_title_text);
         mBadgeView = (ImageView) findViewById(R.id.card_extra_badge);
         mDismissIconView = findViewById(R.id.dismiss_icon);
         mDismissAnimationsHolder = new DismissAnimationsHolder(this);
-        View title = findViewById(R.id.card_info_field);
         mCornerRadius = getResources().getDimensionPixelSize(
                 R.dimen.recents_task_view_rounded_corners_radius);
-        mRecentsRowFocusAnimationHolder = new RecentsRowFocusAnimationHolder(this, title);
+        mRecentsRowFocusAnimationHolder = new RecentsRowFocusAnimationHolder(this, mInfoFieldView);
         SystemServicesProxy ssp = Recents.getSystemServices();
         if (!ssp.isTouchExplorationEnabled()) {
             mDismissIconView.setVisibility(VISIBLE);
@@ -102,6 +104,9 @@
         mBadgeView.setImageDrawable(task.icon);
         setThumbnailView();
         setContentDescription(task.titleDescription);
+        mDismissState = false;
+        mDismissAnimationsHolder.reset();
+        mRecentsRowFocusAnimationHolder.reset();
     }
 
     public Task getTask() {
@@ -196,40 +201,37 @@
     }
 
     @Override
-    public boolean onKeyDown(int keyCode, KeyEvent event) {
-        switch (keyCode) {
+    public boolean dispatchKeyEvent(KeyEvent event) {
+        // Override dispatchKeyEvent() instead of onKeyDown() to prevent warning from ViewRootImpl.
+        switch (event.getKeyCode()) {
             case KeyEvent.KEYCODE_DPAD_DOWN : {
-                if (!isInDismissState()) {
+                if (!isInDismissState() && event.getAction() == KeyEvent.ACTION_DOWN) {
                     setDismissState(true);
                     return true;
                 }
                 break;
             }
             case KeyEvent.KEYCODE_DPAD_UP : {
-                if (isInDismissState()) {
-                    setDismissState(false);
-                    return true;
+                if (event.getAction() == KeyEvent.ACTION_DOWN) {
+                    if (isInDismissState()) {
+                        setDismissState(false);
+                    } else {
+                        ((RecentsTvActivity) getContext()).requestPipControlsFocus();
+                    }
                 }
-                break;
+                return true;
             }
 
-            //Eat right and left key presses when we are in dismiss state
-            case KeyEvent.KEYCODE_DPAD_LEFT : {
-                if (isInDismissState()) {
-                    return true;
-                }
-                break;
-            }
+            // Eat right and left key presses when we are in dismiss state
+            case KeyEvent.KEYCODE_DPAD_LEFT :
             case KeyEvent.KEYCODE_DPAD_RIGHT : {
                 if (isInDismissState()) {
                     return true;
                 }
                 break;
             }
-            default:
-                break;
         }
-        return super.onKeyDown(keyCode, event);
+        return super.dispatchKeyEvent(event);
     }
 
     private void setDismissState(boolean dismissState) {
@@ -252,22 +254,14 @@
         mDismissAnimationsHolder.startDismissAnimation(listener);
     }
 
+    public ViewFocusAnimator getViewFocusAnimator() {
+        return mViewFocusAnimator;
+    }
+
     public RecentsRowFocusAnimationHolder getRecentsRowFocusAnimationHolder() {
         return mRecentsRowFocusAnimationHolder;
     }
 
-    @Override
-    protected void onDetachedFromWindow() {
-        super.onDetachedFromWindow();
-        setDismissState(false);
-    }
-
-    public void reset() {
-        mDismissState = false;
-        mRecentsRowFocusAnimationHolder.reset();
-        mDismissAnimationsHolder.reset();
-    }
-
     private void setThumbnailView() {
         ImageView screenshotView = (ImageView) findViewById(R.id.card_view_banner_icon);
         PackageManager pm = getContext().getPackageManager();
@@ -332,6 +326,10 @@
         return mThumbnailView;
     }
 
+    public View getInfoFieldView() {
+        return mInfoFieldView;
+    }
+
     public View getDismissIconView() {
         return mDismissIconView;
     }
diff --git a/packages/SystemUI/src/com/android/systemui/recents/tv/views/TaskStackHorizontalGridView.java b/packages/SystemUI/src/com/android/systemui/recents/tv/views/TaskStackHorizontalGridView.java
index 9f52abd..f9b8700 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/tv/views/TaskStackHorizontalGridView.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/tv/views/TaskStackHorizontalGridView.java
@@ -18,8 +18,6 @@
 import android.animation.Animator;
 import android.animation.AnimatorSet;
 import android.content.Context;
-import android.os.Handler;
-import android.os.Message;
 import android.support.v17.leanback.widget.HorizontalGridView;
 import android.util.AttributeSet;
 import android.view.View;
@@ -39,14 +37,6 @@
 public class TaskStackHorizontalGridView extends HorizontalGridView implements TaskStackCallbacks {
     private static final int ANIMATION_DELAY_MS = 50;
     private static final int MSG_START_RECENT_ROW_FOCUS_ANIMATION = 100;
-    private final Handler mHandler = new Handler() {
-        @Override
-        public void handleMessage(Message msg) {
-            if (msg.what == MSG_START_RECENT_ROW_FOCUS_ANIMATION) {
-                startRecentsRowFocusAnimation(msg.arg1 == 1);
-            }
-        }
-    };
     private TaskStack mStack;
     private Task mFocusedTask;
     private AnimatorSet mRecentsRowFocusAnimation;
@@ -74,38 +64,15 @@
     }
 
     /**
-     * Resets this view for reuse.
-     */
-    public void reset() {
-        for (int i = 0; i < getChildCount(); i++) {
-            ((TaskCardView) getChildAt(i)).getRecentsRowFocusAnimationHolder().reset();
-        }
-        if (mRecentsRowFocusAnimation != null && mRecentsRowFocusAnimation.isStarted()) {
-            mRecentsRowFocusAnimation.cancel();
-        }
-        mHandler.removeCallbacksAndMessages(null);
-        requestLayout();
-    }
-
-    /**
-     * @param task - Task to reset
-     */
-    private void resetFocusedTask(Task task) {
-        mFocusedTask = null;
-    }
-
-    /**
-     * Sets the task stack.
+     * Initializes the grid view.
      * @param stack
      */
-    public void setStack(TaskStack stack) {
-        //Set new stack
+    public void init(TaskStack stack) {
+        // Set new stack
         mStack = stack;
         if (mStack != null) {
             mStack.setCallbacks(this);
         }
-        //Layout with new stack
-        requestLayout();
     }
 
     /**
@@ -126,13 +93,6 @@
     }
 
     /**
-     * @return - The focused task card view.
-     */
-    public TaskCardView getFocusedTaskCardView() {
-        return ((TaskCardView)findFocus());
-    }
-
-    /**
      * @param task
      * @return Child view for given task
      */
@@ -146,32 +106,31 @@
         return null;
     }
 
+
     /**
-     * Starts the focus change animation.
+     * Starts the Recents row's focus gain animation.
      */
-    public void startRecentsRowFocusAnimation(final boolean hasFocus) {
-        if (getChildCount() == 0) {
-            // Animation request may happen before view is attached.
-            // Post again with small dealy so animation can be run again later.
-            if (getAdapter().getItemCount() > 0) {
-                mHandler.sendMessageDelayed(mHandler.obtainMessage(
-                        MSG_START_RECENT_ROW_FOCUS_ANIMATION, hasFocus ? 1 : 0),
-                        ANIMATION_DELAY_MS);
+    public void startFocusGainAnimation() {
+        for (int i = 0; i < getChildCount(); i++) {
+            TaskCardView v = (TaskCardView) getChildAt(i);
+            if (v.hasFocus()) {
+                v.getViewFocusAnimator().changeSize(true);
             }
-            return;
+            v.getRecentsRowFocusAnimationHolder().startFocusGainAnimation();
         }
-        if (mRecentsRowFocusAnimation != null && mRecentsRowFocusAnimation.isStarted()) {
-            mRecentsRowFocusAnimation.cancel();
+    }
+
+    /**
+     * Starts the Recents row's focus loss animation.
+     */
+    public void startFocusLossAnimation() {
+        for (int i = 0; i < getChildCount(); i++) {
+            TaskCardView v = (TaskCardView) getChildAt(i);
+            if (v.hasFocus()) {
+                v.getViewFocusAnimator().changeSize(false);
+            }
+            v.getRecentsRowFocusAnimationHolder().startFocusLossAnimation();
         }
-        Animator animator = ((TaskCardView) getChildAt(0)).getRecentsRowFocusAnimationHolder()
-                .getFocusChangeAnimator(hasFocus);
-        mRecentsRowFocusAnimation = new AnimatorSet();
-        AnimatorSet.Builder builder = mRecentsRowFocusAnimation.play(animator);
-        for (int i = 1; i < getChildCount(); i++) {
-            builder.with(((TaskCardView) getChildAt(i)).getRecentsRowFocusAnimationHolder()
-                    .getFocusChangeAnimator(hasFocus));
-        }
-        mRecentsRowFocusAnimation.start();
     }
 
     @Override
@@ -181,11 +140,11 @@
     }
 
     @Override
-    public void onStackTaskRemoved(TaskStack stack, Task removedTask, boolean wasFrontMostTask,
-            Task newFrontMostTask, AnimationProps animation, boolean fromDockGesture) {
+    public void onStackTaskRemoved(TaskStack stack, Task removedTask, Task newFrontMostTask,
+            AnimationProps animation, boolean fromDockGesture) {
         ((TaskStackHorizontalViewAdapter) getAdapter()).removeTask(removedTask);
         if (mFocusedTask == removedTask) {
-            resetFocusedTask(removedTask);
+            mFocusedTask = null;
         }
         // If there are no remaining tasks, then just close recents
         if (mStack.getStackTaskCount() == 0) {
diff --git a/packages/SystemUI/src/com/android/systemui/recents/tv/views/TaskStackHorizontalViewAdapter.java b/packages/SystemUI/src/com/android/systemui/recents/tv/views/TaskStackHorizontalViewAdapter.java
index b6b86b4..236d077 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/tv/views/TaskStackHorizontalViewAdapter.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/tv/views/TaskStackHorizontalViewAdapter.java
@@ -43,17 +43,13 @@
     private static final String TAG = "TaskStackViewAdapter";
     private List<Task> mTaskList;
     private TaskStackHorizontalGridView mGridView;
-    private boolean mResetAddedCards;
 
     public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
         private TaskCardView mTaskCardView;
         private Task mTask;
-        private boolean mShouldReset;
         public ViewHolder(View v) {
             super(v);
-            if(v instanceof TaskCardView) {
-                mTaskCardView = (TaskCardView) v;
-            }
+            mTaskCardView = (TaskCardView) v;
         }
 
         public void init(Task task) {
@@ -90,7 +86,6 @@
                 public void onAnimationEnd(Animator animation) {
                     removeTask(task);
                     EventBus.getDefault().send(new DeleteTaskDataEvent(task));
-                    mShouldReset = true;
                 }
 
                 @Override
@@ -131,23 +126,6 @@
     }
 
     @Override
-    public void onViewAttachedToWindow(ViewHolder holder) {
-        if (mResetAddedCards) {
-            holder.mTaskCardView.reset();
-        }
-    }
-
-    @Override
-    public void onViewDetachedFromWindow(ViewHolder holder) {
-        // We only want to reset on view detach if this is the last task being dismissed.
-        // This is so that we do not reset when shifting to apps etc, as it is not needed.
-        if (holder.mShouldReset) {
-            holder.mTaskCardView.reset();
-            holder.mShouldReset = false;
-        }
-    }
-
-    @Override
     public int getItemCount() {
         return mTaskList.size();
     }
@@ -178,8 +156,4 @@
         mTaskList.add(position, task);
         notifyItemInserted(position);
     }
-
-    public void setResetAddedCards(boolean reset) {
-        mResetAddedCards = reset;
-    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackAnimationHelper.java b/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackAnimationHelper.java
index f4c13d7..493e618 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackAnimationHelper.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackAnimationHelper.java
@@ -148,10 +148,12 @@
         for (int i = taskViews.size() - 1; i >= 0; i--) {
             TaskView tv = taskViews.get(i);
             Task task = tv.getTask();
-            boolean currentTaskOccludesLaunchTarget = (launchTargetTask != null &&
-                    launchTargetTask.group.isTaskAboveTask(task, launchTargetTask));
-            boolean hideTask = (launchTargetTask != null &&
-                    launchTargetTask.isFreeformTask() && task.isFreeformTask());
+            boolean currentTaskOccludesLaunchTarget = launchTargetTask != null &&
+                    launchTargetTask.group != null &&
+                    launchTargetTask.group.isTaskAboveTask(task, launchTargetTask);
+            boolean hideTask = launchTargetTask != null &&
+                    launchTargetTask.isFreeformTask() &&
+                    task.isFreeformTask();
 
             // Get the current transform for the task, which will be used to position it offscreen
             stackLayout.getStackTransform(task, stackScroller.getStackScroll(), mTmpTransform,
@@ -221,11 +223,9 @@
             int taskIndexFromBack = i;
             final TaskView tv = taskViews.get(i);
             Task task = tv.getTask();
-            boolean currentTaskOccludesLaunchTarget = false;
-            if (launchTargetTask != null) {
-                currentTaskOccludesLaunchTarget = launchTargetTask.group.isTaskAboveTask(task,
-                        launchTargetTask);
-            }
+            boolean currentTaskOccludesLaunchTarget = launchTargetTask != null &&
+                    launchTargetTask.group != null &&
+                    launchTargetTask.group.isTaskAboveTask(task, launchTargetTask);
 
             // Get the current transform for the task, which will be updated to the final transform
             // to animate to depending on how recents was invoked
@@ -358,8 +358,9 @@
         for (int i = 0; i < taskViewCount; i++) {
             TaskView tv = taskViews.get(i);
             Task task = tv.getTask();
-            boolean currentTaskOccludesLaunchTarget = (launchingTask != null &&
-                    launchingTask.group.isTaskAboveTask(task, launchingTask));
+            boolean currentTaskOccludesLaunchTarget = launchingTask != null &&
+                    launchingTask.group != null &&
+                    launchingTask.group.isTaskAboveTask(task, launchingTask);
 
             if (tv == launchingTaskView) {
                 tv.setClipViewInStack(false);
diff --git a/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackLayoutAlgorithm.java b/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackLayoutAlgorithm.java
index 77b7338..e3fe1ab 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackLayoutAlgorithm.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackLayoutAlgorithm.java
@@ -404,7 +404,7 @@
      * Sets the system insets.
      */
     public boolean setSystemInsets(Rect systemInsets) {
-        boolean changed = mSystemInsets.equals(systemInsets);
+        boolean changed = !mSystemInsets.equals(systemInsets);
         mSystemInsets.set(systemInsets);
         return changed;
     }
@@ -583,11 +583,25 @@
         if (getInitialFocusState() == STATE_UNFOCUSED && mNumStackTasks > 1) {
             if (ignoreScrollToFront || (!launchState.launchedWithAltTab && !scrollToFront)) {
                 // Set the initial scroll to the predefined state (which differs from the stack)
-                float [] initialNormX = new float[] {
-                        getNormalizedXFromUnfocusedY(mSystemInsets.bottom + mInitialBottomOffset,
-                                FROM_BOTTOM),
-                        getNormalizedXFromUnfocusedY(mInitialTopOffset, FROM_TOP)
-                };
+                float [] initialNormX = null;
+                float minBottomTaskNormX = getNormalizedXFromUnfocusedY(mSystemInsets.bottom +
+                        mInitialBottomOffset, FROM_BOTTOM);
+                float maxBottomTaskNormX = getNormalizedXFromUnfocusedY(mFocusedTopPeekHeight +
+                        mTaskRect.height() - mMinMargin, FROM_TOP);
+                if (mNumStackTasks <= 2) {
+                    // For small stacks, position the tasks so that they are top aligned to under
+                    // the action button, but ensure that it is at least a certain offset from the
+                    // bottom of the stack
+                    initialNormX = new float[] {
+                            Math.min(maxBottomTaskNormX, minBottomTaskNormX),
+                            getNormalizedXFromUnfocusedY(mFocusedTopPeekHeight, FROM_TOP)
+                    };
+                } else {
+                    initialNormX = new float[] {
+                            minBottomTaskNormX,
+                            getNormalizedXFromUnfocusedY(mInitialTopOffset, FROM_TOP)
+                    };
+                }
 
                 mUnfocusedRange.offset(0f);
                 List<Task> tasks = stack.getStackTasks();
@@ -881,14 +895,7 @@
             TaskViewTransform frontTransform, boolean ignoreSingleTaskCase, boolean forceUpdate) {
         SystemServicesProxy ssp = Recents.getSystemServices();
 
-        // Compute the focused and unfocused offset
-        float boundedStackScroll = Utilities.clamp(stackScroll, mMinScrollP, mMaxScrollP);
-        mUnfocusedRange.offset(boundedStackScroll);
-        mFocusedRange.offset(boundedStackScroll);
-        float boundedScrollUnfocusedRangeX = mUnfocusedRange.getNormalizedX(taskProgress);
-        float boundedScrollFocusedRangeX = mFocusedRange.getNormalizedX(taskProgress);
-        float boundedScrollUnfocusedNonOverrideRangeX =
-                mUnfocusedRange.getNormalizedX(nonOverrideTaskProgress);
+        // Ensure that the task is in range
         mUnfocusedRange.offset(stackScroll);
         mFocusedRange.offset(stackScroll);
         boolean unfocusedVisible = mUnfocusedRange.isInRange(taskProgress);
@@ -900,9 +907,30 @@
             return;
         }
 
+        // Map the absolute task progress to the normalized x at the stack scroll.  We use this to
+        // calculate positions along the curve.
+        mUnfocusedRange.offset(stackScroll);
+        mFocusedRange.offset(stackScroll);
         float unfocusedRangeX = mUnfocusedRange.getNormalizedX(taskProgress);
         float focusedRangeX = mFocusedRange.getNormalizedX(taskProgress);
 
+        // Map the absolute task progress to the normalized x at the bounded stack scroll.  We use
+        // this to calculate bounded properties, like translationZ and outline alpha.
+        float boundedStackScroll = Utilities.clamp(stackScroll, mMinScrollP, mMaxScrollP);
+        mUnfocusedRange.offset(boundedStackScroll);
+        mFocusedRange.offset(boundedStackScroll);
+        float boundedScrollUnfocusedRangeX = mUnfocusedRange.getNormalizedX(taskProgress);
+        float boundedScrollUnfocusedNonOverrideRangeX =
+                mUnfocusedRange.getNormalizedX(nonOverrideTaskProgress);
+
+        // Map the absolute task progress to the normalized x at the upper bounded stack scroll.
+        // We use this to calculate the dim, which is bounded only on one end.
+        float lowerBoundedStackScroll = Utilities.clamp(stackScroll, -Float.MAX_VALUE, mMaxScrollP);
+        mUnfocusedRange.offset(lowerBoundedStackScroll);
+        mFocusedRange.offset(lowerBoundedStackScroll);
+        float lowerBoundedUnfocusedRangeX = mUnfocusedRange.getNormalizedX(taskProgress);
+        float lowerBoundedFocusedRangeX = mFocusedRange.getNormalizedX(taskProgress);
+
         int x = (mStackRect.width() - mTaskRect.width()) / 2;
         int y;
         float z;
@@ -917,7 +945,8 @@
             y = centerYOffset + getYForDeltaP(tmpP, 0);
             z = mMaxTranslationZ;
             dimAlpha = 0f;
-            viewOutlineAlpha = (OUTLINE_ALPHA_MIN_VALUE + OUTLINE_ALPHA_MAX_VALUE) / 2f;
+            viewOutlineAlpha = OUTLINE_ALPHA_MIN_VALUE +
+                    (OUTLINE_ALPHA_MAX_VALUE - OUTLINE_ALPHA_MIN_VALUE) / 2f;
 
         } else {
             // Otherwise, update the task to the stack layout
@@ -926,9 +955,22 @@
             int focusedY = (int) ((1f - mFocusedCurveInterpolator.getInterpolation(
                     focusedRangeX)) * mStackRect.height());
             float unfocusedDim = mUnfocusedDimCurveInterpolator.getInterpolation(
-                    boundedScrollUnfocusedRangeX);
+                    lowerBoundedUnfocusedRangeX);
             float focusedDim = mFocusedDimCurveInterpolator.getInterpolation(
-                    boundedScrollFocusedRangeX);
+                    lowerBoundedFocusedRangeX);
+
+            // Special case, because we override the initial task positions differently for small
+            // stacks, we clamp the dim to 0 in the initial position, and then only modulate the
+            // dim when the task is scrolled back towards the top of the screen
+            if (mNumStackTasks <= 2 && nonOverrideTaskProgress == 0f) {
+                if (boundedScrollUnfocusedRangeX >= 0.5f) {
+                    unfocusedDim = 0f;
+                } else {
+                    float offset = mUnfocusedDimCurveInterpolator.getInterpolation(0.5f);
+                    unfocusedDim -= offset;
+                    unfocusedDim *= MAX_DIM / (MAX_DIM - offset);
+                }
+            }
 
             y = (mStackRect.top - mTaskRect.top) +
                     (int) Utilities.mapRange(focusState, unfocusedY, focusedY);
diff --git a/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackView.java b/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackView.java
index 1a197b6..231360e 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackView.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackView.java
@@ -1400,8 +1400,8 @@
      * We expect that the {@link TaskView} associated with the removed task is already hidden.
      */
     @Override
-    public void onStackTaskRemoved(TaskStack stack, Task removedTask, boolean wasFrontMostTask,
-            Task newFrontMostTask, AnimationProps animation, boolean fromDockGesture) {
+    public void onStackTaskRemoved(TaskStack stack, Task removedTask, Task newFrontMostTask,
+            AnimationProps animation, boolean fromDockGesture) {
         if (mFocusedTask == removedTask) {
             resetFocusedTask(removedTask);
         }
@@ -1996,6 +1996,10 @@
         if (event.fromDeviceOrientationChange) {
             mDisplayOrientation = Utilities.getAppConfiguration(mContext).orientation;
             mDisplayRect = Recents.getSystemServices().getDisplayRect();
+
+            // Always stop the scroller, otherwise, we may continue setting the stack scroll to the
+            // wrong bounds in the new layout
+            mStackScroller.stopScroller();
         }
         reloadOnConfigurationChange();
 
diff --git a/packages/SystemUI/src/com/android/systemui/stackdivider/Divider.java b/packages/SystemUI/src/com/android/systemui/stackdivider/Divider.java
index e89c136..a0bae20 100644
--- a/packages/SystemUI/src/com/android/systemui/stackdivider/Divider.java
+++ b/packages/SystemUI/src/com/android/systemui/stackdivider/Divider.java
@@ -39,6 +39,7 @@
 public class Divider extends SystemUI {
     private DividerWindowManager mWindowManager;
     private DividerView mView;
+    private final DividerState mDividerState = new DividerState();
     private DockDividerVisibilityListener mDockDividerVisibilityListener;
     private boolean mVisible = false;
     private boolean mMinimized = false;
@@ -76,7 +77,7 @@
         final int width = landscape ? size : MATCH_PARENT;
         final int height = landscape ? MATCH_PARENT : size;
         mWindowManager.add(mView, width, height);
-        mView.setWindowManager(mWindowManager);
+        mView.injectDependencies(mWindowManager, mDividerState);
     }
 
     private void removeDivider() {
diff --git a/packages/SystemUI/src/com/android/systemui/stackdivider/DividerState.java b/packages/SystemUI/src/com/android/systemui/stackdivider/DividerState.java
new file mode 100644
index 0000000..353a974
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/stackdivider/DividerState.java
@@ -0,0 +1,25 @@
+/*
+ * Copyright (C) 2016 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.systemui.stackdivider;
+
+/**
+ * Class to hold state of divider that needs to persist across configuration changes.
+ */
+public class DividerState {
+    public boolean animateAfterRecentsDrawn;
+    public boolean growAfterRecentsDrawn;
+}
diff --git a/packages/SystemUI/src/com/android/systemui/stackdivider/DividerView.java b/packages/SystemUI/src/com/android/systemui/stackdivider/DividerView.java
index f728aa4..998f50f 100644
--- a/packages/SystemUI/src/com/android/systemui/stackdivider/DividerView.java
+++ b/packages/SystemUI/src/com/android/systemui/stackdivider/DividerView.java
@@ -30,12 +30,12 @@
 import android.graphics.Region.Op;
 import android.hardware.display.DisplayManager;
 import android.os.Bundle;
+import android.os.Handler;
 import android.util.AttributeSet;
 import android.view.Display;
 import android.view.DisplayInfo;
 import android.view.GestureDetector;
 import android.view.GestureDetector.SimpleOnGestureListener;
-import android.view.HapticFeedbackConstants;
 import android.view.MotionEvent;
 import android.view.PointerIcon;
 import android.view.VelocityTracker;
@@ -141,8 +141,6 @@
     private DividerSnapAlgorithm mSnapAlgorithm;
     private final Rect mStableInsets = new Rect();
 
-    private boolean mAnimateAfterRecentsDrawn;
-    private boolean mGrowAfterRecentsDrawn;
     private boolean mGrowRecents;
     private ValueAnimator mCurrentAnimator;
     private boolean mEntranceAnimationRunning;
@@ -151,6 +149,8 @@
     private GestureDetector mGestureDetector;
     private boolean mDockedStackMinimized;
     private boolean mAdjustedForIme;
+    private DividerState mState;
+    private final Handler mHandler = new Handler();
 
     private final AccessibilityDelegate mHandleDelegate = new AccessibilityDelegate() {
         @Override
@@ -335,8 +335,9 @@
         }
     }
 
-    public void setWindowManager(DividerWindowManager windowManager) {
+    public void injectDependencies(DividerWindowManager windowManager, DividerState dividerState) {
         mWindowManager = windowManager;
+        mState = dividerState;
     }
 
     public WindowManagerProxy getWindowManagerProxy() {
@@ -558,7 +559,7 @@
                 if (endDelay == 0 || mCancelled) {
                     endAction.run();
                 } else {
-                    postDelayed(endAction, endDelay);
+                    mHandler.postDelayed(endAction, endDelay);
                 }
             }
         });
@@ -1048,31 +1049,39 @@
     public final void onBusEvent(RecentsActivityStartingEvent recentsActivityStartingEvent) {
         if (mGrowRecents && getWindowManagerProxy().getDockSide() == WindowManager.DOCKED_TOP
                 && getCurrentPosition() == getSnapAlgorithm().getLastSplitTarget().position) {
-            mGrowAfterRecentsDrawn = true;
+            mState.growAfterRecentsDrawn = true;
             startDragging(false /* animate */, false /* touching */);
         }
     }
 
     public final void onBusEvent(DockedTopTaskEvent event) {
         if (event.dragMode == NavigationBarGestureHelper.DRAG_MODE_NONE) {
-            mGrowAfterRecentsDrawn = false;
-            mAnimateAfterRecentsDrawn = true;
+            mState.growAfterRecentsDrawn = false;
+            mState.animateAfterRecentsDrawn = true;
             startDragging(false /* animate */, false /* touching */);
         }
         updateDockSide();
         int position = DockedDividerUtils.calculatePositionForBounds(event.initialRect,
                 mDockSide, mDividerSize);
         mEntranceAnimationRunning = true;
+
+        // Insets might not have been fetched yet, so fetch manually if needed.
+        if (mStableInsets.isEmpty()) {
+            SystemServicesProxy.getInstance(mContext).getStableInsets(mStableInsets);
+            mSnapAlgorithm = null;
+            initializeSnapAlgorithm();
+        }
+
         resizeStack(position, mSnapAlgorithm.getMiddleTarget().position,
                 mSnapAlgorithm.getMiddleTarget());
     }
 
     public final void onBusEvent(RecentsDrawnEvent drawnEvent) {
-        if (mAnimateAfterRecentsDrawn) {
-            mAnimateAfterRecentsDrawn = false;
+        if (mState.animateAfterRecentsDrawn) {
+            mState.animateAfterRecentsDrawn = false;
             updateDockSide();
 
-            post(() -> {
+            mHandler.post(() -> {
                 // Delay switching resizing mode because this might cause jank in recents animation
                 // that's longer than this animation.
                 stopDragging(getCurrentPosition(), mSnapAlgorithm.getMiddleTarget(),
@@ -1080,8 +1089,8 @@
                         200 /* endDelay */);
             });
         }
-        if (mGrowAfterRecentsDrawn) {
-            mGrowAfterRecentsDrawn = false;
+        if (mState.growAfterRecentsDrawn) {
+            mState.growAfterRecentsDrawn = false;
             updateDockSide();
             EventBus.getDefault().send(new RecentsGrowingEvent());
             stopDragging(getCurrentPosition(), mSnapAlgorithm.getMiddleTarget(), 336,
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/BaseStatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/BaseStatusBar.java
index 63933d4..91889d3 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/BaseStatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/BaseStatusBar.java
@@ -1887,10 +1887,13 @@
                 public boolean onDismiss() {
                     if (mHeadsUpManager != null && mHeadsUpManager.isHeadsUp(notificationKey)) {
                         // Release the HUN notification to the shade.
+
+                        if (isPanelFullyCollapsed()) {
+                            HeadsUpManager.setIsClickedNotification(row, true);
+                        }
                         //
                         // In most cases, when FLAG_AUTO_CANCEL is set, the notification will
                         // become canceled shortly by NoMan, but we can't assume that.
-                        HeadsUpManager.setIsClickedNotification(row, true);
                         mHeadsUpManager.releaseImmediately(notificationKey);
                     }
                     StatusBarNotification parentToCancel = null;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/ExpandableNotificationRow.java b/packages/SystemUI/src/com/android/systemui/statusbar/ExpandableNotificationRow.java
index c53ab59..b855b7c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/ExpandableNotificationRow.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/ExpandableNotificationRow.java
@@ -18,10 +18,9 @@
 
 import android.animation.Animator;
 import android.animation.AnimatorListenerAdapter;
-import android.animation.AnimatorSet;
 import android.animation.ObjectAnimator;
-import android.animation.ValueAnimator;
 import android.animation.ValueAnimator.AnimatorUpdateListener;
+import android.annotation.Nullable;
 import android.content.Context;
 import android.graphics.drawable.AnimatedVectorDrawable;
 import android.graphics.drawable.AnimationDrawable;
@@ -41,6 +40,9 @@
 import android.widget.Chronometer;
 import android.widget.ImageView;
 
+import com.android.internal.logging.MetricsLogger;
+import com.android.internal.logging.MetricsProto;
+import com.android.internal.logging.MetricsProto.MetricsEvent;
 import com.android.internal.util.NotificationColorUtil;
 import com.android.systemui.R;
 import com.android.systemui.classifier.FalsingManager;
@@ -138,11 +140,14 @@
         @Override
         public void onClick(View v) {
             if (!mShowingPublic && mGroupManager.isSummaryOfGroup(mStatusBarNotification)) {
-                mGroupManager.toggleGroupExpansion(mStatusBarNotification);
-                mOnExpandClickListener.onExpandClicked(mEntry,
-                        mGroupManager.isGroupExpanded(mStatusBarNotification));
+                final boolean wasExpanded = mGroupManager.isGroupExpanded(mStatusBarNotification);
+                boolean nowExpanded = mGroupManager.toggleGroupExpansion(mStatusBarNotification);
+                mOnExpandClickListener.onExpandClicked(mEntry, nowExpanded);
                 mGroupExpansionChanging = true;
                 updateBackgroundForGroupState();
+                MetricsLogger.action(mContext, MetricsEvent.ACTION_NOTIFICATION_GROUP_EXPANDER,
+                        nowExpanded);
+                logExpansionEvent(true /* userAction */, wasExpanded);
             } else {
                 boolean nowExpanded;
                 if (isPinned()) {
@@ -154,6 +159,8 @@
                 }
                 notifyHeightChanged(true);
                 mOnExpandClickListener.onExpandClicked(mEntry, nowExpanded);
+                MetricsLogger.action(mContext, MetricsEvent.ACTION_NOTIFICATION_EXPANDER,
+                        nowExpanded);
             }
         }
     };
@@ -173,6 +180,7 @@
                     return object.getTranslation();
                 }
     };
+    private OnClickListener mOnClickListener;
 
     public boolean isGroupExpansionChanging() {
         if (isChildInGroup()) {
@@ -374,6 +382,7 @@
         mNotificationParent = childInGroup ? parent : null;
         mPrivateLayout.setIsChildInGroup(childInGroup);
         updateBackgroundForGroupState();
+        updateClickAndFocus();
         if (mNotificationParent != null) {
             mNotificationParent.updateBackgroundForGroupState();
         }
@@ -585,6 +594,24 @@
         mOnExpandClickListener = onExpandClickListener;
     }
 
+    @Override
+    public void setOnClickListener(@Nullable OnClickListener l) {
+        super.setOnClickListener(l);
+        mOnClickListener = l;
+        updateClickAndFocus();
+    }
+
+    private void updateClickAndFocus() {
+        boolean normalChild = !isChildInGroup() || isGroupExpanded();
+        boolean clickable = mOnClickListener != null && normalChild;
+        if (isFocusable() != normalChild) {
+            setFocusable(normalChild);
+        }
+        if (isClickable() != clickable) {
+            setClickable(clickable);
+        }
+    }
+
     public void setHeadsUpManager(HeadsUpManager headsUpManager) {
         mHeadsUpManager = headsUpManager;
     }
@@ -1019,7 +1046,9 @@
     public void setUserExpanded(boolean userExpanded, boolean allowChildExpansion) {
         mFalsingManager.setNotificationExpanded();
         if (mIsSummaryWithChildren && !mShowingPublic && allowChildExpansion) {
+            final boolean wasExpanded = mGroupManager.isGroupExpanded(mStatusBarNotification);
             mGroupManager.setGroupExpanded(mStatusBarNotification, userExpanded);
+            logExpansionEvent(true /* userAction */, wasExpanded);
             return;
         }
         if (userExpanded && !mExpandable) return;
@@ -1305,6 +1334,7 @@
         if (mChildrenContainer != null) {
             mChildrenContainer.setChildrenExpanded(expanded);
         }
+        updateClickAndFocus();
     }
 
     public static void applyTint(View v, int color) {
@@ -1476,11 +1506,26 @@
         updateBackground();
     }
 
+    public int getPositionOfChild(ExpandableNotificationRow childRow) {
+        if (mIsSummaryWithChildren) {
+            return mChildrenContainer.getPositionInLinearLayout(childRow);
+        }
+        return 0;
+    }
+
     public void setExpansionLogger(ExpansionLogger logger, String key) {
         mLogger = logger;
         mLoggingKey = key;
     }
 
+    public void onExpandedByGesture(boolean userExpanded) {
+        int event = MetricsEvent.ACTION_NOTIFICATION_GESTURE_EXPANDER;
+        if (mGroupManager.isSummaryOfGroup(getStatusBarNotification())) {
+            event = MetricsEvent.ACTION_NOTIFICATION_GROUP_GESTURE_EXPANDER;
+        }
+        MetricsLogger.action(mContext, event, userExpanded);
+    }
+
     @Override
     public float getIncreasedPaddingAmount() {
         if (mIsSummaryWithChildren) {
@@ -1505,7 +1550,10 @@
     }
 
     private void logExpansionEvent(boolean userAction, boolean wasExpanded) {
-        final boolean nowExpanded = isExpanded();
+        boolean nowExpanded = isExpanded();
+        if (mIsSummaryWithChildren) {
+            nowExpanded = mGroupManager.isGroupExpanded(mStatusBarNotification);
+        }
         if (wasExpanded != nowExpanded && mLogger != null) {
             mLogger.logNotificationExpansion(mLoggingKey, userAction, nowExpanded) ;
         }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationContentView.java b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationContentView.java
index f3c666f..d6c02e4 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationContentView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationContentView.java
@@ -360,7 +360,9 @@
 
     private void setVisible(final boolean isVisible) {
         if (isVisible) {
-
+            // This call can happen multiple times, but removing only removes a single one.
+            // We therefore need to remove the old one.
+            getViewTreeObserver().removeOnPreDrawListener(mEnableAnimationPredrawListener);
             // We only animate if we are drawn at least once, otherwise the view might animate when
             // it's shown the first time
             getViewTreeObserver().addOnPreDrawListener(mEnableAnimationPredrawListener);
@@ -401,12 +403,17 @@
             return mContext.getResources().getDimensionPixelSize(
                         com.android.internal.R.dimen.notification_action_list_height);
         }
+        int hint;
         if (mHeadsUpChild != null) {
-            return mHeadsUpChild.getHeight();
+            hint = mHeadsUpChild.getHeight();
         } else {
-            return mContractedChild.getHeight() + mContext.getResources().getDimensionPixelSize(
-                com.android.internal.R.dimen.notification_action_list_height);
+            hint = mContractedChild.getHeight() + mContext.getResources().getDimensionPixelSize(
+                    com.android.internal.R.dimen.notification_action_list_height);
         }
+        if (mExpandedChild != null) {
+            hint = Math.min(hint, mExpandedChild.getHeight());
+        }
+        return hint;
     }
 
     private void updateContentTransformation() {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationGuts.java b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationGuts.java
index 4650a1f..b523a11 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationGuts.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationGuts.java
@@ -23,6 +23,7 @@
 import android.content.pm.PackageInfo;
 import android.content.pm.PackageManager;
 import android.content.res.ColorStateList;
+import android.content.res.TypedArray;
 import android.graphics.Canvas;
 import android.graphics.drawable.Drawable;
 import android.os.Handler;
@@ -70,6 +71,8 @@
     private ImageView mAutoButton;
     private ColorStateList mActiveSliderTint;
     private ColorStateList mInactiveSliderTint;
+    private float mActiveSliderAlpha = 1.0f;
+    private float mInactiveSliderAlpha;
     private TextView mImportanceSummary;
     private TextView mImportanceTitle;
     private boolean mAuto;
@@ -100,6 +103,11 @@
                 }
             }
         };
+        final TypedArray ta =
+                context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.Theme, 0, 0);
+        mInactiveSliderAlpha =
+                ta.getFloat(com.android.internal.R.styleable.Theme_disabledAlpha, 0.5f);
+        ta.recycle();
     }
 
     public void resetFalsingCheck() {
@@ -299,13 +307,12 @@
     private void applyAuto() {
         mSeekBar.setEnabled(!mAuto);
 
-        final ColorStateList sliderTint = mAuto ? mInactiveSliderTint : mActiveSliderTint;
         final ColorStateList starTint = mAuto ?  mActiveSliderTint : mInactiveSliderTint;
+        final float alpha = mAuto ? mInactiveSliderAlpha : mActiveSliderAlpha;
         Drawable icon = mAutoButton.getDrawable().mutate();
         icon.setTintList(starTint);
         mAutoButton.setImageDrawable(icon);
-        mSeekBar.setProgressTintList(sliderTint);
-        mSeekBar.setThumbTintList(sliderTint);
+        mSeekBar.setAlpha(alpha);
 
         if (mAuto) {
             mSeekBar.setProgress(mNotificationImportance);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarIconView.java b/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarIconView.java
index bc33b30..cdfdad4 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarIconView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarIconView.java
@@ -18,6 +18,7 @@
 
 import android.app.Notification;
 import android.content.Context;
+import android.content.pm.ApplicationInfo;
 import android.content.res.Configuration;
 import android.content.res.Resources;
 import android.graphics.Canvas;
@@ -25,6 +26,7 @@
 import android.graphics.Rect;
 import android.graphics.drawable.Drawable;
 import android.graphics.drawable.Icon;
+import android.os.Parcelable;
 import android.os.UserHandle;
 import android.text.TextUtils;
 import android.util.AttributeSet;
@@ -325,8 +327,20 @@
 
 
     public static String contentDescForNotification(Context c, Notification n) {
-        Notification.Builder builder = Notification.Builder.recoverBuilder(c, n);
-        String appName = builder.loadHeaderAppName();
+        String appName = "";
+        try {
+            Notification.Builder builder = Notification.Builder.recoverBuilder(c, n);
+            appName = builder.loadHeaderAppName();
+        } catch (RuntimeException e) {
+            Log.e(TAG, "Unable to recover builder", e);
+            // Trying to get the app name from the app info instead.
+            Parcelable appInfo = n.extras.getParcelable(
+                    Notification.EXTRA_BUILDER_APPLICATION_INFO);
+            if (appInfo instanceof ApplicationInfo) {
+                appName = String.valueOf(((ApplicationInfo) appInfo).loadLabel(
+                        c.getPackageManager()));
+            }
+        }
 
         CharSequence title = n.extras.getCharSequence(Notification.EXTRA_TITLE);
         CharSequence ticker = n.tickerText;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/HeaderTransformState.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/HeaderTransformState.java
index b66e9f3..8463e06 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/HeaderTransformState.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/HeaderTransformState.java
@@ -109,9 +109,6 @@
     @Override
     public void recycle() {
         super.recycle();
-        if (mWorkProfileState != null) {
-            mWorkProfileState.recycle();
-        }
         sInstancePool.release(this);
     }
 
@@ -120,6 +117,10 @@
         super.reset();
         mExpandButton = null;
         mWorkProfileState = null;
+        if (mWorkProfileState != null) {
+            mWorkProfileState.recycle();
+            mWorkProfileState = null;
+        }
     }
 
     public void setVisible(boolean visible) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/HybridGroupManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/HybridGroupManager.java
index 8f2c81f..7373607 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/HybridGroupManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/HybridGroupManager.java
@@ -112,6 +112,10 @@
         if (!text.equals(reusableView.getText())) {
             reusableView.setText(text);
         }
+        String contentDescription = String.format(mContext.getResources().getQuantityString(
+                R.plurals.notification_group_overflow_description, number), number);
+
+        reusableView.setContentDescription(contentDescription);
         return reusableView;
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationGroupManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationGroupManager.java
index 0df1204..9ecff18d 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationGroupManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationGroupManager.java
@@ -323,12 +323,14 @@
                         : group.summary.row;
     }
 
-    public void toggleGroupExpansion(StatusBarNotification sbn) {
+    /** @return group expansion state after toggling. */
+    public boolean toggleGroupExpansion(StatusBarNotification sbn) {
         NotificationGroup group = mGroupMap.get(getGroupKey(sbn));
         if (group == null) {
-            return;
+            return false;
         }
         setGroupExpanded(group, !group.expanded);
+        return group.expanded;
     }
 
     private boolean isIsolated(StatusBarNotification sbn) {
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 6877f98..268c46b 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
@@ -3018,7 +3018,7 @@
         if ((mSystemUiVisibility & STATUS_OR_NAV_TRANSIENT) != 0  // a transient bar is revealed
                 && event.getAction() == MotionEvent.ACTION_OUTSIDE // touch outside the source bar
                 && event.getX() == 0 && event.getY() == 0  // a touch outside both bars
-                ) {
+                && !mRemoteInputController.isRemoteInputActive()) { // not due to typing in IME
             userAutohide();
         }
     }
@@ -4337,6 +4337,8 @@
 
     // ---------------------- DragDownHelper.OnDragDownListener ------------------------------------
 
+
+    /* Only ever called as a consequence of a lockscreen expansion gesture. */
     @Override
     public boolean onDraggedDown(View startingChild, int dragLengthY) {
         if (hasActiveNotifications()) {
@@ -4347,6 +4349,10 @@
 
             // We have notifications, go to locked shade.
             goToLockedShade(startingChild);
+            if (startingChild instanceof ExpandableNotificationRow) {
+                ExpandableNotificationRow row = (ExpandableNotificationRow) startingChild;
+                row.onExpandedByGesture(true /* drag down is always an open */);
+            }
             return true;
         } else {
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickStatusBarHeader.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickStatusBarHeader.java
index 8bb1f24..3688495 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickStatusBarHeader.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickStatusBarHeader.java
@@ -81,18 +81,16 @@
     protected MultiUserSwitch mMultiUserSwitch;
     private ImageView mMultiUserAvatar;
 
-    private float mDateTimeTranslation;
-    private float mDateTimeAlarmTranslation;
     private float mDateScaleFactor;
     protected float mGearTranslation;
 
     private TouchAnimator mSecondHalfAnimator;
     private TouchAnimator mFirstHalfAnimator;
     private TouchAnimator mDateSizeAnimator;
-    private TouchAnimator mAlarmTranslation;
     protected TouchAnimator mSettingsAlpha;
     private float mExpansionAmount;
     private QSTileHost mHost;
+    private View mEdit;
 
     public QuickStatusBarHeader(Context context, AttributeSet attrs) {
         super(context, attrs);
@@ -104,6 +102,10 @@
 
         mEmergencyOnly = (TextView) findViewById(R.id.header_emergency_calls_only);
 
+        mEdit = findViewById(android.R.id.edit);
+        findViewById(android.R.id.edit).setOnClickListener(view ->
+                mHost.startRunnableDismissingKeyguard(() -> mQsPanel.showEdit(view)));
+
         mDateTimeAlarmGroup = (ViewGroup) findViewById(R.id.date_time_alarm_group);
         mDateTimeAlarmGroup.findViewById(R.id.empty_time_view).setVisibility(View.GONE);
         mDateTimeGroup = (ViewGroup) findViewById(R.id.date_time_group);
@@ -153,16 +155,11 @@
 
         mGearTranslation = mContext.getResources().getDimension(R.dimen.qs_header_gear_translation);
 
-        mDateTimeTranslation = mContext.getResources().getDimension(
-                R.dimen.qs_date_anim_translation);
-        mDateTimeAlarmTranslation = mContext.getResources().getDimension(
-                R.dimen.qs_date_alarm_anim_translation);
         float dateCollapsedSize = mContext.getResources().getDimension(
                 R.dimen.qs_date_collapsed_text_size);
         float dateExpandedSize = mContext.getResources().getDimension(
                 R.dimen.qs_date_text_size);
         mDateScaleFactor = dateExpandedSize / dateCollapsedSize;
-        updateDateTimePosition();
 
         mSecondHalfAnimator = new TouchAnimator.Builder()
                 .addFloat(mAlarmStatus, "alpha", 0, 1)
@@ -184,10 +181,9 @@
 
     protected void updateSettingsAnimator() {
         mSettingsAlpha = new TouchAnimator.Builder()
-                .addFloat(mSettingsContainer, "translationY", -mGearTranslation, 0)
+                .addFloat(mEdit, "translationY", -mGearTranslation, 0)
                 .addFloat(mMultiUserSwitch, "translationY", -mGearTranslation, 0)
-                .addFloat(mSettingsButton, "rotation", -90, 0)
-                .addFloat(mSettingsContainer, "alpha", 0, 1)
+                .addFloat(mEdit, "alpha", 0, 1)
                 .addFloat(mMultiUserSwitch, "alpha", 0, 1)
                 .setStartDelay(QSAnimator.EXPANDED_TILE_DELAY)
                 .build();
@@ -246,7 +242,6 @@
         mSecondHalfAnimator.setPosition(headerExpansionFraction);
         mFirstHalfAnimator.setPosition(headerExpansionFraction);
         mDateSizeAnimator.setPosition(headerExpansionFraction);
-        mAlarmTranslation.setPosition(headerExpansionFraction);
         mSettingsAlpha.setPosition(headerExpansionFraction);
 
         updateAlarmVisibilities();
@@ -267,15 +262,6 @@
         mAlarmStatusCollapsed.setVisibility(mAlarmShowing ? View.VISIBLE : View.INVISIBLE);
     }
 
-    private void updateDateTimePosition() {
-        // This one has its own because we have to rebuild it every time the alarm state changes.
-        mAlarmTranslation = new TouchAnimator.Builder()
-                .addFloat(mDateTimeAlarmGroup, "translationY", 0, mAlarmShowing
-                        ? mDateTimeAlarmTranslation : mDateTimeTranslation)
-                .build();
-        mAlarmTranslation.setPosition(mExpansionAmount);
-    }
-
     public void setListening(boolean listening) {
         if (listening == mListening) {
             return;
@@ -287,7 +273,6 @@
 
     @Override
     public void updateEverything() {
-        updateDateTimePosition();
         updateVisibilities();
         setClickable(false);
     }
@@ -296,7 +281,6 @@
         updateAlarmVisibilities();
         mEmergencyOnly.setVisibility(mExpanded && mShowEmergencyCallsOnly
                 ? View.VISIBLE : View.INVISIBLE);
-        mSettingsContainer.setVisibility(mExpanded ? View.VISIBLE : View.INVISIBLE);
         mSettingsContainer.findViewById(R.id.tuner_icon).setVisibility(
                 TunerService.isTunerEnabled(mContext) ? View.VISIBLE : View.INVISIBLE);
         mMultiUserSwitch.setVisibility(mExpanded && mMultiUserSwitch.hasMultipleUsers()
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/RemoteInputView.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/RemoteInputView.java
index 2f522f0..40ff051 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/RemoteInputView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/RemoteInputView.java
@@ -47,6 +47,7 @@
 import com.android.internal.logging.MetricsLogger;
 import com.android.internal.logging.MetricsProto;
 import com.android.systemui.R;
+import com.android.systemui.statusbar.ExpandableView;
 import com.android.systemui.statusbar.NotificationData;
 import com.android.systemui.statusbar.RemoteInputController;
 import com.android.systemui.statusbar.stack.ScrollContainer;
@@ -284,11 +285,17 @@
 
     private void findScrollContainer() {
         if (mScrollContainer == null) {
+            mScrollContainerChild = null;
             ViewParent p = this;
             while (p != null) {
+                if (mScrollContainerChild == null && p instanceof ExpandableView) {
+                    mScrollContainerChild = (View) p;
+                }
                 if (p.getParent() instanceof ScrollContainer) {
                     mScrollContainer = (ScrollContainer) p.getParent();
-                    mScrollContainerChild = (View) p;
+                    if (mScrollContainerChild == null) {
+                        mScrollContainerChild = (View) p;
+                    }
                     break;
                 }
                 p = p.getParent();
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/stack/NotificationChildrenContainer.java b/packages/SystemUI/src/com/android/systemui/statusbar/stack/NotificationChildrenContainer.java
index cb0b848..ba191cd 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/stack/NotificationChildrenContainer.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/stack/NotificationChildrenContainer.java
@@ -670,6 +670,11 @@
         if (mNotificationHeader != null) {
             mNotificationHeader.setExpanded(childrenExpanded);
         }
+        final int count = mChildren.size();
+        for (int childIdx = 0; childIdx < count; childIdx++) {
+            ExpandableNotificationRow child = mChildren.get(childIdx);
+            child.setChildrenExpanded(childrenExpanded, false);
+        }
     }
 
     public void setNotificationParent(ExpandableNotificationRow parent) {
@@ -677,6 +682,10 @@
         mHeaderUtil = new NotificationHeaderUtil(mNotificationParent);
     }
 
+    public ExpandableNotificationRow getNotificationParent() {
+        return mNotificationParent;
+    }
+
     public NotificationHeaderView getHeaderView() {
         return mNotificationHeader;
     }
@@ -854,4 +863,23 @@
             child.setRemoved();
         }
     }
+
+    public int getPositionInLinearLayout(View childInGroup) {
+        int position = mNotificationHeaderMargin + mNotificatonTopPadding;
+
+        for (int i = 0; i < mChildren.size(); i++) {
+            ExpandableNotificationRow child = mChildren.get(i);
+            boolean notGone = child.getVisibility() != View.GONE;
+            if (notGone) {
+                position += mDividerHeight;
+            }
+            if (child == childInGroup) {
+                return position;
+            }
+            if (notGone) {
+                position += child.getIntrinsicHeight();
+            }
+        }
+        return 0;
+    }
 }
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 19f4074..b58538d03 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/stack/NotificationStackScrollLayout.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/stack/NotificationStackScrollLayout.java
@@ -610,9 +610,13 @@
             ExpandableView expandableView = (ExpandableView) mForcedScroll;
             int positionInLinearLayout = getPositionInLinearLayout(expandableView);
             int targetScroll = targetScrollForView(expandableView, positionInLinearLayout);
+            int outOfViewScroll = positionInLinearLayout + expandableView.getIntrinsicHeight();
 
             targetScroll = Math.max(0, Math.min(targetScroll, getScrollRange()));
-            if (mOwnScrollY < targetScroll || positionInLinearLayout < mOwnScrollY) {
+
+            // Only apply the scroll if we're scrolling the view upwards, or the view is so far up
+            // that it is not visible anymore.
+            if (mOwnScrollY < targetScroll || outOfViewScroll < mOwnScrollY) {
                 mOwnScrollY = targetScroll;
             }
         }
@@ -959,11 +963,13 @@
                 && (mIsExpanded || !((ExpandableNotificationRow) v).isPinned());
     }
 
+    /* Only ever called as a consequence of an expansion gesture in the shade. */
     @Override
     public void setUserExpandedChild(View v, boolean userExpanded) {
         if (v instanceof ExpandableNotificationRow) {
-            ((ExpandableNotificationRow) v).setUserExpanded(userExpanded,
-                    true /* allowChildrenExpansion */);
+            ExpandableNotificationRow row = (ExpandableNotificationRow) v;
+            row.setUserExpanded(userExpanded, true /* allowChildrenExpansion */);
+            row.onExpandedByGesture(userExpanded);
         }
     }
 
@@ -1032,9 +1038,13 @@
     @Override
     public boolean scrollTo(View v) {
         ExpandableView expandableView = (ExpandableView) v;
-        int targetScroll = targetScrollForView(expandableView, getPositionInLinearLayout(v));
+        int positionInLinearLayout = getPositionInLinearLayout(v);
+        int targetScroll = targetScrollForView(expandableView, positionInLinearLayout);
+        int outOfViewScroll = positionInLinearLayout + expandableView.getIntrinsicHeight();
 
-        if (mOwnScrollY < targetScroll) {
+        // Only apply the scroll if we're scrolling the view upwards, or the view is so far up
+        // that it is not visible anymore.
+        if (mOwnScrollY < targetScroll || outOfViewScroll < mOwnScrollY) {
             mScroller.startScroll(mScrollX, mOwnScrollY, 0, targetScroll - mOwnScrollY);
             mDontReportNextOverScroll = true;
             postInvalidateOnAnimation();
@@ -1062,6 +1072,10 @@
             // animating away. To work around that we'll wait until things have settled.
             removeCallbacks(mReclamp);
             postDelayed(mReclamp, 50);
+        } else if (mForcedScroll != null) {
+            // The scroll was requested before we got the actual inset - in case we need
+            // to scroll up some more do so now.
+            scrollTo(mForcedScroll);
         }
         return insets;
     }
@@ -2361,7 +2375,15 @@
         return view.getHeight();
     }
 
-    private int getPositionInLinearLayout(View requestedChild) {
+    private int getPositionInLinearLayout(View requestedView) {
+        ExpandableNotificationRow childInGroup = null;
+        ExpandableNotificationRow requestedRow = null;
+        if (isChildInGroup(requestedView)) {
+            // We're asking for a child in a group. Calculate the position of the parent first,
+            // then within the parent.
+            childInGroup = (ExpandableNotificationRow) requestedView;
+            requestedView = requestedRow = childInGroup.getNotificationParent();
+        }
         int position = 0;
         float previousIncreasedAmount = 0.0f;
         for (int i = 0; i < getChildCount(); i++) {
@@ -2377,7 +2399,10 @@
                 }
                 previousIncreasedAmount = increasedPaddingAmount;
             }
-            if (child == requestedChild) {
+            if (child == requestedView) {
+                if (requestedRow != null) {
+                    position += requestedRow.getPositionOfChild(childInGroup);
+                }
                 return position;
             }
             if (notGone) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/stack/StackScrollState.java b/packages/SystemUI/src/com/android/systemui/statusbar/stack/StackScrollState.java
index d6c5506..8f0cd8e 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/stack/StackScrollState.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/stack/StackScrollState.java
@@ -26,9 +26,8 @@
 import com.android.systemui.statusbar.ExpandableNotificationRow;
 import com.android.systemui.statusbar.ExpandableView;
 
-import java.util.HashMap;
 import java.util.List;
-import java.util.Map;
+import java.util.WeakHashMap;
 
 /**
  * A state of a {@link com.android.systemui.statusbar.stack.NotificationStackScrollLayout} which
@@ -39,12 +38,12 @@
     private static final String CHILD_NOT_FOUND_TAG = "StackScrollStateNoSuchChild";
 
     private final ViewGroup mHostView;
-    private Map<ExpandableView, StackViewState> mStateMap;
+    private WeakHashMap<ExpandableView, StackViewState> mStateMap;
     private final int mClearAllTopPadding;
 
     public StackScrollState(ViewGroup hostView) {
         mHostView = hostView;
-        mStateMap = new HashMap<ExpandableView, StackViewState>();
+        mStateMap = new WeakHashMap<>();
         mClearAllTopPadding = hostView.getContext().getResources().getDimensionPixelSize(
                 R.dimen.clear_all_padding_top);
     }
diff --git a/packages/SystemUI/src/com/android/systemui/tv/pip/PipControlButtonView.java b/packages/SystemUI/src/com/android/systemui/tv/pip/PipControlButtonView.java
index bcf2f67..80c593c 100644
--- a/packages/SystemUI/src/com/android/systemui/tv/pip/PipControlButtonView.java
+++ b/packages/SystemUI/src/com/android/systemui/tv/pip/PipControlButtonView.java
@@ -21,12 +21,11 @@
 import android.content.Context;
 import android.content.res.TypedArray;
 import android.util.AttributeSet;
-import android.view.Gravity;
 import android.view.LayoutInflater;
 import android.view.View.OnFocusChangeListener;
 import android.view.View;
 import android.widget.ImageView;
-import android.widget.LinearLayout;
+import android.widget.RelativeLayout;
 import android.widget.TextView;
 
 import com.android.systemui.R;
@@ -34,31 +33,28 @@
 /**
  * A view containing PIP controls including fullscreen, close, and media controls.
  */
-public class PipControlButtonView extends LinearLayout {
+public class PipControlButtonView extends RelativeLayout {
     private OnFocusChangeListener mFocusChangeListener;
-    private ImageView mButtonImageView;
+    private ImageView mIconImageView;
+    ImageView mButtonImageView;
     private TextView mDescriptionTextView;
-    private Animator mFocusGainAnimator;
-    private Animator mFocusLoseAnimator;
+    private Animator mTextFocusGainAnimator;
+    private Animator mButtonFocusGainAnimator;
+    private Animator mTextFocusLossAnimator;
+    private Animator mButtonFocusLossAnimator;
 
     private final OnFocusChangeListener mInternalFocusChangeListener =
             new OnFocusChangeListener() {
                 @Override
                 public void onFocusChange(View v, boolean hasFocus) {
                     if (hasFocus) {
-                        if (mFocusLoseAnimator.isStarted()) {
-                            mFocusLoseAnimator.cancel();
-                        }
-                        mFocusGainAnimator.start();
+                        startFocusGainAnimation();
                     } else {
-                        if (mFocusGainAnimator.isStarted()) {
-                            mFocusGainAnimator.cancel();
-                        }
-                        mFocusLoseAnimator.start();
+                        startFocusLossAnimation();
                     }
 
                     if (mFocusChangeListener != null) {
-                        mFocusChangeListener.onFocusChange(v, hasFocus);
+                        mFocusChangeListener.onFocusChange(PipControlButtonView.this, hasFocus);
                     }
                 }
             };
@@ -82,9 +78,7 @@
                 .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
         inflater.inflate(R.layout.tv_pip_control_button, this);
 
-        setOrientation(LinearLayout.VERTICAL);
-        setGravity(Gravity.CENTER);
-
+        mIconImageView = (ImageView) findViewById(R.id.icon);
         mButtonImageView = (ImageView) findViewById(R.id.button);
         mDescriptionTextView = (TextView) findViewById(R.id.desc);
 
@@ -103,12 +97,19 @@
         super.onFinishInflate();
         mButtonImageView.setOnFocusChangeListener(mInternalFocusChangeListener);
 
-        mFocusGainAnimator = AnimatorInflater.loadAnimator(getContext(),
-                R.anim.tv_pip_controls_text_focus_gain_animation);
-        mFocusGainAnimator.setTarget(mDescriptionTextView);
-        mFocusLoseAnimator = AnimatorInflater.loadAnimator(getContext(),
-                R.anim.tv_pip_controls_text_focus_lose_animation);
-        mFocusLoseAnimator.setTarget(mDescriptionTextView);
+        mTextFocusGainAnimator = AnimatorInflater.loadAnimator(getContext(),
+                R.anim.tv_pip_controls_focus_gain_animation);
+        mTextFocusGainAnimator.setTarget(mDescriptionTextView);
+        mButtonFocusGainAnimator = AnimatorInflater.loadAnimator(getContext(),
+                R.anim.tv_pip_controls_focus_gain_animation);
+        mButtonFocusGainAnimator.setTarget(mButtonImageView);
+
+        mTextFocusLossAnimator = AnimatorInflater.loadAnimator(getContext(),
+                R.anim.tv_pip_controls_focus_loss_animation);
+        mTextFocusLossAnimator.setTarget(mDescriptionTextView);
+        mButtonFocusLossAnimator = AnimatorInflater.loadAnimator(getContext(),
+                R.anim.tv_pip_controls_focus_loss_animation);
+        mButtonFocusLossAnimator.setTarget(mButtonImageView);
     }
 
     @Override
@@ -125,7 +126,7 @@
      * Sets the drawable for the button with the given resource id.
      */
     public void setImageResource(int resId) {
-        mButtonImageView.setImageResource(resId);
+        mIconImageView.setImageResource(resId);
     }
 
     /**
@@ -136,8 +137,51 @@
         mDescriptionTextView.setText(resId);
     }
 
-    @Override
-    public boolean isFocused() {
-        return mButtonImageView.isFocused();
+    private static void cancelAnimator(Animator animator) {
+        if (animator.isStarted()) {
+            animator.cancel();
+        }
+    }
+
+    /**
+     * Starts the focus gain animation.
+     */
+    public void startFocusGainAnimation() {
+        cancelAnimator(mButtonFocusLossAnimator);
+        cancelAnimator(mTextFocusLossAnimator);
+        mTextFocusGainAnimator.start();
+        if (mButtonImageView.getAlpha() < 1f) {
+            // If we had faded out the ripple drawable, run our manual focus change animation.
+            // See the comment at {@link #startFocusLossAnimation()} for the reason of manual
+            // animator.
+            mButtonFocusGainAnimator.start();
+        }
+    }
+
+    /**
+     * Starts the focus loss animation.
+     */
+    public void startFocusLossAnimation() {
+        cancelAnimator(mButtonFocusGainAnimator);
+        cancelAnimator(mTextFocusGainAnimator);
+        mTextFocusLossAnimator.start();
+        if (mButtonImageView.hasFocus()) {
+            // Button uses ripple that has the default animation for the focus changes.
+            // Howevever, it doesn't expose the API to fade out while it is focused,
+            // so we should manually run the fade out animation when PIP controls row loses focus.
+            mButtonFocusLossAnimator.start();
+        }
+    }
+
+    /**
+     * Resets to initial state.
+     */
+    public void reset() {
+        cancelAnimator(mButtonFocusGainAnimator);
+        cancelAnimator(mTextFocusGainAnimator);
+        cancelAnimator(mButtonFocusLossAnimator);
+        cancelAnimator(mTextFocusLossAnimator);
+        mButtonImageView.setAlpha(1f);
+        mDescriptionTextView.setAlpha(mButtonImageView.hasFocus() ? 1f : 0f);
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/tv/pip/PipControlsView.java b/packages/SystemUI/src/com/android/systemui/tv/pip/PipControlsView.java
index 5614bf9..71740ce 100644
--- a/packages/SystemUI/src/com/android/systemui/tv/pip/PipControlsView.java
+++ b/packages/SystemUI/src/com/android/systemui/tv/pip/PipControlsView.java
@@ -61,8 +61,7 @@
     private PipControlButtonView mCloseButtonView;
     private PipControlButtonView mPlayPauseButtonView;
 
-    private boolean mHasFocus;
-    private OnFocusChangeListener mOnChildFocusChangeListener;
+    private PipControlButtonView mFocusedChild;
 
     private MediaController.Callback mMediaControllerCallback = new MediaController.Callback() {
         @Override
@@ -80,8 +79,12 @@
 
     private final OnFocusChangeListener mFocusChangeListener = new OnFocusChangeListener() {
         @Override
-        public void onFocusChange(View v, boolean hasFocus) {
-            onChildViewFocusChanged();
+        public void onFocusChange(View view, boolean hasFocus) {
+            if (hasFocus) {
+                mFocusedChild = (PipControlButtonView) view;
+            } else if (mFocusedChild == view) {
+                mFocusedChild = null;
+            }
         }
     };
 
@@ -200,23 +203,13 @@
     }
 
     /**
-     * Sets a listener to be invoked when {@link android.view.View.hasFocus()} is changed.
+     * Resets to initial state.
      */
-    public void setOnChildFocusChangeListener(OnFocusChangeListener listener) {
-        mOnChildFocusChangeListener = listener;
-    }
-
-    private void onChildViewFocusChanged() {
-        // At this moment, hasFocus() returns true although there's no focused child.
-        boolean hasFocus = (mFullButtonView != null && mFullButtonView.isFocused())
-                || (mPlayPauseButtonView != null && mPlayPauseButtonView.isFocused())
-                || (mCloseButtonView != null && mCloseButtonView.isFocused());
-        if (mHasFocus != hasFocus) {
-            mHasFocus = hasFocus;
-            if (mOnChildFocusChangeListener != null) {
-                mOnChildFocusChangeListener.onFocusChange(getFocusedChild(), mHasFocus);
-            }
-        }
+    public void reset() {
+        mFullButtonView.reset();
+        mCloseButtonView.reset();
+        mPlayPauseButtonView.reset();
+        mFullButtonView.requestFocus();
     }
 
     /**
@@ -225,4 +218,11 @@
     public void setListener(Listener listener) {
         mListener = listener;
     }
+
+    /**
+     * Returns the focused control button view to animate focused button.
+     */
+    PipControlButtonView getFocusedButton() {
+        return mFocusedChild;
+    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/tv/pip/PipManager.java b/packages/SystemUI/src/com/android/systemui/tv/pip/PipManager.java
index 476598d..30622d2 100644
--- a/packages/SystemUI/src/com/android/systemui/tv/pip/PipManager.java
+++ b/packages/SystemUI/src/com/android/systemui/tv/pip/PipManager.java
@@ -126,7 +126,6 @@
     private int mSuspendPipResizingReason;
 
     private Context mContext;
-    private SystemServicesProxy mSystemServiceProxy;
     private PipRecentsOverlayManager mPipRecentsOverlayManager;
     private IActivityManager mActivityManager;
     private MediaSessionManager mMediaSessionManager;
@@ -213,8 +212,7 @@
         mPipBounds = mDefaultPipBounds;
 
         mActivityManager = ActivityManagerNative.getDefault();
-        mSystemServiceProxy = SystemServicesProxy.getInstance(context);
-        mSystemServiceProxy.registerTaskStackListener(mTaskStackListener);
+        SystemServicesProxy.getInstance(context).registerTaskStackListener(mTaskStackListener);
         IntentFilter intentFilter = new IntentFilter();
         intentFilter.addAction(Intent.ACTION_MEDIA_RESOURCE_GRANTED);
         mContext.registerReceiver(mBroadcastReceiver, intentFilter);
diff --git a/packages/SystemUI/src/com/android/systemui/tv/pip/PipRecentsControlsView.java b/packages/SystemUI/src/com/android/systemui/tv/pip/PipRecentsControlsView.java
index df44dc1..ffe96afa 100644
--- a/packages/SystemUI/src/com/android/systemui/tv/pip/PipRecentsControlsView.java
+++ b/packages/SystemUI/src/com/android/systemui/tv/pip/PipRecentsControlsView.java
@@ -48,12 +48,12 @@
         abstract void onBackPressed();
     }
 
-    final PipManager mPipManager = PipManager.getInstance();
+    private final PipManager mPipManager = PipManager.getInstance();
     private Listener mListener;
     private PipControlsView mPipControlsView;
     private View mScrim;
     private Animator mFocusGainAnimator;
-    private AnimatorSet mFocusLoseAnimatorSet;
+    private AnimatorSet mFocusLossAnimatorSet;
 
     public PipRecentsControlsView(Context context) {
         this(context, null, 0, 0);
@@ -80,12 +80,12 @@
         mScrim = findViewById(R.id.scrim);
 
         mFocusGainAnimator = loadAnimator(mPipControlsView,
-                      R.anim.tv_pip_controls_in_recents_focus_gain_animation);
+                R.anim.tv_pip_controls_in_recents_focus_gain_animation);
 
-        mFocusLoseAnimatorSet = new AnimatorSet();
-        mFocusLoseAnimatorSet.playSequentially(
+        mFocusLossAnimatorSet = new AnimatorSet();
+        mFocusLossAnimatorSet.playSequentially(
                 loadAnimator(mPipControlsView,
-                        R.anim.tv_pip_controls_in_recents_focus_lose_animation),
+                        R.anim.tv_pip_controls_in_recents_focus_loss_animation),
                 loadAnimator(mScrim, R.anim.tv_pip_controls_in_recents_scrim_fade_in_animation));
 
         Rect pipBounds = mPipManager.getRecentsFocusedPipBounds();
@@ -99,21 +99,29 @@
     }
 
     /**
-     * Starts focus gaining animation.
+     * Starts focus gain animation.
      */
     public void startFocusGainAnimation() {
         // Hides the scrim view as soon as possible, before the PIP resize animation starts.
         // If we don't, PIP will be moved down a bit and a gap between the scrim and PIP will be
         // shown at the bottom of the PIP.
         mScrim.setAlpha(0);
-        startAnimator(mFocusGainAnimator, mFocusLoseAnimatorSet);
+        PipControlButtonView focus = mPipControlsView.getFocusedButton();
+        if (focus != null) {
+            focus.startFocusGainAnimation();
+        }
+        startAnimator(mFocusGainAnimator, mFocusLossAnimatorSet);
     }
 
     /**
-     * Starts focus losing animation.
+     * Starts focus loss animation.
      */
-    public void startFocusLoseAnimation() {
-        startAnimator(mFocusLoseAnimatorSet, mFocusGainAnimator);
+    public void startFocusLossAnimation() {
+        PipControlButtonView focus = mPipControlsView.getFocusedButton();
+        if (focus != null) {
+            focus.startFocusLossAnimation();
+        }
+        startAnimator(mFocusLossAnimatorSet, mFocusGainAnimator);
     }
 
     /**
@@ -121,14 +129,14 @@
      */
     public void reset() {
         cancelAnimator(mFocusGainAnimator);
-        cancelAnimator(mFocusLoseAnimatorSet);
+        cancelAnimator(mFocusLossAnimatorSet);
 
         // Reset to initial state (i.e. end of focused)
-        requestFocus();
+        mScrim.setAlpha(0);
         mPipControlsView.setTranslationY(0);
         mPipControlsView.setScaleX(1);
         mPipControlsView.setScaleY(1);
-        mScrim.setAlpha(0);
+        mPipControlsView.reset();
     }
 
     private static void startAnimator(Animator animator, Animator previousAnimator) {
@@ -153,13 +161,20 @@
 
     @Override
     public boolean dispatchKeyEvent(KeyEvent event) {
-        if (!event.isCanceled()
-                && event.getKeyCode() == KeyEvent.KEYCODE_BACK
-                && event.getAction() == KeyEvent.ACTION_UP) {
-            if (mPipControlsView.mListener != null) {
-                ((PipRecentsControlsView.Listener) mPipControlsView.mListener).onBackPressed();
+        if (!event.isCanceled()) {
+            if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
+                    && event.getAction() == KeyEvent.ACTION_UP) {
+                if (mPipControlsView.mListener != null) {
+                    ((PipRecentsControlsView.Listener) mPipControlsView.mListener).onBackPressed();
+                }
+                return true;
+            } else if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_DOWN) {
+                if (event.getAction() == KeyEvent.ACTION_DOWN) {
+                    mPipManager.getPipRecentsOverlayManager().clearFocus();
+                }
+                // Consume the down event always to prevent warning logs from ViewRootImpl.
+                return true;
             }
-            return true;
         }
         return super.dispatchKeyEvent(event);
     }
diff --git a/packages/SystemUI/src/com/android/systemui/tv/pip/PipRecentsOverlayManager.java b/packages/SystemUI/src/com/android/systemui/tv/pip/PipRecentsOverlayManager.java
index 6e4a593..895b8a2 100644
--- a/packages/SystemUI/src/com/android/systemui/tv/pip/PipRecentsOverlayManager.java
+++ b/packages/SystemUI/src/com/android/systemui/tv/pip/PipRecentsOverlayManager.java
@@ -18,15 +18,20 @@
 
 import android.content.Context;
 import android.graphics.PixelFormat;
+import android.graphics.Rect;
 import android.util.Log;
 import android.view.LayoutInflater;
 import android.view.View;
-import android.view.accessibility.AccessibilityEvent;
-import android.view.WindowManager.LayoutParams;
 import android.view.WindowManager;
+import android.view.WindowManager.LayoutParams;
+import android.view.accessibility.AccessibilityEvent;
 
 import com.android.systemui.R;
+import com.android.systemui.recents.misc.SystemServicesProxy;
 
+import static android.view.Gravity.CENTER_HORIZONTAL;
+import static android.view.Gravity.TOP;
+import static android.view.View.MeasureSpec.UNSPECIFIED;
 import static com.android.systemui.tv.pip.PipManager.STATE_PIP_OVERLAY;
 import static com.android.systemui.tv.pip.PipManager.STATE_PIP_RECENTS;
 import static com.android.systemui.tv.pip.PipManager.STATE_PIP_RECENTS_FOCUSED;
@@ -42,13 +47,16 @@
 
     private final PipManager mPipManager = PipManager.getInstance();
     private final WindowManager mWindowManager;
+    private final SystemServicesProxy mSystemServicesProxy;
     private View mOverlayView;
     private PipRecentsControlsView mPipControlsView;
     private View mRecentsView;
+    private boolean mTalkBackEnabled;
 
-    private final LayoutParams mPipRecentsControlsViewLayoutParams;
-    private final LayoutParams mPipRecentsControlsViewFocusedLayoutParams;
+    private LayoutParams mPipRecentsControlsViewLayoutParams;
+    private LayoutParams mPipRecentsControlsViewFocusedLayoutParams;
 
+    private boolean mHasFocusableInRecents;
     private boolean mIsPipRecentsOverlayShown;
     private boolean mIsRecentsShown;
     private boolean mIsPipFocusedInRecent;
@@ -72,18 +80,7 @@
 
     PipRecentsOverlayManager(Context context) {
         mWindowManager = (WindowManager) context.getSystemService(WindowManager.class);
-
-        mPipRecentsControlsViewLayoutParams = new WindowManager.LayoutParams(
-                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT,
-                LayoutParams.TYPE_SYSTEM_DIALOG,
-                LayoutParams.FLAG_NOT_FOCUSABLE | LayoutParams.FLAG_NOT_TOUCHABLE,
-                PixelFormat.TRANSLUCENT);
-        mPipRecentsControlsViewFocusedLayoutParams = new WindowManager.LayoutParams(
-                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT,
-                LayoutParams.TYPE_SYSTEM_DIALOG,
-                0,
-                PixelFormat.TRANSLUCENT);
-
+        mSystemServicesProxy = SystemServicesProxy.getInstance(context);
         initViews(context);
     }
 
@@ -101,6 +98,20 @@
                 }
             }
         });
+
+        mOverlayView.measure(UNSPECIFIED, UNSPECIFIED);
+        mPipRecentsControlsViewLayoutParams = new WindowManager.LayoutParams(
+                mOverlayView.getMeasuredWidth(), mOverlayView.getMeasuredHeight(),
+                LayoutParams.TYPE_SYSTEM_DIALOG,
+                LayoutParams.FLAG_NOT_FOCUSABLE | LayoutParams.FLAG_NOT_TOUCHABLE,
+                PixelFormat.TRANSLUCENT);
+        mPipRecentsControlsViewLayoutParams.gravity = TOP | CENTER_HORIZONTAL;
+        mPipRecentsControlsViewFocusedLayoutParams = new WindowManager.LayoutParams(
+                mOverlayView.getMeasuredWidth(), mOverlayView.getMeasuredHeight(),
+                LayoutParams.TYPE_SYSTEM_DIALOG,
+                0,
+                PixelFormat.TRANSLUCENT);
+        mPipRecentsControlsViewFocusedLayoutParams.gravity = TOP | CENTER_HORIZONTAL;
     }
 
     /**
@@ -111,9 +122,10 @@
         if (mIsPipRecentsOverlayShown) {
             return;
         }
+        mTalkBackEnabled = mSystemServicesProxy.isTouchExplorationEnabled();
+        mRecentsView.setVisibility(mTalkBackEnabled ? View.VISIBLE : View.GONE);
         mIsPipRecentsOverlayShown = true;
         mIsPipFocusedInRecent = true;
-        mPipControlsView.reset();
         mWindowManager.addView(mOverlayView, mPipRecentsControlsViewFocusedLayoutParams);
     }
 
@@ -126,50 +138,46 @@
             return;
         }
         mWindowManager.removeView(mOverlayView);
+        // Resets the controls view when its removed.
+        // If not, changing focus in reset will be show animation when Recents is resumed.
+        mPipControlsView.reset();
         mIsPipRecentsOverlayShown = false;
     }
 
     /**
      * Request focus to the PIP Recents overlay.
-     * Called when the PIP view in {@link com.android.systemui.recents.tv.RecentsTvActivity}
-     * is focused.
      * This should be called only by {@link com.android.systemui.recents.tv.RecentsTvActivity}.
-     * @param allowRecentsFocusable {@code true} if Recents can have focus. (i.e. Has a recent task)
+     * @param hasFocusableInRecents {@code true} if Recents can have focus. (i.e. Has a recent task)
      */
-    public void requestFocus(boolean allowRecentsFocusable) {
-        mRecentsView.setVisibility(allowRecentsFocusable ? View.VISIBLE : View.GONE);
+    public void requestFocus(boolean hasFocusableInRecents) {
+        mHasFocusableInRecents = hasFocusableInRecents;
         if (!mIsPipRecentsOverlayShown || !mIsRecentsShown || mIsPipFocusedInRecent
                 || !mPipManager.isPipShown()) {
             return;
         }
         mIsPipFocusedInRecent = true;
-        mPipManager.resizePinnedStack(STATE_PIP_RECENTS_FOCUSED);
-
-        mWindowManager.updateViewLayout(mOverlayView, mPipRecentsControlsViewFocusedLayoutParams);
-        mPipControlsView.requestFocus();
-        mPipControlsView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
         mPipControlsView.startFocusGainAnimation();
+        mWindowManager.updateViewLayout(mOverlayView, mPipRecentsControlsViewFocusedLayoutParams);
+        mPipManager.resizePinnedStack(STATE_PIP_RECENTS_FOCUSED);
+        if (mTalkBackEnabled) {
+            mPipControlsView.requestFocus();
+            mPipControlsView.sendAccessibilityEvent(
+                    AccessibilityEvent.TYPE_VIEW_FOCUSED);
+        }
     }
 
     /**
      * Request focus to the PIP Recents overlay.
-     * Called when the PIP view in {@link com.android.systemui.recents.tv.RecentsTvActivity}
-     * is focused.
-     * This should be called only by {@link com.android.systemui.recents.tv.RecentsTvActivity}.
      */
     public void clearFocus() {
         if (!mIsPipRecentsOverlayShown || !mIsRecentsShown || !mIsPipFocusedInRecent
-                || !mPipManager.isPipShown()) {
+                || !mPipManager.isPipShown() || !mHasFocusableInRecents) {
             return;
         }
-        if (!mRecentsView.hasFocus()) {
-            // Let mRecentsView's focus listener handle clearFocus().
-            mRecentsView.requestFocus();
-        }
         mIsPipFocusedInRecent = false;
-        mPipManager.resizePinnedStack(STATE_PIP_RECENTS);
+        mPipControlsView.startFocusLossAnimation();
         mWindowManager.updateViewLayout(mOverlayView, mPipRecentsControlsViewLayoutParams);
-        mPipControlsView.startFocusLoseAnimation();
+        mPipManager.resizePinnedStack(STATE_PIP_RECENTS);
         if (mCallback != null) {
             mCallback.onRecentsFocused();
         }
diff --git a/packages/SystemUI/src/com/android/systemui/volume/VolumeDialog.java b/packages/SystemUI/src/com/android/systemui/volume/VolumeDialog.java
index 65b93c7..f2cd885 100644
--- a/packages/SystemUI/src/com/android/systemui/volume/VolumeDialog.java
+++ b/packages/SystemUI/src/com/android/systemui/volume/VolumeDialog.java
@@ -396,6 +396,7 @@
         mSpTexts.add(row.header);
         row.slider = (SeekBar) row.view.findViewById(R.id.volume_row_slider);
         row.slider.setOnSeekBarChangeListener(new VolumeSeekBarChangeListener(row));
+        row.anim = null;
 
         // forward events above the slider into the slider
         row.view.setOnTouchListener(new OnTouchListener() {
diff --git a/packages/VpnDialogs/AndroidManifest.xml b/packages/VpnDialogs/AndroidManifest.xml
index 08257b6..a3d27ce 100644
--- a/packages/VpnDialogs/AndroidManifest.xml
+++ b/packages/VpnDialogs/AndroidManifest.xml
@@ -20,6 +20,7 @@
         package="com.android.vpndialogs">
 
     <uses-permission android:name="android.permission.CONTROL_VPN" />
+    <uses-permission android:name="android.permission.CONNECTIVITY_INTERNAL" />
 
     <application android:label="VpnDialogs"
             android:allowBackup="false" >
diff --git a/packages/VpnDialogs/src/com/android/vpndialogs/ConfirmDialog.java b/packages/VpnDialogs/src/com/android/vpndialogs/ConfirmDialog.java
index f0ca441..72ce9c4 100644
--- a/packages/VpnDialogs/src/com/android/vpndialogs/ConfirmDialog.java
+++ b/packages/VpnDialogs/src/com/android/vpndialogs/ConfirmDialog.java
@@ -25,6 +25,7 @@
 import android.os.RemoteException;
 import android.os.ServiceManager;
 import android.os.UserHandle;
+import android.os.UserManager;
 import android.text.Html;
 import android.text.Html.ImageGetter;
 import android.util.Log;
@@ -55,6 +56,16 @@
             finish();
             return;
         }
+        if (UserManager.get(this).hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
+            finish();
+            return;
+        }
+        final String alwaysOnVpnPackage = getAlwaysOnVpnPackage();
+        // Can't prepare new vpn app when another vpn is always-on
+        if (alwaysOnVpnPackage != null && !alwaysOnVpnPackage.equals(mPackage)) {
+            finish();
+            return;
+        }
         View view = View.inflate(this, R.layout.confirm, null);
         ((TextView) view.findViewById(R.id.warning)).setText(
                 Html.fromHtml(getString(R.string.warning, getVpnLabel()),
@@ -71,6 +82,16 @@
         button.setFilterTouchesWhenObscured(true);
     }
 
+    private String getAlwaysOnVpnPackage() {
+        try {
+           return mService.getAlwaysOnVpnPackage(UserHandle.myUserId());
+        } catch (RemoteException e) {
+            Log.e(TAG, "fail to call getAlwaysOnVpnPackage", e);
+            // Fallback to null to show the dialog
+            return null;
+        }
+    }
+
     private boolean prepareVpn() {
         try {
             return mService.prepareVpn(mPackage, null, UserHandle.myUserId());
diff --git a/proto/src/metrics_constants.proto b/proto/src/metrics_constants.proto
index 40f3a9d..3a14ad2 100644
--- a/proto/src/metrics_constants.proto
+++ b/proto/src/metrics_constants.proto
@@ -2206,6 +2206,19 @@
     // Settings launched from expanded quick settings.
     ACTION_QS_EXPANDED_SETTINGS_LAUNCH = 406;
 
+    // Notification expansion state toggled by the expand affordance.
+    ACTION_NOTIFICATION_EXPANDER = 407;
+
+    // Notification group expansion state toggled by the expand affordance.
+    ACTION_NOTIFICATION_GROUP_EXPANDER = 408;
+
+
+    // Notification expansion state toggled by the expand gesture.
+    ACTION_NOTIFICATION_GESTURE_EXPANDER = 409;
+
+    // Notification group expansion state toggled by the expand gesture.
+    ACTION_NOTIFICATION_GROUP_GESTURE_EXPANDER = 410;
+
     // ---- End N Constants, all N constants go above this line ----
 
     // ------- Begin N App Disambig Shade -----
diff --git a/services/backup/java/com/android/server/backup/BackupManagerService.java b/services/backup/java/com/android/server/backup/BackupManagerService.java
index 1ab8160..acc2ec3 100644
--- a/services/backup/java/com/android/server/backup/BackupManagerService.java
+++ b/services/backup/java/com/android/server/backup/BackupManagerService.java
@@ -146,6 +146,7 @@
 import java.util.Set;
 import java.util.TreeMap;
 import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.concurrent.atomic.AtomicLong;
@@ -4664,7 +4665,7 @@
         // a standalone thread.  The  runner owns this half of the pipe, and closes
         // it to indicate EOD to the other end.
         class SinglePackageBackupPreflight implements BackupRestoreTask, FullBackupPreflight {
-            final AtomicLong mResult = new AtomicLong();
+            final AtomicLong mResult = new AtomicLong(BackupTransport.AGENT_ERROR);
             final CountDownLatch mLatch = new CountDownLatch(1);
             final IBackupTransport mTransport;
 
@@ -4684,8 +4685,13 @@
                     }
                     agent.doMeasureFullBackup(token, mBackupManagerBinder);
 
-                    // now wait to get our result back
-                    mLatch.await();
+                    // Now wait to get our result back.  If this backstop timeout is reached without
+                    // the latch being thrown, flow will continue as though a result or "normal"
+                    // timeout had been produced.  In case of a real backstop timeout, mResult
+                    // will still contain the value it was constructed with, AGENT_ERROR, which
+                    // intentionaly falls into the "just report failure" code.
+                    mLatch.await(TIMEOUT_FULL_BACKUP_INTERVAL, TimeUnit.MILLISECONDS);
+
                     long totalSize = mResult.get();
                     // If preflight timed out, mResult will contain error code as int.
                     if (totalSize < 0) {
@@ -4738,7 +4744,7 @@
             @Override
             public long getExpectedSizeOrErrorCode() {
                 try {
-                    mLatch.await();
+                    mLatch.await(TIMEOUT_FULL_BACKUP_INTERVAL, TimeUnit.MILLISECONDS);
                     return mResult.get();
                 } catch (InterruptedException e) {
                     return BackupTransport.NO_MORE_DATA;
@@ -4763,8 +4769,8 @@
                 mPreflight = new SinglePackageBackupPreflight(transport);
                 mPreflightLatch = new CountDownLatch(1);
                 mBackupLatch = new CountDownLatch(1);
-                mPreflightResult = BackupTransport.TRANSPORT_OK;
-                mBackupResult = BackupTransport.TRANSPORT_OK;
+                mPreflightResult = BackupTransport.AGENT_ERROR;
+                mBackupResult = BackupTransport.AGENT_ERROR;
             }
 
             @Override
@@ -4801,7 +4807,7 @@
             // otherwise return negative error code.
             long getPreflightResultBlocking() {
                 try {
-                    mPreflightLatch.await();
+                    mPreflightLatch.await(TIMEOUT_FULL_BACKUP_INTERVAL, TimeUnit.MILLISECONDS);
                     if (mPreflightResult == BackupTransport.TRANSPORT_OK) {
                         return mPreflight.getExpectedSizeOrErrorCode();
                     } else {
@@ -4814,7 +4820,7 @@
 
             int getBackupResultBlocking() {
                 try {
-                    mBackupLatch.await();
+                    mBackupLatch.await(TIMEOUT_FULL_BACKUP_INTERVAL, TimeUnit.MILLISECONDS);
                     return mBackupResult;
                 } catch (InterruptedException e) {
                     return BackupTransport.AGENT_ERROR;
diff --git a/services/core/java/com/android/server/BluetoothManagerService.java b/services/core/java/com/android/server/BluetoothManagerService.java
index 1f88be5..831ce01 100644
--- a/services/core/java/com/android/server/BluetoothManagerService.java
+++ b/services/core/java/com/android/server/BluetoothManagerService.java
@@ -425,6 +425,24 @@
         return false;
     }
 
+    public int getState() {
+        if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
+                (!checkIfCallerIsForegroundUser())) {
+            Slog.w(TAG, "getState(): not allowed for non-active and non system user");
+            return BluetoothAdapter.STATE_OFF;
+        }
+
+        try {
+            mBluetoothLock.readLock().lock();
+            if (mBluetooth != null) return mBluetooth.getState();
+        } catch (RemoteException e) {
+            Slog.e(TAG, "getState()", e);
+        } finally {
+            mBluetoothLock.readLock().unlock();
+        }
+        return BluetoothAdapter.STATE_OFF;
+    }
+
     class ClientDeathRecipient implements IBinder.DeathRecipient {
         public void binderDied() {
             if (DBG) Slog.d(TAG, "Binder is dead -  unregister Ble App");
diff --git a/services/core/java/com/android/server/DeviceIdleController.java b/services/core/java/com/android/server/DeviceIdleController.java
index 69960c7..bb966f7 100644
--- a/services/core/java/com/android/server/DeviceIdleController.java
+++ b/services/core/java/com/android/server/DeviceIdleController.java
@@ -542,6 +542,8 @@
                 "mms_temp_app_whitelist_duration";
         private static final String KEY_SMS_TEMP_APP_WHITELIST_DURATION =
                 "sms_temp_app_whitelist_duration";
+        private static final String KEY_NOTIFICATION_WHITELIST_DURATION =
+                "notification_whitelist_duration";
 
         /**
          * This is the time, after becoming inactive, that we go in to the first
@@ -752,6 +754,14 @@
          */
         public long SMS_TEMP_APP_WHITELIST_DURATION;
 
+        /**
+         * Amount of time we would like to whitelist an app that is handling a
+         * {@link android.app.PendingIntent} triggered by a {@link android.app.Notification}.
+         * @see Settings.Global#DEVICE_IDLE_CONSTANTS
+         * @see #KEY_NOTIFICATION_WHITELIST_DURATION
+         */
+        public long NOTIFICATION_WHITELIST_DURATION;
+
         private final ContentResolver mResolver;
         private final boolean mHasWatch;
         private final KeyValueListParser mParser = new KeyValueListParser(',');
@@ -842,6 +852,8 @@
                         KEY_MMS_TEMP_APP_WHITELIST_DURATION, 60 * 1000L);
                 SMS_TEMP_APP_WHITELIST_DURATION = mParser.getLong(
                         KEY_SMS_TEMP_APP_WHITELIST_DURATION, 20 * 1000L);
+                NOTIFICATION_WHITELIST_DURATION = mParser.getLong(
+                        KEY_NOTIFICATION_WHITELIST_DURATION, 30 * 1000L);
             }
         }
 
@@ -945,6 +957,10 @@
             pw.print("    "); pw.print(KEY_SMS_TEMP_APP_WHITELIST_DURATION); pw.print("=");
             TimeUtils.formatDuration(SMS_TEMP_APP_WHITELIST_DURATION, pw);
             pw.println();
+
+            pw.print("    "); pw.print(KEY_NOTIFICATION_WHITELIST_DURATION); pw.print("=");
+            TimeUtils.formatDuration(NOTIFICATION_WHITELIST_DURATION, pw);
+            pw.println();
         }
     }
 
@@ -1252,6 +1268,10 @@
             addPowerSaveTempWhitelistAppDirectInternal(0, appId, duration, sync, reason);
         }
 
+        public long getNotificationWhitelistDuration() {
+            return mConstants.NOTIFICATION_WHITELIST_DURATION;
+        }
+
         public void setNetworkPolicyTempWhitelistCallback(Runnable callback) {
             setNetworkPolicyTempWhitelistCallbackInternal(callback);
         }
@@ -1632,7 +1652,7 @@
             }
             entry.first.value = timeNow + duration;
             if (DEBUG) {
-                Slog.d(TAG, "Adding AppId " + appId + " to temp whitelist");
+                Slog.d(TAG, "Adding AppId " + appId + " to temp whitelist. New entry: " + newEntry);
             }
             if (newEntry) {
                 // No pending timeout for the app id, post a delayed message
@@ -1665,12 +1685,18 @@
     }
 
     private void postTempActiveTimeoutMessage(int uid, long delay) {
+        if (DEBUG) {
+            Slog.d(TAG, "postTempActiveTimeoutMessage: uid=" + uid + ", delay=" + delay);
+        }
         mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_TEMP_APP_WHITELIST_TIMEOUT, uid, 0),
                 delay);
     }
 
     void checkTempAppWhitelistTimeout(int uid) {
         final long timeNow = SystemClock.elapsedRealtime();
+        if (DEBUG) {
+            Slog.d(TAG, "checkTempAppWhitelistTimeout: uid=" + uid + ", timeNow=" + timeNow);
+        }
         synchronized (this) {
             Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.get(uid);
             if (entry == null) {
@@ -1694,6 +1720,9 @@
                 }
             } else {
                 // Need more time
+                if (DEBUG) {
+                    Slog.d(TAG, "Time to remove UID " + uid + ": " + entry.first.value);
+                }
                 postTempActiveTimeoutMessage(uid, entry.first.value - timeNow);
             }
         }
@@ -2514,6 +2543,8 @@
         pw.println("    Print currently whitelisted apps.");
         pw.println("  whitelist [package ...]");
         pw.println("    Add (prefix with +) or remove (prefix with -) packages.");
+        pw.println("  tempwhitelist");
+        pw.println("    Print packages that are temporarily whitelisted.");
         pw.println("  tempwhitelist [-u] [package ..]");
         pw.println("    Temporarily place packages in whitelist for 10 seconds.");
     }
@@ -2817,8 +2848,7 @@
                     pw.println("Failed: " + re);
                 }
             } else {
-                pw.println("At least one package name must be specified");
-                return -1;
+                dumpTempWhitelistSchedule(pw, false);
             }
         } else {
             return shell.handleDefaultCommands(cmd);
@@ -2943,20 +2973,8 @@
                     pw.println();
                 }
             }
-            size = mTempWhitelistAppIdEndTimes.size();
-            if (size > 0) {
-                pw.println("  Temp whitelist schedule:");
-                final long timeNow = SystemClock.elapsedRealtime();
-                for (int i = 0; i < size; i++) {
-                    pw.print("    UID=");
-                    pw.print(mTempWhitelistAppIdEndTimes.keyAt(i));
-                    pw.print(": ");
-                    Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.valueAt(i);
-                    TimeUtils.formatDuration(entry.first.value, timeNow, pw);
-                    pw.print(" - ");
-                    pw.println(entry.second);
-                }
-            }
+            dumpTempWhitelistSchedule(pw, true);
+
             size = mTempWhitelistAppIdArray != null ? mTempWhitelistAppIdArray.length : 0;
             if (size > 0) {
                 pw.println("  Temp whitelist app ids:");
@@ -2968,7 +2986,7 @@
             }
 
             pw.print("  mLightEnabled="); pw.print(mLightEnabled);
-            pw.print(" mDeepEnabled="); pw.println(mDeepEnabled);
+            pw.print("  mDeepEnabled="); pw.println(mDeepEnabled);
             pw.print("  mForceIdle="); pw.println(mForceIdle);
             pw.print("  mMotionSensor="); pw.println(mMotionSensor);
             pw.print("  mCurDisplay="); pw.println(mCurDisplay);
@@ -3040,4 +3058,26 @@
             }
         }
     }
-}
+
+    void dumpTempWhitelistSchedule(PrintWriter pw, boolean printTitle) {
+        final int size = mTempWhitelistAppIdEndTimes.size();
+        if (size > 0) {
+            String prefix = "";
+            if (printTitle) {
+                pw.println("  Temp whitelist schedule:");
+                prefix = "    ";
+            }
+            final long timeNow = SystemClock.elapsedRealtime();
+            for (int i = 0; i < size; i++) {
+                pw.print(prefix);
+                pw.print("UID=");
+                pw.print(mTempWhitelistAppIdEndTimes.keyAt(i));
+                pw.print(": ");
+                Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.valueAt(i);
+                TimeUtils.formatDuration(entry.first.value, timeNow, pw);
+                pw.print(" - ");
+                pw.println(entry.second);
+            }
+        }
+    }
+ }
diff --git a/services/core/java/com/android/server/InputMethodManagerService.java b/services/core/java/com/android/server/InputMethodManagerService.java
index 727bf5c..5d8fe7c 100644
--- a/services/core/java/com/android/server/InputMethodManagerService.java
+++ b/services/core/java/com/android/server/InputMethodManagerService.java
@@ -159,6 +159,7 @@
     static final int MSG_BIND_INPUT = 1010;
     static final int MSG_SHOW_SOFT_INPUT = 1020;
     static final int MSG_HIDE_SOFT_INPUT = 1030;
+    static final int MSG_HIDE_CURRENT_INPUT_METHOD = 1035;
     static final int MSG_ATTACH_TOKEN = 1040;
     static final int MSG_CREATE_SESSION = 1050;
 
@@ -2846,6 +2847,11 @@
                 }
                 args.recycle();
                 return true;
+            case MSG_HIDE_CURRENT_INPUT_METHOD:
+                synchronized (mMethodMap) {
+                    hideCurrentInputLocked(0, null);
+                }
+                return true;
             case MSG_ATTACH_TOKEN:
                 args = (SomeArgs)msg.obj;
                 try {
@@ -3880,6 +3886,12 @@
             mHandler.sendMessage(mHandler.obtainMessage(MSG_SWITCH_IME,
                     forwardDirection ? 1 : 0, 0));
         }
+
+        @Override
+        public void hideCurrentInputMethod() {
+            mHandler.removeMessages(MSG_HIDE_CURRENT_INPUT_METHOD);
+            mHandler.sendEmptyMessage(MSG_HIDE_CURRENT_INPUT_METHOD);
+        }
     }
 
     private static String imeWindowStatusToString(final int imeWindowVis) {
diff --git a/services/core/java/com/android/server/LockSettingsService.java b/services/core/java/com/android/server/LockSettingsService.java
index fbbdccc..fb1021e 100644
--- a/services/core/java/com/android/server/LockSettingsService.java
+++ b/services/core/java/com/android/server/LockSettingsService.java
@@ -50,6 +50,7 @@
 import android.os.Process;
 import android.os.RemoteException;
 import android.os.storage.IMountService;
+import android.os.storage.StorageManager;
 import android.os.ServiceManager;
 import android.os.SystemProperties;
 import android.os.UserHandle;
@@ -355,6 +356,10 @@
     private void showEncryptionNotification(UserHandle user, CharSequence title, CharSequence message,
             CharSequence detail, PendingIntent intent) {
         if (DEBUG) Slog.v(TAG, "showing encryption notification, user: " + user.getIdentifier());
+
+        // Suppress all notifications on non-FBE devices for now
+        if (!StorageManager.isFileEncryptedNativeOrEmulated()) return;
+
         Notification notification = new Notification.Builder(mContext)
                 .setSmallIcon(com.android.internal.R.drawable.ic_user_secure)
                 .setWhen(0)
diff --git a/services/core/java/com/android/server/NetworkScoreService.java b/services/core/java/com/android/server/NetworkScoreService.java
index 2a78f90..3745e0b 100644
--- a/services/core/java/com/android/server/NetworkScoreService.java
+++ b/services/core/java/com/android/server/NetworkScoreService.java
@@ -17,12 +17,10 @@
 package com.android.server;
 
 import android.Manifest.permission;
-import android.content.BroadcastReceiver;
 import android.content.ComponentName;
 import android.content.ContentResolver;
 import android.content.Context;
 import android.content.Intent;
-import android.content.IntentFilter;
 import android.content.ServiceConnection;
 import android.content.pm.PackageManager;
 import android.net.INetworkScoreCache;
@@ -33,7 +31,6 @@
 import android.net.ScoredNetwork;
 import android.os.Binder;
 import android.os.IBinder;
-import android.os.PatternMatcher;
 import android.os.RemoteException;
 import android.os.UserHandle;
 import android.provider.Settings;
@@ -42,6 +39,7 @@
 
 import com.android.internal.R;
 import com.android.internal.annotations.GuardedBy;
+import com.android.internal.content.PackageMonitor;
 
 import java.io.FileDescriptor;
 import java.io.PrintWriter;
@@ -62,39 +60,75 @@
 
     private final Context mContext;
     private final Map<Integer, INetworkScoreCache> mScoreCaches;
-    /** Lock used to update mReceiver when scorer package changes occur. */
-    private final Object mReceiverLock = new Object[0];
+    /** Lock used to update mPackageMonitor when scorer package changes occur. */
+    private final Object mPackageMonitorLock = new Object[0];
 
-    /** Clears scores when the active scorer package is no longer valid. */
-    @GuardedBy("mReceiverLock")
-    private ScorerChangedReceiver mReceiver;
+    @GuardedBy("mPackageMonitorLock")
+    private NetworkScorerPackageMonitor mPackageMonitor;
     private ScoringServiceConnection mServiceConnection;
 
-    private class ScorerChangedReceiver extends BroadcastReceiver {
+    /**
+     * Clears scores when the active scorer package is no longer valid and
+     * manages the service connection.
+     */
+    private class NetworkScorerPackageMonitor extends PackageMonitor {
         final String mRegisteredPackage;
 
-        ScorerChangedReceiver(String packageName) {
-            mRegisteredPackage = packageName;
+        private NetworkScorerPackageMonitor(String mRegisteredPackage) {
+            this.mRegisteredPackage = mRegisteredPackage;
         }
 
         @Override
-        public void onReceive(Context context, Intent intent) {
-            String action = intent.getAction();
-            if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
-                    || Intent.ACTION_PACKAGE_REPLACED.equals(action)
-                    || Intent.ACTION_PACKAGE_FULLY_REMOVED.equals(action)) {
-                NetworkScorerAppData activeScorer =
+        public void onPackageAdded(String packageName, int uid) {
+            evaluateBinding(packageName, true /* forceUnbind */);
+        }
+
+        @Override
+        public void onPackageRemoved(String packageName, int uid) {
+            evaluateBinding(packageName, true /* forceUnbind */);
+        }
+
+        @Override
+        public void onPackageModified(String packageName) {
+            evaluateBinding(packageName, false /* forceUnbind */);
+        }
+
+        @Override
+        public boolean onHandleForceStop(Intent intent, String[] packages, int uid, boolean doit) {
+            if (doit) { // "doit" means the force stop happened instead of just being queried for.
+                for (String packageName : packages) {
+                    evaluateBinding(packageName, true /* forceUnbind */);
+                }
+            }
+            return super.onHandleForceStop(intent, packages, uid, doit);
+        }
+
+        @Override
+        public void onPackageUpdateFinished(String packageName, int uid) {
+            evaluateBinding(packageName, true /* forceUnbind */);
+        }
+
+        private void evaluateBinding(String scorerPackageName, boolean forceUnbind) {
+            if (mRegisteredPackage.equals(scorerPackageName)) {
+                if (DBG) {
+                    Log.d(TAG, "Evaluating binding for: " + scorerPackageName
+                            + ", forceUnbind=" + forceUnbind);
+                }
+                final NetworkScorerAppData activeScorer =
                         NetworkScorerAppManager.getActiveScorer(mContext);
                 if (activeScorer == null) {
-                    // Package change has invalidated a scorer.
+                    // Package change has invalidated a scorer, this will also unbind any service
+                    // connection.
                     Log.i(TAG, "Package " + mRegisteredPackage +
                             " is no longer valid, disabling scoring.");
                     setScorerInternal(null);
                 } else if (activeScorer.mScoringServiceClassName == null) {
                     // The scoring service is not available, make sure it's unbound.
                     unbindFromScoringServiceIfNeeded();
-                } else {
-                    // The scoring service may have changed or been added.
+                } else { // The scoring service changed in some way.
+                    if (forceUnbind) {
+                        unbindFromScoringServiceIfNeeded();
+                    }
                     bindToScoringServiceIfNeeded(activeScorer);
                 }
             }
@@ -121,7 +155,7 @@
             Settings.Global.putInt(cr, Settings.Global.NETWORK_SCORING_PROVISIONED, 1);
         }
 
-        registerPackageReceiverIfNeeded();
+        registerPackageMonitorIfNeeded();
     }
 
     /** Called when the system is ready for us to start third-party code. */
@@ -130,33 +164,29 @@
         bindToScoringServiceIfNeeded();
     }
 
-    private void registerPackageReceiverIfNeeded() {
-        if (DBG) Log.d(TAG, "registerPackageReceiverIfNeeded");
+    private void registerPackageMonitorIfNeeded() {
+        if (DBG) Log.d(TAG, "registerPackageMonitorIfNeeded");
         NetworkScorerAppData scorer = NetworkScorerAppManager.getActiveScorer(mContext);
-        synchronized (mReceiverLock) {
-            // Unregister the receiver if the current scorer has changed since last registration.
-            if (mReceiver != null) {
-                if (Log.isLoggable(TAG, Log.VERBOSE)) {
-                    Log.v(TAG, "Unregistering receiver for " + mReceiver.mRegisteredPackage);
+        synchronized (mPackageMonitorLock) {
+            // Unregister the current monitor if needed.
+            if (mPackageMonitor != null) {
+                if (DBG) {
+                    Log.d(TAG, "Unregistering package monitor for "
+                            + mPackageMonitor.mRegisteredPackage);
                 }
-                mContext.unregisterReceiver(mReceiver);
-                mReceiver = null;
+                mPackageMonitor.unregister();
+                mPackageMonitor = null;
             }
 
-            // Register receiver if a scorer is active.
+            // Create and register the monitor if a scorer is active.
             if (scorer != null) {
-                IntentFilter filter = new IntentFilter();
-                filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
-                filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
-                filter.addAction(Intent.ACTION_PACKAGE_FULLY_REMOVED);
-                filter.addDataScheme("package");
-                filter.addDataSchemeSpecificPart(scorer.mPackageName,
-                        PatternMatcher.PATTERN_LITERAL);
-                mReceiver = new ScorerChangedReceiver(scorer.mPackageName);
+                mPackageMonitor = new NetworkScorerPackageMonitor(scorer.mPackageName);
                 // TODO: Need to update when we support per-user scorers. http://b/23422763
-                mContext.registerReceiverAsUser(mReceiver, UserHandle.SYSTEM, filter, null, null);
-                if (Log.isLoggable(TAG, Log.VERBOSE)) {
-                    Log.v(TAG, "Registered receiver for " + scorer.mPackageName);
+                mPackageMonitor.register(mContext, null /* thread */, UserHandle.SYSTEM,
+                        false /* externalStorage */);
+                if (DBG) {
+                    Log.d(TAG, "Registered package monitor for "
+                            + mPackageMonitor.mRegisteredPackage);
                 }
             }
         }
@@ -299,7 +329,7 @@
             // will be made to bind to the new scorer.
             bindToScoringServiceIfNeeded();
             if (result) { // new scorer successfully set
-                registerPackageReceiverIfNeeded();
+                registerPackageMonitorIfNeeded();
 
                 Intent intent = new Intent(NetworkScoreManager.ACTION_SCORER_CHANGED);
                 if (prevScorer != null) { // Directly notify the old scorer.
@@ -391,20 +421,24 @@
     private static class ScoringServiceConnection implements ServiceConnection {
         private final ComponentName mComponentName;
         private boolean mBound = false;
+        private boolean mConnected = false;
 
         ScoringServiceConnection(ComponentName componentName) {
             mComponentName = componentName;
         }
 
         void connect(Context context) {
-            disconnect(context);
-            Intent service = new Intent();
-            service.setComponent(mComponentName);
-            mBound = context.bindServiceAsUser(service, this,
-                    Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE,
-                    UserHandle.SYSTEM);
             if (!mBound) {
-                Log.w(TAG, "Bind call failed for " + service);
+                Intent service = new Intent();
+                service.setComponent(mComponentName);
+                mBound = context.bindServiceAsUser(service, this,
+                        Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE,
+                        UserHandle.SYSTEM);
+                if (!mBound) {
+                    Log.w(TAG, "Bind call failed for " + service);
+                } else {
+                    if (DBG) Log.d(TAG, "ScoringServiceConnection bound.");
+                }
             }
         }
 
@@ -413,6 +447,7 @@
                 if (mBound) {
                     mBound = false;
                     context.unbindService(this);
+                    if (DBG) Log.d(TAG, "ScoringServiceConnection unbound.");
                 }
             } catch (RuntimeException e) {
                 Log.e(TAG, "Unbind failed.", e);
@@ -422,15 +457,20 @@
         @Override
         public void onServiceConnected(ComponentName name, IBinder service) {
             if (DBG) Log.d(TAG, "ScoringServiceConnection: " + name.flattenToString());
+            mConnected = true;
         }
 
         @Override
         public void onServiceDisconnected(ComponentName name) {
-            if (DBG) Log.d(TAG, "ScoringServiceConnection, disconnected: " + name.flattenToString());
+            if (DBG) {
+                Log.d(TAG, "ScoringServiceConnection, disconnected: " + name.flattenToString());
+            }
+            mConnected = false;
         }
 
         public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
-            writer.println("ScoringServiceConnection: " + mComponentName + ", bound: " + mBound);
+            writer.println("ScoringServiceConnection: " + mComponentName + ", bound: " + mBound
+                    + ", connected: " + mConnected);
         }
     }
 }
diff --git a/services/core/java/com/android/server/am/ActiveServices.java b/services/core/java/com/android/server/am/ActiveServices.java
index 95dee01..dcd9b0c 100755
--- a/services/core/java/com/android/server/am/ActiveServices.java
+++ b/services/core/java/com/android/server/am/ActiveServices.java
@@ -753,7 +753,7 @@
 
     public void updateServiceConnectionActivitiesLocked(ProcessRecord clientProc) {
         ArraySet<ProcessRecord> updatedProcesses = null;
-        for (int i=0; i<clientProc.connections.size(); i++) {
+        for (int i = 0; i < clientProc.connections.size(); i++) {
             final ConnectionRecord conn = clientProc.connections.valueAt(i);
             final ProcessRecord proc = conn.binding.service.app;
             if (proc == null || proc == clientProc) {
@@ -831,8 +831,9 @@
 
         int clientLabel = 0;
         PendingIntent clientIntent = null;
+        final boolean isCallerSystem = callerApp.info.uid == Process.SYSTEM_UID;
 
-        if (callerApp.info.uid == Process.SYSTEM_UID) {
+        if (isCallerSystem) {
             // Hacky kind of thing -- allow system stuff to tell us
             // what they are, so we can report this elsewhere for
             // others to know why certain services are running.
@@ -854,6 +855,12 @@
                     "BIND_TREAT_LIKE_ACTIVITY");
         }
 
+        if ((flags & Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0 && !isCallerSystem) {
+            throw new SecurityException(
+                    "Non-system caller " + caller + " (pid=" + Binder.getCallingPid()
+                    + ") set BIND_ALLOW_WHITELIST_MANAGEMENT when binding service " + service);
+        }
+
         final boolean callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND;
         final boolean isBindExternal = (flags & Context.BIND_EXTERNAL_SERVICE) != 0;
 
@@ -1124,6 +1131,11 @@
                 }
 
                 if (r.binding.service.app != null) {
+                    if (r.binding.service.app.whitelistManager) {
+                        // Must reset flag here because on computeOomAdjLocked() the service
+                        // connection will be gone...
+                        r.binding.service.app.whitelistManager = false;
+                    }
                     // This could have made the service less important.
                     if ((r.flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
                         r.binding.service.app.treatLikeActivity = true;
@@ -2189,11 +2201,11 @@
                     // If the app is null, then it was probably removed because the process died,
                     // otherwise wtf
                     if (r.app != null) {
-                        Slog.wtfStack(TAG, "Service done with onDestroy, but not inDestroying: "
+                        Slog.w(TAG, "Service done with onDestroy, but not inDestroying: "
                                 + r + ", app=" + r.app);
                     }
                 } else if (r.executeNesting != 1) {
-                    Slog.wtfStack(TAG, "Service done with onDestroy, but executeNesting="
+                    Slog.w(TAG, "Service done with onDestroy, but executeNesting="
                             + r.executeNesting + ": " + r);
                     // Fake it to keep from ANR due to orphaned entry.
                     r.executeNesting = 1;
diff --git a/services/core/java/com/android/server/am/ActivityManagerDebugConfig.java b/services/core/java/com/android/server/am/ActivityManagerDebugConfig.java
index f2bf4f9..43bb5ee 100644
--- a/services/core/java/com/android/server/am/ActivityManagerDebugConfig.java
+++ b/services/core/java/com/android/server/am/ActivityManagerDebugConfig.java
@@ -90,6 +90,7 @@
     static final boolean DEBUG_VISIBLE_BEHIND = DEBUG_ALL_ACTIVITIES || false;
     static final boolean DEBUG_USAGE_STATS = DEBUG_ALL || false;
     static final boolean DEBUG_PERMISSIONS_REVIEW = DEBUG_ALL || false;
+    static final boolean DEBUG_WHITELISTS = DEBUG_ALL || false;
 
     static final String POSTFIX_ADD_REMOVE = (APPEND_CATEGORY_NAME) ? "_AddRemove" : "";
     static final String POSTFIX_APP = (APPEND_CATEGORY_NAME) ? "_App" : "";
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index ed55263..e07243f 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -199,6 +199,7 @@
 import android.service.voice.IVoiceInteractionSession;
 import android.service.voice.VoiceInteractionManagerInternal;
 import android.service.voice.VoiceInteractionSession;
+import android.telecom.TelecomManager;
 import android.text.format.DateUtils;
 import android.text.format.Time;
 import android.text.style.SuggestionSpan;
@@ -266,6 +267,7 @@
 import static android.app.ActivityManager.StackId.LAST_STATIC_STACK_ID;
 import static android.app.ActivityManager.StackId.PINNED_STACK_ID;
 import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
+import static android.content.pm.PackageManager.FEATURE_LEANBACK_ONLY;
 import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
 import static android.content.pm.PackageManager.GET_PROVIDERS;
 import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
@@ -320,6 +322,7 @@
 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_USAGE_STATS;
 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_VISIBILITY;
 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_VISIBLE_BEHIND;
+import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_WHITELISTS;
 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_BACKUP;
 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_BROADCAST;
 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_CLEANUP;
@@ -1344,6 +1347,7 @@
     boolean mSupportsMultiWindow;
     boolean mSupportsFreeformWindowManagement;
     boolean mSupportsPictureInPicture;
+    boolean mSupportsLeanbackOnly;
     Rect mDefaultPinnedStackBounds;
     IActivityController mController = null;
     boolean mControllerIsAMonkey = false;
@@ -5419,9 +5423,32 @@
                 }
             }
 
+            final int pkgUidF = pkgUid;
+            final int userIdF = userId;
+            final IPackageDataObserver localObserver = new IPackageDataObserver.Stub() {
+                @Override
+                public void onRemoveCompleted(String packageName, boolean succeeded)
+                        throws RemoteException {
+                    synchronized (ActivityManagerService.this) {
+                        finishForceStopPackageLocked(packageName, pkgUidF);
+                    }
+
+                    final Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
+                            Uri.fromParts("package", packageName, null));
+                    intent.putExtra(Intent.EXTRA_UID, pkgUidF);
+                    intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(pkgUidF));
+                    broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
+                            null, null, 0, null, null, null, null, false, false, userIdF);
+
+                    if (observer != null) {
+                        observer.onRemoveCompleted(packageName, succeeded);
+                    }
+                }
+            };
+
             try {
                 // Clear application user data
-                pm.clearApplicationUserData(packageName, observer, userId);
+                pm.clearApplicationUserData(packageName, localObserver, userId);
 
                 synchronized(this) {
                     // Remove all permissions granted from/to this package
@@ -5433,12 +5460,6 @@
                 inm.removeAutomaticZenRules(packageName);
                 inm.setNotificationPolicyAccessGranted(packageName, false);
 
-                Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
-                        Uri.fromParts("package", packageName, null));
-                intent.putExtra(Intent.EXTRA_UID, pkgUid);
-                intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(pkgUid));
-                broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
-                        null, null, 0, null, null, null, null, false, false, userId);
             } catch (RemoteException e) {
             }
         } finally {
@@ -5623,6 +5644,7 @@
                     }
                     if (mUserController.isUserRunningLocked(user, 0)) {
                         forceStopPackageLocked(packageName, pkgUid, "from pid " + callingPid);
+                        finishForceStopPackageLocked(packageName, pkgUid);
                     }
                 }
             }
@@ -5814,6 +5836,9 @@
     private void forceStopPackageLocked(final String packageName, int uid, String reason) {
         forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false,
                 false, true, false, false, UserHandle.getUserId(uid), reason);
+    }
+
+    private void finishForceStopPackageLocked(final String packageName, int uid) {
         Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
                 Uri.fromParts("package", packageName, null));
         if (!mProcessesReady) {
@@ -7112,6 +7137,41 @@
         }
     }
 
+    /**
+     * Whitelists {@code targetUid} to temporarily bypass Power Save mode.
+     *
+     * <p>{@code callerUid} must be allowed to request such whitelist by calling
+     * {@link #addTempPowerSaveWhitelistGrantorUid(int)}.
+     */
+    void tempWhitelistAppForPowerSave(int callerPid, int callerUid, int targetUid, long duration) {
+        if (DEBUG_WHITELISTS) {
+            Slog.d(TAG, "tempWhitelistAppForPowerSave(" + callerPid + ", " + callerUid + ", "
+                    + targetUid + ", " + duration + ")");
+        }
+        synchronized (mPidsSelfLocked) {
+            final ProcessRecord pr = mPidsSelfLocked.get(callerPid);
+            if (pr == null) {
+                Slog.w(TAG, "tempWhitelistAppForPowerSave() no ProcessRecord for pid " + callerPid);
+                return;
+            }
+            if (!pr.whitelistManager) {
+                if (DEBUG_WHITELISTS) {
+                    Slog.d(TAG, "tempWhitelistAppForPowerSave() for target " + targetUid + ": pid "
+                            + callerPid + " is not allowed");
+                }
+                return;
+            }
+        }
+
+        final long token = Binder.clearCallingIdentity();
+        try {
+            mLocalDeviceIdleController.addPowerSaveTempWhitelistAppDirect(targetUid, duration,
+                    true, "pe from uid:" + callerUid);
+        } finally {
+            Binder.restoreCallingIdentity(token);
+        }
+    }
+
     @Override
     public void cancelIntentSender(IIntentSender sender) {
         if (!(sender instanceof PendingIntentRecord)) {
@@ -10108,6 +10168,10 @@
                 mStackSupervisor.setLockTaskModeLocked(null, ActivityManager.LOCK_TASK_MODE_NONE,
                         "stopLockTask", true);
             }
+            TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
+            if (tm != null) {
+                tm.showInCallScreen(false);
+            }
         } finally {
             Binder.restoreCallingIdentity(ident);
         }
@@ -10170,6 +10234,7 @@
             int N = providers.size();
             app.pubProviders.ensureCapacity(N + app.pubProviders.size());
             for (int i=0; i<N; i++) {
+                // TODO: keep logic in sync with installEncryptionUnawareProviders
                 ProviderInfo cpi =
                     (ProviderInfo)providers.get(i);
                 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
@@ -11150,12 +11215,18 @@
                             final PackageInfo pkgInfo = AppGlobals.getPackageManager()
                                     .getPackageInfo(pkgName, matchFlags, userId);
                             if (pkgInfo != null && !ArrayUtils.isEmpty(pkgInfo.providers)) {
-                                for (ProviderInfo provInfo : pkgInfo.providers) {
-                                    if (Objects.equals(provInfo.processName, app.processName)) {
-                                        Log.v(TAG, "Installing " + provInfo);
-                                        app.thread.scheduleInstallProvider(provInfo);
+                                for (ProviderInfo pi : pkgInfo.providers) {
+                                    // TODO: keep in sync with generateApplicationProvidersLocked
+                                    final boolean processMatch = Objects.equals(pi.processName,
+                                            app.processName) || pi.multiprocess;
+                                    final boolean userMatch = isSingleton(pi.processName,
+                                            pi.applicationInfo, pi.name, pi.flags)
+                                                    ? (app.userId == UserHandle.USER_SYSTEM) : true;
+                                    if (processMatch && userMatch) {
+                                        Log.v(TAG, "Installing " + pi);
+                                        app.thread.scheduleInstallProvider(pi);
                                     } else {
-                                        Log.v(TAG, "Skipping " + provInfo);
+                                        Log.v(TAG, "Skipping " + pi);
                                     }
                                 }
                             }
@@ -12785,6 +12856,9 @@
         final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
         final boolean forceResizable = Settings.Global.getInt(
                 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
+        final boolean supportsLeanbackOnly =
+                mContext.getPackageManager().hasSystemFeature(FEATURE_LEANBACK_ONLY);
+
         // Transfer any global setting for forcing RTL layout, into a System Property
         SystemProperties.set(DEVELOPMENT_FORCE_RTL, forceRtl ? "1":"0");
 
@@ -12800,6 +12874,7 @@
             mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
             mAlwaysFinishActivities = alwaysFinishActivities;
             mLenientBackgroundCheck = lenientBackgroundCheck;
+            mSupportsLeanbackOnly = supportsLeanbackOnly;
             mForceResizableActivities = forceResizable;
             mWindowManager.setForceResizableTasks(mForceResizableActivities);
             if (supportsMultiWindow || forceResizable) {
@@ -18789,7 +18864,7 @@
             for (int j = 0; j < activitiesSize; j++) {
                 final ActivityRecord r = app.activities.get(j);
                 if (r.app != app) {
-                    Log.wtf(TAG, "Found activity " + r + " in proc activity list using " + r.app
+                    Log.e(TAG, "Found activity " + r + " in proc activity list using " + r.app
                             + " instead of expected " + app);
                     if (r.app == null || (r.app.uid == app.uid)) {
                         // Only fix things up when they look sane
@@ -18991,6 +19066,9 @@
                     }
                 }
             }
+
+            app.whitelistManager = false;
+
             for (int conni = s.connections.size()-1;
                     conni >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
                             || schedGroup == ProcessList.SCHED_GROUP_BACKGROUND
@@ -19009,6 +19087,10 @@
                         // Binding to ourself is not interesting.
                         continue;
                     }
+                    if ((cr.flags & Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0) {
+                        app.whitelistManager = true;
+                    }
+
                     if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
                         ProcessRecord client = cr.binding.client;
                         int clientAdj = computeOomAdjLocked(client, cachedAdj,
@@ -21285,6 +21367,15 @@
                 }
             }
         }
+
+        @Override
+        public void setPendingIntentWhitelistDuration(IIntentSender target, long duration) {
+            if (!(target instanceof PendingIntentRecord)) {
+                Slog.w(TAG, "markAsSentFromNotification(): not a PendingIntentRecord: " + target);
+                return;
+            }
+            ((PendingIntentRecord) target).setWhitelistDuration(duration);
+        }
     }
 
     private final class SleepTokenImpl extends SleepToken {
diff --git a/services/core/java/com/android/server/am/ActivityStack.java b/services/core/java/com/android/server/am/ActivityStack.java
index 8b637e0..b77381c 100644
--- a/services/core/java/com/android/server/am/ActivityStack.java
+++ b/services/core/java/com/android/server/am/ActivityStack.java
@@ -73,7 +73,6 @@
 import static com.android.server.am.ActivityRecord.STARTING_WINDOW_REMOVED;
 import static com.android.server.am.ActivityRecord.STARTING_WINDOW_SHOWN;
 import static com.android.server.am.ActivityStackSupervisor.FindTaskResult;
-import static com.android.server.am.ActivityStackSupervisor.MOVING;
 import static com.android.server.am.ActivityStackSupervisor.ON_TOP;
 import static com.android.server.am.ActivityStackSupervisor.PRESERVE_WINDOWS;
 import static com.android.server.wm.AppTransition.TRANSIT_ACTIVITY_CLOSE;
@@ -1832,9 +1831,9 @@
         boolean isVisible =
                 !behindFullscreenActivity || r.mLaunchTaskBehind || activityVisibleBehind;
 
-        if (isVisible && r.isRecentsActivity()) {
-            // Recents activity can only be visible if the home stack is the focused stack or we are
-            // in split-screen mode.
+        if (mService.mSupportsLeanbackOnly && isVisible && r.isRecentsActivity()) {
+            // On devices that support leanback only (Android TV), Recents activity can only be
+            // visible if the home stack is the focused stack or we are in split-screen mode.
             isVisible = mStackSupervisor.getStack(DOCKED_STACK_ID) != null
                     || mStackSupervisor.isFocusedStack(this);
         }
@@ -4464,6 +4463,7 @@
         // Short circuit: if the two configurations are equal (the common case), then there is
         // nothing to do.
         final Configuration newConfig = mService.mConfiguration;
+        r.task.sanitizeOverrideConfiguration(newConfig);
         final Configuration taskConfig = r.task.mOverrideConfig;
         if (r.configuration.equals(newConfig)
                 && r.taskConfigOverride.equals(taskConfig)
diff --git a/services/core/java/com/android/server/am/ActivityStackSupervisor.java b/services/core/java/com/android/server/am/ActivityStackSupervisor.java
index 5532958..8d6b7ee 100644
--- a/services/core/java/com/android/server/am/ActivityStackSupervisor.java
+++ b/services/core/java/com/android/server/am/ActivityStackSupervisor.java
@@ -1338,7 +1338,9 @@
 
         // Update any services we are bound to that might care about whether
         // their client may have activities.
-        mService.mServices.updateServiceConnectionActivitiesLocked(r.app);
+        if (r.app != null) {
+            mService.mServices.updateServiceConnectionActivitiesLocked(r.app);
+        }
 
         return true;
     }
@@ -3523,7 +3525,9 @@
     }
 
     void showLockTaskToast() {
-        mLockTaskNotify.showToast(mLockTaskModeState);
+        if (mLockTaskNotify != null) {
+            mLockTaskNotify.showToast(mLockTaskModeState);
+        }
     }
 
     void showLockTaskEscapeMessageLocked(TaskRecord task) {
diff --git a/services/core/java/com/android/server/am/ActivityStarter.java b/services/core/java/com/android/server/am/ActivityStarter.java
index ffaea73..b8480ea 100644
--- a/services/core/java/com/android/server/am/ActivityStarter.java
+++ b/services/core/java/com/android/server/am/ActivityStarter.java
@@ -562,7 +562,16 @@
             startedActivityStackId = mTargetStack.mStackId;
         }
 
-        if (startedActivityStackId == DOCKED_STACK_ID && prevFocusedStackId == HOME_STACK_ID) {
+        // If we launched the activity from a no display activity that was launched from the home
+        // screen, we also need to start recents to un-minimize the docked stack, since the
+        // noDisplay activity will be finished shortly after.
+        // TODO: We should prevent noDisplay activities from affecting task/stack ordering and
+        // visibility instead of using this flag.
+        final boolean noDisplayActivityOverHome = mSourceRecord != null
+                && mSourceRecord.noDisplay
+                && mSourceRecord.task.getTaskToReturnTo() == HOME_ACTIVITY_TYPE;
+        if (startedActivityStackId == DOCKED_STACK_ID
+                && (prevFocusedStackId == HOME_STACK_ID || noDisplayActivityOverHome)) {
             final ActivityStack homeStack = mSupervisor.getStack(HOME_STACK_ID);
             final ActivityRecord topActivityHomeStack = homeStack != null
                     ? homeStack.topRunningActivityLocked() : null;
diff --git a/services/core/java/com/android/server/am/AppErrorDialog.java b/services/core/java/com/android/server/am/AppErrorDialog.java
index ddfab4d..e37feb2 100644
--- a/services/core/java/com/android/server/am/AppErrorDialog.java
+++ b/services/core/java/com/android/server/am/AppErrorDialog.java
@@ -18,13 +18,17 @@
 
 import android.app.ActivityManagerInternal;
 import android.app.ActivityOptions;
+import android.content.BroadcastReceiver;
 import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
 import android.content.pm.IPackageDataObserver;
 import android.content.pm.PackageManager;
 import android.content.res.Resources;
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.Message;
+import android.provider.Settings;
 import android.text.BidiFormatter;
 import android.util.Slog;
 import android.view.LayoutInflater;
@@ -43,6 +47,7 @@
     private final AppErrorResult mResult;
     private final ProcessRecord mProc;
     private final boolean mRepeating;
+    private final boolean mForeground;
 
     private CharSequence mName;
 
@@ -54,9 +59,9 @@
     static final int FORCE_QUIT = 1;
     static final int FORCE_QUIT_AND_REPORT = 2;
     static final int RESTART = 3;
-    static final int RESET = 4;
     static final int MUTE = 5;
     static final int TIMEOUT = 6;
+    static final int CANCEL = 7;
 
     // 5-minute timeout, then we automatically dismiss the crash dialog
     static final long DISMISS_TIMEOUT = 1000 * 60 * 5;
@@ -69,6 +74,7 @@
         mProc = data.proc;
         mResult = data.result;
         mRepeating = data.repeating;
+        mForeground = data.task != null;
         BidiFormatter bidi = BidiFormatter.getInstance();
 
         if ((mProc.pkgList.size() == 1) &&
@@ -86,7 +92,8 @@
                     bidi.unicodeWrap(mName.toString())));
         }
 
-        setCancelable(false);
+        setCancelable(true);
+        setCancelMessage(mHandler.obtainMessage(CANCEL));
 
         WindowManager.LayoutParams attrs = getWindow().getAttributes();
         attrs.setTitle("Application Error: " + mProc.info.processName);
@@ -111,25 +118,41 @@
         LayoutInflater.from(context).inflate(
                 com.android.internal.R.layout.app_error_dialog, frame, true);
 
+        boolean hasRestart = !mRepeating && mForeground;
+        final boolean hasReceiver = mProc.errorReportReceiver != null;
+
         final TextView restart = (TextView) findViewById(com.android.internal.R.id.aerr_restart);
         restart.setOnClickListener(this);
-        restart.setVisibility(!mRepeating ? View.VISIBLE : View.GONE);
-        final TextView reset = (TextView) findViewById(com.android.internal.R.id.aerr_reset);
-        reset.setOnClickListener(this);
-        reset.setVisibility(mRepeating ? View.VISIBLE : View.GONE);
+        restart.setVisibility(hasRestart ? View.VISIBLE : View.GONE);
         final TextView report = (TextView) findViewById(com.android.internal.R.id.aerr_report);
         report.setOnClickListener(this);
-        final boolean hasReceiver = mProc.errorReportReceiver != null;
         report.setVisibility(hasReceiver ? View.VISIBLE : View.GONE);
         final TextView close = (TextView) findViewById(com.android.internal.R.id.aerr_close);
+        close.setVisibility(!hasRestart ? View.VISIBLE : View.GONE);
         close.setOnClickListener(this);
+
+        boolean showMute = !IS_USER_BUILD && Settings.Global.getInt(context.getContentResolver(),
+                Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0) != 0;
         final TextView mute = (TextView) findViewById(com.android.internal.R.id.aerr_mute);
         mute.setOnClickListener(this);
-        mute.setVisibility(!IS_USER_BUILD ? View.VISIBLE : View.GONE);
+        mute.setVisibility(showMute ? View.VISIBLE : View.GONE);
 
         findViewById(com.android.internal.R.id.customPanel).setVisibility(View.VISIBLE);
     }
 
+    @Override
+    public void onStart() {
+        super.onStart();
+        getContext().registerReceiver(mReceiver,
+                new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
+    }
+
+    @Override
+    protected void onStop() {
+        super.onStop();
+        getContext().unregisterReceiver(mReceiver);
+    }
+
     private final Handler mHandler = new Handler() {
         public void handleMessage(Message msg) {
             final int result = msg.what;
@@ -163,9 +186,6 @@
             case com.android.internal.R.id.aerr_restart:
                 mHandler.obtainMessage(RESTART).sendToTarget();
                 break;
-            case com.android.internal.R.id.aerr_reset:
-                mHandler.obtainMessage(RESET).sendToTarget();
-                break;
             case com.android.internal.R.id.aerr_report:
                 mHandler.obtainMessage(FORCE_QUIT_AND_REPORT).sendToTarget();
                 break;
@@ -180,6 +200,15 @@
         }
     }
 
+    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(intent.getAction())) {
+                cancel();
+            }
+        }
+    };
+
     static class Data {
         AppErrorResult result;
         TaskRecord task;
diff --git a/services/core/java/com/android/server/am/AppErrors.java b/services/core/java/com/android/server/am/AppErrors.java
index 3ed9969..49106f4 100644
--- a/services/core/java/com/android/server/am/AppErrors.java
+++ b/services/core/java/com/android/server/am/AppErrors.java
@@ -370,38 +370,9 @@
 
         Intent appErrorIntent = null;
         MetricsLogger.action(mContext, MetricsProto.MetricsEvent.ACTION_APP_CRASH, res);
-        if (res == AppErrorDialog.TIMEOUT) {
+        if (res == AppErrorDialog.TIMEOUT || res == AppErrorDialog.CANCEL) {
             res = AppErrorDialog.FORCE_QUIT;
         }
-        if (res == AppErrorDialog.RESET) {
-            String[] packageList = r.getPackageList();
-            if (packageList != null) {
-                PackageManager pm = mContext.getPackageManager();
-                final Semaphore s = new Semaphore(0);
-                for (int i = 0; i < packageList.length; i++) {
-                    if (i < packageList.length - 1) {
-                        pm.deleteApplicationCacheFiles(packageList[i], null);
-                    } else {
-                        pm.deleteApplicationCacheFiles(packageList[i],
-                                new IPackageDataObserver.Stub() {
-                                    @Override
-                                    public void onRemoveCompleted(String packageName,
-                                                                  boolean succeeded) {
-                                        s.release();
-                                    }
-                                });
-
-                        // Wait until cache has been cleared before we restart.
-                        try {
-                            s.acquire();
-                        } catch (InterruptedException e) {
-                        }
-                    }
-                }
-            }
-            // If there was nothing to reset, just restart;
-            res = AppErrorDialog.RESTART;
-        }
         synchronized (mService) {
             if (res == AppErrorDialog.MUTE) {
                 stopReportingCrashesLocked(r);
diff --git a/services/core/java/com/android/server/am/LockTaskNotify.java b/services/core/java/com/android/server/am/LockTaskNotify.java
index afde322..8c18c46 100644
--- a/services/core/java/com/android/server/am/LockTaskNotify.java
+++ b/services/core/java/com/android/server/am/LockTaskNotify.java
@@ -21,7 +21,6 @@
 import android.os.Handler;
 import android.os.Message;
 import android.view.WindowManager;
-import android.view.accessibility.AccessibilityManager;
 import android.widget.Toast;
 
 import com.android.internal.R;
@@ -35,13 +34,10 @@
 
     private final Context mContext;
     private final H mHandler;
-    private AccessibilityManager mAccessibilityManager;
     private Toast mLastToast;
 
     public LockTaskNotify(Context context) {
         mContext = context;
-        mAccessibilityManager = (AccessibilityManager)
-                mContext.getSystemService(Context.ACCESSIBILITY_SERVICE);
         mHandler = new H();
     }
 
@@ -54,8 +50,7 @@
         if (lockTaskModeState == ActivityManager.LOCK_TASK_MODE_LOCKED) {
             text = mContext.getString(R.string.lock_to_app_toast_locked);
         } else if (lockTaskModeState == ActivityManager.LOCK_TASK_MODE_PINNED) {
-            text = mContext.getString(mAccessibilityManager.isEnabled()
-                    ? R.string.lock_to_app_toast_accessible : R.string.lock_to_app_toast);
+            text = mContext.getString(R.string.lock_to_app_toast);
         }
         if (text == null) {
             return;
diff --git a/services/core/java/com/android/server/am/PendingIntentRecord.java b/services/core/java/com/android/server/am/PendingIntentRecord.java
index 1f8d26b..c1ff4dd 100644
--- a/services/core/java/com/android/server/am/PendingIntentRecord.java
+++ b/services/core/java/com/android/server/am/PendingIntentRecord.java
@@ -47,6 +47,7 @@
     final WeakReference<PendingIntentRecord> ref;
     boolean sent = false;
     boolean canceled = false;
+    private long whitelistDuration = 0;
 
     String stringName;
     String lastTagPrefix;
@@ -66,9 +67,9 @@
         final int flags;
         final int hashCode;
         final int userId;
-        
+
         private static final int ODD_PRIME_NUMBER = 37;
-        
+
         Key(int _t, String _p, ActivityRecord _a, String _w,
                 int _r, Intent[] _i, String[] _it, int _f, Bundle _o, int _userId) {
             type = _t;
@@ -106,7 +107,7 @@
             //Slog.i(ActivityManagerService.TAG, this + " hashCode=0x"
             //        + Integer.toHexString(hashCode));
         }
-        
+
         public boolean equals(Object otherObj) {
             if (otherObj == null) {
                 return false;
@@ -198,6 +199,11 @@
         ref = new WeakReference<PendingIntentRecord>(this);
     }
 
+    void setWhitelistDuration(long duration) {
+        this.whitelistDuration = duration;
+        this.stringName = null;
+    }
+
     public void send(int code, Intent intent, String resolvedType, IIntentReceiver finishedReceiver,
             String requiredPermission, Bundle options) {
         sendInner(code, intent, resolvedType, finishedReceiver,
@@ -216,6 +222,14 @@
         if (intent != null) intent.setDefusable(true);
         if (options != null) options.setDefusable(true);
 
+        if (whitelistDuration > 0 && !canceled) {
+            // Must call before acquiring the lock. It's possible the method return before sending
+            // the intent due to some validations inside the lock, in which case the UID shouldn't
+            // be whitelisted, but since the whitelist is temporary, that would be ok.
+            owner.tempWhitelistAppForPowerSave(Binder.getCallingPid(), Binder.getCallingUid(), uid,
+                    whitelistDuration);
+        }
+
         synchronized (owner) {
             final ActivityContainer activityContainer = (ActivityContainer)container;
             if (activityContainer != null && activityContainer.mParentActivity != null &&
@@ -361,7 +375,7 @@
             }
         }
     }
-    
+
     void dump(PrintWriter pw, String prefix) {
         pw.print(prefix); pw.print("uid="); pw.print(uid);
                 pw.print(" packageName="); pw.print(key.packageName);
@@ -383,6 +397,7 @@
             pw.print(prefix); pw.print("sent="); pw.print(sent);
                     pw.print(" canceled="); pw.println(canceled);
         }
+        pw.print(prefix); pw.println("whitelistDuration="); pw.println(whitelistDuration);
     }
 
     public String toString() {
@@ -396,6 +411,9 @@
         sb.append(key.packageName);
         sb.append(' ');
         sb.append(key.typeName());
+        if (whitelistDuration > 0) {
+            sb.append( " (whitelistDuration: ").append(whitelistDuration).append("ms)");
+        }
         sb.append('}');
         return stringName = sb.toString();
     }
diff --git a/services/core/java/com/android/server/am/ProcessRecord.java b/services/core/java/com/android/server/am/ProcessRecord.java
index da18f32..691fd2a 100644
--- a/services/core/java/com/android/server/am/ProcessRecord.java
+++ b/services/core/java/com/android/server/am/ProcessRecord.java
@@ -194,6 +194,8 @@
 
     // Process is currently hosting a backup agent for backup or restore
     public boolean inFullBackup;
+    // App is allowed to manage whitelists such as temporary Power Save mode whitelist.
+    boolean whitelistManager;
 
     void dump(PrintWriter pw, String prefix) {
         final long now = SystemClock.uptimeMillis();
@@ -376,6 +378,9 @@
                     }
                     pw.println();
         }
+        if (whitelistManager) {
+            pw.print(prefix); pw.print("whitelistManager="); pw.println(whitelistManager);
+        }
         if (activities.size() > 0) {
             pw.print(prefix); pw.println("Activities:");
             for (int i=0; i<activities.size(); i++) {
diff --git a/services/core/java/com/android/server/am/RetailDemoModeService.java b/services/core/java/com/android/server/am/RetailDemoModeService.java
index bf2ba93..a1106f5 100644
--- a/services/core/java/com/android/server/am/RetailDemoModeService.java
+++ b/services/core/java/com/android/server/am/RetailDemoModeService.java
@@ -17,6 +17,9 @@
 package com.android.server.am;
 
 import android.app.ActivityManagerNative;
+import android.app.Notification;
+import android.app.NotificationManager;
+import android.app.PendingIntent;
 import android.content.BroadcastReceiver;
 import android.content.ContentResolver;
 import android.content.Context;
@@ -25,6 +28,8 @@
 import android.content.pm.UserInfo;
 import android.database.ContentObserver;
 import android.net.Uri;
+import android.os.Environment;
+import android.os.FileUtils;
 import android.os.Handler;
 import android.os.PowerManager;
 import android.os.ServiceManager;
@@ -33,24 +38,31 @@
 import android.provider.Settings;
 import android.util.Slog;
 
+import com.android.internal.os.BackgroundThread;
+import com.android.internal.R;
 import com.android.server.ServiceThread;
 import com.android.server.SystemService;
 import com.android.server.pm.UserManagerService;
 
+import java.io.File;
+
 public class RetailDemoModeService extends SystemService {
     private static final boolean DEBUG = false;
 
     private static final String TAG = RetailDemoModeService.class.getSimpleName();
     private static final String DEMO_USER_NAME = "Demo";
+    private static final String ACTION_RESET_DEMO = "com.android.server.am.ACTION_RESET_DEMO";
 
     private static final long SCREEN_WAKEUP_DELAY = 5000;
 
     private ActivityManagerService mAms;
     private UserManagerService mUms;
+    private NotificationManager mNm;
     private PowerManager mPm;
     private PowerManager.WakeLock mWakeLock;
     private Handler mHandler;
     private ServiceThread mHandlerThread;
+    private PendingIntent mResetDemoPendingIntent;
 
     private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
         @Override
@@ -70,6 +82,9 @@
                         }
                     }, SCREEN_WAKEUP_DELAY);
                     break;
+                case ACTION_RESET_DEMO:
+                    createAndSwitchToDemoUser();
+                    break;
             }
         }
     };
@@ -78,6 +93,26 @@
         super(context);
     }
 
+    private Notification createResetNotification() {
+        return new Notification.Builder(getContext())
+                .setContentTitle(getContext().getString(R.string.reset_retail_demo_mode_title))
+                .setContentText(getContext().getString(R.string.reset_retail_demo_mode_text))
+                .setOngoing(true)
+                .setSmallIcon(R.drawable.platlogo)
+                .setShowWhen(false)
+                .setVisibility(Notification.VISIBILITY_PUBLIC)
+                .setContentIntent(getResetDemoPendingIntent())
+                .build();
+    }
+
+    private PendingIntent getResetDemoPendingIntent() {
+        if (mResetDemoPendingIntent == null) {
+            Intent intent = new Intent(ACTION_RESET_DEMO);
+            mResetDemoPendingIntent = PendingIntent.getBroadcast(getContext(), 0, intent, 0);
+        }
+        return mResetDemoPendingIntent;
+    }
+
     private void createAndSwitchToDemoUser() {
         if (DEBUG) {
             Slog.d(TAG, "Switching to a new demo user");
@@ -111,25 +146,54 @@
 
     private void registerSettingsChangeObserver() {
         final Uri deviceDemoModeUri = Settings.Global.getUriFor(Settings.Global.DEVICE_DEMO_MODE);
+        final Uri deviceProvisionedUri = Settings.Global.getUriFor(
+                Settings.Global.DEVICE_PROVISIONED);
         final ContentResolver cr = getContext().getContentResolver();
         final ContentObserver deviceDemoModeSettingObserver = new ContentObserver(mHandler) {
             @Override
             public void onChange(boolean selfChange, Uri uri, int userId) {
+                boolean deviceInDemoMode = UserManager.isDeviceInDemoMode(getContext());
                 if (deviceDemoModeUri.equals(uri)) {
-                    if (UserManager.isDeviceInDemoMode(getContext())) {
+                    if (deviceInDemoMode) {
                         createAndSwitchToDemoUser();
                     }
                 }
+                // If device is provisioned and left demo mode - run the cleanup in demo folder
+                if (!deviceInDemoMode && isDeviceProvisioned()) {
+                    // Run on the bg thread to not block the fg thread
+                    BackgroundThread.getHandler().post(new Runnable() {
+                        @Override
+                        public void run() {
+                            if (!deleteDemoFolderContents()) {
+                                Slog.w(TAG, "Failed to delete demo folder contents");
+                            }
+                        }
+                    });
+                }
             }
         };
         cr.registerContentObserver(deviceDemoModeUri, false, deviceDemoModeSettingObserver,
                 UserHandle.USER_SYSTEM);
+        cr.registerContentObserver(deviceProvisionedUri, false, deviceDemoModeSettingObserver,
+                UserHandle.USER_SYSTEM);
+    }
+
+    boolean isDeviceProvisioned() {
+        return Settings.Global.getInt(
+                getContext().getContentResolver(), Settings.Global.DEVICE_PROVISIONED, 0) != 0;
+    }
+
+    private boolean deleteDemoFolderContents() {
+        File dir = Environment.getDataPreloadsDemoDirectory();
+        Slog.i(TAG, "Deleting contents of " + dir);
+        return FileUtils.deleteContents(dir);
     }
 
     private void registerBroadcastReceiver() {
         final IntentFilter filter = new IntentFilter();
         filter.addAction(Intent.ACTION_SCREEN_OFF);
-        getContext().registerReceiverAsUser(mBroadcastReceiver, UserHandle.ALL, filter, null, null);
+        filter.addAction(ACTION_RESET_DEMO);
+        getContext().registerReceiver(mBroadcastReceiver, filter);
     }
 
     @Override
@@ -151,6 +215,8 @@
         mPm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
         mWakeLock = mPm
                 .newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, TAG);
+        mNm = NotificationManager.from(getContext());
+
         if (UserManager.isDeviceInDemoMode(getContext())) {
             createAndSwitchToDemoUser();
         }
@@ -175,5 +241,6 @@
         if (!mWakeLock.isHeld()) {
             mWakeLock.acquire();
         }
+        mNm.notifyAsUser(TAG, 1, createResetNotification(), UserHandle.of(userId));
     }
 }
diff --git a/services/core/java/com/android/server/am/TaskRecord.java b/services/core/java/com/android/server/am/TaskRecord.java
index 8e9af40..c0adad0 100644
--- a/services/core/java/com/android/server/am/TaskRecord.java
+++ b/services/core/java/com/android/server/am/TaskRecord.java
@@ -73,6 +73,8 @@
 import static android.content.pm.ActivityInfo.RESIZE_MODE_CROP_WINDOWS;
 import static android.content.pm.ActivityInfo.RESIZE_MODE_FORCE_RESIZEABLE;
 import static android.content.pm.ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
+import static android.content.res.Configuration.SCREENLAYOUT_LONG_MASK;
+import static android.content.res.Configuration.SCREENLAYOUT_SIZE_MASK;
 import static android.provider.Settings.Secure.USER_SETUP_COMPLETE;
 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ADD_REMOVE;
 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_LOCKTASK;
@@ -1574,6 +1576,24 @@
         return bounds;
     }
 
+    /**
+     * Update fields that are not overridden for task from global configuration.
+     *
+     * @param globalConfig global configuration to update from.
+     */
+    void sanitizeOverrideConfiguration(Configuration globalConfig) {
+        // screenLayout field is set in #calculateOverrideConfig but only part of it is really
+        // overridden - aspect ratio and size. Other flags (like layout direction) can be updated
+        // separately in global config and they also must be updated in override config.
+        int overrideScreenLayout = mOverrideConfig.screenLayout;
+        int newScreenLayout = globalConfig.screenLayout;
+        newScreenLayout = (newScreenLayout & ~SCREENLAYOUT_LONG_MASK)
+                | (overrideScreenLayout & SCREENLAYOUT_LONG_MASK);
+        newScreenLayout = (newScreenLayout & ~SCREENLAYOUT_SIZE_MASK)
+                | (overrideScreenLayout & SCREENLAYOUT_SIZE_MASK);
+        mOverrideConfig.screenLayout = newScreenLayout;
+    }
+
     static Rect validateBounds(Rect bounds) {
         if (bounds != null && bounds.isEmpty()) {
             Slog.wtf(TAG, "Received strange task bounds: " + bounds, new Throwable());
diff --git a/services/core/java/com/android/server/am/UserController.java b/services/core/java/com/android/server/am/UserController.java
index 2023173..ee85a57 100644
--- a/services/core/java/com/android/server/am/UserController.java
+++ b/services/core/java/com/android/server/am/UserController.java
@@ -18,7 +18,6 @@
 
 import static android.Manifest.permission.INTERACT_ACROSS_USERS;
 import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
-import static android.app.ActivityManager.FLAG_AND_UNLOCKING_OR_UNLOCKED;
 import static android.app.ActivityManager.USER_OP_ERROR_IS_SYSTEM;
 import static android.app.ActivityManager.USER_OP_ERROR_RELATED_USERS_CANNOT_STOP;
 import static android.app.ActivityManager.USER_OP_IS_CURRENT;
@@ -234,6 +233,7 @@
             // but we might immediately step into RUNNING below if the user
             // storage is already unlocked.
             if (uss.setState(STATE_BOOTING, STATE_RUNNING_LOCKED)) {
+                getUserManagerInternal().setUserState(userId, uss.state);
                 Intent intent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED, null);
                 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
                 intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
@@ -277,7 +277,7 @@
             if (!StorageManager.isUserKeyUnlocked(userId)) return;
 
             if (uss.setState(STATE_RUNNING_LOCKED, STATE_RUNNING_UNLOCKING)) {
-                getUserManagerInternal().setUserUnlockingOrUnlocked(userId, true);
+                getUserManagerInternal().setUserState(userId, uss.state);
                 uss.mUnlockProgress.start();
 
                 // Prepare app storage before we go any further
@@ -308,7 +308,7 @@
             if (!StorageManager.isUserKeyUnlocked(userId)) return;
 
             if (uss.setState(STATE_RUNNING_UNLOCKING, STATE_RUNNING_UNLOCKED)) {
-                getUserManagerInternal().setUserUnlockingOrUnlocked(userId, true);
+                getUserManagerInternal().setUserState(userId, uss.state);
                 uss.mUnlockProgress.finish();
 
                 // Dispatch unlocked to external apps
@@ -482,7 +482,7 @@
         if (uss.state != UserState.STATE_STOPPING
                 && uss.state != UserState.STATE_SHUTDOWN) {
             uss.setState(UserState.STATE_STOPPING);
-            getUserManagerInternal().setUserUnlockingOrUnlocked(userId, false);
+            getUserManagerInternal().setUserState(userId, uss.state);
             updateStartedUserArrayLocked();
 
             long ident = Binder.clearCallingIdentity();
@@ -544,7 +544,7 @@
             }
             uss.setState(UserState.STATE_SHUTDOWN);
         }
-        getUserManagerInternal().setUserUnlockingOrUnlocked(userId, false);
+        getUserManagerInternal().setUserState(userId, uss.state);
 
         mService.mBatteryStatsService.noteEvent(
                 BatteryStats.HistoryItem.EVENT_USER_RUNNING_FINISH,
@@ -573,6 +573,7 @@
                 stopped = true;
                 // User can no longer run.
                 mStartedUsers.remove(userId);
+                getUserManagerInternal().removeUserState(userId);
                 mUserLru.remove(Integer.valueOf(userId));
                 updateStartedUserArrayLocked();
 
@@ -780,7 +781,9 @@
                 // If the user we are switching to is not currently started, then
                 // we need to start it now.
                 if (mStartedUsers.get(userId) == null) {
-                    mStartedUsers.put(userId, new UserState(UserHandle.of(userId)));
+                    UserState userState = new UserState(UserHandle.of(userId));
+                    mStartedUsers.put(userId, userState);
+                    getUserManagerInternal().setUserState(userId, userState.state);
                     updateStartedUserArrayLocked();
                     needStart = true;
                 }
@@ -814,15 +817,14 @@
                     // so we can just fairly silently bring the user back from
                     // the almost-dead.
                     uss.setState(uss.lastState);
-                    if (isUserRunningLocked(userId, FLAG_AND_UNLOCKING_OR_UNLOCKED)) {
-                        getUserManagerInternal().setUserUnlockingOrUnlocked(userId, true);
-                    }
+                    getUserManagerInternal().setUserState(userId, uss.state);
                     updateStartedUserArrayLocked();
                     needStart = true;
                 } else if (uss.state == UserState.STATE_SHUTDOWN) {
                     // This means ACTION_SHUTDOWN has been sent, so we will
                     // need to treat this as a new boot of the user.
                     uss.setState(UserState.STATE_BOOTING);
+                    getUserManagerInternal().setUserState(userId, uss.state);
                     updateStartedUserArrayLocked();
                     needStart = true;
                 }
diff --git a/services/core/java/com/android/server/connectivity/Vpn.java b/services/core/java/com/android/server/connectivity/Vpn.java
index 32b9429..1bdb48a 100644
--- a/services/core/java/com/android/server/connectivity/Vpn.java
+++ b/services/core/java/com/android/server/connectivity/Vpn.java
@@ -262,18 +262,37 @@
      * It uses {@link VpnConfig#LEGACY_VPN} as its package name, and
      * it can be revoked by itself.
      *
-     * @param oldPackage The package name of the old VPN application.
-     * @param newPackage The package name of the new VPN application.
+     * Note: when we added VPN pre-consent in http://ag/522961 the names oldPackage
+     * and newPackage become misleading, because when an app is pre-consented, we
+     * actually prepare oldPackage, not newPackage.
+     *
+     * Their meanings actually are:
+     *
+     * - oldPackage non-null, newPackage null: App calling VpnService#prepare().
+     * - oldPackage null, newPackage non-null: ConfirmDialog calling prepareVpn().
+     * - oldPackage non-null, newPackage=LEGACY_VPN: Used internally to disconnect
+     *   and revoke any current app VPN and re-prepare legacy vpn.
+     *
+     * TODO: Rename the variables - or split this method into two - and end this
+     * confusion.
+     *
+     * @param oldPackage The package name of the old VPN application
+     * @param newPackage The package name of the new VPN application
+     *
      * @return true if the operation is succeeded.
      */
     public synchronized boolean prepare(String oldPackage, String newPackage) {
-        // Stop an existing always-on VPN from being dethroned by other apps.
-        if (mAlwaysOn && !TextUtils.equals(mPackage, newPackage)) {
-            return false;
-        }
-
         if (oldPackage != null) {
-            if (getAppUid(oldPackage, mUserHandle) != mOwnerUID) {
+            // Stop an existing always-on VPN from being dethroned by other apps.
+            // TODO: Replace TextUtils.equals by isCurrentPreparedPackage when ConnectivityService
+            // can unset always-on after always-on package is uninstalled. Make sure when package
+            // is reinstalled, the consent dialog is not shown.
+            if (mAlwaysOn && !TextUtils.equals(mPackage, oldPackage)) {
+                return false;
+            }
+
+            // Package is not same or old package was reinstalled.
+            if (!isCurrentPreparedPackage(oldPackage)) {
                 // The package doesn't match. We return false (to obtain user consent) unless the
                 // user has already consented to that VPN package.
                 if (!oldPackage.equals(VpnConfig.LEGACY_VPN) && isVpnUserPreConsented(oldPackage)) {
@@ -291,17 +310,30 @@
 
         // Return true if we do not need to revoke.
         if (newPackage == null || (!newPackage.equals(VpnConfig.LEGACY_VPN) &&
-                getAppUid(newPackage, mUserHandle) == mOwnerUID)) {
+                isCurrentPreparedPackage(newPackage))) {
             return true;
         }
 
         // Check that the caller is authorized.
         enforceControlPermission();
 
+        // Stop an existing always-on VPN from being dethroned by other apps.
+        // TODO: Replace TextUtils.equals by isCurrentPreparedPackage when ConnectivityService
+        // can unset always-on after always-on package is uninstalled
+        if (mAlwaysOn && !TextUtils.equals(mPackage, newPackage)) {
+            return false;
+        }
+
         prepareInternal(newPackage);
         return true;
     }
 
+    private boolean isCurrentPreparedPackage(String packageName) {
+        // We can't just check that packageName matches mPackage, because if the app was uninstalled
+        // and reinstalled it will no longer be prepared. Instead check the UID.
+        return getAppUid(packageName, mUserHandle) == mOwnerUID;
+    }
+
     /** Prepare the VPN for the given package. Does not perform permission checks. */
     private void prepareInternal(String newPackage) {
         long token = Binder.clearCallingIdentity();
@@ -555,8 +587,7 @@
         try {
             // Restricted users are not allowed to create VPNs, they are tied to Owner
             UserInfo user = mgr.getUserInfo(mUserHandle);
-            if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN,
-                    new UserHandle(mUserHandle))) {
+            if (user.isRestricted()) {
                 throw new SecurityException("Restricted users cannot establish VPNs");
             }
 
@@ -1055,18 +1086,27 @@
     }
 
     /**
-     * @return {@code true} if the set of users blocked whilst waiting for VPN to connect includes
-     *         the UID {@param uid}, {@code false} otherwise.
+     * @return {@code true} if {@param uid} is blocked by an always-on VPN.
+     *         A UID is blocked if it's included in one of the mBlockedUsers ranges and the VPN is
+     *         not connected, or if the VPN is connected but does not apply to the UID.
      *
      * @see #mBlockedUsers
      */
     public synchronized boolean isBlockingUid(int uid) {
-        for (UidRange uidRange : mBlockedUsers) {
-            if (uidRange.contains(uid)) {
-                return true;
-            }
+        if (!mLockdown) {
+            return false;
         }
-        return false;
+
+        if (mNetworkInfo.isConnected()) {
+            return !appliesToUid(uid);
+        } else {
+            for (UidRange uidRange : mBlockedUsers) {
+                if (uidRange.contains(uid)) {
+                    return true;
+                }
+            }
+            return false;
+        }
     }
 
     private native int jniCreate(int mtu);
diff --git a/services/core/java/com/android/server/job/JobSchedulerService.java b/services/core/java/com/android/server/job/JobSchedulerService.java
index 491ee18..1b8eccb 100644
--- a/services/core/java/com/android/server/job/JobSchedulerService.java
+++ b/services/core/java/com/android/server/job/JobSchedulerService.java
@@ -16,6 +16,9 @@
 
 package com.android.server.job;
 
+import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
+import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
+
 import java.io.FileDescriptor;
 import java.io.PrintWriter;
 import java.util.ArrayList;
@@ -41,6 +44,7 @@
 import android.content.pm.PackageManager;
 import android.content.pm.ServiceInfo;
 import android.content.pm.PackageManager.NameNotFoundException;
+import android.net.Uri;
 import android.os.BatteryStats;
 import android.os.Binder;
 import android.os.Handler;
@@ -217,7 +221,41 @@
             if (DEBUG) {
                 Slog.d(TAG, "Receieved: " + intent.getAction());
             }
-            if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
+            if (Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())) {
+                // Purge the app's jobs if the whole package was just disabled.  When this is
+                // the case the component name will be a bare package name.
+                final String pkgName = getPackageName(intent);
+                final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
+                if (pkgName != null && pkgUid != -1) {
+                    final String[] changedComponents = intent.getStringArrayExtra(
+                            Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST);
+                    if (changedComponents != null) {
+                        for (String component : changedComponents) {
+                            if (component.equals(pkgName)) {
+                                if (DEBUG) {
+                                    Slog.d(TAG, "Package state change: " + pkgName);
+                                }
+                                try {
+                                    final int userId = UserHandle.getUserId(pkgUid);
+                                    IPackageManager pm = AppGlobals.getPackageManager();
+                                    final int state = pm.getApplicationEnabledSetting(pkgName, userId);
+                                    if (state == COMPONENT_ENABLED_STATE_DISABLED
+                                            || state ==  COMPONENT_ENABLED_STATE_DISABLED_USER) {
+                                        if (DEBUG) {
+                                            Slog.d(TAG, "Removing jobs for package " + pkgName
+                                                    + " in user " + userId);
+                                        }
+                                        cancelJobsForUid(pkgUid, true);
+                                    }
+                                } catch (RemoteException e) { /* cannot happen */ }
+                                break;
+                            }
+                        }
+                    }
+                } else {
+                    Slog.w(TAG, "PACKAGE_CHANGED for " + pkgName + " / uid " + pkgUid);
+                }
+            } else if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
                 // If this is an outright uninstall rather than the first half of an
                 // app update sequence, cancel the jobs associated with the app.
                 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
@@ -237,6 +275,12 @@
         }
     };
 
+    private String getPackageName(Intent intent) {
+        Uri uri = intent.getData();
+        String pkg = uri != null ? uri.getSchemeSpecificPart() : null;
+        return pkg;
+    }
+
     final private IUidObserver mUidObserver = new IUidObserver.Stub() {
         @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
             updateUidState(uid, procState);
@@ -520,7 +564,9 @@
     public void onBootPhase(int phase) {
         if (PHASE_SYSTEM_SERVICES_READY == phase) {
             // Register br for package removals and user removals.
-            final IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_REMOVED);
+            final IntentFilter filter = new IntentFilter();
+            filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
+            filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
             filter.addDataScheme("package");
             getContext().registerReceiverAsUser(
                     mBroadcastReceiver, UserHandle.ALL, filter, null, null);
diff --git a/services/core/java/com/android/server/job/JobServiceContext.java b/services/core/java/com/android/server/job/JobServiceContext.java
index 4fd1350..31528e5 100644
--- a/services/core/java/com/android/server/job/JobServiceContext.java
+++ b/services/core/java/com/android/server/job/JobServiceContext.java
@@ -223,10 +223,11 @@
      * stop executing.
      */
     JobStatus getRunningJob() {
+        final JobStatus job;
         synchronized (mLock) {
-            return mRunningJob == null ?
-                    null : new JobStatus(mRunningJob);
+            job = mRunningJob;
         }
+        return job == null ? null : new JobStatus(job);
     }
 
     /** Called externally when a job that was scheduled for execution should be cancelled. */
diff --git a/services/core/java/com/android/server/notification/ManagedServices.java b/services/core/java/com/android/server/notification/ManagedServices.java
index 53c5a6d..dc85dd7 100644
--- a/services/core/java/com/android/server/notification/ManagedServices.java
+++ b/services/core/java/com/android/server/notification/ManagedServices.java
@@ -16,6 +16,10 @@
 
 package com.android.server.notification;
 
+import static android.content.Context.BIND_ALLOW_WHITELIST_MANAGEMENT;
+import static android.content.Context.BIND_AUTO_CREATE;
+import static android.content.Context.BIND_FOREGROUND_SERVICE;
+
 import android.annotation.NonNull;
 import android.app.ActivityManager;
 import android.app.PendingIntent;
@@ -43,7 +47,6 @@
 import android.os.UserManager;
 import android.provider.Settings;
 import android.text.TextUtils;
-import android.util.ArrayMap;
 import android.util.ArraySet;
 import android.util.Log;
 import android.util.Slog;
@@ -56,7 +59,6 @@
 import java.util.Arrays;
 import java.util.HashSet;
 import java.util.List;
-import java.util.Map.Entry;
 import java.util.Objects;
 import java.util.Set;
 
@@ -681,7 +683,7 @@
             };
             if (!mContext.bindServiceAsUser(intent,
                 serviceConnection,
-                Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE,
+                BIND_AUTO_CREATE | BIND_FOREGROUND_SERVICE | BIND_ALLOW_WHITELIST_MANAGEMENT,
                 new UserHandle(userid))) {
                 mServicesBinding.remove(servicesBindingTag);
                 Slog.w(TAG, "Unable to bind " + getCaption() + " service: " + intent);
diff --git a/services/core/java/com/android/server/notification/NotificationManagerService.java b/services/core/java/com/android/server/notification/NotificationManagerService.java
index 946e4f7..a8b1a4a 100644
--- a/services/core/java/com/android/server/notification/NotificationManagerService.java
+++ b/services/core/java/com/android/server/notification/NotificationManagerService.java
@@ -40,11 +40,13 @@
 import static android.service.notification.NotificationListenerService.TRIM_LIGHT;
 import static android.service.notification.NotificationListenerService.Ranking.IMPORTANCE_DEFAULT;
 import static android.service.notification.NotificationListenerService.Ranking.IMPORTANCE_NONE;
+
 import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
 
 import android.Manifest;
 import android.annotation.Nullable;
 import android.app.ActivityManager;
+import android.app.ActivityManagerInternal;
 import android.app.ActivityManagerNative;
 import android.app.AppGlobals;
 import android.app.AppOpsManager;
@@ -56,6 +58,7 @@
 import android.app.NotificationManager;
 import android.app.NotificationManager.Policy;
 import android.app.PendingIntent;
+import android.app.RemoteInput;
 import android.app.StatusBarManager;
 import android.app.backup.BackupManager;
 import android.app.usage.UsageEvents;
@@ -64,6 +67,7 @@
 import android.content.ComponentName;
 import android.content.ContentResolver;
 import android.content.Context;
+import android.content.IIntentSender;
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.content.pm.ApplicationInfo;
@@ -90,6 +94,7 @@
 import android.os.IInterface;
 import android.os.Looper;
 import android.os.Message;
+import android.os.Parcelable;
 import android.os.Process;
 import android.os.RemoteException;
 import android.os.SystemClock;
@@ -127,6 +132,7 @@
 import com.android.internal.statusbar.NotificationVisibility;
 import com.android.internal.util.FastXmlSerializer;
 import com.android.internal.util.Preconditions;
+import com.android.server.DeviceIdleController;
 import com.android.server.EventLogTags;
 import com.android.server.LocalServices;
 import com.android.server.SystemService;
@@ -2542,6 +2548,8 @@
                     + " id=" + id + " notification=" + notification);
         }
 
+        markAsSentFromNotification(notification);
+
         // Sanitize inputs
         notification.priority = clamp(notification.priority, Notification.PRIORITY_MIN,
                 Notification.PRIORITY_MAX);
@@ -2556,6 +2564,66 @@
         idOut[0] = id;
     }
 
+    private static void markAsSentFromNotification(Notification notification) {
+        final ActivityManagerInternal am = LocalServices.getService(ActivityManagerInternal.class);
+        final long duration = LocalServices.getService(DeviceIdleController.LocalService.class)
+                .getNotificationWhitelistDuration();
+
+        int size = 0;
+        if (notification.contentIntent != null) {
+            am.setPendingIntentWhitelistDuration(notification.contentIntent.getTarget(), duration);
+        }
+        if (notification.deleteIntent != null) {
+            am.setPendingIntentWhitelistDuration(notification.deleteIntent.getTarget(), duration);
+        }
+        if (notification.fullScreenIntent != null) {
+            am.setPendingIntentWhitelistDuration(notification.fullScreenIntent.getTarget(),
+                    duration);
+        }
+        if (notification.actions != null) {
+            for (Notification.Action action: notification.actions) {
+                if (action.actionIntent == null) {
+                    continue;
+                }
+                am.setPendingIntentWhitelistDuration(action.actionIntent.getTarget(), duration);
+                setPendingIntentWhitelistDuration(am, duration, action.getExtras());
+                final RemoteInput[] remoteInputs = action.getRemoteInputs();
+                if (remoteInputs != null) {
+                    for (RemoteInput remoteInput : remoteInputs) {
+                        setPendingIntentWhitelistDuration(am, duration, remoteInput.getExtras());
+                    }
+                }
+            }
+        }
+    }
+
+    private static void setPendingIntentWhitelistDuration(ActivityManagerInternal am, long duration,
+            Bundle extras) {
+        for (String key : extras.keySet()) {
+            setPendingIntentWhitelistDuration(am, duration, extras.getParcelable(key));
+            final Parcelable[] parcelableArray = extras.getParcelableArray(key);
+            if (parcelableArray != null) {
+                for (Parcelable parcelable: parcelableArray) {
+                    setPendingIntentWhitelistDuration(am, duration, parcelable);
+                }
+            }
+            final ArrayList<Parcelable> parcelableList = extras.getParcelableArrayList(key);
+            if (parcelableList != null) {
+                for (Parcelable parcelable: parcelableList) {
+                    setPendingIntentWhitelistDuration(am, duration, parcelable);
+                }
+            }
+        }
+    }
+
+    private static void setPendingIntentWhitelistDuration(ActivityManagerInternal am, long duration,
+            Parcelable parcelable) {
+        if (parcelable instanceof PendingIntent) {
+            am.setPendingIntentWhitelistDuration(((PendingIntent) parcelable).getTarget(),
+                    duration);
+        }
+    }
+
     private class EnqueueNotificationRunnable implements Runnable {
         private final NotificationRecord r;
         private final int userId;
@@ -3813,8 +3881,10 @@
 
         @Override
         public void onUserSwitched(int user) {
-            for (ManagedServiceInfo info : mServices) {
-                unregisterService(info.service, info.userid);
+            synchronized (mNotificationList) {
+                for (ManagedServiceInfo info : mServices) {
+                    unregisterService(info.service, info.userid);
+                }
             }
             registerRanker();
         }
diff --git a/services/core/java/com/android/server/notification/NotificationRecord.java b/services/core/java/com/android/server/notification/NotificationRecord.java
index 7c89e9f..367f8cb 100644
--- a/services/core/java/com/android/server/notification/NotificationRecord.java
+++ b/services/core/java/com/android/server/notification/NotificationRecord.java
@@ -318,8 +318,12 @@
 
     public void setContactAffinity(float contactAffinity) {
         mContactAffinity = contactAffinity;
+        if (mImportance < IMPORTANCE_HIGH &&
+                mContactAffinity >= ValidateNotificationPeople.STARRED_CONTACT) {
+            setImportance(IMPORTANCE_HIGH, getPeopleExplanation());
+        }
         if (mImportance < IMPORTANCE_DEFAULT &&
-                mContactAffinity > ValidateNotificationPeople.VALID_CONTACT) {
+                mContactAffinity >= ValidateNotificationPeople.VALID_CONTACT) {
             setImportance(IMPORTANCE_DEFAULT, getPeopleExplanation());
         }
     }
diff --git a/services/core/java/com/android/server/pm/BackgroundDexOptService.java b/services/core/java/com/android/server/pm/BackgroundDexOptService.java
index ee02a99..87f0581 100644
--- a/services/core/java/com/android/server/pm/BackgroundDexOptService.java
+++ b/services/core/java/com/android/server/pm/BackgroundDexOptService.java
@@ -154,7 +154,6 @@
                     // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
                     // trade-off worth doing to save boot time work.
                     pm.performDexOpt(pkg,
-                            /* instruction set */ null,
                             /* checkProfiles */ false,
                             PackageManagerService.REASON_BOOT,
                             /* force */ false);
@@ -192,7 +191,6 @@
                     // Optimize package if needed. Note that there can be no race between
                     // concurrent jobs because PackageDexOptimizer.performDexOpt is synchronized.
                     if (pm.performDexOpt(pkg,
-                            /* instruction set */ null,
                             /* checkProfiles */ true,
                             PackageManagerService.REASON_BACKGROUND_DEXOPT,
                             /* force */ false)) {
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index 35bcaa9..eb4d755 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -2395,6 +2395,10 @@
             mPromoteSystemApps =
                     mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
 
+            // When upgrading from pre-N, we need to handle package extraction like first boot,
+            // as there is no profiling data available.
+            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
+
             // 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) {
@@ -2407,11 +2411,6 @@
                 }
             }
 
-            // When upgrading from pre-N, we need to handle package extraction like first boot,
-            // as there is no profiling data available.
-            mIsPreNUpgrade = !mSettings.isNWorkDone();
-            mSettings.setNWorkDone();
-
             // Collect vendor overlay packages.
             // (Do this before scanning any apps.)
             // For security and version matching reason, only consider
@@ -7267,7 +7266,6 @@
             // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
             // trade-off worth doing to save boot time work.
             int dexOptStatus = performDexOptTraced(pkg.packageName,
-                    null /* instructionSet */,
                     false /* checkProfiles */,
                     getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
                     false /* force */);
@@ -7309,33 +7307,33 @@
 
     // TODO: this is not used nor needed. Delete it.
     @Override
-    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
-        int dexOptStatus = performDexOptTraced(packageName, instructionSet,
+    public boolean performDexOptIfNeeded(String packageName) {
+        int dexOptStatus = performDexOptTraced(packageName,
                 false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
         return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
     }
 
     @Override
-    public boolean performDexOpt(String packageName, String instructionSet,
+    public boolean performDexOpt(String packageName,
             boolean checkProfiles, int compileReason, boolean force) {
-        int dexOptStatus = performDexOptTraced(packageName, instructionSet, checkProfiles,
+        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
                 getCompilerFilterForReason(compileReason), force);
         return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
     }
 
     @Override
-    public boolean performDexOptMode(String packageName, String instructionSet,
+    public boolean performDexOptMode(String packageName,
             boolean checkProfiles, String targetCompilerFilter, boolean force) {
-        int dexOptStatus = performDexOptTraced(packageName, instructionSet, checkProfiles,
+        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
                 targetCompilerFilter, force);
         return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
     }
 
-    private int performDexOptTraced(String packageName, String instructionSet,
+    private int performDexOptTraced(String packageName,
                 boolean checkProfiles, String targetCompilerFilter, boolean force) {
         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
         try {
-            return performDexOptInternal(packageName, instructionSet, checkProfiles,
+            return performDexOptInternal(packageName, checkProfiles,
                     targetCompilerFilter, force);
         } finally {
             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
@@ -7344,10 +7342,9 @@
 
     // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
     // if the package can now be considered up to date for the given filter.
-    private int performDexOptInternal(String packageName, String instructionSet,
+    private int performDexOptInternal(String packageName,
                 boolean checkProfiles, String targetCompilerFilter, boolean force) {
         PackageParser.Package p;
-        final String targetInstructionSet;
         synchronized (mPackages) {
             p = mPackages.get(packageName);
             if (p == null) {
@@ -7355,15 +7352,11 @@
                 return PackageDexOptimizer.DEX_OPT_FAILED;
             }
             mPackageUsage.write(false);
-
-            targetInstructionSet = instructionSet != null ? instructionSet :
-                    getPrimaryInstructionSet(p.applicationInfo);
         }
         long callingId = Binder.clearCallingIdentity();
         try {
             synchronized (mInstallLock) {
-                final String[] instructionSets = new String[] { targetInstructionSet };
-                return performDexOptInternalWithDependenciesLI(p, instructionSets, checkProfiles,
+                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
                         targetCompilerFilter, force);
             }
         } finally {
@@ -7384,7 +7377,7 @@
     }
 
     private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
-            String instructionSets[], boolean checkProfiles, String targetCompilerFilter,
+            boolean checkProfiles, String targetCompilerFilter,
             boolean force) {
         // Select the dex optimizer based on the force parameter.
         // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
@@ -7396,6 +7389,7 @@
         // Optimize all dependencies first. Note: we ignore the return value and march on
         // on errors.
         Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
+        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
         if (!deps.isEmpty()) {
             for (PackageParser.Package depPackage : deps) {
                 // TODO: Analyze and investigate if we (should) profile libraries.
@@ -7405,7 +7399,6 @@
                         getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY));
             }
         }
-
         return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
                 targetCompilerFilter);
     }
@@ -7477,14 +7470,11 @@
         }
 
         synchronized (mInstallLock) {
-            final String[] instructionSets = new String[] {
-                    getPrimaryInstructionSet(pkg.applicationInfo) };
-
             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
 
             // Whoever is calling forceDexOpt wants a fully compiled package.
             // Don't use profiles since that may cause compilation to be skipped.
-            final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets,
+            final int res = performDexOptInternalWithDependenciesLI(pkg,
                     false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
                     true /* force */);
 
@@ -16300,11 +16290,11 @@
         final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
         removeKeystoreDataIfNeeded(userId, appId);
 
-        final UserManager um = mContext.getSystemService(UserManager.class);
+        UserManagerInternal umInternal = getUserManagerInternal();
         final int flags;
-        if (um.isUserUnlockingOrUnlocked(userId)) {
+        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
             flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
-        } else if (um.isUserRunning(userId)) {
+        } else if (umInternal.isUserRunning(userId)) {
             flags = StorageManager.FLAG_STORAGE_DE;
         } else {
             flags = 0;
@@ -19063,11 +19053,12 @@
         // Reconcile app data for all started/unlocked users
         final StorageManager sm = mContext.getSystemService(StorageManager.class);
         final UserManager um = mContext.getSystemService(UserManager.class);
+        UserManagerInternal umInternal = getUserManagerInternal();
         for (UserInfo user : um.getUsers()) {
             final int flags;
-            if (um.isUserUnlockingOrUnlocked(user.id)) {
+            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
                 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
-            } else if (um.isUserRunning(user.id)) {
+            } else if (umInternal.isUserRunning(user.id)) {
                 flags = StorageManager.FLAG_STORAGE_DE;
             } else {
                 continue;
@@ -19491,11 +19482,12 @@
         }
 
         final UserManager um = mContext.getSystemService(UserManager.class);
+        UserManagerInternal umInternal = getUserManagerInternal();
         for (UserInfo user : um.getUsers()) {
             final int flags;
-            if (um.isUserUnlockingOrUnlocked(user.id)) {
+            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
                 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
-            } else if (um.isUserRunning(user.id)) {
+            } else if (umInternal.isUserRunning(user.id)) {
                 flags = StorageManager.FLAG_STORAGE_DE;
             } else {
                 continue;
diff --git a/services/core/java/com/android/server/pm/PackageManagerServiceUtils.java b/services/core/java/com/android/server/pm/PackageManagerServiceUtils.java
index b305ba7..751c585 100644
--- a/services/core/java/com/android/server/pm/PackageManagerServiceUtils.java
+++ b/services/core/java/com/android/server/pm/PackageManagerServiceUtils.java
@@ -34,6 +34,8 @@
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
 import java.util.Date;
 import java.util.HashSet;
 import java.util.Iterator;
@@ -66,15 +68,15 @@
     }
 
     private static void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs,
+            long estimatedPreviousSystemUseTime,
             long dexOptLRUThresholdInMills) {
         // Filter out packages that aren't recently used.
         int total = pkgs.size();
         int skipped = 0;
-        long now = System.currentTimeMillis();
         for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
             PackageParser.Package pkg = i.next();
             long then = pkg.getLatestForegroundPackageUseTimeInMills();
-            if (then + dexOptLRUThresholdInMills < now) {
+            if (then < estimatedPreviousSystemUseTime - dexOptLRUThresholdInMills) {
                 if (DEBUG_DEXOPT) {
                     Log.i(TAG, "Skipping dexopt of " + pkg.packageName +
                             " last used in foreground: " +
@@ -82,6 +84,12 @@
                 }
                 i.remove();
                 skipped++;
+            } else {
+                if (DEBUG_DEXOPT) {
+                    Log.i(TAG, "Will dexopt " + pkg.packageName +
+                            " last used in foreground: " +
+                            ((then == 0) ? "never" : new Date(then)));
+                }
             }
         }
         if (DEBUG_DEXOPT) {
@@ -136,8 +144,24 @@
 
         // Filter out packages that aren't recently used, add all remaining apps.
         // TODO: add a property to control this?
-        if (packageManagerService.isHistoricalPackageUsageAvailable()) {
-            filterRecentlyUsedApps(remainingPkgs, SEVEN_DAYS_IN_MILLISECONDS);
+        if (!remainingPkgs.isEmpty() && packageManagerService.isHistoricalPackageUsageAvailable()) {
+            if (DEBUG_DEXOPT) {
+                Log.i(TAG, "Looking at historical package use");
+            }
+            // Get the package that was used last.
+            PackageParser.Package lastUsed = Collections.max(remainingPkgs, (pkg1, pkg2) ->
+                    Long.compare(pkg1.getLatestForegroundPackageUseTimeInMills(),
+                            pkg2.getLatestForegroundPackageUseTimeInMills()));
+            if (DEBUG_DEXOPT) {
+                Log.i(TAG, "Taking package " + lastUsed.packageName + " as reference in time use");
+            }
+            long estimatedPreviousSystemUseTime =
+                    lastUsed.getLatestForegroundPackageUseTimeInMills();
+            // Be defensive if for some reason package usage has bogus data.
+            if (estimatedPreviousSystemUseTime != 0) {
+                filterRecentlyUsedApps(remainingPkgs, estimatedPreviousSystemUseTime,
+                        SEVEN_DAYS_IN_MILLISECONDS);
+            }
         }
         result.addAll(remainingPkgs);
 
diff --git a/services/core/java/com/android/server/pm/PackageManagerShellCommand.java b/services/core/java/com/android/server/pm/PackageManagerShellCommand.java
index 1eeff14..beff8fc 100644
--- a/services/core/java/com/android/server/pm/PackageManagerShellCommand.java
+++ b/services/core/java/com/android/server/pm/PackageManagerShellCommand.java
@@ -358,7 +358,7 @@
                 mInterface.clearApplicationProfileData(packageName);
             }
 
-            boolean result = mInterface.performDexOptMode(packageName, null /* instructionSet */,
+            boolean result = mInterface.performDexOptMode(packageName,
                     checkProfiles, targetCompilerFilter, forceCompilation);
             if (!result) {
                 failedPackages.add(packageName);
diff --git a/services/core/java/com/android/server/pm/Settings.java b/services/core/java/com/android/server/pm/Settings.java
index 5e22e58..5126305 100644
--- a/services/core/java/com/android/server/pm/Settings.java
+++ b/services/core/java/com/android/server/pm/Settings.java
@@ -191,7 +191,6 @@
     private static final String TAG_DEFAULT_BROWSER = "default-browser";
     private static final String TAG_DEFAULT_DIALER = "default-dialer";
     private static final String TAG_VERSION = "version";
-    private static final String TAG_N_WORK = "n-work";
 
     private static final String ATTR_NAME = "name";
     private static final String ATTR_USER = "user";
@@ -398,17 +397,6 @@
 
     public final KeySetManagerService mKeySetManagerService = new KeySetManagerService(mPackages);
 
-    /**
-     * Used to track whether N+ work has been done. This is similar to the file-system level
-     * and denotes that first-boot or upgrade-to-N work has been done.
-     *
-     * Note: the flag has been added to a) allow tracking while an API level check is impossible
-     *       and b) to merge upgrade as well as first boot (because the flag is false, by default).
-     *
-     * STOPSHIP: b/27872764
-     */
-    private boolean mIsNWorkDone = false;
-
     Settings(Object lock) {
         this(Environment.getDataDirectory(), lock);
     }
@@ -2396,10 +2384,6 @@
 
             mKeySetManagerService.writeKeySetManagerServiceLPr(serializer);
 
-            serializer.startTag(null, TAG_N_WORK);
-            serializer.attribute(null, ATTR_DONE, Boolean.toString(mIsNWorkDone));
-            serializer.endTag(null, TAG_N_WORK);
-
             serializer.endTag(null, "packages");
 
             serializer.endDocument();
@@ -2937,8 +2921,6 @@
                     ver.sdkVersion = XmlUtils.readIntAttribute(parser, ATTR_SDK_VERSION);
                     ver.databaseVersion = XmlUtils.readIntAttribute(parser, ATTR_SDK_VERSION);
                     ver.fingerprint = XmlUtils.readStringAttribute(parser, ATTR_FINGERPRINT);
-                } else if (TAG_N_WORK.equals(tagName)) {
-                    mIsNWorkDone = XmlUtils.readBooleanAttribute(parser, ATTR_DONE, false);
                 } else {
                     Slog.w(PackageManagerService.TAG, "Unknown element under <packages>: "
                             + parser.getName());
@@ -4233,14 +4215,6 @@
         return res;
     }
 
-    public boolean isNWorkDone() {
-        return mIsNWorkDone;
-    }
-
-    void setNWorkDone() {
-        mIsNWorkDone = true;
-    }
-
     static void printFlags(PrintWriter pw, int val, Object[] spec) {
         pw.print("[ ");
         for (int i=0; i<spec.length; i+=2) {
diff --git a/services/core/java/com/android/server/pm/ShortcutLauncher.java b/services/core/java/com/android/server/pm/ShortcutLauncher.java
index db2b9f4..e667838 100644
--- a/services/core/java/com/android/server/pm/ShortcutLauncher.java
+++ b/services/core/java/com/android/server/pm/ShortcutLauncher.java
@@ -36,6 +36,8 @@
 
 /**
  * Launcher information used by {@link ShortcutService}.
+ *
+ * All methods should be guarded by {@code #mShortcutUser.mService.mLock}.
  */
 class ShortcutLauncher extends ShortcutPackageItem {
     private static final String TAG = ShortcutService.TAG;
@@ -125,7 +127,8 @@
                 if (si == null) {
                     continue;
                 }
-                if (si.isDynamic() || (prevSet != null && prevSet.contains(id))) {
+                if (si.isDynamic() || si.isManifestShortcut()
+                        || (prevSet != null && prevSet.contains(id))) {
                     newSet.add(id);
                 }
             }
diff --git a/services/core/java/com/android/server/pm/ShortcutPackage.java b/services/core/java/com/android/server/pm/ShortcutPackage.java
index c298683..bca3777 100644
--- a/services/core/java/com/android/server/pm/ShortcutPackage.java
+++ b/services/core/java/com/android/server/pm/ShortcutPackage.java
@@ -20,6 +20,7 @@
 import android.annotation.UserIdInt;
 import android.content.ComponentName;
 import android.content.Intent;
+import android.content.pm.PackageInfo;
 import android.content.pm.ShortcutInfo;
 import android.os.PersistableBundle;
 import android.text.format.Formatter;
@@ -28,6 +29,7 @@
 import android.util.Slog;
 
 import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.util.Preconditions;
 import com.android.internal.util.XmlUtils;
 
 import org.xmlpull.v1.XmlPullParser;
@@ -44,6 +46,11 @@
 
 /**
  * Package information used by {@link ShortcutService}.
+ * User information used by {@link ShortcutService}.
+ *
+ * All methods should be guarded by {@code #mShortcutUser.mService.mLock}.
+ *
+ * TODO Max dynamic shortcuts cap should be per activity.
  */
 class ShortcutPackage extends ShortcutPackageItem {
     private static final String TAG = ShortcutService.TAG;
@@ -55,7 +62,6 @@
     private static final String TAG_CATEGORIES = "categories";
 
     private static final String ATTR_NAME = "name";
-    private static final String ATTR_DYNAMIC_COUNT = "dynamic-count";
     private static final String ATTR_CALL_COUNT = "call-count";
     private static final String ATTR_LAST_RESET = "last-reset";
     private static final String ATTR_ID = "id";
@@ -84,11 +90,6 @@
     final private ArrayMap<String, ShortcutInfo> mShortcuts = new ArrayMap<>();
 
     /**
-     * # of dynamic shortcuts.
-     */
-    private int mDynamicShortcutCount = 0;
-
-    /**
      * # of times the package has called rate-limited APIs.
      */
     private int mApiCallCount;
@@ -129,19 +130,19 @@
      * exists (as opposed to Launcher trying to fetch shortcuts from a non-existent package), so
      * we do some initialization for the package.
      */
-    private void onShortcutPublish() {
+    private void ensurePackageVersionInfo() {
         // Make sure we have the version code for the app.  We need the version code in
         // handlePackageUpdated().
         if (getPackageInfo().getVersionCode() < 0) {
             final ShortcutService s = mShortcutUser.mService;
 
-            final int versionCode = s.getApplicationVersionCode(getPackageName(), getOwnerUserId());
-            if (ShortcutService.DEBUG) {
-                Slog.d(TAG, String.format("Package %s version = %d", getPackageName(),
-                        versionCode));
-            }
-            if (versionCode >= 0) {
-                getPackageInfo().setVersionCode(versionCode);
+            final PackageInfo pi = s.getPackageInfo(getPackageName(), getOwnerUserId());
+            if (pi != null) {
+                if (ShortcutService.DEBUG) {
+                    Slog.d(TAG, String.format("Package %s version = %d", getPackageName(),
+                            pi.versionCode));
+                }
+                getPackageInfo().updateVersionInfo(pi);
                 s.scheduleSaveUser(getOwnerUserId());
             }
         }
@@ -168,17 +169,42 @@
         return mShortcuts.get(id);
     }
 
-    private ShortcutInfo deleteShortcut(@NonNull String id) {
+    private void ensureNotImmutable(@Nullable ShortcutInfo shortcut) {
+        if (shortcut != null && shortcut.isImmutable()) {
+            throw new IllegalArgumentException(
+                    "Manifest shortcut ID=" + shortcut.getId()
+                            + " may not be manipulated via APIs");
+        }
+    }
+
+    private void ensureNotImmutable(@NonNull String id) {
+        ensureNotImmutable(mShortcuts.get(id));
+    }
+
+    public void ensureImmutableShortcutsNotIncludedWithIds(@NonNull List<String> shortcutIds) {
+        for (int i = shortcutIds.size() - 1; i >= 0; i--) {
+            ensureNotImmutable(shortcutIds.get(i));
+        }
+    }
+
+    public void ensureImmutableShortcutsNotIncluded(@NonNull List<ShortcutInfo> shortcuts) {
+        for (int i = shortcuts.size() - 1; i >= 0; i--) {
+            ensureNotImmutable(shortcuts.get(i).getId());
+        }
+    }
+
+    private ShortcutInfo deleteShortcutInner(@NonNull String id) {
         final ShortcutInfo shortcut = mShortcuts.remove(id);
         if (shortcut != null) {
             mShortcutUser.mService.removeIcon(getPackageUserId(), shortcut);
-            shortcut.clearFlags(ShortcutInfo.FLAG_DYNAMIC | ShortcutInfo.FLAG_PINNED);
+            shortcut.clearFlags(ShortcutInfo.FLAG_DYNAMIC | ShortcutInfo.FLAG_PINNED
+                    | ShortcutInfo.FLAG_MANIFEST);
         }
         return shortcut;
     }
 
-    void addShortcut(@NonNull ShortcutInfo newShortcut) {
-        deleteShortcut(newShortcut.getId());
+    private void addShortcutInner(@NonNull ShortcutInfo newShortcut) {
+        deleteShortcutInner(newShortcut.getId());
         mShortcutUser.mService.saveIconAndFixUpShortcut(getPackageUserId(), newShortcut);
         mShortcuts.put(newShortcut.getId(), newShortcut);
     }
@@ -188,39 +214,41 @@
      *
      * It checks the max number of dynamic shortcuts.
      */
-    public void addDynamicShortcut(@NonNull ShortcutInfo newShortcut) {
+    public void addOrUpdateDynamicShortcut(@NonNull ShortcutInfo newShortcut) {
 
-        onShortcutPublish();
+        Preconditions.checkArgument(newShortcut.isEnabled(),
+                "add/setDynamicShortcuts() cannot publish disabled shortcuts");
+
+        ensurePackageVersionInfo();
 
         newShortcut.addFlags(ShortcutInfo.FLAG_DYNAMIC);
 
         final ShortcutInfo oldShortcut = mShortcuts.get(newShortcut.getId());
 
         final boolean wasPinned;
-        final int newDynamicCount;
 
         if (oldShortcut == null) {
             wasPinned = false;
-            newDynamicCount = mDynamicShortcutCount + 1; // adding a dynamic shortcut.
         } else {
+            // It's an update case.
+            // Make sure the target is updatable. (i.e. should be mutable.)
+            oldShortcut.ensureUpdatableWith(newShortcut);
+
             wasPinned = oldShortcut.isPinned();
-            if (oldShortcut.isDynamic()) {
-                newDynamicCount = mDynamicShortcutCount; // not adding a dynamic shortcut.
-            } else {
-                newDynamicCount = mDynamicShortcutCount + 1; // adding a dynamic shortcut.
+            if (!oldShortcut.isEnabled()) {
+                newShortcut.addFlags(ShortcutInfo.FLAG_DISABLED);
             }
         }
 
-        // Make sure there's still room.
-        mShortcutUser.mService.enforceMaxDynamicShortcuts(newDynamicCount);
+        // TODO Check max dynamic count.
+        // mShortcutUser.mService.enforceMaxDynamicShortcuts(newDynamicCount);
 
         // Okay, make it dynamic and add.
         if (wasPinned) {
             newShortcut.addFlags(ShortcutInfo.FLAG_PINNED);
         }
 
-        addShortcut(newShortcut);
-        mDynamicShortcutCount = newDynamicCount;
+        addShortcutInner(newShortcut);
     }
 
     /**
@@ -232,7 +260,7 @@
         for (int i = mShortcuts.size() - 1; i >= 0; i--) {
             final ShortcutInfo si = mShortcuts.valueAt(i);
 
-            if (si.isPinned() || si.isDynamic()) continue;
+            if (si.isAlive()) continue;
 
             if (removeList == null) {
                 removeList = new ArrayList<>();
@@ -241,7 +269,7 @@
         }
         if (removeList != null) {
             for (int i = removeList.size() - 1; i >= 0; i--) {
-                deleteShortcut(removeList.get(i));
+                deleteShortcutInner(removeList.get(i));
             }
         }
     }
@@ -250,29 +278,68 @@
      * Remove all dynamic shortcuts.
      */
     public void deleteAllDynamicShortcuts() {
+        boolean changed = false;
         for (int i = mShortcuts.size() - 1; i >= 0; i--) {
-            mShortcuts.valueAt(i).clearFlags(ShortcutInfo.FLAG_DYNAMIC);
+            final ShortcutInfo si = mShortcuts.valueAt(i);
+            if (si.isDynamic()) {
+                changed = true;
+                si.clearFlags(ShortcutInfo.FLAG_DYNAMIC);
+            }
         }
-        removeOrphans();
-        mDynamicShortcutCount = 0;
+        if (changed) {
+            removeOrphans();
+        }
     }
 
     /**
      * Remove a dynamic shortcut by ID.
      */
     public void deleteDynamicWithId(@NonNull String shortcutId) {
+        deleteOrDisableWithId(shortcutId, /* disable =*/ false, /* overrideImmutable=*/ false);
+    }
+
+    public void disableWithId(@NonNull String shortcutId, String disabledMessage,
+            int disabledMessageResId, boolean overrideImmutable) {
+        final ShortcutInfo disabled = deleteOrDisableWithId(shortcutId, /* disable =*/ true,
+                overrideImmutable);
+
+        if (disabled != null) {
+            if (disabledMessage != null) {
+                disabled.setDisabledMessage(disabledMessage);
+            } else if (disabledMessageResId != 0) {
+                disabled.setDisabledMessageResId(disabledMessageResId);
+            }
+        }
+    }
+
+    @Nullable
+    private ShortcutInfo deleteOrDisableWithId(@NonNull String shortcutId, boolean disable,
+            boolean overrideImmutable) {
         final ShortcutInfo oldShortcut = mShortcuts.get(shortcutId);
 
-        if (oldShortcut == null) {
-            return;
+        if (oldShortcut == null || !oldShortcut.isEnabled()) {
+            return null; // Doesn't exist or already disabled.
         }
-        if (oldShortcut.isDynamic()) {
-            mDynamicShortcutCount--;
+        if (!overrideImmutable) {
+            ensureNotImmutable(oldShortcut);
         }
         if (oldShortcut.isPinned()) {
-            oldShortcut.clearFlags(ShortcutInfo.FLAG_DYNAMIC);
+            oldShortcut.clearFlags(ShortcutInfo.FLAG_DYNAMIC | ShortcutInfo.FLAG_MANIFEST);
+            if (disable) {
+                oldShortcut.addFlags(ShortcutInfo.FLAG_DISABLED);
+            }
+            return oldShortcut;
         } else {
-            deleteShortcut(shortcutId);
+            deleteShortcutInner(shortcutId);
+            return null;
+        }
+    }
+
+    public void enableWithId(@NonNull String shortcutId) {
+        final ShortcutInfo shortcut = mShortcuts.get(shortcutId);
+        if (shortcut != null) {
+            ensureNotImmutable(shortcut);
+            shortcut.clearFlags(ShortcutInfo.FLAG_DISABLED);
         }
     }
 
@@ -430,22 +497,19 @@
         for (int i = 0; i < mShortcuts.size(); i++) {
             final ShortcutInfo si = mShortcuts.valueAt(i);
 
-            // If it's called by non-launcher (i.e. publisher, always include -> true.
-            // Otherwise, only include non-dynamic pinned one, if the calling launcher has pinned
-            // it.
+            // Need to adjust PINNED flag depending on the caller.
+            // Basically if the caller is a launcher (callingLauncher != null) and the launcher
+            // isn't pinning it, then we need to clear PINNED for this caller.
             final boolean isPinnedByCaller = (callingLauncher == null)
                     || ((pinnedByCallerSet != null) && pinnedByCallerSet.contains(si.getId()));
-            if (!si.isDynamic()) {
-                if (!si.isPinned()) {
-                    s.wtf("Shortcut not pinned: package " + getPackageName()
-                            + ", user=" + getPackageUserId() + ", id=" + si.getId());
-                    continue;
-                }
+
+            if (si.isFloating()) {
                 if (!isPinnedByCaller) {
                     continue;
                 }
             }
             final ShortcutInfo clone = si.clone(cloneFlag);
+
             // Fix up isPinned for the caller.  Note we need to do it before the "test" callback,
             // since it may check isPinned.
             if (!isPinnedByCaller) {
@@ -486,32 +550,81 @@
     }
 
     /**
-     * Called when the package is updated.  If there are shortcuts with resource icons, update
-     * their timestamps.
+     * Called when the package is updated or added.
+     *
+     * Add case:
+     * - Publish manifest shortcuts.
+     *
+     * Update case:
+     * - Re-publish manifest shortcuts.
+     * - If there are shortcuts with resources (icons or strings), update their timestamps.
+     *
+     * @return TRUE if any shortcuts have been changed.
      */
-    public void handlePackageUpdated(int newVersionCode) {
-        if (getPackageInfo().getVersionCode() >= newVersionCode) {
-            // Version hasn't changed; nothing to do.
-            return;
-        }
-        if (ShortcutService.DEBUG) {
-            Slog.d(TAG, String.format("Package %s updated, version %d -> %d", getPackageName(),
-                    getPackageInfo().getVersionCode(), newVersionCode));
+    public boolean handlePackageAddedOrUpdated(boolean isNewApp) {
+        final PackageInfo pi = mShortcutUser.mService.getPackageInfo(
+                getPackageName(), getPackageUserId());
+        if (pi == null) {
+            return false; // Shouldn't happen.
         }
 
-        getPackageInfo().setVersionCode(newVersionCode);
+        if (!isNewApp) {
+            // Make sure the version code or last update time has changed.
+            // Otherwise, nothing to do.
+            if (getPackageInfo().getVersionCode() >= pi.versionCode
+                    && getPackageInfo().getLastUpdateTime() >= pi.lastUpdateTime) {
+                return false;
+            }
+        }
+
+        // Now prepare to publish manifest shortcuts.
+        List<ShortcutInfo> newManifestShortcutList = null;
+        try {
+            newManifestShortcutList = ShortcutParser.parseShortcuts(mShortcutUser.mService,
+                    getPackageName(), getPackageUserId());
+        } catch (IOException|XmlPullParserException e) {
+            Slog.e(TAG, "Failed to load shortcuts from AndroidManifest.xml.", e);
+        }
+        final int manifestShortcutSize = newManifestShortcutList == null ? 0
+                : newManifestShortcutList.size();
+        if (ShortcutService.DEBUG) {
+            Slog.d(TAG, String.format("Package %s has %d manifest shortcut(s)",
+                    getPackageName(), manifestShortcutSize));
+        }
+        if (isNewApp && (manifestShortcutSize == 0)) {
+            // If it's a new app, and it doesn't have manifest shortcuts, then nothing to do.
+
+            // If it's an update, then it may already have manifest shortcuts, which need to be
+            // disabled.
+            return false;
+        }
+        if (ShortcutService.DEBUG) {
+            Slog.d(TAG, String.format("Package %s %s, version %d -> %d", getPackageName(),
+                    (isNewApp ? "added" : "updated"),
+                    getPackageInfo().getVersionCode(), pi.versionCode));
+        }
+
+        getPackageInfo().updateVersionInfo(pi);
 
         final ShortcutService s = mShortcutUser.mService;
 
         boolean changed = false;
-        for (int i = mShortcuts.size() - 1; i >= 0; i--) {
-            final ShortcutInfo si = mShortcuts.valueAt(i);
 
-            if (si.hasAnyResources()) {
-                changed = true;
-                si.setTimestamp(s.injectCurrentTimeMillis());
+        // For existing shortcuts, update timestamps if they have any resources.
+        if (!isNewApp) {
+            for (int i = mShortcuts.size() - 1; i >= 0; i--) {
+                final ShortcutInfo si = mShortcuts.valueAt(i);
+
+                if (si.hasAnyResources()) {
+                    changed = true;
+                    si.setTimestamp(s.injectCurrentTimeMillis());
+                }
             }
         }
+
+        // (Re-)publish manifest shortcut.
+        changed |= publishManifestShortcuts(newManifestShortcutList);
+
         if (changed) {
             // This will send a notification to the launcher, and also save .
             s.packageShortcutsChanged(getPackageName(), getPackageUserId());
@@ -519,6 +632,97 @@
             // Still save the version code.
             s.scheduleSaveUser(getPackageUserId());
         }
+        return changed;
+    }
+
+    private boolean publishManifestShortcuts(List<ShortcutInfo> newManifestShortcutList) {
+        if (ShortcutService.DEBUG) {
+            Slog.d(TAG, String.format(
+                    "Package %s: publishing manifest shortcuts", getPackageName()));
+        }
+        boolean changed = false;
+
+        // TODO: Check dynamic count
+
+        // TODO: Kick out dynamic if too many
+
+        // Keep the previous IDs.
+        ArraySet<String> toDisableList = null;
+        for (int i = mShortcuts.size() - 1; i >= 0; i--) {
+            final ShortcutInfo si = mShortcuts.valueAt(i);
+
+            if (si.isManifestShortcut()) {
+                if (toDisableList == null) {
+                    toDisableList = new ArraySet<>();
+                }
+                toDisableList.add(si.getId());
+            }
+        }
+
+        // Publish new ones.
+        if (newManifestShortcutList != null) {
+            final int newListSize = newManifestShortcutList.size();
+
+            for (int i = 0; i < newListSize; i++) {
+                changed = true;
+
+                final ShortcutInfo newShortcut = newManifestShortcutList.get(i);
+                final boolean newDisabled = !newShortcut.isEnabled();
+
+                final String id =  newShortcut.getId();
+                final ShortcutInfo oldShortcut = mShortcuts.get(id);
+
+                boolean wasPinned = false;
+
+                if (oldShortcut != null) {
+                    if (!oldShortcut.isOriginallyFromManifest()) {
+                        Slog.e(TAG, "Shortcut with ID=" + newShortcut.getId()
+                                + " exists but is not from AndroidManifest.xml, not updating.");
+                        continue;
+                    }
+                    // Take over the pinned flag.
+                    if (oldShortcut.isPinned()) {
+                        wasPinned = true;
+                        newShortcut.addFlags(ShortcutInfo.FLAG_PINNED);
+                    }
+                }
+                if (newDisabled && !wasPinned) {
+                    // If the shortcut is disabled, and it was *not* pinned, then this
+                    // just doesn't have to be published.
+                    // Just keep it in toDisableList, so the previous one would be removed.
+                    continue;
+                }
+                // TODO: Check dynamic count
+
+                // Note even if enabled=false, we still need to update all fields, so do it
+                // regardless.
+                addShortcutInner(newShortcut); // This will clean up the old one too.
+
+                if (!newDisabled && toDisableList != null) {
+                    // Still alive, don't remove.
+                    toDisableList.remove(id);
+                }
+            }
+        }
+
+        // Disable the previous manifest shortcuts that are no longer in the manifest.
+        if (toDisableList != null) {
+            if (ShortcutService.DEBUG) {
+                Slog.d(TAG, String.format(
+                        "Package %s: disabling %d stale shortcuts", getPackageName(),
+                        toDisableList.size()));
+            }
+            for (int i = toDisableList.size() - 1; i >= 0; i--) {
+                changed = true;
+
+                final String id = toDisableList.valueAt(i);
+
+                disableWithId(id, /* disable message =*/ null, /* disable message resid */ 0,
+                        /* overrideImmutable=*/ true);
+            }
+            removeOrphans();
+        }
+        return changed;
     }
 
     public void dump(@NonNull PrintWriter pw, @NonNull String prefix) {
@@ -597,7 +801,6 @@
         out.startTag(null, TAG_ROOT);
 
         ShortcutService.writeAttr(out, ATTR_NAME, getPackageName());
-        ShortcutService.writeAttr(out, ATTR_DYNAMIC_COUNT, mDynamicShortcutCount);
         ShortcutService.writeAttr(out, ATTR_CALL_COUNT, mApiCallCount);
         ShortcutService.writeAttr(out, ATTR_LAST_RESET, mLastResetTime);
         getPackageInfo().saveToXml(out);
@@ -619,7 +822,7 @@
         out.startTag(null, TAG_SHORTCUT);
         ShortcutService.writeAttr(out, ATTR_ID, si.getId());
         // writeAttr(out, "package", si.getPackageName()); // not needed
-        ShortcutService.writeAttr(out, ATTR_ACTIVITY, si.getActivityComponent());
+        ShortcutService.writeAttr(out, ATTR_ACTIVITY, si.getActivity());
         // writeAttr(out, "icon", si.getIcon());  // We don't save it.
         ShortcutService.writeAttr(out, ATTR_TITLE, si.getTitle());
         ShortcutService.writeAttr(out, ATTR_TITLE_RES_ID, si.getTitleResId());
@@ -670,8 +873,6 @@
         final ShortcutPackage ret = new ShortcutPackage(shortcutUser,
                 shortcutUser.getUserId(), packageName);
 
-        ret.mDynamicShortcutCount =
-                ShortcutService.parseIntAttribute(parser, ATTR_DYNAMIC_COUNT);
         ret.mApiCallCount =
                 ShortcutService.parseIntAttribute(parser, ATTR_CALL_COUNT);
         ret.mLastResetTime =
diff --git a/services/core/java/com/android/server/pm/ShortcutPackageInfo.java b/services/core/java/com/android/server/pm/ShortcutPackageInfo.java
index ae9709e..7f5d931 100644
--- a/services/core/java/com/android/server/pm/ShortcutPackageInfo.java
+++ b/services/core/java/com/android/server/pm/ShortcutPackageInfo.java
@@ -15,6 +15,7 @@
  */
 package com.android.server.pm;
 
+import android.annotation.NonNull;
 import android.annotation.UserIdInt;
 import android.content.pm.PackageInfo;
 import android.util.Slog;
@@ -34,12 +35,15 @@
 
 /**
  * Package information used by {@link android.content.pm.ShortcutManager} for backup / restore.
+ *
+ * All methods should be guarded by {@code ShortcutService.mLock}.
  */
 class ShortcutPackageInfo {
     private static final String TAG = ShortcutService.TAG;
 
     static final String TAG_ROOT = "package-info";
     private static final String ATTR_VERSION = "version";
+    private static final String ATTR_LAST_UPDATE_TIME = "last_udpate_time";
     private static final String ATTR_SHADOW = "shadow";
 
     private static final String TAG_SIGNATURE = "signature";
@@ -53,16 +57,20 @@
      */
     private boolean mIsShadow;
     private int mVersionCode = VERSION_UNKNOWN;
+    private long mLastUpdateTime;
     private ArrayList<byte[]> mSigHashes;
 
-    private ShortcutPackageInfo(int versionCode, ArrayList<byte[]> sigHashes, boolean isShadow) {
+    private ShortcutPackageInfo(int versionCode, long lastUpdateTime,
+            ArrayList<byte[]> sigHashes, boolean isShadow) {
         mVersionCode = versionCode;
+        mLastUpdateTime = lastUpdateTime;
         mIsShadow = isShadow;
         mSigHashes = sigHashes;
     }
 
     public static ShortcutPackageInfo newEmpty() {
-        return new ShortcutPackageInfo(VERSION_UNKNOWN, new ArrayList<>(0), /* isShadow */ false);
+        return new ShortcutPackageInfo(VERSION_UNKNOWN, /* last update time =*/ 0,
+                new ArrayList<>(0), /* isShadow */ false);
     }
 
     public boolean isShadow() {
@@ -77,8 +85,15 @@
         return mVersionCode;
     }
 
-    public void setVersionCode(int versionCode) {
-        mVersionCode = versionCode;
+    public long getLastUpdateTime() {
+        return mLastUpdateTime;
+    }
+
+    public void updateVersionInfo(@NonNull PackageInfo pi) {
+        if (pi != null) {
+            mVersionCode = pi.versionCode;
+            mLastUpdateTime = pi.lastUpdateTime;
+        }
     }
 
     public boolean hasSignatures() {
@@ -111,7 +126,7 @@
             Slog.e(TAG, "Can't get signatures: package=" + packageName);
             return null;
         }
-        final ShortcutPackageInfo ret = new ShortcutPackageInfo(pi.versionCode,
+        final ShortcutPackageInfo ret = new ShortcutPackageInfo(pi.versionCode, pi.lastUpdateTime,
                 BackupUtils.hashSignatureArray(pi.signatures), /* shadow=*/ false);
 
         return ret;
@@ -131,6 +146,7 @@
             return;
         }
         mVersionCode = pi.versionCode;
+        mLastUpdateTime = pi.lastUpdateTime;
         mSigHashes = BackupUtils.hashSignatureArray(pi.signatures);
     }
 
@@ -139,6 +155,7 @@
         out.startTag(null, TAG_ROOT);
 
         ShortcutService.writeAttr(out, ATTR_VERSION, mVersionCode);
+        ShortcutService.writeAttr(out, ATTR_LAST_UPDATE_TIME, mLastUpdateTime);
         ShortcutService.writeAttr(out, ATTR_SHADOW, mIsShadow);
 
         for (int i = 0; i < mSigHashes.size(); i++) {
@@ -154,6 +171,9 @@
 
         final int versionCode = ShortcutService.parseIntAttribute(parser, ATTR_VERSION);
 
+        final long lastUpdateTime = ShortcutService.parseIntAttribute(
+                parser, ATTR_LAST_UPDATE_TIME);
+
         // When restoring from backup, it's always shadow.
         final boolean shadow =
                 fromBackup || ShortcutService.parseBooleanAttribute(parser, ATTR_SHADOW);
@@ -185,6 +205,7 @@
 
         // Successfully loaded; replace the feilds.
         mVersionCode = versionCode;
+        mLastUpdateTime = lastUpdateTime;
         mIsShadow = shadow;
         mSigHashes = hashes;
     }
@@ -205,6 +226,11 @@
         pw.print(mVersionCode);
         pw.println();
 
+        pw.print(prefix);
+        pw.print("  Last package update time: ");
+        pw.print(mLastUpdateTime);
+        pw.println();
+
         for (int i = 0; i < mSigHashes.size(); i++) {
             pw.print(prefix);
             pw.print("    ");
diff --git a/services/core/java/com/android/server/pm/ShortcutPackageItem.java b/services/core/java/com/android/server/pm/ShortcutPackageItem.java
index 0c2417c..d08b974 100644
--- a/services/core/java/com/android/server/pm/ShortcutPackageItem.java
+++ b/services/core/java/com/android/server/pm/ShortcutPackageItem.java
@@ -26,6 +26,9 @@
 
 import java.io.IOException;
 
+/**
+ * All methods should be guarded by {@code #mShortcutUser.mService.mLock}.
+ */
 abstract class ShortcutPackageItem {
     private static final String TAG = ShortcutService.TAG;
 
diff --git a/services/core/java/com/android/server/pm/ShortcutParser.java b/services/core/java/com/android/server/pm/ShortcutParser.java
new file mode 100644
index 0000000..44d0a9f
--- /dev/null
+++ b/services/core/java/com/android/server/pm/ShortcutParser.java
@@ -0,0 +1,236 @@
+/*
+ * Copyright (C) 2016 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.server.pm;
+
+import android.annotation.Nullable;
+import android.annotation.UserIdInt;
+import android.content.ComponentName;
+import android.content.Intent;
+import android.content.pm.ActivityInfo;
+import android.content.pm.PackageInfo;
+import android.content.pm.ShortcutInfo;
+import android.content.res.TypedArray;
+import android.content.res.XmlResourceParser;
+import android.net.Uri;
+import android.text.TextUtils;
+import android.util.ArraySet;
+import android.util.AttributeSet;
+import android.util.Slog;
+import android.util.Xml;
+
+import com.android.internal.R;
+import com.android.internal.annotations.VisibleForTesting;
+
+import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+public class ShortcutParser {
+    private static final String TAG = ShortcutService.TAG;
+
+    private static final boolean DEBUG = ShortcutService.DEBUG || false; // DO NOT SUBMIT WITH TRUE
+
+    @VisibleForTesting
+    static final String METADATA_KEY = "android.pm.Shortcuts";
+
+    private static final String TAG_SHORTCUTS = "shortcuts";
+    private static final String TAG_SHORTCUT = "shortcut";
+
+    @Nullable
+    public static List<ShortcutInfo> parseShortcuts(ShortcutService service,
+            String packageName, @UserIdInt int userId) throws IOException, XmlPullParserException {
+        final PackageInfo pi = service.injectGetActivitiesWithMetadata(packageName, userId);
+
+        List<ShortcutInfo> result = null;
+
+        if (pi != null && pi.activities != null) {
+            for (ActivityInfo activityInfo : pi.activities) {
+                result = parseShortcutsOneFile(service, activityInfo, packageName, userId, result);
+            }
+        }
+        return result;
+    }
+
+    private static List<ShortcutInfo> parseShortcutsOneFile(
+            ShortcutService service,
+            ActivityInfo activityInfo, String packageName, @UserIdInt int userId,
+            List<ShortcutInfo> result) throws IOException, XmlPullParserException {
+        XmlResourceParser parser = null;
+        try {
+            parser = service.injectXmlMetaData(activityInfo, METADATA_KEY);
+            if (parser == null) {
+                return result;
+            }
+
+            final ComponentName activity = new ComponentName(packageName, activityInfo.name);
+
+            final AttributeSet attrs = Xml.asAttributeSet(parser);
+
+            int type;
+
+            outer:
+            while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
+                    && (type != XmlPullParser.END_TAG || parser.getDepth() > 0)) {
+                if (type != XmlPullParser.START_TAG) {
+                    continue;
+                }
+                final int depth = parser.getDepth();
+                final String tag = parser.getName();
+
+                if (depth == 1 && TAG_SHORTCUTS.equals(tag)) {
+                    continue; // Root tag.
+                }
+                if (depth == 2 && TAG_SHORTCUT.equals(tag)) {
+                    final ShortcutInfo si = parseShortcutAttributes(
+                            service, attrs, packageName, activity, userId);
+                    if (ShortcutService.DEBUG) {
+                        Slog.d(TAG, "Shortcut=" + si);
+                    }
+                    if (result != null) {
+                        for (int i = result.size() - 1; i >= 0; i--) {
+                            if (si.getId().equals(result.get(i).getId())) {
+                                Slog.w(TAG, "Duplicate shortcut ID detected, skipping.");
+                                continue outer;
+                            }
+                        }
+                    }
+
+                    if (si != null) {
+                        if (result == null) {
+                            result = new ArrayList<>();
+                        }
+                        result.add(si);
+                    }
+                    continue;
+                }
+                Slog.w(TAG, "Unknown tag " + tag);
+            }
+        } finally {
+            if (parser != null) {
+                parser.close();
+            }
+        }
+        return result;
+    }
+
+    private static ShortcutInfo parseShortcutAttributes(ShortcutService service,
+            AttributeSet attrs, String packageName, ComponentName activity,
+            @UserIdInt int userId) {
+        final TypedArray sa = service.mContext.getResources().obtainAttributes(attrs,
+                R.styleable.Shortcut);
+        try {
+            final String id = sa.getString(R.styleable.Shortcut_shortcutId);
+            final boolean enabled = sa.getBoolean(R.styleable.Shortcut_enabled, true);
+            final int rank = sa.getInt(R.styleable.Shortcut_shortcutRank, 0);
+            final int iconResId = sa.getResourceId(R.styleable.Shortcut_shortcutIcon, 0);
+            final int titleResId = sa.getResourceId(R.styleable.Shortcut_shortcutTitle, 0);
+            final int textResId = sa.getResourceId(R.styleable.Shortcut_shortcutText, 0);
+            final int disabledMessageResId = sa.getResourceId(
+                    R.styleable.Shortcut_shortcutDisabledMessage, 0);
+            final String categories = sa.getString(R.styleable.Shortcut_shortcutCategories);
+            String intentAction = sa.getString(R.styleable.Shortcut_shortcutIntentAction);
+            final String intentData = sa.getString(R.styleable.Shortcut_shortcutIntentData);
+
+            if (TextUtils.isEmpty(id)) {
+                Slog.w(TAG, "Shortcut ID must be provided. activity=" + activity);
+                return null;
+            }
+            if (titleResId == 0) {
+                Slog.w(TAG, "Shortcut title must be provided. activity=" + activity);
+                return null;
+            }
+            if (TextUtils.isEmpty(intentAction)) {
+                if (enabled) {
+                    Slog.w(TAG, "Shortcut intent action must be provided. activity=" + activity);
+                    return null;
+                } else {
+                    // Disabled shortcut doesn't have to have an action, but just set VIEW as the
+                    // default.
+                    intentAction = Intent.ACTION_VIEW;
+                }
+            }
+
+            final ArraySet<String> categoriesSet;
+            if (categories == null) {
+                categoriesSet = null;
+            } else {
+                final String[] arr = categories.split(":");
+                categoriesSet = new ArraySet<>(arr.length);
+                for (String v : arr) {
+                    categoriesSet.add(v);
+                }
+            }
+            final Intent intent = new Intent(intentAction);
+            if (!TextUtils.isEmpty(intentData)) {
+                intent.setData(Uri.parse(intentData));
+            }
+
+            return createShortcutFromManifest(
+                    service,
+                    userId,
+                    id,
+                    packageName,
+                    activity,
+                    titleResId,
+                    textResId,
+                    disabledMessageResId,
+                    categoriesSet,
+                    intent,
+                    rank,
+                    iconResId,
+                    enabled);
+        } finally {
+            sa.recycle();
+        }
+    }
+
+    private static ShortcutInfo createShortcutFromManifest(ShortcutService service,
+            @UserIdInt int userId, String id, String packageName, ComponentName activityComponent,
+            int titleResId, int textResId, int disabledMessageResId, Set<String> categories,
+            Intent intent, int rank, int iconResId, boolean enabled) {
+
+        final int flags =
+                (enabled ? ShortcutInfo.FLAG_MANIFEST : ShortcutInfo.FLAG_DISABLED)
+                | ShortcutInfo.FLAG_IMMUTABLE
+                | ((iconResId != 0) ? ShortcutInfo.FLAG_HAS_ICON_RES : 0);
+
+        return new ShortcutInfo(
+                userId,
+                id,
+                packageName,
+                activityComponent,
+                null, // icon
+                null, // title string
+                titleResId,
+                null, // text string
+                textResId,
+                null, // disabled message string
+                disabledMessageResId,
+                categories,
+                intent,
+                null, // intent extras
+                rank,
+                null, // extras
+                service.injectCurrentTimeMillis(),
+                flags,
+                iconResId,
+                null); // bitmap path
+    }
+}
diff --git a/services/core/java/com/android/server/pm/ShortcutService.java b/services/core/java/com/android/server/pm/ShortcutService.java
index 6a10f41..dc0404c 100644
--- a/services/core/java/com/android/server/pm/ShortcutService.java
+++ b/services/core/java/com/android/server/pm/ShortcutService.java
@@ -25,6 +25,7 @@
 import android.content.ComponentName;
 import android.content.Context;
 import android.content.Intent;
+import android.content.pm.ActivityInfo;
 import android.content.pm.ApplicationInfo;
 import android.content.pm.IPackageManager;
 import android.content.pm.IShortcutService;
@@ -39,6 +40,7 @@
 import android.content.pm.ShortcutInfo;
 import android.content.pm.ShortcutServiceInternal;
 import android.content.pm.ShortcutServiceInternal.ShortcutChangeListener;
+import android.content.res.XmlResourceParser;
 import android.graphics.Bitmap;
 import android.graphics.Bitmap.CompressFormat;
 import android.graphics.Canvas;
@@ -103,6 +105,7 @@
 import java.net.URISyntaxException;
 import java.nio.charset.StandardCharsets;
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.List;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicLong;
@@ -111,16 +114,21 @@
 
 /**
  * TODO:
- * - Manifest shortcuts.
+ * - Implement # of dynamic shortcuts cap.
  *
- * - Implement disableShortcuts().
+ * - HandleUnlockUser needs to be async.  Wait on it in onCleanupUser.
  *
  * - Implement reportShortcutUsed().
  *
+ * - validateForXml() should be removed.
+ *
  * - Ranks should be recalculated after each update.
  *
  * - When the system locale changes, update timestamps for shortcuts with string resources,
- *   and notify the launcher.
+ *   and notify the launcher.  Right now, it resets the throttling, but timestamps are not changed
+ *   and there's no notification either.
+ *
+ * - getIconMaxWidth()/getIconMaxHeight() should use xdpi and ydpi.
  *
  * - Default launcher check does take a few ms.  Worth caching.
  *
@@ -128,11 +136,13 @@
  *   internal bitmap handling.
  *
  * - Add more call stats.
+ *
+ * - Rename getMaxDynamicShortcutCount and mMaxDynamicShortcuts
  */
 public class ShortcutService extends IShortcutService.Stub {
     static final String TAG = "ShortcutService";
 
-    static final boolean DEBUG = false; // STOPSHIP if true
+    static final boolean DEBUG = true; // STOPSHIP if true
     static final boolean DEBUG_LOAD = false; // STOPSHIP if true
     static final boolean DEBUG_PROCSTATE = false; // STOPSHIP if true
 
@@ -301,8 +311,11 @@
         int GET_APPLICATION_INFO = 3;
         int LAUNCHER_PERMISSION_CHECK = 4;
         int CLEANUP_DANGLING_BITMAPS = 5;
+        int GET_ACTIVITIES_WITH_METADATA = 6;
+        int GET_INSTALLED_APPLICATIONS = 7;
+        int CHECK_PACKAGE_CHANGES = 8;
 
-        int COUNT = CLEANUP_DANGLING_BITMAPS + 1;
+        int COUNT = CHECK_PACKAGE_CHANGES + 1;
     }
 
     final Object mStatLock = new Object();
@@ -444,6 +457,9 @@
 
     /** lifecycle event */
     void handleUnlockUser(int userId) {
+        if (DEBUG) {
+            Slog.d(TAG, "handleUnlockUser: user=" + userId);
+        }
         synchronized (mLock) {
             // Preload
             getUserShortcutsLocked(userId);
@@ -642,10 +658,10 @@
         out.endTag(null, tag);
     }
 
-    static void writeAttr(XmlSerializer out, String name, String value) throws IOException {
+    static void writeAttr(XmlSerializer out, String name, CharSequence value) throws IOException {
         if (TextUtils.isEmpty(value)) return;
 
-        out.attribute(null, name, value);
+        out.attribute(null, name, value.toString());
     }
 
     static void writeAttr(XmlSerializer out, String name, long value) throws IOException {
@@ -1090,7 +1106,7 @@
     FileOutputStreamWithPath openIconFileForWrite(@UserIdInt int userId, ShortcutInfo shortcut)
             throws IOException {
         final File packagePath = new File(getUserBitmapFilePath(userId),
-                shortcut.getPackageName());
+                shortcut.getPackage());
         if (!packagePath.isDirectory()) {
             packagePath.mkdirs();
             if (!packagePath.isDirectory()) {
@@ -1129,7 +1145,6 @@
             }
 
             Bitmap bitmap;
-            Bitmap bitmapToRecycle = null;
             try {
                 switch (icon.getType()) {
                     case Icon.TYPE_RESOURCE: {
@@ -1181,9 +1196,6 @@
                     }
                 }
             } finally {
-                if (bitmapToRecycle != null) {
-                    bitmapToRecycle.recycle();
-                }
                 // Once saved, we won't use the original icon information, so null it out.
                 shortcut.clearIcon();
             }
@@ -1196,7 +1208,7 @@
     // so override in unit tests.
     // TODO CTS this case.
     void injectValidateIconResPackage(ShortcutInfo shortcut, Icon icon) {
-        if (!shortcut.getPackageName().equals(icon.getResPackage())) {
+        if (!shortcut.getPackage().equals(icon.getResPackage())) {
             throw new IllegalArgumentException(
                     "Icon resource must reside in shortcut owner package");
         }
@@ -1353,10 +1365,9 @@
      */
     private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate) {
         Preconditions.checkNotNull(shortcut, "Null shortcut detected");
-        if (shortcut.getActivityComponent() != null) {
+        if (shortcut.getActivity() != null) {
             Preconditions.checkState(
-                    shortcut.getPackageName().equals(
-                            shortcut.getActivityComponent().getPackageName()),
+                    shortcut.getPackage().equals(shortcut.getActivity().getPackageName()),
                     "Activity package name mismatch");
         }
 
@@ -1399,7 +1410,7 @@
         }
     }
 
-    private static void validateForXml(String s) {
+    private static void validateForXml(CharSequence s) {
         if (TextUtils.isEmpty(s)) {
             return;
         }
@@ -1427,6 +1438,8 @@
         synchronized (mLock) {
             final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
 
+            ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
+
             // Throttling.
             if (!ps.tryApiCall()) {
                 return false;
@@ -1444,7 +1457,7 @@
             // Then, add/update all.  We need to make sure to take over "pinned" flag.
             for (int i = 0; i < size; i++) {
                 final ShortcutInfo newShortcut = newShortcuts.get(i);
-                ps.addDynamicShortcut(newShortcut);
+                ps.addOrUpdateDynamicShortcut(newShortcut);
             }
         }
         packageShortcutsChanged(packageName, userId);
@@ -1462,6 +1475,8 @@
         synchronized (mLock) {
             final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
 
+            ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
+
             // Throttling.
             if (!ps.tryApiCall()) {
                 return false;
@@ -1473,11 +1488,22 @@
 
                 final ShortcutInfo target = ps.findShortcutById(source.getId());
                 if (target != null) {
+                    if (target.isEnabled() != source.isEnabled()) {
+                        Slog.w(TAG,
+                                "ShortcutInfo.enabled cannot be changed with updateShortcuts()");
+                    }
+
                     final boolean replacingIcon = (source.getIcon() != null);
                     if (replacingIcon) {
                         removeIcon(userId, target);
                     }
 
+                    if (source.getActivity() != null &&
+                            !source.getActivity().equals(target.getActivity())) {
+                        // TODO When activity is changing, check the dynamic count.
+                    }
+
+                    // Note copyNonNullFieldsFrom() does the "udpatable with?" check too.
                     target.copyNonNullFieldsFrom(source);
 
                     if (replacingIcon) {
@@ -1502,6 +1528,8 @@
         synchronized (mLock) {
             final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
 
+            ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
+
             // Throttling.
             if (!ps.tryApiCall()) {
                 return false;
@@ -1513,7 +1541,7 @@
                 fixUpIncomingShortcutInfo(newShortcut, /* forUpdate= */ false);
 
                 // Add it.
-                ps.addDynamicShortcut(newShortcut);
+                ps.addOrUpdateDynamicShortcut(newShortcut);
             }
         }
         packageShortcutsChanged(packageName, userId);
@@ -1528,7 +1556,32 @@
         Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
 
         synchronized (mLock) {
-            // TODO implement it.
+            final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
+
+            ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
+
+            for (int i = shortcutIds.size() - 1; i >= 0; i--) {
+                ps.disableWithId(Preconditions.checkStringNotEmpty((String) shortcutIds.get(i)),
+                        disabledMessage, disabledMessageResId,
+                        /* overrideImmutable=*/ false);
+            }
+        }
+        packageShortcutsChanged(packageName, userId);
+    }
+
+    @Override
+    public void enableShortcuts(String packageName, List shortcutIds, @UserIdInt int userId) {
+        verifyCaller(packageName, userId);
+        Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
+
+        synchronized (mLock) {
+            final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
+
+            ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
+
+            for (int i = shortcutIds.size() - 1; i >= 0; i--) {
+                ps.enableWithId((String) shortcutIds.get(i));
+            }
         }
         packageShortcutsChanged(packageName, userId);
     }
@@ -1540,8 +1593,12 @@
         Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
 
         synchronized (mLock) {
+            final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
+
+            ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
+
             for (int i = shortcutIds.size() - 1; i >= 0; i--) {
-                getPackageShortcutsLocked(packageName, userId).deleteDynamicWithId(
+                ps.deleteDynamicWithId(
                         Preconditions.checkStringNotEmpty((String) shortcutIds.get(i)));
             }
         }
@@ -1570,6 +1627,17 @@
     }
 
     @Override
+    public ParceledListSlice<ShortcutInfo> getManifestShortcuts(String packageName,
+            @UserIdInt int userId) {
+        verifyCaller(packageName, userId);
+        synchronized (mLock) {
+            return getShortcutsWithQueryLocked(
+                    packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
+                    ShortcutInfo::isManifestShortcut);
+        }
+    }
+
+    @Override
     public ParceledListSlice<ShortcutInfo> getPinnedShortcuts(String packageName,
             @UserIdInt int userId) {
         verifyCaller(packageName, userId);
@@ -1883,18 +1951,24 @@
                             return false;
                         }
                         if (componentName != null) {
-                            if (si.getActivityComponent() != null
-                                    && !si.getActivityComponent().equals(componentName)) {
+                            if (si.getActivity() != null
+                                    && !si.getActivity().equals(componentName)) {
                                 return false;
                             }
                         }
-                        final boolean matchDynamic =
-                                ((queryFlags & ShortcutQuery.FLAG_GET_DYNAMIC) != 0)
-                                        && si.isDynamic();
-                        final boolean matchPinned =
-                                ((queryFlags & ShortcutQuery.FLAG_GET_PINNED) != 0)
-                                        && si.isPinned();
-                        return matchDynamic || matchPinned;
+                        if (((queryFlags & ShortcutQuery.FLAG_GET_DYNAMIC) != 0)
+                                && si.isDynamic()) {
+                            return true;
+                        }
+                        if (((queryFlags & ShortcutQuery.FLAG_GET_PINNED) != 0)
+                                && si.isPinned()) {
+                            return true;
+                        }
+                        if (((queryFlags & ShortcutQuery.FLAG_GET_MANIFEST) != 0)
+                                && si.isManifestShortcut()) {
+                            return true;
+                        }
+                        return false;
                     }, cloneFlag, callingPackage, launcherUserId);
         }
 
@@ -1967,7 +2041,7 @@
                 final ShortcutInfo si = getShortcutInfoLocked(
                         launcherUserId, callingPackage, packageName, shortcutId, userId);
                 // "si == null" should suffice here, but check the flags too just to make sure.
-                if (si == null || !(si.isDynamic() || si.isPinned())) {
+                if (si == null || !si.isEnabled() || !si.isAlive()) {
                     return null;
                 }
                 return si.getIntent();
@@ -2114,31 +2188,37 @@
         if (DEBUG) {
             Slog.d(TAG, "checkPackageChanges() ownerUserId=" + ownerUserId);
         }
-        final ArrayList<PackageWithUser> gonePackages = new ArrayList<>();
 
-        synchronized (mLock) {
-            final ShortcutUser user = getUserShortcutsLocked(ownerUserId);
+        final long start = injectElapsedRealtime();
+        try {
+            final ArrayList<PackageWithUser> gonePackages = new ArrayList<>();
 
-            user.forAllPackageItems(spi -> {
-                if (spi.getPackageInfo().isShadow()) {
-                    return; // Don't delete shadow information.
+            synchronized (mLock) {
+                final ShortcutUser user = getUserShortcutsLocked(ownerUserId);
+
+                // Find packages that have been uninstalled.
+                user.forAllPackageItems(spi -> {
+                    if (spi.getPackageInfo().isShadow()) {
+                        return; // Don't delete shadow information.
+                    }
+                    if (!isPackageInstalled(spi.getPackageName(), spi.getPackageUserId())) {
+                        gonePackages.add(PackageWithUser.of(spi));
+                    }
+                });
+                if (gonePackages.size() > 0) {
+                    for (int i = gonePackages.size() - 1; i >= 0; i--) {
+                        final PackageWithUser pu = gonePackages.get(i);
+                        cleanUpPackageLocked(pu.packageName, ownerUserId, pu.userId);
+                    }
                 }
-                final int versionCode = getApplicationVersionCode(
-                        spi.getPackageName(), spi.getPackageUserId());
-                if (versionCode >= 0) {
-                    // Package still installed, see if it's updated.
-                    getUserShortcutsLocked(ownerUserId).handlePackageUpdated(
-                            spi.getPackageName(), versionCode);
-                } else {
-                    gonePackages.add(PackageWithUser.of(spi));
-                }
-            });
-            if (gonePackages.size() > 0) {
-                for (int i = gonePackages.size() - 1; i >= 0; i--) {
-                    final PackageWithUser pu = gonePackages.get(i);
-                    cleanUpPackageLocked(pu.packageName, ownerUserId, pu.userId);
-                }
+
+                // Then for each installed app, publish manifest shortcuts when needed.
+                forInstalledApplications(ownerUserId, ai -> {
+                    user.handlePackageAddedOrUpdated(ai.packageName);
+                });
             }
+        } finally {
+            logDurationStat(Stats.CHECK_PACKAGE_CHANGES, start);
         }
     }
 
@@ -2147,8 +2227,9 @@
             Slog.d(TAG, String.format("handlePackageAdded: %s user=%d", packageName, userId));
         }
         synchronized (mLock) {
-            forEachLoadedUserLocked(user ->
-                    user.attemptToRestoreIfNeededAndSave(this, packageName, userId));
+            final ShortcutUser user = getUserShortcutsLocked(userId);
+            user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
+            user.handlePackageAddedOrUpdated(packageName);
         }
     }
 
@@ -2158,14 +2239,12 @@
                     packageName, userId));
         }
         synchronized (mLock) {
-            forEachLoadedUserLocked(user ->
-                    user.attemptToRestoreIfNeededAndSave(this, packageName, userId));
+            final ShortcutUser user = getUserShortcutsLocked(userId);
+            user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
 
-            final int versionCode = getApplicationVersionCode(packageName, userId);
-            if (versionCode < 0) {
-                return; // shouldn't happen
+            if (isPackageInstalled(packageName, userId)) {
+                user.handlePackageAddedOrUpdated(packageName);
             }
-            getUserShortcutsLocked(userId).handlePackageUpdated(packageName, versionCode);
         }
     }
 
@@ -2187,10 +2266,16 @@
 
     // === PackageManager interaction ===
 
+    @Nullable
     PackageInfo getPackageInfoWithSignatures(String packageName, @UserIdInt int userId) {
         return injectPackageInfo(packageName, userId, true);
     }
 
+    @Nullable
+    PackageInfo getPackageInfo(String packageName, @UserIdInt int userId) {
+        return injectPackageInfo(packageName, userId, false);
+    }
+
     int injectGetPackageUid(@NonNull String packageName, @UserIdInt int userId) {
         final long token = injectClearCallingIdentity();
         try {
@@ -2205,6 +2290,7 @@
         }
     }
 
+    @Nullable
     @VisibleForTesting
     PackageInfo injectPackageInfo(String packageName, @UserIdInt int userId,
             boolean getSignatures) {
@@ -2227,6 +2313,7 @@
         }
     }
 
+    @Nullable
     @VisibleForTesting
     ApplicationInfo injectApplicationInfo(String packageName, @UserIdInt int userId) {
         final long start = injectElapsedRealtime();
@@ -2244,6 +2331,61 @@
         }
     }
 
+    @Nullable
+    @VisibleForTesting
+    PackageInfo injectGetActivitiesWithMetadata(String packageName, @UserIdInt int userId) {
+        final long start = injectElapsedRealtime();
+        final long token = injectClearCallingIdentity();
+        try {
+            return mIPackageManager.getPackageInfo(packageName,
+                    PACKAGE_MATCH_FLAGS | PackageManager.GET_ACTIVITIES
+                            | PackageManager.GET_META_DATA, userId);
+        } catch (RemoteException e) {
+            // Shouldn't happen.
+            Slog.wtf(TAG, "RemoteException", e);
+            return null;
+        } finally {
+            injectRestoreCallingIdentity(token);
+
+            logDurationStat(Stats.GET_ACTIVITIES_WITH_METADATA, start);
+        }
+    }
+
+    @Nullable
+    @VisibleForTesting
+    List<ApplicationInfo> injectInstalledApplications(@UserIdInt int userId) {
+        final long start = injectElapsedRealtime();
+        final long token = injectClearCallingIdentity();
+        try {
+            final ParceledListSlice<ApplicationInfo> parceledList =
+                    mIPackageManager.getInstalledApplications(PACKAGE_MATCH_FLAGS, userId);
+            if (parceledList == null) {
+                return Collections.emptyList();
+            }
+            return parceledList.getList();
+        } catch (RemoteException e) {
+            // Shouldn't happen.
+            Slog.wtf(TAG, "RemoteException", e);
+            return null;
+        } finally {
+            injectRestoreCallingIdentity(token);
+
+            logDurationStat(Stats.GET_INSTALLED_APPLICATIONS, start);
+        }
+    }
+
+    private void forInstalledApplications(@UserIdInt int userId,
+            Consumer<ApplicationInfo> callback) {
+        final List<ApplicationInfo> list = injectInstalledApplications(userId);
+        for (int i = list.size() - 1; i >= 0; i--) {
+            final ApplicationInfo ai = list.get(i);
+
+            if ((ai.flags & ApplicationInfo.FLAG_INSTALLED) != 0) {
+                callback.accept(ai);
+            }
+        }
+    }
+
     private boolean isApplicationFlagSet(String packageName, int userId, int flags) {
         final ApplicationInfo ai = injectApplicationInfo(packageName, userId);
         return (ai != null) && ((ai.flags & flags) == flags);
@@ -2253,15 +2395,10 @@
         return isApplicationFlagSet(packageName, userId, ApplicationInfo.FLAG_INSTALLED);
     }
 
-    /**
-     * @return the version code of the package, or -1 if the app is not installed.
-     */
-    int getApplicationVersionCode(String packageName, int userId) {
-        final ApplicationInfo ai = injectApplicationInfo(packageName, userId);
-        if ((ai == null) || ((ai.flags & ApplicationInfo.FLAG_INSTALLED) == 0)) {
-            return -1;
-        }
-        return ai.versionCode;
+    @Nullable
+    XmlResourceParser injectXmlMetaData(ActivityInfo activityInfo, String key) {
+// TODO Doesn't seem like ACROSS_USER is needed, but double check.
+        return activityInfo.loadXmlMetaData(mContext.getPackageManager(), key);
     }
 
     // === Backup & restore ===
@@ -2402,8 +2539,10 @@
                 dumpStatLS(pw, p, Stats.GET_PACKAGE_INFO, "getPackageInfo()");
                 dumpStatLS(pw, p, Stats.GET_PACKAGE_INFO_WITH_SIG, "getPackageInfo(SIG)");
                 dumpStatLS(pw, p, Stats.GET_APPLICATION_INFO, "getApplicationInfo");
-
                 dumpStatLS(pw, p, Stats.CLEANUP_DANGLING_BITMAPS, "cleanupDanglingBitmaps");
+                dumpStatLS(pw, p, Stats.GET_ACTIVITIES_WITH_METADATA, "getActivities+metadata");
+                dumpStatLS(pw, p, Stats.GET_INSTALLED_APPLICATIONS, "getInstalledApplications");
+                dumpStatLS(pw, p, Stats.CHECK_PACKAGE_CHANGES, "checkPackageChanges");
             }
 
             for (int i = 0; i < mUsers.size(); i++) {
@@ -2783,12 +2922,19 @@
     }
 
     @VisibleForTesting
-    ShortcutInfo getPackageShortcutForTest(String packageName, String shortcutId, int userId) {
+    ShortcutPackage getPackageShortcutForTest(String packageName, int userId) {
         synchronized (mLock) {
             final ShortcutUser user = mUsers.get(userId);
             if (user == null) return null;
 
-            final ShortcutPackage pkg = user.getAllPackagesForTest().get(packageName);
+            return user.getAllPackagesForTest().get(packageName);
+        }
+    }
+
+    @VisibleForTesting
+    ShortcutInfo getPackageShortcutForTest(String packageName, String shortcutId, int userId) {
+        synchronized (mLock) {
+            final ShortcutPackage pkg = getPackageShortcutForTest(packageName, userId);
             if (pkg == null) return null;
 
             return pkg.findShortcutById(shortcutId);
diff --git a/services/core/java/com/android/server/pm/ShortcutUser.java b/services/core/java/com/android/server/pm/ShortcutUser.java
index d38cfba..840c3df 100644
--- a/services/core/java/com/android/server/pm/ShortcutUser.java
+++ b/services/core/java/com/android/server/pm/ShortcutUser.java
@@ -24,6 +24,7 @@
 import android.util.Slog;
 import android.util.SparseArray;
 
+import com.android.internal.annotations.GuardedBy;
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.util.Preconditions;
 
@@ -40,6 +41,8 @@
 
 /**
  * User information used by {@link ShortcutService}.
+ *
+ * All methods should be guarded by {@code #mService.mLock}.
  */
 class ShortcutUser {
     private static final String TAG = ShortcutService.TAG;
@@ -230,19 +233,16 @@
         }
     }
 
-    /**
-     * Called when a package is updated.
-     */
-    public void handlePackageUpdated(@NonNull String packageName,
-            int newVersionCode) {
-        if (!mPackages.containsKey(packageName)) {
-            return;
+    public void handlePackageAddedOrUpdated(@NonNull String packageName) {
+        final boolean isNewApp = !mPackages.containsKey(packageName);
+
+        final ShortcutPackage shortcutPackage = getPackageShortcuts(packageName);
+
+        if (!shortcutPackage.handlePackageAddedOrUpdated(isNewApp)) {
+            if (isNewApp) {
+                mPackages.remove(packageName);
+            }
         }
-        final ShortcutPackage p = getPackageShortcutsIfExists(packageName);
-        if (p == null) {
-            return; // No need to instantiate ShortcutPackage.
-        }
-        p.handlePackageUpdated(newVersionCode);
     }
 
     public void attemptToRestoreIfNeededAndSave(ShortcutService s, @NonNull String packageName,
diff --git a/services/core/java/com/android/server/pm/UserManagerService.java b/services/core/java/com/android/server/pm/UserManagerService.java
index 4541e2e..9c62b20 100644
--- a/services/core/java/com/android/server/pm/UserManagerService.java
+++ b/services/core/java/com/android/server/pm/UserManagerService.java
@@ -22,7 +22,6 @@
 import android.Manifest;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
-import android.annotation.SystemApi;
 import android.annotation.UserIdInt;
 import android.app.Activity;
 import android.app.ActivityManager;
@@ -32,7 +31,6 @@
 import android.app.IActivityManager;
 import android.app.IStopUserCallback;
 import android.app.KeyguardManager;
-import android.app.admin.DevicePolicyManager;
 import android.content.BroadcastReceiver;
 import android.content.ComponentName;
 import android.content.Context;
@@ -78,6 +76,7 @@
 import android.util.Slog;
 import android.util.SparseArray;
 import android.util.SparseBooleanArray;
+import android.util.SparseIntArray;
 import android.util.TimeUtils;
 import android.util.Xml;
 
@@ -90,6 +89,7 @@
 import com.android.internal.util.XmlUtils;
 import com.android.internal.widget.LockPatternUtils;
 import com.android.server.LocalServices;
+import com.android.server.am.UserState;
 
 import libcore.io.IoUtils;
 import libcore.util.Objects;
@@ -331,8 +331,8 @@
     @GuardedBy("mUsersLock")
     private boolean mForceEphemeralUsers;
 
-    @GuardedBy("mUsersLock")
-    private final SparseBooleanArray mUnlockingOrUnlockedUsers = new SparseBooleanArray();
+    @GuardedBy("mUserStates")
+    private final SparseIntArray mUserStates = new SparseIntArray();
 
     private static UserManagerService sInstance;
 
@@ -379,6 +379,7 @@
         mLocalService = new LocalService();
         LocalServices.addService(UserManagerInternal.class, mLocalService);
         mLockPatternUtils = new LockPatternUtils(mContext);
+        mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
     }
 
     void systemReady() {
@@ -2380,7 +2381,9 @@
         synchronized (mUsersLock) {
             mUsers.remove(userHandle);
             mIsUserManaged.delete(userHandle);
-            mUnlockingOrUnlockedUsers.delete(userHandle);
+        }
+        synchronized (mUserStates) {
+            mUserStates.delete(userHandle);
         }
         synchronized (mRestrictionsLock) {
             mBaseUserRestrictions.remove(userHandle);
@@ -3081,6 +3084,9 @@
                 pw.println();
                 pw.println("  Device managed: " + mIsDeviceManaged);
             }
+            synchronized (mUserStates) {
+                pw.println("  Started users state: " + mUserStates);
+            }
             // Dump some capabilities
             pw.println();
             pw.println("  Max users: " + UserManager.getMaxSupportedUsers());
@@ -3267,16 +3273,32 @@
         }
 
         @Override
-        public void setUserUnlockingOrUnlocked(int userId, boolean unlockingOrUnlocked) {
-            synchronized (mUsersLock) {
-                mUnlockingOrUnlockedUsers.put(userId, unlockingOrUnlocked);
+        public boolean isUserRunning(int userId) {
+            synchronized (mUserStates) {
+                return mUserStates.get(userId, -1) >= 0;
+            }
+        }
+
+        @Override
+        public void setUserState(int userId, int userState) {
+            synchronized (mUserStates) {
+                mUserStates.put(userId, userState);
+            }
+        }
+
+        @Override
+        public void removeUserState(int userId) {
+            synchronized (mUserStates) {
+                mUserStates.delete(userId);
             }
         }
 
         @Override
         public boolean isUserUnlockingOrUnlocked(int userId) {
-            synchronized (mUsersLock) {
-                return mUnlockingOrUnlockedUsers.get(userId);
+            synchronized (mUserStates) {
+                int state = mUserStates.get(userId, -1);
+                return (state == UserState.STATE_RUNNING_UNLOCKING)
+                        || (state == UserState.STATE_RUNNING_UNLOCKED);
             }
         }
     }
diff --git a/services/core/java/com/android/server/policy/PhoneWindowManager.java b/services/core/java/com/android/server/policy/PhoneWindowManager.java
index f0e35e0..14ed190 100644
--- a/services/core/java/com/android/server/policy/PhoneWindowManager.java
+++ b/services/core/java/com/android/server/policy/PhoneWindowManager.java
@@ -4360,6 +4360,11 @@
             pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
             // ...with content insets above the nav bar
             cf.bottom = vf.bottom = mStableBottom;
+            if (mStatusBar != null && mFocusedWindow == mStatusBar && canReceiveInput(mStatusBar)) {
+                // The status bar forces the navigation bar while it's visible. Make sure the IME
+                // avoids the navigation bar in that case.
+                pf.right = df.right = of.right = cf.right = vf.right = mStableRight;
+            }
             // IM dock windows always go to the bottom of the screen.
             attrs.gravity = Gravity.BOTTOM;
             mDockLayer = win.getSurfaceLayer();
diff --git a/services/core/java/com/android/server/policy/WindowOrientationListener.java b/services/core/java/com/android/server/policy/WindowOrientationListener.java
index a32c017..8ef0acb 100644
--- a/services/core/java/com/android/server/policy/WindowOrientationListener.java
+++ b/services/core/java/com/android/server/policy/WindowOrientationListener.java
@@ -49,6 +49,7 @@
             "debug.orientation.log", false);
 
     private static final boolean USE_GRAVITY_SENSOR = false;
+    private static final int DEFAULT_BATCH_LATENCY = 100000;
 
     private Handler mHandler;
     private SensorManager mSensorManager;
@@ -118,7 +119,12 @@
                     Slog.d(TAG, "WindowOrientationListener enabled");
                 }
                 mOrientationJudge.resetLocked();
-                mSensorManager.registerListener(mOrientationJudge, mSensor, mRate, mHandler);
+                if (mSensor.getType() == Sensor.TYPE_ACCELEROMETER) {
+                    mSensorManager.registerListener(
+                            mOrientationJudge, mSensor, mRate, DEFAULT_BATCH_LATENCY, mHandler);
+                } else {
+                    mSensorManager.registerListener(mOrientationJudge, mSensor, mRate, mHandler);
+                }
                 mEnabled = true;
             }
         }
diff --git a/services/core/java/com/android/server/power/ShutdownThread.java b/services/core/java/com/android/server/power/ShutdownThread.java
index 5b9d139..8ce2fd9 100644
--- a/services/core/java/com/android/server/power/ShutdownThread.java
+++ b/services/core/java/com/android/server/power/ShutdownThread.java
@@ -543,7 +543,8 @@
                 }
 
                 try {
-                    bluetoothOff = bluetooth == null || !bluetooth.isEnabled();
+                    bluetoothOff = bluetooth == null ||
+                            bluetooth.getState() == BluetoothAdapter.STATE_OFF;
                     if (!bluetoothOff) {
                         Log.w(TAG, "Disabling Bluetooth...");
                         bluetooth.disable(false);  // disable but don't persist new state
@@ -577,7 +578,7 @@
 
                     if (!bluetoothOff) {
                         try {
-                            bluetoothOff = !bluetooth.isEnabled();
+                            bluetoothOff = bluetooth.getState() == BluetoothAdapter.STATE_OFF;
                         } catch (RemoteException ex) {
                             Log.e(TAG, "RemoteException during bluetooth shutdown", ex);
                             bluetoothOff = true;
diff --git a/services/core/java/com/android/server/wm/DockedStackDividerController.java b/services/core/java/com/android/server/wm/DockedStackDividerController.java
index 1b31d07c..e73649d 100644
--- a/services/core/java/com/android/server/wm/DockedStackDividerController.java
+++ b/services/core/java/com/android/server/wm/DockedStackDividerController.java
@@ -45,9 +45,11 @@
 import android.view.animation.AnimationUtils;
 import android.view.animation.Interpolator;
 import android.view.animation.PathInterpolator;
+import android.view.inputmethod.InputMethodManagerInternal;
 
 import com.android.internal.policy.DividerSnapAlgorithm;
 import com.android.internal.policy.DockedDividerUtils;
+import com.android.server.LocalServices;
 import com.android.server.wm.DimLayer.DimLayerUser;
 import com.android.server.wm.WindowManagerService.H;
 
@@ -131,6 +133,7 @@
     private float mLastAnimationProgress;
     private float mLastDividerProgress;
     private final DividerSnapAlgorithm[] mSnapAlgorithmForRotation = new DividerSnapAlgorithm[4];
+    private boolean mImeHideRequested;
 
     DockedStackDividerController(WindowManagerService service, DisplayContent displayContent) {
         mService = service;
@@ -375,11 +378,39 @@
             }
         }
         mDockedStackListeners.finishBroadcast();
-        if (!exists) {
+        if (exists) {
+            InputMethodManagerInternal inputMethodManagerInternal =
+                    LocalServices.getService(InputMethodManagerInternal.class);
+            if (inputMethodManagerInternal != null) {
+
+                // Hide the current IME to avoid problems with animations from IME adjustment when
+                // attaching the docked stack.
+                inputMethodManagerInternal.hideCurrentInputMethod();
+                mImeHideRequested = true;
+            }
+        } else {
             setMinimizedDockedStack(false);
         }
     }
 
+    /**
+     * Resets the state that IME hide has been requested. See {@link #isImeHideRequested}.
+     */
+    void resetImeHideRequested() {
+        mImeHideRequested = false;
+    }
+
+    /**
+     * The docked stack divider controller makes sure the IME gets hidden when attaching the docked
+     * stack, to avoid animation problems. This flag indicates whether the request to hide the IME
+     * has been sent in an asynchronous manner, and the IME should be treated as hidden already.
+     *
+     * @return whether IME hide request has been sent
+     */
+    boolean isImeHideRequested() {
+        return mImeHideRequested;
+    }
+
     void notifyDockedStackMinimizedChanged(boolean minimizedDock, long animDuration) {
         mService.mH.removeMessages(NOTIFY_DOCKED_STACK_MINIMIZED_CHANGED);
         mService.mH.obtainMessage(NOTIFY_DOCKED_STACK_MINIMIZED_CHANGED,
@@ -606,7 +637,12 @@
     private void setMinimizedDockedStack(boolean minimized) {
         final TaskStack stack = mDisplayContent.getDockedStackVisibleForUserLocked();
         notifyDockedStackMinimizedChanged(minimized, 0);
-        setMinimizeAmount(stack, minimized ? 1f : 0f);
+        if (stack == null) {
+            return;
+        }
+        if (stack.setAdjustedForMinimizedDock(minimized ? 1f : 0f)) {
+            mService.mWindowPlacerLocked.performSurfacePlacement();
+        }
     }
 
     private boolean isAnimationMaximizing() {
@@ -690,8 +726,11 @@
         float t = Math.min(1f, (float) (now - mAnimationStartTime) / mAnimationDuration);
         t = (isAnimationMaximizing() ? TOUCH_RESPONSE_INTERPOLATOR : mMinimizedDockInterpolator)
                 .getInterpolation(t);
-        setMinimizeAmount(stack, getMinimizeAmount(stack, t));
-
+        if (stack != null) {
+            if (stack.setAdjustedForMinimizedDock(getMinimizeAmount(stack, t))) {
+                mService.mWindowPlacerLocked.performSurfacePlacement();
+            }
+        }
         if (t >= 1.0f) {
             mAnimatingForMinimizedDockedStack = false;
             return false;
@@ -700,42 +739,6 @@
         }
     }
 
-    void setMinimizeAmount(TaskStack dockedStack, float minimizeAmount) {
-        final ArrayList<TaskStack> stacks = mDisplayContent.getStacks();
-
-        // If the docked stack is not visible, clear the complementary stack on all stacks.
-        if (dockedStack == null) {
-            for (int i = stacks.size() - 1; i >= 0; --i) {
-                final TaskStack stack = stacks.get(i);
-                stack.resetAdjustedForComplementDock();
-            }
-            return;
-        }
-
-        // Otherwise if the docked stack minimize amount has changed, update the adjusted bounds
-        // on the other stack that's currently visible, so that the stack's getDimBounds()
-        // occupies what's left by the docked stack. This is needed so that stuff like wallpaper
-        // gets cropped properly to the area left by the dock.
-        if (dockedStack.setAdjustedForMinimizedDock(minimizeAmount)) {
-            final boolean adjusted =
-                    dockedStack.isVisibleForUserLocked() && minimizeAmount != 0.0f;
-            dockedStack.getDimBounds(mTmpRect2);
-            int dockSide = dockedStack.getDockSide();
-            for (int i = stacks.size() - 1; i >= 0; --i) {
-                final TaskStack stack = stacks.get(i);
-                if (stack == dockedStack) {
-                    continue;
-                }
-                if (stack.isVisibleLocked() && adjusted) {
-                    stack.setAdjustedForComplementDock(mTmpRect2, dockSide);
-                } else {
-                    stack.resetAdjustedForComplementDock();
-                }
-            }
-            mService.mWindowPlacerLocked.performSurfacePlacement();
-        }
-    }
-
     private float getInterpolatedAnimationValue(float t) {
         return t * mAnimationTarget + (1 - t) * mAnimationStart;
     }
diff --git a/services/core/java/com/android/server/wm/TaskStack.java b/services/core/java/com/android/server/wm/TaskStack.java
index 114d9be..8be5b19 100644
--- a/services/core/java/com/android/server/wm/TaskStack.java
+++ b/services/core/java/com/android/server/wm/TaskStack.java
@@ -123,7 +123,6 @@
     private float mAdjustImeAmount;
     private float mAdjustDividerAmount;
     private final int mDockedStackMinimizeThickness;
-    private boolean mAdjustedForForComplementDock;
 
     // If this is true, we are in the bounds animating mode.
     // The task will be down or upscaled to perfectly fit the
@@ -243,9 +242,7 @@
                 insetBounds = mFullyAdjustedImeBounds;
             }
         }
-        if (!mAdjustedForForComplementDock) {
-            alignTasksToAdjustedBounds(adjusted ? mAdjustedBounds : mBounds, insetBounds);
-        }
+        alignTasksToAdjustedBounds(adjusted ? mAdjustedBounds : mBounds, insetBounds);
         mDisplayContent.layoutNeeded = true;
     }
 
@@ -864,7 +861,6 @@
         mImeWin = imeWin;
         mImeGoingAway = false;
         if (!mAdjustedForIme || forceUpdate) {
-            mAdjustedForForComplementDock = false;
             mAdjustedForIme = true;
             mAdjustImeAmount = 0f;
             mAdjustDividerAmount = 0f;
@@ -927,12 +923,10 @@
      * @return Whether the amount has changed and a layout is needed.
      */
     boolean setAdjustedForMinimizedDock(float minimizeAmount) {
-        mAdjustedForForComplementDock = false;
-
         if (minimizeAmount != mMinimizeAmount) {
             mMinimizeAmount = minimizeAmount;
             updateAdjustedBounds();
-            return true;
+            return isVisibleForUserLocked();
         } else {
             return false;
         }
@@ -942,33 +936,6 @@
         return mMinimizeAmount != 0f;
     }
 
-    void setAdjustedForComplementDock(Rect dockBounds, int dockSide) {
-        if (mMinimizeAmount != 0f || mAdjustedForIme) {
-            return;
-        }
-        mTmpAdjustedBounds.set(mBounds);
-        if (dockSide == DOCKED_TOP) {
-            mTmpAdjustedBounds.top = dockBounds.bottom;
-        } else if (dockSide == DOCKED_LEFT) {
-            mTmpAdjustedBounds.left = dockBounds.right;
-        } else if (dockSide == DOCKED_RIGHT) {
-            mTmpAdjustedBounds.right = dockBounds.left;
-        } else {
-            Slog.w(TAG_WM, "setAdjustedForComplementDock: invalid dock side " + dockSide);
-            return;
-        }
-        mAdjustedForForComplementDock = true;
-        setAdjustedBounds(mTmpAdjustedBounds);
-    }
-
-    void resetAdjustedForComplementDock() {
-        if (mAdjustedForForComplementDock) {
-            mAdjustedForForComplementDock = false;
-            mTmpAdjustedBounds.setEmpty();
-            setAdjustedBounds(mTmpAdjustedBounds);
-        }
-    }
-
     /**
      * Puts all visible tasks that are adjusted for IME into resizing mode and adds the windows
      * to the list of to be drawn windows the service is waiting for.
diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java
index c7148c1..3f4c1d5 100644
--- a/services/core/java/com/android/server/wm/WindowManagerService.java
+++ b/services/core/java/com/android/server/wm/WindowManagerService.java
@@ -2834,6 +2834,8 @@
             }
 
             win.mRelayoutCalled = true;
+            win.mInRelayout = true;
+
             final int oldVisibility = win.mViewVisibility;
             win.mViewVisibility = viewVisibility;
             if (DEBUG_SCREEN_ON) {
@@ -2974,6 +2976,7 @@
             if (DEBUG_LAYOUT) {
                 Slog.v(TAG_WM, "Relayout complete " + win + ": outFrame=" + outFrame.toShortString());
             }
+            win.mInRelayout = false;
         }
 
         if (configChanged) {
@@ -3566,6 +3569,8 @@
         final ArrayList<Task> tasks = displayContent.getTasks();
         final boolean inMultiWindow = isStackVisibleLocked(DOCKED_STACK_ID)
                 || isStackVisibleLocked(FREEFORM_WORKSPACE_STACK_ID);
+        final boolean dockMinimized =
+                getDefaultDisplayContentLocked().mDividerControllerLocked.isMinimizedDock();
         for (int taskNdx = tasks.size() - 1; taskNdx >= 0; --taskNdx) {
             AppTokenList tokens = tasks.get(taskNdx).mAppTokens;
             final int firstToken = tokens.size() - 1;
@@ -3600,8 +3605,10 @@
                     continue;
                 }
 
-                // No app except the home app may specify the screen orientation in multi-window.
-                if (inMultiWindow && !atoken.mTask.isHomeTask()) {
+                // No app except the home app may specify the screen orientation in multi-window,
+                // and only if the docked stack is minimized to avoid weirdness when home task
+                // temporarily gets moved to the front.
+                if (inMultiWindow && (!atoken.mTask.isHomeTask() || !dockMinimized)) {
                     continue;
                 }
 
@@ -7593,7 +7600,8 @@
 
     void adjustForImeIfNeeded(final DisplayContent displayContent) {
         final WindowState imeWin = mInputMethodWindow;
-        final boolean imeVisible = imeWin != null && imeWin.isVisibleLw() && imeWin.isDisplayedLw();
+        final boolean imeVisible = imeWin != null && imeWin.isVisibleLw() && imeWin.isDisplayedLw()
+                && !displayContent.mDividerControllerLocked.isImeHideRequested();
         final boolean dockVisible = isStackVisibleLocked(DOCKED_STACK_ID);
         final TaskStack imeTargetStack = getImeFocusStackLocked();
         final int imeDockSide = (dockVisible && imeTargetStack != null) ?
diff --git a/services/core/java/com/android/server/wm/WindowState.java b/services/core/java/com/android/server/wm/WindowState.java
index be27c82..ff95afc 100644
--- a/services/core/java/com/android/server/wm/WindowState.java
+++ b/services/core/java/com/android/server/wm/WindowState.java
@@ -362,6 +362,8 @@
      */
     boolean mRelayoutCalled;
 
+    boolean mInRelayout;
+
     /**
      * If the application has called relayout() with changes that can
      * impact its window's size, we need to perform a layout pass on it
@@ -1630,6 +1632,12 @@
         return task != null && task.inDockedWorkspace();
     }
 
+    // TODO: Strange usage of word workspace here and above.
+    boolean inPinnedWorkspace() {
+        final Task task = getTask();
+        return task != null && task.inPinnedWorkspace();
+    }
+
     boolean isDockedInEffect() {
         final Task task = getTask();
         return task != null && task.isDockedInEffect();
diff --git a/services/core/java/com/android/server/wm/WindowStateAnimator.java b/services/core/java/com/android/server/wm/WindowStateAnimator.java
index 42eddd5..37d6faf5 100644
--- a/services/core/java/com/android/server/wm/WindowStateAnimator.java
+++ b/services/core/java/com/android/server/wm/WindowStateAnimator.java
@@ -23,7 +23,6 @@
 import static android.view.WindowManager.LayoutParams.FLAG_SCALED;
 import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_STARTING;
 import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD;
-import static android.view.WindowManager.LayoutParams.TYPE_WALLPAPER;
 import static com.android.server.wm.AppWindowAnimator.sDummyAnimation;
 import static com.android.server.wm.DragResizeMode.DRAG_RESIZE_MODE_FREEFORM;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ADD_REMOVE;
@@ -1328,33 +1327,6 @@
             return;
         }
 
-        // We crop wallpaper windows to the stack bounds of their current target to avoid them
-        // showing behind transparent windows in other stacks in split-screen mode.
-        if (w.getBaseType() == TYPE_WALLPAPER) {
-            final WindowState wallpaperTarget = mWallpaperControllerLocked.getWallpaperTarget();
-            if (wallpaperTarget != null) {
-                final Task task = wallpaperTarget.getTask();
-                final WindowStateAnimator winAnimator = wallpaperTarget.mWinAnimator;
-                // We can only crop the wallpaper using final crop with stack bounds if the target
-                // is not animating, or if it's animating with clip mode STACK_CLIP_AFTER_ANIM.
-                // If it's animating with mode STACK_CLIP_NONE, we shouldn't crop either the task
-                // itself or the wallpaper. If it's animating with STACK_CLIP_BEFORE_ANIM, the crop
-                // is before the transform on the task itself.
-                final boolean useFinalCropOnWallpaper = !winAnimator.isAnimationSet()
-                        || winAnimator.resolveStackClip() == STACK_CLIP_AFTER_ANIM;
-                if (task != null && !task.isFullscreen()
-                        && task.cropWindowsToStackBounds()
-                        && useFinalCropOnWallpaper){
-                    final TaskStack stack = task.mStack;
-                    if (stack != null && !stack.isFullscreen()) {
-                        stack.getDimBounds(mTmpStackBounds);
-                        finalClipRect.set(mTmpStackBounds);
-                    }
-                }
-            }
-            return;
-        }
-
         final Task task = w.getTask();
         if (task == null || !task.cropWindowsToStackBounds()) {
             return;
@@ -1428,8 +1400,24 @@
         float extraHScale = (float) 1.0;
         float extraVScale = (float) 1.0;
 
-        mSurfaceResized = mSurfaceController.setSizeInTransaction(
-                mTmpSize.width(), mTmpSize.height(), recoveringMemory);
+        // Once relayout has been called at least once, we need to make sure
+        // we only resize the client surface during calls to relayout. For
+        // clients which use indeterminate measure specs (MATCH_PARENT),
+        // we may try and change their window size without a call to relayout.
+        // However, this would be unsafe, as the client may be in the middle
+        // of producing a frame at the old size, having just completed layout
+        // to find the surface size changed underneath it.
+        //
+        // TODO: For N we only apply this fix to the pinned workspace. As we
+        // aren't observing known issues here outside of PiP resizing. (Typically
+        // the other windows that use -1 are PopupWindows which aren't likely
+        // to be rendering while we resize).
+        if (!w.inPinnedWorkspace() || (!w.mRelayoutCalled || w.mInRelayout)) {
+            mSurfaceResized = mSurfaceController.setSizeInTransaction(
+                    mTmpSize.width(), mTmpSize.height(), recoveringMemory);
+        } else {
+            mSurfaceResized = false;
+        }
         mForceScaleUntilResize = mForceScaleUntilResize && !mSurfaceResized;
 
 
@@ -1437,10 +1425,12 @@
         if ((task != null && task.mStack.getForceScaleToCrop()) || mForceScaleUntilResize) {
             int hInsets = w.getAttrs().surfaceInsets.left + w.getAttrs().surfaceInsets.right;
             int vInsets = w.getAttrs().surfaceInsets.top + w.getAttrs().surfaceInsets.bottom;
+            float surfaceWidth = mSurfaceController.getWidth();
+            float surfaceHeight = mSurfaceController.getHeight();
             // We want to calculate the scaling based on the content area, not based on
             // the entire surface, so that we scale in sync with windows that don't have insets.
-            extraHScale = (mTmpClipRect.width() - hInsets) / (float)(mTmpSize.width() - hInsets);
-            extraVScale = (mTmpClipRect.height() - vInsets) / (float)(mTmpSize.height() - vInsets);
+            extraHScale = (mTmpClipRect.width() - hInsets) / (float)(surfaceWidth - hInsets);
+            extraVScale = (mTmpClipRect.height() - vInsets) / (float)(surfaceHeight - vInsets);
 
             // In the case of ForceScaleToCrop we scale entire tasks together,
             // and so we need to scale our offsets relative to the task bounds
@@ -1462,14 +1452,14 @@
             // Since we are scaled to fit in our previously desired crop, we can now
             // expose the whole window in buffer space, and not risk extending
             // past where the system would have cropped us
-            mTmpClipRect.set(0, 0, mTmpSize.width(), mTmpSize.height());
+            mTmpClipRect.set(0, 0, (int)surfaceWidth, (int)surfaceHeight);
             mTmpFinalClipRect.setEmpty();
 
             // Various surfaces in the scaled stack may resize at different times.
             // We need to ensure for each surface, that we disable transformation matrix
             // scaling in the same transaction which we resize the surface in.
             // As we are in SCALING_MODE_SCALE_TO_WINDOW, SurfaceFlinger will
-            // then take over the scaling until the new buffer arrives, and things
+            // then take over the scaling until the new buffer arrives, and things 
             // will be seamless.
             mForceScaleUntilResize = true;
         } else {
@@ -1755,6 +1745,10 @@
                 mWin.mAppToken.onFirstWindowDrawn(mWin, this);
             }
 
+            if (mWin.mAttrs.type == TYPE_INPUT_METHOD) {
+                mWin.mDisplayContent.mDividerControllerLocked.resetImeHideRequested();
+            }
+
             return true;
         }
         return false;
diff --git a/services/core/java/com/android/server/wm/WindowSurfaceController.java b/services/core/java/com/android/server/wm/WindowSurfaceController.java
index af47369..9646a49 100644
--- a/services/core/java/com/android/server/wm/WindowSurfaceController.java
+++ b/services/core/java/com/android/server/wm/WindowSurfaceController.java
@@ -454,6 +454,15 @@
         return mSurfaceY;
     }
 
+    float getWidth() {
+        return mSurfaceW;
+    }
+
+    float getHeight() {
+        return mSurfaceH;
+    }
+
+
     public void dump(PrintWriter pw, String prefix, boolean dumpAll) {
         if (dumpAll) {
             pw.print(prefix); pw.print("mSurface="); pw.println(mSurfaceControl);
diff --git a/services/core/jni/com_android_server_location_FlpHardwareProvider.cpp b/services/core/jni/com_android_server_location_FlpHardwareProvider.cpp
index 8ea9bfc..06d2031 100644
--- a/services/core/jni/com_android_server_location_FlpHardwareProvider.cpp
+++ b/services/core/jni/com_android_server_location_FlpHardwareProvider.cpp
@@ -78,7 +78,7 @@
   env->ThrowNew(exceptionClass, methodName);
 }
 
-static bool IsValidCallbackThread() {
+static bool IsValidCallbackThreadEnvOnly() {
   JNIEnv* env = AndroidRuntime::getJNIEnv();
 
   if(sCallbackEnv == NULL || sCallbackEnv != env) {
@@ -89,6 +89,20 @@
   return true;
 }
 
+static bool IsValidCallbackThread() {
+  // sCallbacksObject is created when FlpHardwareProvider on Java side is
+  // initialized. Sometimes the hardware may call a function before the Java
+  // side is ready. In order to prevent a system crash, check whether
+  // sCallbacksObj has been created. If not, simply ignore this event from
+  // hardware.
+  if (sCallbacksObj == NULL) {
+    ALOGE("Attempt to use FlpHardwareProvider blocked, because it hasn't been initialized.");
+    return false;
+  }
+
+  return IsValidCallbackThreadEnvOnly();
+}
+
 static void BatchingCapabilitiesCallback(int32_t capabilities) {
   if(!IsValidCallbackThread()) {
     return;
@@ -154,7 +168,7 @@
     }
     case DISASSOCIATE_JVM:
     {
-      if (!IsValidCallbackThread()) {
+      if (!IsValidCallbackThreadEnvOnly()) {
         ALOGE(
             "Attempted to dissasociate an unnownk callback thread : '%s'.",
             __FUNCTION__
@@ -661,16 +675,6 @@
     TranslateToObject(lastLocation, locationObject);
   }
 
-  // sCallbacksObject is created when FlpHardwareProvider on Java side is
-  // initialized. Sometimes the hardware may call this function before the Java
-  // side is ready. In order to prevent the system crash, check whether
-  // sCallbacksObj has been created. If not, simply ignore this event from
-  // hardware.
-  if (sCallbacksObj == NULL) {
-    ALOGE("FlpHardwareProvider hasn't been initialized.");
-    return;
-  }
-
   sCallbackEnv->CallVoidMethod(
       sCallbacksObj,
       sOnGeofenceMonitorStatus,
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
index 1af9ccb..9a7e64b3 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
@@ -3810,12 +3810,16 @@
             // If caller has PO (or DO) it can change the password, so see if that's the case first.
             ActiveAdmin admin = getActiveAdminWithPolicyForUidLocked(
                     null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, callingUid);
-            final boolean preN = getTargetSdk(admin.info.getPackageName(),
-                    userHandle) <= android.os.Build.VERSION_CODES.M;
-            if (admin == null) {
+            final boolean preN;
+            if (admin != null) {
+                preN = getTargetSdk(admin.info.getPackageName(),
+                        userHandle) <= android.os.Build.VERSION_CODES.M;
+            } else {
                 // Otherwise, make sure the caller has any active admin with the right policy.
                 admin = getActiveAdminForCallerLocked(null,
                         DeviceAdminInfo.USES_POLICY_RESET_PASSWORD);
+                preN = getTargetSdk(admin.info.getPackageName(),
+                        userHandle) <= android.os.Build.VERSION_CODES.M;
 
                 // As of N, password resetting to empty/null is not allowed anymore.
                 // TODO Should we allow DO/PO to set an empty password?
diff --git a/services/net/java/android/net/apf/ApfFilter.java b/services/net/java/android/net/apf/ApfFilter.java
index 538e8f8..485f2f5 100644
--- a/services/net/java/android/net/apf/ApfFilter.java
+++ b/services/net/java/android/net/apf/ApfFilter.java
@@ -597,12 +597,13 @@
     private void generateIPv4FilterLocked(ApfGenerator gen) throws IllegalInstructionException {
         // Here's a basic summary of what the IPv4 filter program does:
         //
-        // if it's multicast and we're dropping multicast:
-        //   drop
-        // if it's not broadcast:
-        //   pass
-        // if it's not DHCP destined to our MAC:
-        //   drop
+        // if filtering multicast (i.e. multicast lock not held):
+        //   if it's multicast:
+        //     drop
+        //   if it's not broadcast:
+        //     pass
+        //   if it's not DHCP destined to our MAC:
+        //     drop
         // pass
 
         if (mMulticastFilter) {
@@ -610,27 +611,27 @@
             gen.addLoad8(Register.R0, IPV4_DEST_ADDR_OFFSET);
             gen.addAnd(0xf0);
             gen.addJumpIfR0Equals(0xe0, gen.DROP_LABEL);
-        }
 
-        // Drop all broadcasts besides DHCP addressed to us
-        // If not a broadcast packet, pass
-        gen.addLoadImmediate(Register.R0, ETH_DEST_ADDR_OFFSET);
-        gen.addJumpIfBytesNotEqual(Register.R0, ETH_BROADCAST_MAC_ADDRESS, gen.PASS_LABEL);
-        // If not UDP, drop
-        gen.addLoad8(Register.R0, IPV4_PROTOCOL_OFFSET);
-        gen.addJumpIfR0NotEquals(IPPROTO_UDP, gen.DROP_LABEL);
-        // If fragment, drop. This matches the BPF filter installed by the DHCP client.
-        gen.addLoad16(Register.R0, IPV4_FRAGMENT_OFFSET_OFFSET);
-        gen.addJumpIfR0AnyBitsSet(IPV4_FRAGMENT_OFFSET_MASK, gen.DROP_LABEL);
-        // If not to DHCP client port, drop
-        gen.addLoadFromMemory(Register.R1, gen.IPV4_HEADER_SIZE_MEMORY_SLOT);
-        gen.addLoad16Indexed(Register.R0, UDP_DESTINATION_PORT_OFFSET);
-        gen.addJumpIfR0NotEquals(DHCP_CLIENT_PORT, gen.DROP_LABEL);
-        // If not DHCP to our MAC address, drop
-        gen.addLoadImmediate(Register.R0, DHCP_CLIENT_MAC_OFFSET);
-        // NOTE: Relies on R1 containing IPv4 header offset.
-        gen.addAddR1();
-        gen.addJumpIfBytesNotEqual(Register.R0, mHardwareAddress, gen.DROP_LABEL);
+            // Drop all broadcasts besides DHCP addressed to us
+            // If not a broadcast packet, pass
+            gen.addLoadImmediate(Register.R0, ETH_DEST_ADDR_OFFSET);
+            gen.addJumpIfBytesNotEqual(Register.R0, ETH_BROADCAST_MAC_ADDRESS, gen.PASS_LABEL);
+            // If not UDP, drop
+            gen.addLoad8(Register.R0, IPV4_PROTOCOL_OFFSET);
+            gen.addJumpIfR0NotEquals(IPPROTO_UDP, gen.DROP_LABEL);
+            // If fragment, drop. This matches the BPF filter installed by the DHCP client.
+            gen.addLoad16(Register.R0, IPV4_FRAGMENT_OFFSET_OFFSET);
+            gen.addJumpIfR0AnyBitsSet(IPV4_FRAGMENT_OFFSET_MASK, gen.DROP_LABEL);
+            // If not to DHCP client port, drop
+            gen.addLoadFromMemory(Register.R1, gen.IPV4_HEADER_SIZE_MEMORY_SLOT);
+            gen.addLoad16Indexed(Register.R0, UDP_DESTINATION_PORT_OFFSET);
+            gen.addJumpIfR0NotEquals(DHCP_CLIENT_PORT, gen.DROP_LABEL);
+            // If not DHCP to our MAC address, drop
+            gen.addLoadImmediate(Register.R0, DHCP_CLIENT_MAC_OFFSET);
+            // NOTE: Relies on R1 containing IPv4 header offset.
+            gen.addAddR1();
+            gen.addJumpIfBytesNotEqual(Register.R0, mHardwareAddress, gen.DROP_LABEL);
+        }
 
         // Otherwise, pass
         gen.addJump(gen.PASS_LABEL);
diff --git a/services/net/java/android/net/dhcp/DhcpClient.java b/services/net/java/android/net/dhcp/DhcpClient.java
index 99b10c3..96c852b 100644
--- a/services/net/java/android/net/dhcp/DhcpClient.java
+++ b/services/net/java/android/net/dhcp/DhcpClient.java
@@ -84,7 +84,7 @@
 public class DhcpClient extends StateMachine {
 
     private static final String TAG = "DhcpClient";
-    private static final boolean DBG = false;
+    private static final boolean DBG = true;
     private static final boolean STATE_DBG = false;
     private static final boolean MSG_DBG = false;
     private static final boolean PACKET_DBG = false;
diff --git a/services/tests/servicestests/res/values/strings.xml b/services/tests/servicestests/res/values/strings.xml
new file mode 100644
index 0000000..2f9d06c
--- /dev/null
+++ b/services/tests/servicestests/res/values/strings.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2016 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="shortcut_title1"></string>
+    <string name="shortcut_text1"></string>
+    <string name="shortcut_disabled_message1"></string>
+    <string name="shortcut_title2"></string>
+    <string name="shortcut_text2"></string>
+    <string name="shortcut_disabled_message2"></string>
+</resources>
diff --git a/services/tests/servicestests/res/xml/shortcut_0.xml b/services/tests/servicestests/res/xml/shortcut_0.xml
new file mode 100644
index 0000000..fda001e
--- /dev/null
+++ b/services/tests/servicestests/res/xml/shortcut_0.xml
@@ -0,0 +1,2 @@
+<shortcuts xmlns:android="http://schemas.android.com/apk/res/android" >
+</shortcuts>
diff --git a/services/tests/servicestests/res/xml/shortcut_1.xml b/services/tests/servicestests/res/xml/shortcut_1.xml
new file mode 100644
index 0000000..c370e74
--- /dev/null
+++ b/services/tests/servicestests/res/xml/shortcut_1.xml
@@ -0,0 +1,14 @@
+<shortcuts xmlns:android="http://schemas.android.com/apk/res/android" >
+    <shortcut
+        android:shortcutId="ms1"
+        android:enabled="true"
+        android:shortcutRank="1"
+        android:shortcutIcon="@drawable/icon1"
+        android:shortcutTitle="@string/shortcut_title1"
+        android:shortcutText="@string/shortcut_text1"
+        android:shortcutDisabledMessage="@string/shortcut_disabled_message1"
+        android:shortcutCategories="android.shortcut.conversation:android.shortcut.media"
+        android:shortcutIntentAction="action1"
+        android:shortcutIntentData="data1"
+    />
+</shortcuts>
diff --git a/services/tests/servicestests/res/xml/shortcut_1_disable.xml b/services/tests/servicestests/res/xml/shortcut_1_disable.xml
new file mode 100644
index 0000000..08ecac3
--- /dev/null
+++ b/services/tests/servicestests/res/xml/shortcut_1_disable.xml
@@ -0,0 +1,11 @@
+<shortcuts xmlns:android="http://schemas.android.com/apk/res/android" >
+    <shortcut
+        android:shortcutId="ms1"
+        android:enabled="false"
+        android:shortcutRank="1"
+        android:shortcutIcon="@drawable/icon2"
+        android:shortcutTitle="@string/shortcut_title2"
+        android:shortcutText="@string/shortcut_text2"
+        android:shortcutDisabledMessage="@string/shortcut_disabled_message2"
+    />
+</shortcuts>
diff --git a/services/tests/servicestests/res/xml/shortcut_2.xml b/services/tests/servicestests/res/xml/shortcut_2.xml
new file mode 100644
index 0000000..9e923f3
--- /dev/null
+++ b/services/tests/servicestests/res/xml/shortcut_2.xml
@@ -0,0 +1,26 @@
+<shortcuts xmlns:android="http://schemas.android.com/apk/res/android" >
+    <shortcut
+        android:shortcutId="ms1"
+        android:enabled="true"
+        android:shortcutRank="1"
+        android:shortcutIcon="@drawable/icon1"
+        android:shortcutTitle="@string/shortcut_title1"
+        android:shortcutText="@string/shortcut_text1"
+        android:shortcutDisabledMessage="@string/shortcut_disabled_message1"
+        android:shortcutCategories="android.shortcut.conversation:android.shortcut.media"
+        android:shortcutIntentAction="action1"
+        android:shortcutIntentData="http://a.b.c/"
+    />
+    <shortcut
+        android:shortcutId="ms2"
+        android:enabled="true"
+        android:shortcutRank="2"
+        android:shortcutIcon="@drawable/icon2"
+        android:shortcutTitle="@string/shortcut_title2"
+        android:shortcutText="@string/shortcut_text2"
+        android:shortcutDisabledMessage="@string/shortcut_disabled_message2"
+        android:shortcutCategories="android.shortcut.conversation"
+        android:shortcutIntentAction="action2"
+        android:shortcutIntentData="http://a.b.c/2"
+    />
+</shortcuts>
diff --git a/services/tests/servicestests/res/xml/shortcut_2_duplicate.xml b/services/tests/servicestests/res/xml/shortcut_2_duplicate.xml
new file mode 100644
index 0000000..d90c18d
--- /dev/null
+++ b/services/tests/servicestests/res/xml/shortcut_2_duplicate.xml
@@ -0,0 +1,12 @@
+<shortcuts xmlns:android="http://schemas.android.com/apk/res/android" >
+    <shortcut
+        android:shortcutId="ms1"
+        android:shortcutTitle="@string/shortcut_title1"
+        android:shortcutIntentAction="action1"
+    />
+    <shortcut
+        android:shortcutId="ms1"
+        android:shortcutTitle="@string/shortcut_title2"
+        android:shortcutIntentAction="action2"
+    />
+</shortcuts>
diff --git a/services/tests/servicestests/res/xml/shortcut_5.xml b/services/tests/servicestests/res/xml/shortcut_5.xml
new file mode 100644
index 0000000..f3f71d2
--- /dev/null
+++ b/services/tests/servicestests/res/xml/shortcut_5.xml
@@ -0,0 +1,40 @@
+<shortcuts xmlns:android="http://schemas.android.com/apk/res/android" >
+    <shortcut
+        android:shortcutId="ms1"
+        android:enabled="true"
+        android:shortcutRank="1"
+        android:shortcutIcon="@drawable/icon1"
+        android:shortcutTitle="@string/shortcut_title1"
+        android:shortcutText="@string/shortcut_text1"
+        android:shortcutDisabledMessage="@string/shortcut_disabled_message1"
+        android:shortcutCategories="android.shortcut.conversation:android.shortcut.media"
+        android:shortcutIntentAction="action1"
+        android:shortcutIntentData="http://a.b.c/1"
+    />
+    <shortcut
+        android:shortcutId="ms2"
+        android:enabled="true"
+        android:shortcutRank="2"
+        android:shortcutIcon="@drawable/icon2"
+        android:shortcutTitle="@string/shortcut_title2"
+        android:shortcutText="@string/shortcut_text2"
+        android:shortcutDisabledMessage="@string/shortcut_disabled_message2"
+        android:shortcutCategories="android.shortcut.conversation"
+        android:shortcutIntentAction="action2"
+    />
+    <shortcut
+        android:shortcutId="ms3"
+        android:shortcutTitle="@string/shortcut_title1"
+        android:shortcutIntentAction="android.intent.action.VIEW"
+    />
+    <shortcut
+        android:shortcutId="ms4"
+        android:shortcutTitle="@string/shortcut_title1"
+        android:shortcutIntentAction="android.intent.action.VIEW"
+    />
+    <shortcut
+        android:shortcutId="ms5"
+        android:shortcutTitle="@string/shortcut_title1"
+        android:shortcutIntentAction="android.intent.action.VIEW"
+    />
+</shortcuts>
diff --git a/services/tests/servicestests/res/xml/shortcut_error_1.xml b/services/tests/servicestests/res/xml/shortcut_error_1.xml
new file mode 100644
index 0000000..2c51420
--- /dev/null
+++ b/services/tests/servicestests/res/xml/shortcut_error_1.xml
@@ -0,0 +1,11 @@
+<shortcuts xmlns:android="http://schemas.android.com/apk/res/android" >
+    <shortcut
+        android:shortcutTitle="@string/shortcut_title1"
+        android:shortcutIntentAction="android.intent.action.VIEW"
+    />
+    <shortcut
+        android:shortcutId="x1"
+        android:shortcutTitle="@string/shortcut_title1"
+        android:shortcutIntentAction="android.intent.action.VIEW"
+    />
+</shortcuts>
diff --git a/services/tests/servicestests/res/xml/shortcut_error_2.xml b/services/tests/servicestests/res/xml/shortcut_error_2.xml
new file mode 100644
index 0000000..d075e7d
--- /dev/null
+++ b/services/tests/servicestests/res/xml/shortcut_error_2.xml
@@ -0,0 +1,11 @@
+<shortcuts xmlns:android="http://schemas.android.com/apk/res/android" >
+    <shortcut
+        android:shortcutId="manifest-shortcut-3"
+        android:shortcutIntentAction="android.intent.action.VIEW"
+    />
+    <shortcut
+        android:shortcutId="x2"
+        android:shortcutTitle="@string/shortcut_title1"
+        android:shortcutIntentAction="android.intent.action.VIEW"
+    />
+</shortcuts>
diff --git a/services/tests/servicestests/res/xml/shortcut_error_3.xml b/services/tests/servicestests/res/xml/shortcut_error_3.xml
new file mode 100644
index 0000000..30bf56e
--- /dev/null
+++ b/services/tests/servicestests/res/xml/shortcut_error_3.xml
@@ -0,0 +1,11 @@
+<shortcuts xmlns:android="http://schemas.android.com/apk/res/android" >
+    <shortcut
+        android:shortcutId="manifest-shortcut-3"
+        android:shortcutTitle="@string/shortcut_title1"
+    />
+    <shortcut
+        android:shortcutId="x3"
+        android:shortcutTitle="@string/shortcut_title1"
+        android:shortcutIntentAction="android.intent.action.VIEW"
+    />
+</shortcuts>
diff --git a/services/tests/servicestests/src/android/net/apf/ApfTest.java b/services/tests/servicestests/src/android/net/apf/ApfTest.java
index 9e04d23..fae82ca 100644
--- a/services/tests/servicestests/src/android/net/apf/ApfTest.java
+++ b/services/tests/servicestests/src/android/net/apf/ApfTest.java
@@ -663,7 +663,7 @@
     @LargeTest
     public void testApfFilterIPv4() throws Exception {
         MockIpManagerCallback ipManagerCallback = new MockIpManagerCallback();
-        ApfFilter apfFilter = new TestApfFilter(ipManagerCallback, false /* multicastFilter */);
+        ApfFilter apfFilter = new TestApfFilter(ipManagerCallback, true /* multicastFilter */);
         byte[] program = ipManagerCallback.getApfProgram();
 
         // Verify empty packet of 100 zero bytes is passed
@@ -726,46 +726,57 @@
         byte[] program = ipManagerCallback.getApfProgram();
 
         // Construct IPv4 and IPv6 multicast packets.
-        ByteBuffer v4packet = ByteBuffer.wrap(new byte[100]);
-        v4packet.putShort(ETH_ETHERTYPE_OFFSET, (short)ETH_P_IP);
-        v4packet.position(IPV4_DEST_ADDR_OFFSET);
-        v4packet.put(new byte[]{(byte)224,0,0,1});
+        ByteBuffer mcastv4packet = ByteBuffer.wrap(new byte[100]);
+        mcastv4packet.putShort(ETH_ETHERTYPE_OFFSET, (short)ETH_P_IP);
+        mcastv4packet.position(IPV4_DEST_ADDR_OFFSET);
+        mcastv4packet.put(new byte[]{(byte)224,0,0,1});
 
-        ByteBuffer v6packet = ByteBuffer.wrap(new byte[100]);
-        v6packet.putShort(ETH_ETHERTYPE_OFFSET, (short)ETH_P_IPV6);
-        v6packet.put(IPV6_NEXT_HEADER_OFFSET, (byte)IPPROTO_UDP);
-        v6packet.position(IPV6_DEST_ADDR_OFFSET);
-        v6packet.put(new byte[]{(byte)0xff,2,0,0,0,0,0,0,0,0,0,0,0,0,0,(byte)0xfb});
+        ByteBuffer mcastv6packet = ByteBuffer.wrap(new byte[100]);
+        mcastv6packet.putShort(ETH_ETHERTYPE_OFFSET, (short)ETH_P_IPV6);
+        mcastv6packet.put(IPV6_NEXT_HEADER_OFFSET, (byte)IPPROTO_UDP);
+        mcastv6packet.position(IPV6_DEST_ADDR_OFFSET);
+        mcastv6packet.put(new byte[]{(byte)0xff,2,0,0,0,0,0,0,0,0,0,0,0,0,0,(byte)0xfb});
+
+        // Construct IPv4 broadcast packet.
+        ByteBuffer bcastv4packet = ByteBuffer.wrap(new byte[100]);
+        bcastv4packet.put(ETH_BROADCAST_MAC_ADDRESS);
+        bcastv4packet.putShort(ETH_ETHERTYPE_OFFSET, (short)ETH_P_IP);
+        bcastv4packet.position(IPV4_DEST_ADDR_OFFSET);
+        bcastv4packet.put(new byte[]{(byte)192,(byte)0,(byte)2,(byte)63});
 
         // Verify initially disabled multicast filter is off
-        assertPass(program, v4packet.array(), 0);
-        assertPass(program, v6packet.array(), 0);
+        assertPass(program, bcastv4packet.array(), 0);
+        assertPass(program, mcastv4packet.array(), 0);
+        assertPass(program, mcastv6packet.array(), 0);
 
         // Turn on multicast filter and verify it works
         ipManagerCallback.resetApfProgramWait();
         apfFilter.setMulticastFilter(true);
         program = ipManagerCallback.getApfProgram();
-        assertDrop(program, v4packet.array(), 0);
-        assertDrop(program, v6packet.array(), 0);
+        assertDrop(program, bcastv4packet.array(), 0);
+        assertDrop(program, mcastv4packet.array(), 0);
+        assertDrop(program, mcastv6packet.array(), 0);
 
         // Turn off multicast filter and verify it's off
         ipManagerCallback.resetApfProgramWait();
         apfFilter.setMulticastFilter(false);
         program = ipManagerCallback.getApfProgram();
-        assertPass(program, v4packet.array(), 0);
-        assertPass(program, v6packet.array(), 0);
+        assertPass(program, bcastv4packet.array(), 0);
+        assertPass(program, mcastv4packet.array(), 0);
+        assertPass(program, mcastv6packet.array(), 0);
 
         // Verify it can be initialized to on
         ipManagerCallback.resetApfProgramWait();
         apfFilter.shutdown();
         apfFilter = new TestApfFilter(ipManagerCallback, true /* multicastFilter */);
         program = ipManagerCallback.getApfProgram();
-        assertDrop(program, v4packet.array(), 0);
-        assertDrop(program, v6packet.array(), 0);
+        assertDrop(program, bcastv4packet.array(), 0);
+        assertDrop(program, mcastv4packet.array(), 0);
+        assertDrop(program, mcastv6packet.array(), 0);
 
         // Verify that ICMPv6 multicast is not dropped.
-        v6packet.put(IPV6_NEXT_HEADER_OFFSET, (byte)IPPROTO_ICMPV6);
-        assertPass(program, v6packet.array(), 0);
+        mcastv6packet.put(IPV6_NEXT_HEADER_OFFSET, (byte)IPPROTO_ICMPV6);
+        assertPass(program, mcastv6packet.array(), 0);
 
         apfFilter.shutdown();
     }
diff --git a/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest.java b/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest.java
index 8a2a58c..1a0a003 100644
--- a/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest.java
+++ b/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest.java
@@ -15,17 +15,22 @@
  */
 package com.android.server.pm;
 
+import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertAllDisabled;
 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertAllDynamic;
 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertAllDynamicOrPinned;
+import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertAllEnabled;
 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertAllHaveIcon;
 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertAllHaveIconFile;
 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertAllHaveIconResId;
 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertAllHaveIntents;
 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertAllHaveTitle;
+import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertAllImmutable;
 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertAllKeyFieldsOnly;
+import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertAllManifest;
 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertAllNotHaveIntents;
 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertAllNotHaveTitle;
 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertAllNotKeyFieldsOnly;
+import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertAllNotManifest;
 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertAllPinned;
 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertAllStringsResolved;
 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertAllUnique;
@@ -33,8 +38,10 @@
 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertBundleEmpty;
 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertCallbackNotReceived;
 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertCallbackReceived;
+import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertCannotUpdateImmutable;
 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertDynamicAndPinned;
 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertDynamicOnly;
+import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertEmpty;
 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertExpectException;
 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertShortcutIds;
 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.findShortcut;
@@ -70,6 +77,7 @@
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
+import android.content.pm.ActivityInfo;
 import android.content.pm.ApplicationInfo;
 import android.content.pm.ILauncherApps;
 import android.content.pm.LauncherApps;
@@ -83,6 +91,7 @@
 import android.content.pm.Signature;
 import android.content.pm.UserInfo;
 import android.content.res.Resources;
+import android.content.res.XmlResourceParser;
 import android.graphics.Bitmap;
 import android.graphics.Bitmap.CompressFormat;
 import android.graphics.BitmapFactory;
@@ -143,6 +152,11 @@
  adb shell am instrument -e class com.android.server.pm.ShortcutManagerTest \
  -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
 
+
+ * TODO More tests for pinning + manifest shortcuts
+ * TODO Manifest shortcuts + app upgrade -> launcher callback.
+ *      Also locale change should trigger launcehr callbacks too, when they use strign resoucres.
+ *      (not implemented yet.)
  * TODO: Add checks with assertAllNotHaveIcon()
  * TODO: Detailed test for hasShortcutPermissionInner().
  * TODO: Add tests for the command line functions too.
@@ -155,9 +169,9 @@
      * Whether to enable dump or not.  Should be only true when debugging to avoid bugs where
      * dump affecting the behavior.
      */
-    private static final boolean ENABLE_DUMP = false; // DO NOT SUBMIT WITH true
+    private static final boolean ENABLE_DUMP = true; // DO NOT SUBMIT WITH true
 
-    private static final boolean DUMP_IN_TEARDOWN = false; // DO NOT SUBMIT WITH true
+    private static final boolean DUMP_IN_TEARDOWN = true; // DO NOT SUBMIT WITH true
 
     private static final String[] EMPTY_STRINGS = new String[0]; // Just for readability.
 
@@ -229,6 +243,15 @@
         public int getUserId() {
             return UserHandle.USER_SYSTEM;
         }
+
+        public PackageInfo injectGetActivitiesWithMetadata(
+                String packageName, @UserIdInt int userId) {
+            return ShortcutManagerTest.this.injectGetActivitiesWithMetadata(packageName, userId);
+        }
+
+        public XmlResourceParser injectXmlMetaData(ActivityInfo activityInfo, String key) {
+            return ShortcutManagerTest.this.injectXmlMetaData(activityInfo, key);
+        }
     }
 
     /** ShortcutService with injection override methods. */
@@ -339,6 +362,21 @@
         }
 
         @Override
+        List<ApplicationInfo> injectInstalledApplications(@UserIdInt int userId) {
+            return getInstalledApplications(userId);
+        }
+
+        @Override
+        PackageInfo injectGetActivitiesWithMetadata(String packageName, @UserIdInt int userId) {
+            return mContext.injectGetActivitiesWithMetadata(packageName, userId);
+        }
+
+        @Override
+        XmlResourceParser injectXmlMetaData(ActivityInfo activityInfo, String key) {
+            return mContext.injectXmlMetaData(activityInfo, key);
+        }
+
+        @Override
         void postToHandler(Runnable r) {
             final long token = mContext.injectClearCallingIdentity();
             r.run();
@@ -524,6 +562,9 @@
 
     private final ArrayList<String> mCallerPermissions = new ArrayList<>();
 
+    private final HashMap<String, HashMap<ComponentName, Integer>> mActivityMetadataResId
+            = new HashMap<>();
+
     static {
         QUERY_ALL.setQueryFlags(
                 ShortcutQuery.FLAG_GET_DYNAMIC | ShortcutQuery.FLAG_GET_PINNED);
@@ -720,6 +761,12 @@
         });
     }
 
+    private void updatePackageLastUpdateTime(String packageName, long increment) {
+        updatePackageInfo(packageName, pi -> {
+            pi.lastUpdateTime += increment;
+        });
+    }
+
     private void uninstallPackage(int userId, String packageName) {
         if (ENABLE_DUMP) {
             Log.i(TAG, "Unnstall package " + packageName + " / " + userId);
@@ -742,8 +789,12 @@
         final PackageInfo ret = new PackageInfo();
         ret.packageName = pi.packageName;
         ret.versionCode = pi.versionCode;
+        ret.lastUpdateTime = pi.lastUpdateTime;
+
         ret.applicationInfo = new ApplicationInfo(pi.applicationInfo);
         ret.applicationInfo.uid = UserHandle.getUid(userId, pi.applicationInfo.uid);
+        ret.applicationInfo.packageName = pi.packageName;
+
         if (mUninstalledPackages.contains(PackageWithUser.of(userId, packageName))) {
             ret.applicationInfo.flags &= ~ApplicationInfo.FLAG_INSTALLED;
         }
@@ -755,6 +806,66 @@
         return ret;
     }
 
+    private void addApplicationInfo(PackageInfo pi, List<ApplicationInfo> list) {
+        if (pi != null && pi.applicationInfo != null) {
+            list.add(pi.applicationInfo);
+        }
+    }
+
+    private List<ApplicationInfo> getInstalledApplications(int userId) {
+        final ArrayList<ApplicationInfo> ret = new ArrayList<>();
+
+        addApplicationInfo(getInjectedPackageInfo(CALLING_PACKAGE_1, userId, false), ret);
+        addApplicationInfo(getInjectedPackageInfo(CALLING_PACKAGE_2, userId, false), ret);
+        addApplicationInfo(getInjectedPackageInfo(CALLING_PACKAGE_3, userId, false), ret);
+        addApplicationInfo(getInjectedPackageInfo(CALLING_PACKAGE_4, userId, false), ret);
+        addApplicationInfo(getInjectedPackageInfo(LAUNCHER_1, userId, false), ret);
+        addApplicationInfo(getInjectedPackageInfo(LAUNCHER_2, userId, false), ret);
+        addApplicationInfo(getInjectedPackageInfo(LAUNCHER_3, userId, false), ret);
+        addApplicationInfo(getInjectedPackageInfo(LAUNCHER_4, userId, false), ret);
+
+        return ret;
+    }
+
+    private void addManifestShortcutResource(ComponentName activity, int resId) {
+        final String packageName = activity.getPackageName();
+        HashMap<ComponentName, Integer> map = mActivityMetadataResId.get(packageName);
+        if (map == null) {
+            map = new HashMap<>();
+            mActivityMetadataResId.put(packageName, map);
+        }
+        map.put(activity, resId);
+    }
+
+    private PackageInfo injectGetActivitiesWithMetadata(String packageName, @UserIdInt int userId) {
+        final PackageInfo ret = getInjectedPackageInfo(packageName, userId,
+                /* getSignatures=*/ false);
+
+        final HashMap<ComponentName, Integer> activities = mActivityMetadataResId.get(packageName);
+        if (activities != null) {
+            final ArrayList<ActivityInfo> list = new ArrayList<>();
+
+            for (ComponentName cn : activities.keySet()) {
+                ActivityInfo ai = new ActivityInfo();
+                ai.packageName = cn.getPackageName();
+                ai.name = cn.getClassName();
+                ai.metaData = new Bundle();
+                ai.metaData.putInt(ShortcutParser.METADATA_KEY, activities.get(cn));
+                list.add(ai);
+            }
+            ret.activities = list.toArray(new ActivityInfo[list.size()]);
+        }
+        return ret;
+    }
+
+    private XmlResourceParser injectXmlMetaData(ActivityInfo activityInfo, String key) {
+        if (!ShortcutParser.METADATA_KEY.equals(key) || activityInfo.metaData == null) {
+            return null;
+        }
+        final int resId = activityInfo.metaData.getInt(key);
+        return getTestContext().getResources().getXml(resId);
+    }
+
     /** Replace the current calling package */
     private void setCaller(String packageName, int userId) {
         mInjectedClientPackage = packageName;
@@ -883,6 +994,12 @@
                 makeIntent(Intent.ACTION_VIEW, ShortcutActivity.class), /* weight =*/ 0);
     }
 
+    private ShortcutInfo makeShortcutWithTitle(String id, String title) {
+        return makeShortcut(
+                id, title, /* activity =*/ null, /* icon =*/ null,
+                makeIntent(Intent.ACTION_VIEW, ShortcutActivity.class), /* weight =*/ 0);
+    }
+
     /**
      * Make a shortcut with an ID and timestamp.
      */
@@ -949,7 +1066,7 @@
             Icon icon, Intent intent, int rank) {
         final ShortcutInfo.Builder  b = new ShortcutInfo.Builder(mClientContext)
                 .setId(id)
-                .setActivityComponent(new ComponentName(mClientContext.getPackageName(), "dummy"))
+                .setActivity(new ComponentName(mClientContext.getPackageName(), "dummy"))
                 .setTitle(title)
                 .setRank(rank)
                 .setIntent(intent);
@@ -957,7 +1074,7 @@
             b.setIcon(icon);
         }
         if (activity != null) {
-            b.setActivityComponent(activity);
+            b.setActivity(activity);
         }
         final ShortcutInfo s = b.build();
 
@@ -1126,8 +1243,10 @@
         return new File(si.getBitmapPath()).getName();
     }
 
-    private ShortcutInfo getPackageShortcut(String packageName, String shortcutId) {
-        return getPackageShortcut(packageName, shortcutId, getCallingUserId());
+    private List<ShortcutInfo> getCallerShortcuts() {
+        final ShortcutPackage p = mService.getPackageShortcutForTest(
+                getCallingPackage(), getCallingUserId());
+        return p == null ? null : p.getAllShortcutsForTest();
     }
 
     private ShortcutInfo getCallerShortcut(String shortcutId) {
@@ -1157,6 +1276,13 @@
         return infoList.get(0);
     }
 
+    private Intent genPackageAddIntent(String pakcageName, int userId) {
+        Intent i = new Intent(Intent.ACTION_PACKAGE_ADDED);
+        i.setData(Uri.parse("package:" + pakcageName));
+        i.putExtra(Intent.EXTRA_USER_HANDLE, userId);
+        return i;
+    }
+
     private Intent genPackageDeleteIntent(String pakcageName, int userId) {
         Intent i = new Intent(Intent.ACTION_PACKAGE_REMOVED);
         i.setData(Uri.parse("package:" + pakcageName));
@@ -1291,9 +1417,9 @@
 
     // === Test for app side APIs ===
 
-    /** Test for {@link android.content.pm.ShortcutManager#getMaxDynamicShortcutCount()} */
+    /** Test for {@link android.content.pm.ShortcutManager#getMaxShortcutCountForActivity()} */
     public void testGetMaxDynamicShortcutCount() {
-        assertEquals(MAX_SHORTCUTS, mManager.getMaxDynamicShortcutCount());
+        assertEquals(MAX_SHORTCUTS, mManager.getMaxShortcutCountForActivity());
     }
 
     /** Test for {@link android.content.pm.ShortcutManager#getRemainingCallCount()} */
@@ -1301,6 +1427,11 @@
         assertEquals(MAX_UPDATES_PER_INTERVAL, mManager.getRemainingCallCount());
     }
 
+    public void getIconMaxDimensions() {
+        assertEquals(MAX_ICON_DIMENSION, mManager.getIconMaxWidth());
+        assertEquals(MAX_ICON_DIMENSION, mManager.getIconMaxHeight());
+    }
+
     /** Test for {@link android.content.pm.ShortcutManager#getRateLimitResetTime()} */
     public void testGetRateLimitResetTime() {
         assertEquals(START_TIME + INTERVAL, mManager.getRateLimitResetTime());
@@ -2393,7 +2524,7 @@
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
             ShortcutInfo si = new ShortcutInfo.Builder(mClientContext)
                     .setId("id")
-                    .setActivityComponent(new ComponentName(mClientContext, "dummy"))
+                    .setActivity(new ComponentName(mClientContext, "dummy"))
                     .setTitleResId(10)
                     .setTextResId(11)
                     .setDisabledMessageResId(12)
@@ -2404,7 +2535,7 @@
         runWithCaller(CALLING_PACKAGE_1, USER_P0, () -> {
             ShortcutInfo si = new ShortcutInfo.Builder(mClientContext)
                     .setId("id")
-                    .setActivityComponent(new ComponentName(mClientContext, "dummy"))
+                    .setActivity(new ComponentName(mClientContext, "dummy"))
                     .setTitleResId(10)
                     .setTextResId(11)
                     .setDisabledMessageResId(12)
@@ -2514,7 +2645,6 @@
     }
 
     public void testPinShortcutAndGetPinnedShortcuts() {
-        // Create some shortcuts.
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
             final ShortcutInfo s1_1 = makeShortcutWithTimestamp("s1", 1000);
             final ShortcutInfo s1_2 = makeShortcutWithTimestamp("s2", 2000);
@@ -2551,38 +2681,155 @@
             assertShortcutIds(mManager.getPinnedShortcuts(), "s2");
             mManager.removeDynamicShortcuts(list("s2"));
             assertShortcutIds(mManager.getPinnedShortcuts(), "s2");
+
+            assertShortcutIds(mManager.getDynamicShortcuts(), "s1");
         });
 
         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
             assertShortcutIds(mManager.getPinnedShortcuts(), "s3", "s4");
             mManager.removeDynamicShortcuts(list("s3"));
             assertShortcutIds(mManager.getPinnedShortcuts(), "s3", "s4");
+
+            assertShortcutIds(mManager.getDynamicShortcuts(), "s2", "s4");
         });
 
         runWithCaller(CALLING_PACKAGE_3, USER_0, () -> {
             assertShortcutIds(mManager.getPinnedShortcuts() /* none */);
             mManager.removeDynamicShortcuts(list("s2"));
             assertShortcutIds(mManager.getPinnedShortcuts() /* none */);
+
+            assertEmpty(mManager.getDynamicShortcuts());
         });
 
         // Get pinned shortcuts from launcher
         runWithCaller(LAUNCHER_1, USER_0, () -> {
             // CALLING_PACKAGE_1 deleted s2, but it's pinned, so it still exists.
-            assertShortcutIds(assertAllPinned(assertAllNotKeyFieldsOnly(
+            assertShortcutIds(assertAllPinned(assertAllNotKeyFieldsOnly(assertAllEnabled(
                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
-                    /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), getCallingUser()))),
+                    /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), getCallingUser())))),
                     "s2");
 
+            assertShortcutIds(assertAllPinned(assertAllNotKeyFieldsOnly(assertAllEnabled(
+                    mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
+                    /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), getCallingUser())))),
+                    "s3", "s4");
+
+            assertShortcutIds(assertAllPinned(assertAllNotKeyFieldsOnly(assertAllEnabled(
+                    mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_3,
+                    /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), getCallingUser()))))
+                    /* none */);
+        });
+    }
+
+    /**
+     * This is similar to the above test, except it used "disable" instead of "remove".  It also
+     * does "enable".
+     */
+    public void testDisableAndEnableShortcuts() {
+        runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
+            final ShortcutInfo s1_1 = makeShortcutWithTimestamp("s1", 1000);
+            final ShortcutInfo s1_2 = makeShortcutWithTimestamp("s2", 2000);
+
+            assertTrue(mManager.setDynamicShortcuts(list(s1_1, s1_2)));
+        });
+
+        runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
+            final ShortcutInfo s2_2 = makeShortcutWithTimestamp("s2", 1500);
+            final ShortcutInfo s2_3 = makeShortcutWithTimestamp("s3", 3000);
+            final ShortcutInfo s2_4 = makeShortcutWithTimestamp("s4", 500);
+            assertTrue(mManager.setDynamicShortcuts(list(s2_2, s2_3, s2_4)));
+        });
+
+        runWithCaller(CALLING_PACKAGE_3, USER_0, () -> {
+            final ShortcutInfo s3_2 = makeShortcutWithTimestamp("s2", 1000);
+            assertTrue(mManager.setDynamicShortcuts(list(s3_2)));
+        });
+
+        // Pin some.
+        runWithCaller(LAUNCHER_1, USER_0, () -> {
+            mLauncherApps.pinShortcuts(CALLING_PACKAGE_1,
+                    list("s2", "s3"), getCallingUser());
+
+            mLauncherApps.pinShortcuts(CALLING_PACKAGE_2,
+                    list("s3", "s4", "s5"), getCallingUser());
+
+            mLauncherApps.pinShortcuts(CALLING_PACKAGE_3,
+                    list("s3"), getCallingUser());  // Note ID doesn't exist
+        });
+
+        // Disable some.
+        runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
+            assertShortcutIds(mManager.getPinnedShortcuts(), "s2");
+
+            mManager.disableShortcuts(list("s2"));
+
+            assertShortcutIds(mManager.getPinnedShortcuts(), "s2");
+            assertShortcutIds(mManager.getDynamicShortcuts(), "s1");
+        });
+
+        runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
+            assertShortcutIds(mManager.getPinnedShortcuts(), "s3", "s4");
+
+            // disable should work even if a shortcut is not dynamic, so try calling "remove" first
+            // here.
+            mManager.removeDynamicShortcuts(list("s3"));
+            mManager.disableShortcuts(list("s3"));
+
+            assertShortcutIds(mManager.getPinnedShortcuts(), "s3", "s4");
+            assertShortcutIds(mManager.getDynamicShortcuts(), "s2", "s4");
+        });
+
+        runWithCaller(CALLING_PACKAGE_3, USER_0, () -> {
+            assertShortcutIds(mManager.getPinnedShortcuts() /* none */);
+
+            mManager.disableShortcuts(list("s2"));
+
+            assertShortcutIds(mManager.getPinnedShortcuts() /* none */);
+
+            assertEmpty(mManager.getDynamicShortcuts());
+            assertEmpty(getCallerShortcuts());
+        });
+
+        // Get pinned shortcuts from launcher
+        runWithCaller(LAUNCHER_1, USER_0, () -> {
+            // CALLING_PACKAGE_1 deleted s2, but it's pinned, so it still exists.
+            assertShortcutIds(assertAllPinned(assertAllNotKeyFieldsOnly(assertAllDisabled(
+                    mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
+                    /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), getCallingUser())))),
+                    "s2");
+            assertFalse(mLauncherApps.startShortcut(
+                    CALLING_PACKAGE_1, "s2", null, null, HANDLE_USER_0));
+
             assertShortcutIds(assertAllPinned(assertAllNotKeyFieldsOnly(
                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), getCallingUser()))),
                     "s3", "s4");
+            assertFalse(mLauncherApps.startShortcut(
+                    CALLING_PACKAGE_2, "s3", null, null, HANDLE_USER_0));
+            assertTrue(mLauncherApps.startShortcut(
+                    CALLING_PACKAGE_2, "s4", null, null, HANDLE_USER_0));
 
-            assertShortcutIds(assertAllPinned(assertAllNotKeyFieldsOnly(
+            assertShortcutIds(assertAllPinned(assertAllNotKeyFieldsOnly(assertAllEnabled(
                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_3,
-                    /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), getCallingUser())))
+                    /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), getCallingUser()))))
                     /* none */);
         });
+
+        runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
+            mManager.enableShortcuts(list("s2"));
+
+            assertShortcutIds(mManager.getPinnedShortcuts(), "s2");
+            assertShortcutIds(mManager.getDynamicShortcuts(), "s1");
+        });
+        runWithCaller(LAUNCHER_1, USER_0, () -> {
+            // CALLING_PACKAGE_1 deleted s2, but it's pinned, so it still exists.
+            assertShortcutIds(assertAllPinned(assertAllNotKeyFieldsOnly(assertAllEnabled(
+                    mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
+                    /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), getCallingUser())))),
+                    "s2");
+            assertTrue(mLauncherApps.startShortcut(
+                    CALLING_PACKAGE_1, "s2", null, null, HANDLE_USER_0));
+        });
     }
 
     public void testPinShortcutAndGetPinnedShortcuts_multi() {
@@ -6007,14 +6254,14 @@
                 () -> new ShortcutInfo.Builder(getTestContext()).setIntent(new Intent()));
         assertExpectException(
                 NullPointerException.class,
-                "activityComponent must be provided",
+                "activity must be provided",
                 () -> new ShortcutInfo.Builder(getTestContext()).setId("id").build()
                         .enforceMandatoryFields());
         assertExpectException(
                 IllegalArgumentException.class,
                 "title must be provided",
                 () -> new ShortcutInfo.Builder(getTestContext()).setId("id")
-                        .setActivityComponent(
+                        .setActivity(
                                 new ComponentName(getTestContext().getPackageName(), "s"))
                         .build()
                         .enforceMandatoryFields());
@@ -6022,7 +6269,7 @@
                 NullPointerException.class,
                 "Intent must be provided",
                 () -> new ShortcutInfo.Builder(getTestContext()).setId("id")
-                        .setActivityComponent(
+                        .setActivity(
                                 new ComponentName(getTestContext().getPackageName(), "s"))
                         .setTitle("x").build()
                         .enforceMandatoryFields());
@@ -6035,7 +6282,7 @@
                 .setTitle("title")
                 .setIntent(makeIntent("action", ShortcutActivity.class))
                 .build());
-        assertEquals(mClientContext.getPackageName(), si.getPackageName());
+        assertEquals(mClientContext.getPackageName(), si.getPackage());
         assertEquals(USER_10, si.getUserId());
         assertEquals(HANDLE_USER_10, si.getUserHandle());
         assertEquals("id", si.getId());
@@ -6047,7 +6294,7 @@
 
         si = new ShortcutInfo.Builder(getTestContext())
                 .setId("id")
-                .setActivityComponent(new ComponentName("a", "b"))
+                .setActivity(new ComponentName("a", "b"))
                 .setIcon(Icon.createWithResource(mClientContext, 123))
                 .setTitle("title")
                 .setText("text")
@@ -6063,9 +6310,9 @@
 
         si = parceled(si);
 
-        assertEquals(getTestContext().getPackageName(), si.getPackageName());
+        assertEquals(getTestContext().getPackageName(), si.getPackage());
         assertEquals("id", si.getId());
-        assertEquals(new ComponentName("a", "b"), si.getActivityComponent());
+        assertEquals(new ComponentName("a", "b"), si.getActivity());
         assertEquals(123, si.getIcon().getResId());
         assertEquals("title", si.getTitle());
         assertEquals("text", si.getText());
@@ -6090,7 +6337,7 @@
 
         si = new ShortcutInfo.Builder(getTestContext())
                 .setId("id")
-                .setActivityComponent(new ComponentName("a", "b"))
+                .setActivity(new ComponentName("a", "b"))
                 .setIcon(Icon.createWithResource(mClientContext, 123))
                 .setTitleResId(10)
                 .setTextResId(11)
@@ -6106,9 +6353,9 @@
 
         si = parceled(si);
 
-        assertEquals(getTestContext().getPackageName(), si.getPackageName());
+        assertEquals(getTestContext().getPackageName(), si.getPackage());
         assertEquals("id", si.getId());
-        assertEquals(new ComponentName("a", "b"), si.getActivityComponent());
+        assertEquals(new ComponentName("a", "b"), si.getActivity());
         assertEquals(123, si.getIcon().getResId());
         assertEquals(10, si.getTitleResId());
         assertEquals(11, si.getTextResId());
@@ -6131,7 +6378,7 @@
         pb.putInt("k", 1);
         ShortcutInfo sorig = new ShortcutInfo.Builder(mClientContext)
                 .setId("id")
-                .setActivityComponent(new ComponentName("a", "b"))
+                .setActivity(new ComponentName("a", "b"))
                 .setIcon(Icon.createWithResource(mClientContext, 123))
                 .setTitle("title")
                 .setText("text")
@@ -6149,9 +6396,9 @@
 
         assertEquals(USER_11, si.getUserId());
         assertEquals(HANDLE_USER_11, si.getUserHandle());
-        assertEquals(mClientContext.getPackageName(), si.getPackageName());
+        assertEquals(mClientContext.getPackageName(), si.getPackage());
         assertEquals("id", si.getId());
-        assertEquals(new ComponentName("a", "b"), si.getActivityComponent());
+        assertEquals(new ComponentName("a", "b"), si.getActivity());
         assertEquals(123, si.getIcon().getResId());
         assertEquals("title", si.getTitle());
         assertEquals("text", si.getText());
@@ -6168,9 +6415,9 @@
 
         si = sorig.clone(ShortcutInfo.CLONE_REMOVE_FOR_CREATOR);
 
-        assertEquals(mClientContext.getPackageName(), si.getPackageName());
+        assertEquals(mClientContext.getPackageName(), si.getPackage());
         assertEquals("id", si.getId());
-        assertEquals(new ComponentName("a", "b"), si.getActivityComponent());
+        assertEquals(new ComponentName("a", "b"), si.getActivity());
         assertEquals(null, si.getIcon());
         assertEquals("title", si.getTitle());
         assertEquals("text", si.getText());
@@ -6188,9 +6435,9 @@
 
         si = sorig.clone(ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER);
 
-        assertEquals(mClientContext.getPackageName(), si.getPackageName());
+        assertEquals(mClientContext.getPackageName(), si.getPackage());
         assertEquals("id", si.getId());
-        assertEquals(new ComponentName("a", "b"), si.getActivityComponent());
+        assertEquals(new ComponentName("a", "b"), si.getActivity());
         assertEquals(null, si.getIcon());
         assertEquals("title", si.getTitle());
         assertEquals("text", si.getText());
@@ -6207,9 +6454,9 @@
 
         si = sorig.clone(ShortcutInfo.CLONE_REMOVE_NON_KEY_INFO);
 
-        assertEquals(mClientContext.getPackageName(), si.getPackageName());
+        assertEquals(mClientContext.getPackageName(), si.getPackage());
         assertEquals("id", si.getId());
-        assertEquals(null, si.getActivityComponent());
+        assertEquals(null, si.getActivity());
         assertEquals(null, si.getIcon());
         assertEquals(null, si.getTitle());
         assertEquals(null, si.getText());
@@ -6232,7 +6479,7 @@
         pb.putInt("k", 1);
         ShortcutInfo sorig = new ShortcutInfo.Builder(mClientContext)
                 .setId("id")
-                .setActivityComponent(new ComponentName("a", "b"))
+                .setActivity(new ComponentName("a", "b"))
                 .setIcon(Icon.createWithResource(mClientContext, 123))
                 .setTitleResId(10)
                 .setTextResId(11)
@@ -6250,9 +6497,9 @@
 
         assertEquals(USER_11, si.getUserId());
         assertEquals(HANDLE_USER_11, si.getUserHandle());
-        assertEquals(mClientContext.getPackageName(), si.getPackageName());
+        assertEquals(mClientContext.getPackageName(), si.getPackage());
         assertEquals("id", si.getId());
-        assertEquals(new ComponentName("a", "b"), si.getActivityComponent());
+        assertEquals(new ComponentName("a", "b"), si.getActivity());
         assertEquals(123, si.getIcon().getResId());
         assertEquals(10, si.getTitleResId());
         assertEquals(11, si.getTextResId());
@@ -6269,9 +6516,9 @@
 
         si = sorig.clone(ShortcutInfo.CLONE_REMOVE_FOR_CREATOR);
 
-        assertEquals(mClientContext.getPackageName(), si.getPackageName());
+        assertEquals(mClientContext.getPackageName(), si.getPackage());
         assertEquals("id", si.getId());
-        assertEquals(new ComponentName("a", "b"), si.getActivityComponent());
+        assertEquals(new ComponentName("a", "b"), si.getActivity());
         assertEquals(null, si.getIcon());
         assertEquals(10, si.getTitleResId());
         assertEquals(11, si.getTextResId());
@@ -6289,9 +6536,9 @@
 
         si = sorig.clone(ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER);
 
-        assertEquals(mClientContext.getPackageName(), si.getPackageName());
+        assertEquals(mClientContext.getPackageName(), si.getPackage());
         assertEquals("id", si.getId());
-        assertEquals(new ComponentName("a", "b"), si.getActivityComponent());
+        assertEquals(new ComponentName("a", "b"), si.getActivity());
         assertEquals(null, si.getIcon());
         assertEquals(10, si.getTitleResId());
         assertEquals(11, si.getTextResId());
@@ -6308,9 +6555,9 @@
 
         si = sorig.clone(ShortcutInfo.CLONE_REMOVE_NON_KEY_INFO);
 
-        assertEquals(mClientContext.getPackageName(), si.getPackageName());
+        assertEquals(mClientContext.getPackageName(), si.getPackage());
         assertEquals("id", si.getId());
-        assertEquals(null, si.getActivityComponent());
+        assertEquals(null, si.getActivity());
         assertEquals(null, si.getIcon());
         assertEquals(0, si.getTitleResId());
         assertEquals(0, si.getTextResId());
@@ -6336,7 +6583,7 @@
                 .build();
         ShortcutInfo si = sorig.clone(/* clone flags*/ 0);
 
-        assertEquals(getTestContext().getPackageName(), si.getPackageName());
+        assertEquals(getTestContext().getPackageName(), si.getPackage());
         assertEquals("id", si.getId());
         assertEquals("title", si.getTitle());
         assertEquals("action", si.getIntent().getAction());
@@ -6344,7 +6591,7 @@
 
         si = sorig.clone(ShortcutInfo.CLONE_REMOVE_FOR_CREATOR);
 
-        assertEquals(getTestContext().getPackageName(), si.getPackageName());
+        assertEquals(getTestContext().getPackageName(), si.getPackage());
         assertEquals("id", si.getId());
         assertEquals("title", si.getTitle());
         assertEquals("action", si.getIntent().getAction());
@@ -6352,7 +6599,7 @@
 
         si = sorig.clone(ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER);
 
-        assertEquals(getTestContext().getPackageName(), si.getPackageName());
+        assertEquals(getTestContext().getPackageName(), si.getPackage());
         assertEquals("id", si.getId());
         assertEquals("title", si.getTitle());
         assertEquals(null, si.getIntent());
@@ -6360,7 +6607,7 @@
 
         si = sorig.clone(ShortcutInfo.CLONE_REMOVE_NON_KEY_INFO);
 
-        assertEquals(getTestContext().getPackageName(), si.getPackageName());
+        assertEquals(getTestContext().getPackageName(), si.getPackage());
         assertEquals("id", si.getId());
         assertEquals(null, si.getTitle());
         assertEquals(null, si.getIntent());
@@ -6372,7 +6619,7 @@
         pb.putInt("k", 1);
         ShortcutInfo sorig = new ShortcutInfo.Builder(getTestContext())
                 .setId("id")
-                .setActivityComponent(new ComponentName("a", "b"))
+                .setActivity(new ComponentName("a", "b"))
                 .setIcon(Icon.createWithResource(mClientContext, 123))
                 .setTitle("title")
                 .setText("text")
@@ -6390,9 +6637,9 @@
 
         si = sorig.clone(/* flags=*/ 0);
         si.copyNonNullFieldsFrom(new ShortcutInfo.Builder(getTestContext()).setId("id")
-                .setActivityComponent(new ComponentName("x", "y")).build());
+                .setActivity(new ComponentName("x", "y")).build());
         assertEquals("text", si.getText());
-        assertEquals(new ComponentName("x", "y"), si.getActivityComponent());
+        assertEquals(new ComponentName("x", "y"), si.getActivity());
 
         si = sorig.clone(/* flags=*/ 0);
         si.copyNonNullFieldsFrom(new ShortcutInfo.Builder(getTestContext()).setId("id")
@@ -6500,7 +6747,7 @@
         pb.putInt("k", 1);
         ShortcutInfo sorig = new ShortcutInfo.Builder(getTestContext())
                 .setId("id")
-                .setActivityComponent(new ComponentName("a", "b"))
+                .setActivity(new ComponentName("a", "b"))
                 .setIcon(Icon.createWithResource(mClientContext, 123))
                 .setTitleResId(10)
                 .setTextResId(11)
@@ -6518,9 +6765,9 @@
 
         si = sorig.clone(/* flags=*/ 0);
         si.copyNonNullFieldsFrom(new ShortcutInfo.Builder(getTestContext()).setId("id")
-                .setActivityComponent(new ComponentName("x", "y")).build());
+                .setActivity(new ComponentName("x", "y")).build());
         assertEquals(11, si.getTextResId());
-        assertEquals(new ComponentName("x", "y"), si.getActivityComponent());
+        assertEquals(new ComponentName("x", "y"), si.getActivity());
 
         si = sorig.clone(/* flags=*/ 0);
         si.copyNonNullFieldsFrom(new ShortcutInfo.Builder(getTestContext()).setId("id")
@@ -6633,7 +6880,7 @@
         pb.putInt("k", 1);
         ShortcutInfo sorig = new ShortcutInfo.Builder(mClientContext)
                 .setId("id")
-                .setActivityComponent(new ComponentName(mClientContext, ShortcutActivity2.class))
+                .setActivity(new ComponentName(mClientContext, ShortcutActivity2.class))
                 .setIcon(bmp32x32)
                 .setTitle("title")
                 .setText("text")
@@ -6659,9 +6906,9 @@
 
         assertEquals(USER_10, si.getUserId());
         assertEquals(HANDLE_USER_10, si.getUserHandle());
-        assertEquals(CALLING_PACKAGE_1, si.getPackageName());
+        assertEquals(CALLING_PACKAGE_1, si.getPackage());
         assertEquals("id", si.getId());
-        assertEquals(ShortcutActivity2.class.getName(), si.getActivityComponent().getClassName());
+        assertEquals(ShortcutActivity2.class.getName(), si.getActivity().getClassName());
         assertEquals(null, si.getIcon());
         assertEquals("title", si.getTitle());
         assertEquals("text", si.getText());
@@ -6688,7 +6935,7 @@
         pb.putInt("k", 1);
         ShortcutInfo sorig = new ShortcutInfo.Builder(mClientContext)
                 .setId("id")
-                .setActivityComponent(new ComponentName(mClientContext, ShortcutActivity2.class))
+                .setActivity(new ComponentName(mClientContext, ShortcutActivity2.class))
                 .setIcon(bmp32x32)
                 .setTitleResId(10)
                 .setTextResId(11)
@@ -6714,9 +6961,9 @@
 
         assertEquals(USER_10, si.getUserId());
         assertEquals(HANDLE_USER_10, si.getUserHandle());
-        assertEquals(CALLING_PACKAGE_1, si.getPackageName());
+        assertEquals(CALLING_PACKAGE_1, si.getPackage());
         assertEquals("id", si.getId());
-        assertEquals(ShortcutActivity2.class.getName(), si.getActivityComponent().getClassName());
+        assertEquals(ShortcutActivity2.class.getName(), si.getActivity().getClassName());
         assertEquals(null, si.getIcon());
         assertEquals(10, si.getTitleResId());
         assertEquals(11, si.getTextResId());
@@ -6743,7 +6990,7 @@
         pb.putInt("k", 1);
         ShortcutInfo sorig = new ShortcutInfo.Builder(mClientContext)
                 .setId("id")
-                .setActivityComponent(new ComponentName(mClientContext, ShortcutActivity2.class))
+                .setActivity(new ComponentName(mClientContext, ShortcutActivity2.class))
                 .setIcon(bmp32x32)
                 .setTitle("title")
                 .setText("text")
@@ -6768,9 +7015,9 @@
         ShortcutInfo si;
         si = mService.getPackageShortcutForTest(CALLING_PACKAGE_1, "id", USER_0);
 
-        assertEquals(CALLING_PACKAGE_1, si.getPackageName());
+        assertEquals(CALLING_PACKAGE_1, si.getPackage());
         assertEquals("id", si.getId());
-        assertEquals(ShortcutActivity2.class.getName(), si.getActivityComponent().getClassName());
+        assertEquals(ShortcutActivity2.class.getName(), si.getActivity().getClassName());
         assertEquals(null, si.getIcon());
         assertEquals("title", si.getTitle());
         assertEquals("text", si.getText());
@@ -6796,7 +7043,7 @@
         pb.putInt("k", 1);
         ShortcutInfo sorig = new ShortcutInfo.Builder(mClientContext)
                 .setId("id")
-                .setActivityComponent(new ComponentName(mClientContext, ShortcutActivity2.class))
+                .setActivity(new ComponentName(mClientContext, ShortcutActivity2.class))
                 .setIcon(bmp32x32)
                 .setTitleResId(10)
                 .setTextResId(11)
@@ -6821,9 +7068,9 @@
         ShortcutInfo si;
         si = mService.getPackageShortcutForTest(CALLING_PACKAGE_1, "id", USER_0);
 
-        assertEquals(CALLING_PACKAGE_1, si.getPackageName());
+        assertEquals(CALLING_PACKAGE_1, si.getPackage());
         assertEquals("id", si.getId());
-        assertEquals(ShortcutActivity2.class.getName(), si.getActivityComponent().getClassName());
+        assertEquals(ShortcutActivity2.class.getName(), si.getActivity().getClassName());
         assertEquals(null, si.getIcon());
         assertEquals(10, si.getTitleResId());
         assertEquals(11, si.getTextResId());
@@ -6849,4 +7096,810 @@
         // Dump after having some icons.
         dumpsysOnLogcat("test1", /* force= */ true);
     }
+
+    public void testManifestShortcut_publishOnUnlockUser() {
+        addManifestShortcutResource(
+                new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
+                R.xml.shortcut_1);
+        addManifestShortcutResource(
+                new ComponentName(CALLING_PACKAGE_2, ShortcutActivity.class.getName()),
+                R.xml.shortcut_2);
+        addManifestShortcutResource(
+                new ComponentName(CALLING_PACKAGE_3, ShortcutActivity.class.getName()),
+                R.xml.shortcut_5);
+
+        // Unlock user-0.
+        mService.handleUnlockUser(USER_0);
+
+        runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
+            assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
+                    mManager.getManifestShortcuts()))),
+                    "ms1");
+            assertEmpty(mManager.getPinnedShortcuts());
+        });
+
+        runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
+            assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
+                    mManager.getManifestShortcuts()))),
+                    "ms1", "ms2");
+            assertEmpty(mManager.getPinnedShortcuts());
+        });
+
+        runWithCaller(CALLING_PACKAGE_3, USER_0, () -> {
+            assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
+                    mManager.getManifestShortcuts()))),
+                    "ms1", "ms2", "ms3", "ms4", "ms5");
+            assertEmpty(mManager.getPinnedShortcuts());
+        });
+
+        // Try on another user, with some packages uninstalled.
+        uninstallPackage(USER_10, CALLING_PACKAGE_1);
+        uninstallPackage(USER_10, CALLING_PACKAGE_3);
+
+        mService.handleUnlockUser(USER_10);
+
+        runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
+            assertEmpty(mManager.getManifestShortcuts());
+            assertEmpty(mManager.getPinnedShortcuts());
+        });
+
+        runWithCaller(CALLING_PACKAGE_2, USER_10, () -> {
+            assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
+                    mManager.getManifestShortcuts()))),
+                    "ms1", "ms2");
+            assertEmpty(mManager.getPinnedShortcuts());
+        });
+
+        runWithCaller(CALLING_PACKAGE_3, USER_10, () -> {
+            assertEmpty(mManager.getManifestShortcuts());
+            assertEmpty(mManager.getPinnedShortcuts());
+        });
+
+        // Now change the resources for package 1, and unlock again.
+        // But we still see *old* shortcuts, because the package version and install time
+        // hasn't changed.
+        shutdownServices();
+
+        addManifestShortcutResource(
+                new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
+                R.xml.shortcut_5);
+        addManifestShortcutResource(
+                new ComponentName(CALLING_PACKAGE_3, ShortcutActivity.class.getName()),
+                R.xml.shortcut_1);
+
+        initService();
+        mService.handleUnlockUser(USER_0);
+
+        runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
+            assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
+                    mManager.getManifestShortcuts()))),
+                    "ms1");
+            assertEmpty(mManager.getPinnedShortcuts());
+        });
+
+        runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
+            assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
+                    mManager.getManifestShortcuts()))),
+                    "ms1", "ms2");
+            assertEmpty(mManager.getPinnedShortcuts());
+        });
+
+        runWithCaller(CALLING_PACKAGE_3, USER_0, () -> {
+            assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
+                    mManager.getManifestShortcuts()))),
+                    "ms1", "ms2", "ms3", "ms4", "ms5");
+            assertEmpty(mManager.getPinnedShortcuts());
+        });
+
+        // Do it again, but this time we change the app version, so we do detect the changes.
+        shutdownServices();
+
+        updatePackageVersion(CALLING_PACKAGE_1, 1);
+        updatePackageLastUpdateTime(CALLING_PACKAGE_3, 1);
+
+        initService();
+        mService.handleUnlockUser(USER_0);
+
+        runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
+            assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
+                    mManager.getManifestShortcuts()))),
+                    "ms1", "ms2", "ms3", "ms4", "ms5");
+            assertEmpty(mManager.getPinnedShortcuts());
+        });
+
+        runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
+            assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
+                    mManager.getManifestShortcuts()))),
+                    "ms1", "ms2");
+            assertEmpty(mManager.getPinnedShortcuts());
+        });
+
+        runWithCaller(CALLING_PACKAGE_3, USER_0, () -> {
+            assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
+                    mManager.getManifestShortcuts()))),
+                    "ms1");
+            assertEmpty(mManager.getPinnedShortcuts());
+        });
+
+        // Next, try removing all shortcuts, with some of them pinned.
+        runWithCaller(LAUNCHER_1, USER_0, () -> {
+            mLauncherApps.pinShortcuts(CALLING_PACKAGE_1, list("ms3"), HANDLE_USER_0);
+            mLauncherApps.pinShortcuts(CALLING_PACKAGE_2, list("ms2"), HANDLE_USER_0);
+            mLauncherApps.pinShortcuts(CALLING_PACKAGE_3, list("ms1"), HANDLE_USER_0);
+        });
+        runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
+            assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
+                    mManager.getManifestShortcuts()))),
+                    "ms1", "ms2", "ms3", "ms4", "ms5");
+            assertShortcutIds(assertAllImmutable(assertAllPinned(assertAllManifest(
+                    assertAllEnabled(mManager.getPinnedShortcuts())))),
+                    "ms3");
+        });
+
+        runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
+            assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
+                    mManager.getManifestShortcuts()))),
+                    "ms1", "ms2");
+            assertShortcutIds(assertAllImmutable(assertAllPinned(assertAllManifest(
+                    assertAllEnabled(mManager.getPinnedShortcuts())))),
+                    "ms2");
+        });
+
+        runWithCaller(CALLING_PACKAGE_3, USER_0, () -> {
+            assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
+                    mManager.getManifestShortcuts()))),
+                    "ms1");
+            assertShortcutIds(assertAllImmutable(assertAllPinned(assertAllManifest(
+                    assertAllEnabled(mManager.getPinnedShortcuts())))),
+                    "ms1");
+        });
+
+        shutdownServices();
+
+        addManifestShortcutResource(
+                new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
+                R.xml.shortcut_0);
+        addManifestShortcutResource(
+                new ComponentName(CALLING_PACKAGE_2, ShortcutActivity.class.getName()),
+                R.xml.shortcut_1);
+        addManifestShortcutResource(
+                new ComponentName(CALLING_PACKAGE_3, ShortcutActivity.class.getName()),
+                R.xml.shortcut_0);
+
+        updatePackageVersion(CALLING_PACKAGE_1, 1);
+        updatePackageVersion(CALLING_PACKAGE_2, 1);
+        updatePackageVersion(CALLING_PACKAGE_3, 1);
+
+        initService();
+        mService.handleUnlockUser(USER_0);
+
+        runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
+            assertEmpty(mManager.getManifestShortcuts());
+            assertShortcutIds(assertAllImmutable(assertAllPinned(assertAllNotManifest(
+                    assertAllDisabled(mManager.getPinnedShortcuts())))),
+                    "ms3");
+        });
+
+        runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
+            assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
+                    mManager.getManifestShortcuts()))),
+                    "ms1");
+            assertShortcutIds(assertAllImmutable(assertAllPinned(assertAllNotManifest(
+                    assertAllDisabled(mManager.getPinnedShortcuts())))),
+                    "ms2");
+        });
+
+        runWithCaller(CALLING_PACKAGE_3, USER_0, () -> {
+            assertEmpty(mManager.getManifestShortcuts());
+            assertShortcutIds(assertAllImmutable(assertAllPinned(assertAllNotManifest(
+                    assertAllDisabled(mManager.getPinnedShortcuts())))),
+                    "ms1");
+        });
+
+        // Make sure we don't have ShortcutPackage for packages that don't have shortcuts.
+        assertNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_4, USER_0));
+        assertNull(mService.getPackageShortcutForTest(LAUNCHER_1, USER_0));
+    }
+
+
+    public void testManifestShortcut_publishOnBroadcast() {
+        // First, no packages are installed.
+        uninstallPackage(USER_0, CALLING_PACKAGE_1);
+        uninstallPackage(USER_0, CALLING_PACKAGE_2);
+        uninstallPackage(USER_0, CALLING_PACKAGE_3);
+        uninstallPackage(USER_0, CALLING_PACKAGE_4);
+        uninstallPackage(USER_10, CALLING_PACKAGE_1);
+        uninstallPackage(USER_10, CALLING_PACKAGE_2);
+        uninstallPackage(USER_10, CALLING_PACKAGE_3);
+        uninstallPackage(USER_10, CALLING_PACKAGE_4);
+
+        mService.handleUnlockUser(USER_0);
+        mService.handleUnlockUser(USER_10);
+
+        // Originally no manifest shortcuts.
+        runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
+            assertEmpty(mManager.getManifestShortcuts());
+            assertEmpty(mManager.getPinnedShortcuts());
+        });
+
+        runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
+            assertEmpty(mManager.getManifestShortcuts());
+            assertEmpty(mManager.getPinnedShortcuts());
+        });
+
+        runWithCaller(CALLING_PACKAGE_3, USER_0, () -> {
+            assertEmpty(mManager.getManifestShortcuts());
+            assertEmpty(mManager.getPinnedShortcuts());
+        });
+
+        // Package 1 updated, with manifest shortcuts.
+        addManifestShortcutResource(
+                new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
+                R.xml.shortcut_1);
+        updatePackageVersion(CALLING_PACKAGE_1, 1);
+        mService.mPackageMonitor.onReceive(getTestContext(),
+                genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
+
+        runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
+            assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
+                    mManager.getManifestShortcuts()))),
+                    "ms1");
+            assertEmpty(mManager.getPinnedShortcuts());
+        });
+
+        runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
+            assertEmpty(mManager.getManifestShortcuts());
+            assertEmpty(mManager.getPinnedShortcuts());
+        });
+
+        // Package 2 updated, with manifest shortcuts.
+
+        addManifestShortcutResource(
+                new ComponentName(CALLING_PACKAGE_2, ShortcutActivity.class.getName()),
+                R.xml.shortcut_5);
+        updatePackageVersion(CALLING_PACKAGE_2, 1);
+        mService.mPackageMonitor.onReceive(getTestContext(),
+                genPackageAddIntent(CALLING_PACKAGE_2, USER_0));
+
+        runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
+            assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
+                    mManager.getManifestShortcuts()))),
+                    "ms1");
+            assertEmpty(mManager.getPinnedShortcuts());
+        });
+
+        runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
+            assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
+                    mManager.getManifestShortcuts()))),
+                    "ms1", "ms2", "ms3", "ms4", "ms5");
+            assertEmpty(mManager.getPinnedShortcuts());
+        });
+
+        // Package 2 updated, with less manifest shortcuts.
+        // This time we use updatePackageLastUpdateTime() instead of updatePackageVersion().
+
+        dumpsysOnLogcat("Before pinning");
+
+        // Also pin some.
+        runWithCaller(LAUNCHER_1, USER_0, () -> {
+            mLauncherApps.pinShortcuts(CALLING_PACKAGE_2, list("ms2", "ms3"), HANDLE_USER_0);
+        });
+
+        dumpsysOnLogcat("After pinning");
+
+        addManifestShortcutResource(
+                new ComponentName(CALLING_PACKAGE_2, ShortcutActivity.class.getName()),
+                R.xml.shortcut_2);
+        updatePackageLastUpdateTime(CALLING_PACKAGE_2, 1);
+        mService.mPackageMonitor.onReceive(getTestContext(),
+                genPackageAddIntent(CALLING_PACKAGE_2, USER_0));
+
+        runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
+            assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
+                    mManager.getManifestShortcuts()))),
+                    "ms1");
+            assertEmpty(mManager.getPinnedShortcuts());
+        });
+
+        runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
+            assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
+                    mManager.getManifestShortcuts()))),
+                    "ms1", "ms2");
+            assertShortcutIds(assertAllImmutable(assertAllPinned(
+                    mManager.getPinnedShortcuts())),
+                    "ms2", "ms3");
+            // ms3 is no longer in manifest, so should be disabled.
+            // but ms1 and ms2 should be enabled.
+            assertAllEnabled(list(getCallerShortcut("ms1")));
+            assertAllEnabled(list(getCallerShortcut("ms2")));
+            assertAllDisabled(list(getCallerShortcut("ms3")));
+        });
+
+        // Package 2 on user 10 has no shortcuts yet.
+        runWithCaller(CALLING_PACKAGE_2, USER_10, () -> {
+            assertEmpty(mManager.getManifestShortcuts());
+            assertEmpty(mManager.getPinnedShortcuts());
+        });
+        // Send PACKAGE_ADD broadcast to have Package 2 on user-10 publish manifest shortcuts.
+        mService.mPackageMonitor.onReceive(getTestContext(),
+                genPackageAddIntent(CALLING_PACKAGE_2, USER_10));
+
+        runWithCaller(CALLING_PACKAGE_2, USER_10, () -> {
+            assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
+                    mManager.getManifestShortcuts()))),
+                    "ms1", "ms2");
+            assertEmpty(mManager.getPinnedShortcuts());
+        });
+
+        // But it shouldn't affect user-0.
+        runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
+            assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
+                    mManager.getManifestShortcuts()))),
+                    "ms1", "ms2");
+            assertShortcutIds(assertAllImmutable(assertAllPinned(
+                    mManager.getPinnedShortcuts())),
+                    "ms2", "ms3");
+            assertAllEnabled(list(getCallerShortcut("ms1")));
+            assertAllEnabled(list(getCallerShortcut("ms2")));
+            assertAllDisabled(list(getCallerShortcut("ms3")));
+        });
+
+        // Package 2 now has no manifest shortcuts.
+        addManifestShortcutResource(
+                new ComponentName(CALLING_PACKAGE_2, ShortcutActivity.class.getName()),
+                R.xml.shortcut_0);
+        updatePackageLastUpdateTime(CALLING_PACKAGE_2, 1);
+        mService.mPackageMonitor.onReceive(getTestContext(),
+                genPackageAddIntent(CALLING_PACKAGE_2, USER_0));
+
+        // No manifest shortcuts, and pinned ones are disabled.
+        runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
+            assertEmpty(mManager.getManifestShortcuts());
+            assertShortcutIds(assertAllImmutable(assertAllPinned(assertAllDisabled(
+                    mManager.getPinnedShortcuts()))),
+                    "ms2", "ms3");
+        });
+    }
+
+    public void testManifestShortcuts_missingMandatoryFields() {
+        // Start with no apps installed.
+        uninstallPackage(USER_0, CALLING_PACKAGE_1);
+        uninstallPackage(USER_0, CALLING_PACKAGE_2);
+        uninstallPackage(USER_0, CALLING_PACKAGE_3);
+        uninstallPackage(USER_0, CALLING_PACKAGE_4);
+
+        mService.handleUnlockUser(USER_0);
+
+        // Make sure no manifest shortcuts.
+        runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
+            assertEmpty(mManager.getManifestShortcuts());
+        });
+
+        // Package 1 updated, which has one valid manifest shortcut and one invalid.
+        addManifestShortcutResource(
+                new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
+                R.xml.shortcut_error_1);
+        updatePackageVersion(CALLING_PACKAGE_1, 1);
+        mService.mPackageMonitor.onReceive(getTestContext(),
+                genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
+
+        // Only the valid one is published.
+        runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
+            assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
+                    mManager.getManifestShortcuts()))),
+                    "x1");
+        });
+
+        // Package 1 updated, which has one valid manifest shortcut and one invalid.
+        addManifestShortcutResource(
+                new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
+                R.xml.shortcut_error_2);
+        updatePackageVersion(CALLING_PACKAGE_1, 1);
+        mService.mPackageMonitor.onReceive(getTestContext(),
+                genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
+
+        // Only the valid one is published.
+        runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
+            assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
+                    mManager.getManifestShortcuts()))),
+                    "x2");
+        });
+
+        // Package 1 updated, which has one valid manifest shortcut and one invalid.
+        addManifestShortcutResource(
+                new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
+                R.xml.shortcut_error_3);
+        updatePackageVersion(CALLING_PACKAGE_1, 1);
+        mService.mPackageMonitor.onReceive(getTestContext(),
+                genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
+
+        // Only the valid one is published.
+        runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
+            assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
+                    mManager.getManifestShortcuts()))),
+                    "x3");
+        });
+    }
+
+    public void testManifestShortcuts_checkAllFields() {
+        mService.handleUnlockUser(USER_0);
+
+        // Package 1 updated, which has one valid manifest shortcut and one invalid.
+        addManifestShortcutResource(
+                new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
+                R.xml.shortcut_5);
+        updatePackageVersion(CALLING_PACKAGE_1, 1);
+        mService.mPackageMonitor.onReceive(getTestContext(),
+                genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
+
+        // Only the valid one is published.
+        runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
+            assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
+                    mManager.getManifestShortcuts()))),
+                    "ms1", "ms2", "ms3", "ms4", "ms5");
+
+            // check first shortcut.
+            ShortcutInfo si = getCallerShortcut("ms1");
+
+            assertEquals("ms1", si.getId());
+            assertEquals(R.drawable.icon1, si.getIconResourceId());
+            assertEquals(new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
+                    si.getActivity());
+            assertEquals(R.string.shortcut_title1, si.getTitleResId());
+            assertEquals(R.string.shortcut_text1, si.getTextResId());
+            assertEquals(R.string.shortcut_disabled_message1, si.getDisabledMessageResId());
+            assertEquals(set("android.shortcut.conversation", "android.shortcut.media"),
+                    si.getCategories());
+            assertEquals("action1", si.getIntent().getAction());
+            assertEquals(Uri.parse("http://a.b.c/1"), si.getIntent().getData());
+
+            // check another
+            si = getCallerShortcut("ms2");
+
+            assertEquals("ms2", si.getId());
+            assertEquals(R.drawable.icon2, si.getIconResourceId());
+            assertEquals(R.string.shortcut_title2, si.getTitleResId());
+            assertEquals(R.string.shortcut_text2, si.getTextResId());
+            assertEquals(R.string.shortcut_disabled_message2, si.getDisabledMessageResId());
+            assertEquals(set("android.shortcut.conversation"), si.getCategories());
+            assertEquals("action2", si.getIntent().getAction());
+            assertEquals(null, si.getIntent().getData());
+
+            // check another
+            si = getCallerShortcut("ms3");
+
+            assertEquals("ms3", si.getId());
+            assertEquals(0, si.getIconResourceId());
+            assertEquals(R.string.shortcut_title1, si.getTitleResId());
+            assertEquals(0, si.getTextResId());
+            assertEquals(0, si.getDisabledMessageResId());
+            assertEquals(null, si.getCategories());
+            assertEquals("android.intent.action.VIEW", si.getIntent().getAction());
+            assertEquals(null, si.getIntent().getData());
+        });
+    }
+
+    public void testManifestShortcuts_updateAndDisabled_notPinned() {
+        mService.handleUnlockUser(USER_0);
+
+        // First, just publish a manifest shortcut.
+        addManifestShortcutResource(
+                new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
+                R.xml.shortcut_1);
+        updatePackageVersion(CALLING_PACKAGE_1, 1);
+        mService.mPackageMonitor.onReceive(getTestContext(),
+                genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
+
+        // Only the valid one is published.
+        runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
+            assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
+                    mManager.getManifestShortcuts()))),
+                    "ms1");
+            assertEmpty(mManager.getPinnedShortcuts());
+
+            // Make sure there's no other dangling shortcuts.
+            assertShortcutIds(getCallerShortcuts(), "ms1");
+        });
+
+        // Now version up, the manifest shortcut is disabled now.
+        addManifestShortcutResource(
+                new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
+                R.xml.shortcut_1_disable);
+        updatePackageVersion(CALLING_PACKAGE_1, 1);
+        mService.mPackageMonitor.onReceive(getTestContext(),
+                genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
+
+        // Because shortcut 1 wasn't pinned, it'll just go away.
+        runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
+            assertEmpty(mManager.getManifestShortcuts());
+            assertEmpty(mManager.getPinnedShortcuts());
+
+            // Make sure there's no other dangling shortcuts.
+            assertEmpty(getCallerShortcuts());
+        });
+    }
+
+    public void testManifestShortcuts_updateAndDisabled_pinned() {
+        mService.handleUnlockUser(USER_0);
+
+        // First, just publish a manifest shortcut.
+        addManifestShortcutResource(
+                new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
+                R.xml.shortcut_1);
+        updatePackageVersion(CALLING_PACKAGE_1, 1);
+        mService.mPackageMonitor.onReceive(getTestContext(),
+                genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
+
+        // Only the valid one is published.
+        runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
+            assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
+                    mManager.getManifestShortcuts()))),
+                    "ms1");
+            assertEmpty(mManager.getPinnedShortcuts());
+
+            // Make sure there's no other dangling shortcuts.
+            assertShortcutIds(getCallerShortcuts(), "ms1");
+        });
+
+        runWithCaller(LAUNCHER_1, USER_0, () -> {
+            mLauncherApps.pinShortcuts(CALLING_PACKAGE_1, list("ms1"), HANDLE_USER_0);
+        });
+
+        // Now upgrade, the manifest shortcut is disabled now.
+        addManifestShortcutResource(
+                new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
+                R.xml.shortcut_1_disable);
+        updatePackageVersion(CALLING_PACKAGE_1, 1);
+        mService.mPackageMonitor.onReceive(getTestContext(),
+                genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
+
+        // Because shortcut 1 was pinned, it'll still exist as pinned, but disabled.
+        runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
+            assertEmpty(mManager.getManifestShortcuts());
+            assertShortcutIds(assertAllNotManifest(assertAllImmutable(assertAllDisabled(
+                    mManager.getPinnedShortcuts()))),
+                    "ms1");
+
+            // Make sure the fields are updated.
+            ShortcutInfo si = getCallerShortcut("ms1");
+
+            assertEquals("ms1", si.getId());
+            assertEquals(R.drawable.icon2, si.getIconResourceId());
+            assertEquals(R.string.shortcut_title2, si.getTitleResId());
+            assertEquals(R.string.shortcut_text2, si.getTextResId());
+            assertEquals(R.string.shortcut_disabled_message2, si.getDisabledMessageResId());
+            assertEquals(Intent.ACTION_VIEW, si.getIntent().getAction());
+
+            // Make sure there's no other dangling shortcuts.
+            assertShortcutIds(getCallerShortcuts(), "ms1");
+        });
+    }
+
+    public void testManifestShortcuts_duplicateInSingleActivity() {
+        mService.handleUnlockUser(USER_0);
+
+        // The XML has two shortcuts with the same ID.
+        addManifestShortcutResource(
+                new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
+                R.xml.shortcut_2_duplicate);
+        updatePackageVersion(CALLING_PACKAGE_1, 1);
+        mService.mPackageMonitor.onReceive(getTestContext(),
+                genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
+
+        runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
+            assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
+                    mManager.getManifestShortcuts()))),
+                    "ms1");
+
+            // Make sure the first one has survived.  (the second one has a different title.)
+            ShortcutInfo si = getCallerShortcut("ms1");
+            assertEquals(R.string.shortcut_title1, si.getTitleResId());
+
+            // Make sure there's no other dangling shortcuts.
+            assertShortcutIds(getCallerShortcuts(), "ms1");
+        });
+    }
+
+    public void testManifestShortcuts_duplicateInTwoActivities() {
+        mService.handleUnlockUser(USER_0);
+
+        // ShortcutActivity has shortcut ms1
+        addManifestShortcutResource(
+                new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
+                R.xml.shortcut_1);
+
+        // ShortcutActivity2 has two shortcuts, ms1 and ms2.
+        addManifestShortcutResource(
+                new ComponentName(CALLING_PACKAGE_1, ShortcutActivity2.class.getName()),
+                R.xml.shortcut_2);
+        updatePackageVersion(CALLING_PACKAGE_1, 1);
+        mService.mPackageMonitor.onReceive(getTestContext(),
+                genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
+
+        runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
+            assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
+                    mManager.getManifestShortcuts()))),
+                    "ms1", "ms2");
+
+            // ms1 should belong to ShortcutActivity.
+            ShortcutInfo si = getCallerShortcut("ms1");
+            assertEquals(R.string.shortcut_title1, si.getTitleResId());
+            assertEquals(new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
+                    si.getActivity());
+
+            // ms2 should belong to ShortcutActivity*2*.
+            si = getCallerShortcut("ms2");
+            assertEquals(R.string.shortcut_title2, si.getTitleResId());
+            assertEquals(new ComponentName(CALLING_PACKAGE_1, ShortcutActivity2.class.getName()),
+                    si.getActivity());
+
+            // Make sure there's no other dangling shortcuts.
+            assertShortcutIds(getCallerShortcuts(), "ms1", "ms2");
+        });
+    }
+
+    /**
+     * Manifest shortcuts cannot override shortcuts that were published via the APIs.
+     */
+    public void testManifestShortcuts_cannotOverrideNonManifest() {
+        mService.handleUnlockUser(USER_0);
+
+        // Create a non-pinned dynamic shortcut and a non-dynamic pinned shortcut.
+
+        runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
+            mManager.setDynamicShortcuts(list(
+                    makeShortcut("ms1", "title1",
+                    new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
+                    /* icon */ null, new Intent("action1"), /* rank */ 0),
+                    makeShortcut("ms2", "title2",
+                    new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
+                    /* icon */ null, new Intent("action1"), /* rank */ 0)));
+        });
+
+        runWithCaller(LAUNCHER_1, USER_0, () -> {
+            mLauncherApps.pinShortcuts(CALLING_PACKAGE_1, list("ms2"), HANDLE_USER_0);
+        });
+
+        runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
+            mManager.removeDynamicShortcuts(list("ms2"));
+
+            assertShortcutIds(mManager.getDynamicShortcuts(), "ms1");
+            assertShortcutIds(mManager.getPinnedShortcuts(), "ms2");
+            assertEmpty(mManager.getManifestShortcuts());
+        });
+
+        // Then update the app with 5 manifest shortcuts.
+        // Make sure "ms1" and "ms2" won't be replaced.
+        addManifestShortcutResource(
+                new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
+                R.xml.shortcut_5);
+        updatePackageVersion(CALLING_PACKAGE_1, 1);
+        mService.mPackageMonitor.onReceive(getTestContext(),
+                genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
+
+        runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
+            assertShortcutIds(assertAllNotManifest(mManager.getDynamicShortcuts()), "ms1");
+            assertShortcutIds(assertAllNotManifest(mManager.getPinnedShortcuts()), "ms2");
+            assertShortcutIds(assertAllManifest(mManager.getManifestShortcuts()),
+                    "ms3", "ms4", "ms5");
+
+            // ms1 and ms2 shouold keep the original title.
+            ShortcutInfo si = getCallerShortcut("ms1");
+            assertEquals("title1", si.getTitle());
+
+            si = getCallerShortcut("ms2");
+            assertEquals("title2", si.getTitle());
+        });
+    }
+
+    private void checkManifestShortcuts_immutable_verify() {
+        runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
+            assertShortcutIds(assertAllNotManifest(assertAllEnabled(
+                    mManager.getDynamicShortcuts())),
+                    "s1");
+            assertShortcutIds(assertAllManifest(assertAllEnabled(
+                    mManager.getManifestShortcuts())),
+                    "ms1");
+            assertShortcutIds(assertAllNotManifest(assertAllDisabled(
+                    mManager.getPinnedShortcuts())),
+                    "ms2");
+
+            assertEquals("t1", getCallerShortcut("s1").getTitle());
+
+            // Make sure there are no other shortcuts.
+            assertShortcutIds(getCallerShortcuts(), "s1", "ms1", "ms2");
+        });
+    }
+
+    /**
+     * Make sure the APIs won't work on manifest shortcuts.
+     */
+    public void testManifestShortcuts_immutable() {
+        mService.handleUnlockUser(USER_0);
+
+        // Create a non-pinned manifest shortcut, a pinned shortcut that was originally
+        // a manifest shortcut, as well as a dynamic shortcut.
+
+        addManifestShortcutResource(
+                new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
+                R.xml.shortcut_2);
+        updatePackageVersion(CALLING_PACKAGE_1, 1);
+        mService.mPackageMonitor.onReceive(getTestContext(),
+                genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
+
+        runWithCaller(LAUNCHER_1, USER_0, () -> {
+            mLauncherApps.pinShortcuts(CALLING_PACKAGE_1, list("ms2"), HANDLE_USER_0);
+        });
+
+        addManifestShortcutResource(
+                new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
+                R.xml.shortcut_1);
+        updatePackageVersion(CALLING_PACKAGE_1, 1);
+        mService.mPackageMonitor.onReceive(getTestContext(),
+                genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
+
+        runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
+            mManager.addDynamicShortcuts(list(makeShortcutWithTitle("s1", "t1")));
+        });
+
+        checkManifestShortcuts_immutable_verify();
+
+        // Note that even though the first argument is not immutable and only the second one
+        // is immutable, the first argument should not be executed either.
+
+        runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
+            assertCannotUpdateImmutable(() -> {
+                mManager.setDynamicShortcuts(list(makeShortcut("xx"), makeShortcut("ms1")));
+            });
+            assertCannotUpdateImmutable(() -> {
+                mManager.setDynamicShortcuts(list(makeShortcut("xx"), makeShortcut("ms2")));
+            });
+        });
+        checkManifestShortcuts_immutable_verify();
+
+        runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
+            assertCannotUpdateImmutable(() -> {
+                mManager.addDynamicShortcuts(list(makeShortcut("xx"), makeShortcut("ms1")));
+            });
+            assertCannotUpdateImmutable(() -> {
+                mManager.addDynamicShortcuts(list(makeShortcut("xx"), makeShortcut("ms2")));
+            });
+        });
+        checkManifestShortcuts_immutable_verify();
+
+
+        runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
+            assertCannotUpdateImmutable(() -> {
+                mManager.updateShortcuts(list(makeShortcut("s1"), makeShortcut("ms1")));
+            });
+            assertCannotUpdateImmutable(() -> {
+                mManager.updateShortcuts(list(makeShortcut("s1"), makeShortcut("ms2")));
+            });
+        });
+        checkManifestShortcuts_immutable_verify();
+
+        runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
+            assertCannotUpdateImmutable(() -> {
+                mManager.removeDynamicShortcuts(list("s1", "ms1"));
+            });
+            assertCannotUpdateImmutable(() -> {
+                mManager.removeDynamicShortcuts(list("s2", "ms2"));
+            });
+        });
+        checkManifestShortcuts_immutable_verify();
+
+        runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
+            assertCannotUpdateImmutable(() -> {
+                mManager.disableShortcuts(list("s1", "ms1"));
+            });
+        });
+        checkManifestShortcuts_immutable_verify();
+
+        runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
+            assertCannotUpdateImmutable(() -> {
+                mManager.enableShortcuts(list("s1", "ms2"));
+            });
+        });
+        checkManifestShortcuts_immutable_verify();
+    }
 }
diff --git a/services/tests/shortcutmanagerutils/src/com/android/server/pm/shortcutmanagertest/ShortcutManagerTestUtils.java b/services/tests/shortcutmanagerutils/src/com/android/server/pm/shortcutmanagertest/ShortcutManagerTestUtils.java
index c23f9e6..7fa8a800 100644
--- a/services/tests/shortcutmanagerutils/src/com/android/server/pm/shortcutmanagertest/ShortcutManagerTestUtils.java
+++ b/services/tests/shortcutmanagerutils/src/com/android/server/pm/shortcutmanagertest/ShortcutManagerTestUtils.java
@@ -246,11 +246,22 @@
             reset(o);
         }
     }
+
+    public static <T> List<T> assertEmpty(List<T> list) {
+        assertEquals(0, list.size());
+        return list;
+    }
+
     public static void assertExpectException(Class<? extends Throwable> expectedExceptionType,
             String expectedExceptionMessageRegex, Runnable r) {
         assertExpectException("", expectedExceptionType, expectedExceptionMessageRegex, r);
     }
 
+    public static void assertCannotUpdateImmutable(Runnable r) {
+        assertExpectException(
+                IllegalArgumentException.class, "may not be manipulated via APIs", r);
+    }
+
     public static void assertDynamicShortcutCountExceeded(Runnable r) {
         assertExpectException(IllegalArgumentException.class,
                 "Max number of dynamic shortcuts exceeded", r);
@@ -383,6 +394,46 @@
         return actualShortcuts;
     }
 
+    public static List<ShortcutInfo> assertAllManifest(
+            List<ShortcutInfo> actualShortcuts) {
+        for (ShortcutInfo s : actualShortcuts) {
+            assertTrue("ID " + s.getId(), s.isManifestShortcut());
+        }
+        return actualShortcuts;
+    }
+
+    public static List<ShortcutInfo> assertAllNotManifest(
+            List<ShortcutInfo> actualShortcuts) {
+        for (ShortcutInfo s : actualShortcuts) {
+            assertFalse("ID " + s.getId(), s.isManifestShortcut());
+        }
+        return actualShortcuts;
+    }
+
+    public static List<ShortcutInfo> assertAllDisabled(
+            List<ShortcutInfo> actualShortcuts) {
+        for (ShortcutInfo s : actualShortcuts) {
+            assertTrue("ID " + s.getId(), !s.isEnabled());
+        }
+        return actualShortcuts;
+    }
+
+    public static List<ShortcutInfo> assertAllEnabled(
+            List<ShortcutInfo> actualShortcuts) {
+        for (ShortcutInfo s : actualShortcuts) {
+            assertTrue("ID " + s.getId(), s.isEnabled());
+        }
+        return actualShortcuts;
+    }
+
+    public static List<ShortcutInfo> assertAllImmutable(
+            List<ShortcutInfo> actualShortcuts) {
+        for (ShortcutInfo s : actualShortcuts) {
+            assertTrue("ID " + s.getId(), s.isImmutable());
+        }
+        return actualShortcuts;
+    }
+
     public static List<ShortcutInfo> assertAllStringsResolved(
             List<ShortcutInfo> actualShortcuts) {
         for (ShortcutInfo s : actualShortcuts) {
@@ -398,6 +449,7 @@
 
     public static void assertPinnedOnly(ShortcutInfo si) {
         assertFalse(si.isDynamic());
+        assertFalse(si.isManifestShortcut());
         assertTrue(si.isPinned());
     }
 
diff --git a/telephony/java/android/telephony/TelephonyManager.java b/telephony/java/android/telephony/TelephonyManager.java
index fe1027a..736539c 100644
--- a/telephony/java/android/telephony/TelephonyManager.java
+++ b/telephony/java/android/telephony/TelephonyManager.java
@@ -69,6 +69,12 @@
  * a reference to an instance through
  * {@link android.content.Context#getSystemService
  * Context.getSystemService(Context.TELEPHONY_SERVICE)}.
+ *
+ * The returned TelephonyManager will use the default subscription for all calls.
+ * To call an API for a specific subscription, use {@link #createForSubscriptionId(int)}. e.g.
+ * <code>
+ *   telephonyManager = defaultSubTelephonyManager.createForSubscriptionId(subId);
+ * </code>
  * <p>
  * Note that access to some telephony information is
  * permission-protected. Your application cannot access the protected
@@ -104,6 +110,7 @@
     }
 
     private final Context mContext;
+    private final int mSubId;
     private SubscriptionManager mSubscriptionManager;
 
     private static String multiSimConfig =
@@ -124,6 +131,12 @@
 
     /** @hide */
     public TelephonyManager(Context context) {
+      this(context, SubscriptionManager.DEFAULT_SUBSCRIPTION_ID);
+    }
+
+    /** @hide */
+    public TelephonyManager(Context context, int subId) {
+        mSubId = subId;
         Context appContext = context.getApplicationContext();
         if (appContext != null) {
             mContext = appContext;
@@ -141,6 +154,7 @@
     /** @hide */
     private TelephonyManager() {
         mContext = null;
+        mSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
     }
 
     private static TelephonyManager sInstance = new TelephonyManager();
@@ -234,6 +248,16 @@
         return (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
     }
 
+    /**
+     * Create a new TelephonyManager object pinned to the given subscription ID.
+     *
+     * @return a TelephonyManager that uses the given subId for all calls.
+     */
+    public TelephonyManager createForSubscriptionId(int subId) {
+      // Don't reuse any TelephonyManager objects.
+      return new TelephonyManager(mContext, subId);
+    }
+
     /** {@hide} */
     public boolean isMultiSimEnabled() {
         return (multiSimConfig.equals("dsds") || multiSimConfig.equals("dsda") ||
@@ -926,7 +950,7 @@
      * @hide
      */
     public void enableLocationUpdates() {
-            enableLocationUpdates(getDefaultSubscription());
+        enableLocationUpdates(getSubId());
     }
 
     /**
@@ -938,8 +962,8 @@
      * CONTROL_LOCATION_UPDATES}
      *
      * @param subId for which the location updates are enabled
+     * @hide
      */
-    /** @hide */
     public void enableLocationUpdates(int subId) {
         try {
             ITelephony telephony = getITelephony();
@@ -960,7 +984,7 @@
      * @hide
      */
     public void disableLocationUpdates() {
-            disableLocationUpdates(getDefaultSubscription());
+        disableLocationUpdates(getSubId());
     }
 
     /** @hide */
@@ -1021,7 +1045,7 @@
      */
     @SystemApi
     public int getCurrentPhoneType() {
-        return getCurrentPhoneType(getDefaultSubscription());
+        return getCurrentPhoneType(getSubId());
     }
 
     /**
@@ -1032,8 +1056,8 @@
      * @see #PHONE_TYPE_CDMA
      *
      * @param subId for which phone type is returned
+     * @hide
      */
-    /** {@hide} */
     @SystemApi
     public int getCurrentPhoneType(int subId) {
         int phoneId;
@@ -1261,7 +1285,7 @@
      * on a CDMA network).
      */
     public String getNetworkOperatorName() {
-        return getNetworkOperatorName(getDefaultSubscription());
+        return getNetworkOperatorName(getSubId());
     }
 
     /**
@@ -1272,6 +1296,7 @@
      * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
      * on a CDMA network).
      * @param subId
+     * @hide
      */
     public String getNetworkOperatorName(int subId) {
         int phoneId = SubscriptionManager.getPhoneId(subId);
@@ -1298,6 +1323,7 @@
      * on a CDMA network).
      *
      * @param subId
+     * @hide
      */
     public String getNetworkOperator(int subId) {
         int phoneId = SubscriptionManager.getPhoneId(subId);
@@ -1326,7 +1352,7 @@
      * Availability: Only when user registered to a network.
      */
     public boolean isNetworkRoaming() {
-        return isNetworkRoaming(getDefaultSubscription());
+        return isNetworkRoaming(getSubId());
     }
 
     /**
@@ -1336,6 +1362,7 @@
      * Availability: Only when user registered to a network.
      *
      * @param subId
+     * @hide
      */
     public boolean isNetworkRoaming(int subId) {
         int phoneId = SubscriptionManager.getPhoneId(subId);
@@ -1364,6 +1391,7 @@
      * on a CDMA network).
      *
      * @param subId for which Network CountryIso is returned
+     * @hide
      */
     public String getNetworkCountryIso(int subId) {
         int phoneId = SubscriptionManager.getPhoneId(subId);
@@ -1472,6 +1500,7 @@
      * <p>
      * Requires Permission:
      *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
+     * @hide
      */
    public int getNetworkType(int subId) {
        try {
@@ -1516,10 +1545,9 @@
      * <p>
      * Requires Permission:
      *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
-     * @hide
      */
     public int getDataNetworkType() {
-        return getDataNetworkType(getDefaultSubscription());
+        return getDataNetworkType(getSubId());
     }
 
     /**
@@ -1532,6 +1560,7 @@
      * <p>
      * Requires Permission:
      *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
+     * @hide
      */
     public int getDataNetworkType(int subId) {
         try{
@@ -1557,10 +1586,9 @@
      * <p>
      * Requires Permission:
      *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
-     * @hide
      */
     public int getVoiceNetworkType() {
-        return getVoiceNetworkType(getDefaultSubscription());
+        return getVoiceNetworkType(getSubId());
     }
 
     /**
@@ -1569,6 +1597,7 @@
      * <p>
      * Requires Permission:
      *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
+     * @hide
      */
     public int getVoiceNetworkType(int subId) {
         try{
@@ -1843,6 +1872,7 @@
      * @see #getSimState
      *
      * @param subId for which SimOperator is returned
+     * @hide
      */
     public String getSimOperator(int subId) {
         return getSimOperatorNumeric(subId);
@@ -1919,6 +1949,7 @@
      * @see #getSimState
      *
      * @param subId for which SimOperatorName is returned
+     * @hide
      */
     public String getSimOperatorName(int subId) {
         int phoneId = SubscriptionManager.getPhoneId(subId);
@@ -1946,6 +1977,7 @@
      * Returns the ISO country code equivalent for the SIM provider's country code.
      *
      * @param subId for which SimCountryIso is returned
+     * @hide
      */
     public String getSimCountryIso(int subId) {
         int phoneId = SubscriptionManager.getPhoneId(subId);
@@ -1970,7 +2002,7 @@
      *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
      */
     public String getSimSerialNumber() {
-         return getSimSerialNumber(getDefaultSubscription());
+         return getSimSerialNumber(getSubId());
     }
 
     /**
@@ -1980,6 +2012,7 @@
      * @param subId for which Sim Serial number is returned
      * Requires Permission:
      *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
+     * @hide
      */
     public String getSimSerialNumber(int subId) {
         try {
@@ -2010,7 +2043,7 @@
      * @hide
      */
     public int getLteOnCdmaMode() {
-        return getLteOnCdmaMode(getDefaultSubscription());
+        return getLteOnCdmaMode(getSubId());
     }
 
     /**
@@ -2025,8 +2058,8 @@
      * <p>
      * Requires Permission:
      *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
+     * @hide
      */
-    /** {@hide} */
     public int getLteOnCdmaMode(int subId) {
         try {
             ITelephony telephony = getITelephony();
@@ -2056,7 +2089,7 @@
      *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
      */
     public String getSubscriberId() {
-        return getSubscriberId(getDefaultSubscription());
+        return getSubscriberId(getSubId());
     }
 
     /**
@@ -2068,6 +2101,7 @@
      *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
      *
      * @param subId whose subscriber id is returned
+     * @hide
      */
     public String getSubscriberId(int subId) {
         try {
@@ -2112,6 +2146,7 @@
      *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
      *
      * @param subId whose subscriber id is returned
+     * @hide
      */
     public String getGroupIdLevel1(int subId) {
         try {
@@ -2139,7 +2174,7 @@
      * The default SMS app can also use this.
      */
     public String getLine1Number() {
-        return getLine1Number(getDefaultSubscription());
+        return getLine1Number(getSubId());
     }
 
     /**
@@ -2154,6 +2189,7 @@
      * The default SMS app can also use this.
      *
      * @param subId whose phone number for line 1 is returned
+     * @hide
      */
     public String getLine1Number(int subId) {
         String number = null;
@@ -2194,7 +2230,7 @@
      * @return true if the operation was executed correctly.
      */
     public boolean setLine1NumberForDisplay(String alphaTag, String number) {
-        return setLine1NumberForDisplay(getDefaultSubscription(), alphaTag, number);
+        return setLine1NumberForDisplay(getSubId(), alphaTag, number);
     }
 
     /**
@@ -2210,6 +2246,7 @@
      * @param alphaTag alpha-tagging of the dailing nubmer
      * @param number The dialing number
      * @return true if the operation was executed correctly.
+     * @hide
      */
     public boolean setLine1NumberForDisplay(int subId, String alphaTag, String number) {
         try {
@@ -2232,7 +2269,7 @@
      * nobody seems to call this.
      */
     public String getLine1AlphaTag() {
-        return getLine1AlphaTag(getDefaultSubscription());
+        return getLine1AlphaTag(getSubId());
     }
 
     /**
@@ -2244,6 +2281,7 @@
      *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
      * @param subId whose alphabetic identifier associated with line 1 is returned
      * nobody seems to call this.
+     * @hide
      */
     public String getLine1AlphaTag(int subId) {
         String alphaTag = null;
@@ -2300,7 +2338,7 @@
      * @hide
      */
     public String getMsisdn() {
-        return getMsisdn(getDefaultSubscription());
+        return getMsisdn(getSubId());
     }
 
     /**
@@ -2311,8 +2349,8 @@
      *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
      *
      * @param subId for which msisdn is returned
+     * @hide
      */
-    /** {@hide} */
     public String getMsisdn(int subId) {
         try {
             IPhoneSubInfo info = getSubscriberInfo();
@@ -2334,7 +2372,7 @@
      *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
      */
     public String getVoiceMailNumber() {
-        return getVoiceMailNumber(getDefaultSubscription());
+        return getVoiceMailNumber(getSubId());
     }
 
     /**
@@ -2344,6 +2382,7 @@
      * Requires Permission:
      *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
      * @param subId whose voice mail number is returned
+     * @hide
      */
     public String getVoiceMailNumber(int subId) {
         try {
@@ -2368,7 +2407,7 @@
      * @hide
      */
     public String getCompleteVoiceMailNumber() {
-        return getCompleteVoiceMailNumber(getDefaultSubscription());
+        return getCompleteVoiceMailNumber(getSubId());
     }
 
     /**
@@ -2378,8 +2417,8 @@
      *   {@link android.Manifest.permission#CALL_PRIVILEGED CALL_PRIVILEGED}
      *
      * @param subId
+     * @hide
      */
-    /** {@hide} */
     public String getCompleteVoiceMailNumber(int subId) {
         try {
             IPhoneSubInfo info = getSubscriberInfo();
@@ -2404,7 +2443,7 @@
      * @param number The voicemail number.
      */
     public boolean setVoiceMailNumber(String alphaTag, String number) {
-        return setVoiceMailNumber(getDefaultSubscription(), alphaTag, number);
+        return setVoiceMailNumber(getSubId(), alphaTag, number);
     }
 
     /**
@@ -2416,6 +2455,7 @@
      * @param subId The subscription id.
      * @param alphaTag The alpha tag to display.
      * @param number The voicemail number.
+     * @hide
      */
     public boolean setVoiceMailNumber(int subId, String alphaTag, String number) {
         try {
@@ -2533,7 +2573,7 @@
      * @hide
      */
     public int getVoiceMessageCount() {
-        return getVoiceMessageCount(getDefaultSubscription());
+        return getVoiceMessageCount(getSubId());
     }
 
     /**
@@ -2542,8 +2582,8 @@
      * Requires Permission:
      *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
      * @param subId whose voice message count is returned
+     * @hide
      */
-    /** {@hide} */
     public int getVoiceMessageCount(int subId) {
         try {
             ITelephony telephony = getITelephony();
@@ -2566,7 +2606,7 @@
      *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
      */
     public String getVoiceMailAlphaTag() {
-        return getVoiceMailAlphaTag(getDefaultSubscription());
+        return getVoiceMailAlphaTag(getSubId());
     }
 
     /**
@@ -2577,6 +2617,7 @@
      * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
      * @param subId whose alphabetic identifier associated with the
      * voice mail number is returned
+     * @hide
      */
     public String getVoiceMailAlphaTag(int subId) {
         try {
@@ -2694,6 +2735,7 @@
      * for a subscription.
      *
      * @param subId whose call state is returned
+     * @hide
      */
     public int getCallState(int subId) {
         int phoneId = SubscriptionManager.getPhoneId(subId);
@@ -2863,7 +2905,7 @@
      * @hide
      */
     public int getCdmaEriIconIndex() {
-        return getCdmaEriIconIndex(getDefaultSubscription());
+        return getCdmaEriIconIndex(getSubId());
     }
 
     /**
@@ -2871,8 +2913,8 @@
      * <p>
      * Requires Permission:
      *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
+     * @hide
      */
-    /** {@hide} */
     public int getCdmaEriIconIndex(int subId) {
         try {
             ITelephony telephony = getITelephony();
@@ -2898,7 +2940,7 @@
      * @hide
      */
     public int getCdmaEriIconMode() {
-        return getCdmaEriIconMode(getDefaultSubscription());
+        return getCdmaEriIconMode(getSubId());
     }
 
     /**
@@ -2909,8 +2951,8 @@
      * <p>
      * Requires Permission:
      *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
+     * @hide
      */
-    /** {@hide} */
     public int getCdmaEriIconMode(int subId) {
         try {
             ITelephony telephony = getITelephony();
@@ -2934,7 +2976,7 @@
      * @hide
      */
     public String getCdmaEriText() {
-        return getCdmaEriText(getDefaultSubscription());
+        return getCdmaEriText(getSubId());
     }
 
     /**
@@ -2943,8 +2985,8 @@
      * <p>
      * Requires Permission:
      *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
+     * @hide
      */
-    /** {@hide} */
     public String getCdmaEriText(int subId) {
         try {
             ITelephony telephony = getITelephony();
@@ -3097,7 +3139,7 @@
      * @return an IccOpenLogicalChannelResponse object.
      */
     public IccOpenLogicalChannelResponse iccOpenLogicalChannel(String AID) {
-        return iccOpenLogicalChannel(getDefaultSubscription(), AID);
+        return iccOpenLogicalChannel(getSubId(), AID);
     }
 
     /**
@@ -3112,6 +3154,7 @@
      * @param subId The subscription to use.
      * @param AID Application id. See ETSI 102.221 and 101.220.
      * @return an IccOpenLogicalChannelResponse object.
+     * @hide
      */
     public IccOpenLogicalChannelResponse iccOpenLogicalChannel(int subId, String AID) {
         try {
@@ -3138,7 +3181,7 @@
      * @return true if the channel was closed successfully.
      */
     public boolean iccCloseLogicalChannel(int channel) {
-        return iccCloseLogicalChannel(getDefaultSubscription(), channel);
+        return iccCloseLogicalChannel(getSubId(), channel);
     }
 
     /**
@@ -3154,6 +3197,7 @@
      * @param channel is the channel id to be closed as retruned by a successful
      *            iccOpenLogicalChannel.
      * @return true if the channel was closed successfully.
+     * @hide
      */
     public boolean iccCloseLogicalChannel(int subId, int channel) {
         try {
@@ -3189,7 +3233,7 @@
      */
     public String iccTransmitApduLogicalChannel(int channel, int cla,
             int instruction, int p1, int p2, int p3, String data) {
-        return iccTransmitApduLogicalChannel(getDefaultSubscription(), channel, cla,
+        return iccTransmitApduLogicalChannel(getSubId(), channel, cla,
                     instruction, p1, p2, p3, data);
     }
 
@@ -3214,6 +3258,7 @@
      * @param data Data to be sent with the APDU.
      * @return The APDU response from the ICC card with the status appended at
      *            the end.
+     * @hide
      */
     public String iccTransmitApduLogicalChannel(int subId, int channel, int cla,
             int instruction, int p1, int p2, int p3, String data) {
@@ -3249,7 +3294,7 @@
      */
     public String iccTransmitApduBasicChannel(int cla,
             int instruction, int p1, int p2, int p3, String data) {
-        return iccTransmitApduBasicChannel(getDefaultSubscription(), cla,
+        return iccTransmitApduBasicChannel(getSubId(), cla,
                     instruction, p1, p2, p3, data);
     }
 
@@ -3272,6 +3317,7 @@
      * @param data Data to be sent with the APDU.
      * @return The APDU response from the ICC card with the status appended at
      *            the end.
+     * @hide
      */
     public String iccTransmitApduBasicChannel(int subId, int cla,
             int instruction, int p1, int p2, int p3, String data) {
@@ -3303,7 +3349,7 @@
      */
     public byte[] iccExchangeSimIO(int fileID, int command, int p1, int p2, int p3,
             String filePath) {
-        return iccExchangeSimIO(getDefaultSubscription(), fileID, command, p1, p2, p3, filePath);
+        return iccExchangeSimIO(getSubId(), fileID, command, p1, p2, p3, filePath);
     }
 
     /**
@@ -3321,6 +3367,7 @@
      * @param p3 P3 value of the APDU command.
      * @param filePath
      * @return The APDU response.
+     * @hide
      */
     public byte[] iccExchangeSimIO(int subId, int fileID, int command, int p1, int p2,
             int p3, String filePath) {
@@ -3349,7 +3396,7 @@
      *         returns an empty string.
      */
     public String sendEnvelopeWithStatus(String content) {
-        return sendEnvelopeWithStatus(getDefaultSubscription(), content);
+        return sendEnvelopeWithStatus(getSubId(), content);
     }
 
     /**
@@ -3366,6 +3413,7 @@
      * @return The APDU response from the ICC card in hexadecimal format
      *         with the last 4 bytes being the status word. If the command fails,
      *         returns an empty string.
+     * @hide
      */
     public String sendEnvelopeWithStatus(int subId, String content) {
         try {
@@ -3485,6 +3533,19 @@
     }
 
     /**
+     * Return an appropriate subscription ID for any situation.
+     *
+     * If this object has been created with {@link #createForSubscriptionId}, then the provided
+     * subId is returned. Otherwise, the default subId will be returned.
+     */
+    private int getSubId() {
+      if (mSubId == SubscriptionManager.DEFAULT_SUBSCRIPTION_ID) {
+        return getDefaultSubscription();
+      }
+      return mSubId;
+    }
+
+    /**
      * Returns Default subscription.
      */
     private static int getDefaultSubscription() {
@@ -3766,7 +3827,7 @@
      * @see #hasCarrierPrivileges
      */
     public String getIccAuthentication(int appType, int authType, String data) {
-        return getIccAuthentication(getDefaultSubscription(), appType, authType, data);
+        return getIccAuthentication(getSubId(), appType, authType, data);
     }
 
     /**
@@ -3784,8 +3845,8 @@
      * @return the response of authentication, or null if not available
      *
      * @see #hasCarrierPrivileges
+     * @hide
      */
-
     public String getIccAuthentication(int subId, int appType, int authType, String data) {
         try {
             IPhoneSubInfo info = getSubscriberInfo();
@@ -3864,6 +3925,7 @@
      * Or the calling app has carrier privileges. @see #hasCarrierPrivileges
      *
      * @hide
+     * TODO: Add an overload that takes no args.
      */
     public void setNetworkSelectionModeAutomatic(int subId) {
         try {
@@ -3889,6 +3951,7 @@
      * Or the calling app has carrier privileges. @see #hasCarrierPrivileges
      *
      * @hide
+     * TODO: Add an overload that takes no args.
      */
     public CellNetworkScanResult getCellNetworkScanResults(int subId) {
         try {
@@ -3912,6 +3975,7 @@
      * Or the calling app has carrier privileges. @see #hasCarrierPrivileges
      *
      * @hide
+     * TODO: Add an overload that takes no args.
      */
     public boolean setNetworkSelectionModeManual(int subId, OperatorInfo operator,
             boolean persistSelection) {
@@ -3963,7 +4027,7 @@
      * @return true on success; false on any failure.
      */
     public boolean setPreferredNetworkTypeToGlobal() {
-        return setPreferredNetworkTypeToGlobal(getDefaultSubscription());
+        return setPreferredNetworkTypeToGlobal(getSubId());
     }
 
     /**
@@ -3974,6 +4038,7 @@
      * @see #hasCarrierPrivileges
      *
      * @return true on success; false on any failure.
+     * @hide
      */
     public boolean setPreferredNetworkTypeToGlobal(int subId) {
         return setPreferredNetworkType(subId, RILConstants.NETWORK_MODE_LTE_CDMA_EVDO_GSM_WCDMA);
@@ -4023,7 +4088,7 @@
      * @return true if the app has carrier privileges.
      */
     public boolean hasCarrierPrivileges() {
-        return hasCarrierPrivileges(getDefaultSubscription());
+        return hasCarrierPrivileges(getSubId());
     }
 
     /**
@@ -4035,12 +4100,13 @@
      *
      * @param subId The subscription to use.
      * @return true if the app has carrier privileges.
+     * @hide
      */
     public boolean hasCarrierPrivileges(int subId) {
         try {
             ITelephony telephony = getITelephony();
             if (telephony != null) {
-                return telephony.getCarrierPrivilegeStatus(subId) ==
+                return telephony.getCarrierPrivilegeStatus(mSubId) ==
                     CARRIER_PRIVILEGE_STATUS_HAS_ACCESS;
             }
         } catch (RemoteException ex) {
@@ -4066,7 +4132,7 @@
      * @return true if the operation was executed correctly.
      */
     public boolean setOperatorBrandOverride(String brand) {
-        return setOperatorBrandOverride(getDefaultSubscription(), brand);
+        return setOperatorBrandOverride(getSubId(), brand);
     }
 
     /**
@@ -4083,6 +4149,7 @@
      * @param subId The subscription to use.
      * @param brand The brand name to display/set.
      * @return true if the operation was executed correctly.
+     * @hide
      */
     public boolean setOperatorBrandOverride(int subId, String brand) {
         try {
@@ -4119,7 +4186,7 @@
     public boolean setRoamingOverride(List<String> gsmRoamingList,
             List<String> gsmNonRoamingList, List<String> cdmaRoamingList,
             List<String> cdmaNonRoamingList) {
-        return setRoamingOverride(getDefaultSubscription(), gsmRoamingList, gsmNonRoamingList,
+        return setRoamingOverride(getSubId(), gsmRoamingList, gsmNonRoamingList,
                 cdmaRoamingList, cdmaNonRoamingList);
     }
 
@@ -4166,7 +4233,7 @@
     /** @hide */
     @SystemApi
     public String getCdmaMdn() {
-        return getCdmaMdn(getDefaultSubscription());
+        return getCdmaMdn(getSubId());
     }
 
     /** @hide */
@@ -4187,7 +4254,7 @@
     /** @hide */
     @SystemApi
     public String getCdmaMin() {
-        return getCdmaMin(getDefaultSubscription());
+        return getCdmaMin(getSubId());
     }
 
     /** @hide */
@@ -4730,7 +4797,8 @@
      * retrieves value for setting "name", and if that is not found throws
      * SettingNotFoundException
      *
-     * @hide */
+     * @hide
+     */
     public static int getIntWithSubId(ContentResolver cr, String name, int subId)
             throws SettingNotFoundException {
         try {
diff --git a/tests/UiBench/src/com/android/test/uibench/FullscreenOverdrawActivity.java b/tests/UiBench/src/com/android/test/uibench/FullscreenOverdrawActivity.java
index f1ecc56..b9c5fac 100644
--- a/tests/UiBench/src/com/android/test/uibench/FullscreenOverdrawActivity.java
+++ b/tests/UiBench/src/com/android/test/uibench/FullscreenOverdrawActivity.java
@@ -19,8 +19,11 @@
 import android.animation.ValueAnimator;
 import android.content.Context;
 import android.graphics.Canvas;
+import android.graphics.ColorFilter;
+import android.graphics.PixelFormat;
 import android.graphics.Color;
 import android.graphics.Paint;
+import android.graphics.drawable.Drawable;
 import android.os.Bundle;
 import android.support.v7.app.AppCompatActivity;
 import android.view.View;
@@ -31,37 +34,48 @@
  * This should all be optimized out by the renderer.
  */
 public class FullscreenOverdrawActivity extends AppCompatActivity {
-    private class OverdrawView extends View {
+    private class OverdrawDrawable extends Drawable {
         Paint paint = new Paint();
         int mColorValue = 0;
 
-        public OverdrawView(Context context) {
-            super(context);
-        }
-
         @SuppressWarnings("unused")
         public void setColorValue(int colorValue) {
             mColorValue = colorValue;
-            invalidate();
+            invalidateSelf();
         }
 
         @Override
-        protected void onDraw(Canvas canvas) {
+        public void draw(Canvas canvas) {
             paint.setColor(Color.rgb(mColorValue, 255 - mColorValue, 255));
 
             for (int i = 0; i < 400; i++) {
-                canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
+                canvas.drawRect(getBounds(), paint);
             }
         }
+
+        @Override
+        public void setAlpha(int alpha) {
+        }
+
+        @Override
+        public void setColorFilter(ColorFilter colorFilter) {
+        }
+
+        @Override
+        public int getOpacity() {
+            return PixelFormat.OPAQUE;
+        }
     }
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
 
-        OverdrawView overdrawView = new OverdrawView(this);
-        setContentView(overdrawView);
+        OverdrawDrawable overdraw = new OverdrawDrawable();
+        getWindow().setBackgroundDrawable(overdraw);
 
-        ObjectAnimator objectAnimator = ObjectAnimator.ofInt(overdrawView, "colorValue", 0, 255);
+        setContentView(new View(this));
+
+        ObjectAnimator objectAnimator = ObjectAnimator.ofInt(overdraw, "colorValue", 0, 255);
         objectAnimator.setRepeatMode(ValueAnimator.REVERSE);
         objectAnimator.setRepeatCount(ValueAnimator.INFINITE);
         objectAnimator.start();