Merge "Restrict updates of system packages" into nyc-dev
diff --git a/Android.mk b/Android.mk
index 7d7aa48..b590761 100644
--- a/Android.mk
+++ b/Android.mk
@@ -215,6 +215,7 @@
 	core/java/android/nfc/INfcCardEmulation.aidl \
 	core/java/android/nfc/INfcFCardEmulation.aidl \
 	core/java/android/nfc/INfcUnlockHandler.aidl \
+	core/java/android/nfc/ITagRemovedCallback.aidl \
 	core/java/android/os/IBatteryPropertiesListener.aidl \
 	core/java/android/os/IBatteryPropertiesRegistrar.aidl \
 	core/java/android/os/ICancellationSignal.aidl \
@@ -1142,50 +1143,54 @@
 LOCAL_ADDITIONAL_JAVA_DIR:=$(framework_docs_LOCAL_ADDITIONAL_JAVA_DIR)
 LOCAL_ADDITIONAL_DEPENDENCIES:=$(framework_docs_LOCAL_ADDITIONAL_DEPENDENCIES)
 # specify a second html input dir and an output path relative to OUT_DIR)
-LOCAL_ADDITIONAL_HTML_DIR:=docs/html-intl/intl /
+LOCAL_ADDITIONAL_HTML_DIR:=docs/html-intl /
 
 LOCAL_MODULE := ds
 
 LOCAL_DROIDDOC_OPTIONS:= \
 		$(framework_docs_LOCAL_DROIDDOC_OPTIONS) \
 		-devsite \
+		-hdf devsite true \
 		-toroot / \
 		-hdf android.whichdoc online \
-		-hdf devsite true
+		$(sample_groups) \
+		-useUpdatedTemplates \
+		-hdf android.hasSamples true \
+		-samplesdir $(samples_dir)
 
-LOCAL_DROIDDOC_CUSTOM_TEMPLATE_DIR:=build/tools/droiddoc/templates-sdk
+LOCAL_DROIDDOC_CUSTOM_TEMPLATE_DIR:=build/tools/droiddoc/templates-sdk-dev
 
 include $(BUILD_DROIDDOC)
 
-# ==== docs for the ndk =======================
+# ==== site updates for docs (on the androiddevdocs app engine server) =======================
 include $(CLEAR_VARS)
+
 LOCAL_SRC_FILES:=$(framework_docs_LOCAL_SRC_FILES)
 LOCAL_INTERMEDIATE_SOURCES:=$(framework_docs_LOCAL_INTERMEDIATE_SOURCES)
 LOCAL_STATIC_JAVA_LIBRARIES:=$(framework_docs_LOCAL_STATIC_JAVA_LIBRARIES)
 LOCAL_JAVA_LIBRARIES:=$(framework_docs_LOCAL_JAVA_LIBRARIES)
 LOCAL_MODULE_CLASS:=$(framework_docs_LOCAL_MODULE_CLASS)
 LOCAL_DROIDDOC_SOURCE_PATH:=$(framework_docs_LOCAL_DROIDDOC_SOURCE_PATH)
-LOCAL_DROIDDOC_HTML_DIR:=docs/html-ndk
+LOCAL_DROIDDOC_HTML_DIR:=$(framework_docs_LOCAL_DROIDDOC_HTML_DIR)
 LOCAL_ADDITIONAL_JAVA_DIR:=$(framework_docs_LOCAL_ADDITIONAL_JAVA_DIR)
 LOCAL_ADDITIONAL_DEPENDENCIES:=$(framework_docs_LOCAL_ADDITIONAL_DEPENDENCIES)
-# specify a second html input dir and an output path relative to OUT_DIR)
-LOCAL_ADDITIONAL_HTML_DIR:=docs/html-intl/intl /
+LOCAL_ADDITIONAL_HTML_DIR:=docs/html-intl /
 
-LOCAL_MODULE := online-ndk
+LOCAL_MODULE := online-sdk-dev
 
 LOCAL_DROIDDOC_OPTIONS:= \
 		$(framework_docs_LOCAL_DROIDDOC_OPTIONS) \
 		-toroot / \
 		-hdf android.whichdoc online \
 		$(sample_groups) \
+		-useUpdatedTemplates \
 		-hdf android.hasSamples true \
 		-samplesdir $(samples_dir)
 
-LOCAL_DROIDDOC_CUSTOM_TEMPLATE_DIR:=build/tools/droiddoc/templates-sdk
+LOCAL_DROIDDOC_CUSTOM_TEMPLATE_DIR:=build/tools/droiddoc/templates-sdk-dev
 
 include $(BUILD_DROIDDOC)
 
-
 # ==== docs that have all of the stuff that's @hidden =======================
 include $(CLEAR_VARS)
 
diff --git a/api/current.txt b/api/current.txt
index 4dfbe63..b7b65f1 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -2699,7 +2699,7 @@
     method public void addListener(android.accessibilityservice.AccessibilityService.MagnificationController.OnMagnificationChangedListener, android.os.Handler);
     method public float getCenterX();
     method public float getCenterY();
-    method public android.graphics.Region getMagnifiedRegion();
+    method public android.graphics.Region getMagnificationRegion();
     method public float getScale();
     method public boolean removeListener(android.accessibilityservice.AccessibilityService.MagnificationController.OnMagnificationChangedListener);
     method public boolean reset(boolean);
@@ -4924,7 +4924,6 @@
     field public static final int DEFAULT_LIGHTS = 4; // 0x4
     field public static final int DEFAULT_SOUND = 1; // 0x1
     field public static final int DEFAULT_VIBRATE = 2; // 0x2
-    field public static final java.lang.String EXTRA_ALLOW_GENERATED_REPLIES = "android.allowGeneratedReplies";
     field public static final java.lang.String EXTRA_BACKGROUND_IMAGE_URI = "android.backgroundImageUri";
     field public static final java.lang.String EXTRA_BIG_TEXT = "android.bigText";
     field public static final java.lang.String EXTRA_CHRONOMETER_COUNTS_DOWN = "android.chronometerCountsDown";
@@ -5007,6 +5006,7 @@
     ctor public deprecated Notification.Action(int, java.lang.CharSequence, android.app.PendingIntent);
     method public android.app.Notification.Action clone();
     method public int describeContents();
+    method public boolean getAllowGeneratedReplies();
     method public android.os.Bundle getExtras();
     method public android.graphics.drawable.Icon getIcon();
     method public android.app.RemoteInput[] getRemoteInputs();
@@ -5026,6 +5026,7 @@
     method public android.app.Notification.Action build();
     method public android.app.Notification.Action.Builder extend(android.app.Notification.Action.Extender);
     method public android.os.Bundle getExtras();
+    method public android.app.Notification.Action.Builder setAllowGeneratedReplies(boolean);
   }
 
   public static abstract interface Notification.Action.Extender {
@@ -5193,11 +5194,9 @@
     ctor public Notification.MessagingStyle(java.lang.CharSequence);
     method public android.app.Notification.MessagingStyle addMessage(java.lang.CharSequence, long, java.lang.CharSequence);
     method public android.app.Notification.MessagingStyle addMessage(android.app.Notification.MessagingStyle.Message);
-    method public boolean getAllowGeneratedReplies();
     method public java.lang.CharSequence getConversationTitle();
     method public java.util.List<android.app.Notification.MessagingStyle.Message> getMessages();
     method public java.lang.CharSequence getUserDisplayName();
-    method public android.app.Notification.MessagingStyle setAllowGeneratedReplies(boolean);
     method public android.app.Notification.MessagingStyle setConversationTitle(java.lang.CharSequence);
     field public static final int MAXIMUM_RETAINED_MESSAGES = 25; // 0x19
   }
@@ -5242,6 +5241,7 @@
     method public boolean getContentIntentAvailableOffline();
     method public int getCustomContentHeight();
     method public int getCustomSizePreset();
+    method public java.lang.String getDismissalId();
     method public android.app.PendingIntent getDisplayIntent();
     method public int getGravity();
     method public boolean getHintAmbientBigPicture();
@@ -5259,6 +5259,7 @@
     method public android.app.Notification.WearableExtender setContentIntentAvailableOffline(boolean);
     method public android.app.Notification.WearableExtender setCustomContentHeight(int);
     method public android.app.Notification.WearableExtender setCustomSizePreset(int);
+    method public android.app.Notification.WearableExtender setDismissalId(java.lang.String);
     method public android.app.Notification.WearableExtender setDisplayIntent(android.app.PendingIntent);
     method public android.app.Notification.WearableExtender setGravity(int);
     method public android.app.Notification.WearableExtender setHintAmbientBigPicture(boolean);
@@ -20729,20 +20730,20 @@
     field public static final int VP8Level_Version2 = 4; // 0x4
     field public static final int VP8Level_Version3 = 8; // 0x8
     field public static final int VP8ProfileMain = 1; // 0x1
-    field public static final int VP9Level1 = 0; // 0x0
-    field public static final int VP9Level11 = 1; // 0x1
-    field public static final int VP9Level2 = 2; // 0x2
-    field public static final int VP9Level21 = 4; // 0x4
-    field public static final int VP9Level3 = 8; // 0x8
-    field public static final int VP9Level31 = 16; // 0x10
-    field public static final int VP9Level4 = 32; // 0x20
-    field public static final int VP9Level41 = 64; // 0x40
-    field public static final int VP9Level5 = 128; // 0x80
-    field public static final int VP9Level51 = 256; // 0x100
-    field public static final int VP9Level52 = 512; // 0x200
-    field public static final int VP9Level6 = 1024; // 0x400
-    field public static final int VP9Level61 = 2048; // 0x800
-    field public static final int VP9Level62 = 4096; // 0x1000
+    field public static final int VP9Level1 = 1; // 0x1
+    field public static final int VP9Level11 = 2; // 0x2
+    field public static final int VP9Level2 = 4; // 0x4
+    field public static final int VP9Level21 = 8; // 0x8
+    field public static final int VP9Level3 = 16; // 0x10
+    field public static final int VP9Level31 = 32; // 0x20
+    field public static final int VP9Level4 = 64; // 0x40
+    field public static final int VP9Level41 = 128; // 0x80
+    field public static final int VP9Level5 = 256; // 0x100
+    field public static final int VP9Level51 = 512; // 0x200
+    field public static final int VP9Level52 = 1024; // 0x400
+    field public static final int VP9Level6 = 2048; // 0x800
+    field public static final int VP9Level61 = 4096; // 0x1000
+    field public static final int VP9Level62 = 8192; // 0x2000
     field public static final int VP9Profile0 = 1; // 0x1
     field public static final int VP9Profile1 = 2; // 0x2
     field public static final int VP9Profile2 = 4; // 0x4
@@ -25011,6 +25012,7 @@
     method public deprecated void enableForegroundNdefPush(android.app.Activity, android.nfc.NdefMessage);
     method public void enableReaderMode(android.app.Activity, android.nfc.NfcAdapter.ReaderCallback, int, android.os.Bundle);
     method public static android.nfc.NfcAdapter getDefaultAdapter(android.content.Context);
+    method public boolean ignore(android.nfc.Tag, int, android.nfc.NfcAdapter.OnTagRemovedListener, android.os.Handler);
     method public boolean invokeBeam(android.app.Activity);
     method public boolean isEnabled();
     method public boolean isNdefPushEnabled();
@@ -25053,6 +25055,10 @@
     method public abstract void onNdefPushComplete(android.nfc.NfcEvent);
   }
 
+  public static abstract interface NfcAdapter.OnTagRemovedListener {
+    method public abstract void onTagRemoved();
+  }
+
   public static abstract interface NfcAdapter.ReaderCallback {
     method public abstract void onTagDiscovered(android.nfc.Tag);
   }
@@ -25069,7 +25075,6 @@
 
   public final class Tag implements android.os.Parcelable {
     method public int describeContents();
-    method public boolean done(int);
     method public byte[] getId();
     method public java.lang.String[] getTechList();
     method public void writeToParcel(android.os.Parcel, int);
diff --git a/api/system-current.txt b/api/system-current.txt
index 3344b52..6b5f1e9 100644
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -2810,7 +2810,7 @@
     method public void addListener(android.accessibilityservice.AccessibilityService.MagnificationController.OnMagnificationChangedListener, android.os.Handler);
     method public float getCenterX();
     method public float getCenterY();
-    method public android.graphics.Region getMagnifiedRegion();
+    method public android.graphics.Region getMagnificationRegion();
     method public float getScale();
     method public boolean removeListener(android.accessibilityservice.AccessibilityService.MagnificationController.OnMagnificationChangedListener);
     method public boolean reset(boolean);
@@ -5067,7 +5067,6 @@
     field public static final int DEFAULT_LIGHTS = 4; // 0x4
     field public static final int DEFAULT_SOUND = 1; // 0x1
     field public static final int DEFAULT_VIBRATE = 2; // 0x2
-    field public static final java.lang.String EXTRA_ALLOW_GENERATED_REPLIES = "android.allowGeneratedReplies";
     field public static final java.lang.String EXTRA_BACKGROUND_IMAGE_URI = "android.backgroundImageUri";
     field public static final java.lang.String EXTRA_BIG_TEXT = "android.bigText";
     field public static final java.lang.String EXTRA_CHRONOMETER_COUNTS_DOWN = "android.chronometerCountsDown";
@@ -5152,6 +5151,7 @@
     ctor public deprecated Notification.Action(int, java.lang.CharSequence, android.app.PendingIntent);
     method public android.app.Notification.Action clone();
     method public int describeContents();
+    method public boolean getAllowGeneratedReplies();
     method public android.os.Bundle getExtras();
     method public android.graphics.drawable.Icon getIcon();
     method public android.app.RemoteInput[] getRemoteInputs();
@@ -5171,6 +5171,7 @@
     method public android.app.Notification.Action build();
     method public android.app.Notification.Action.Builder extend(android.app.Notification.Action.Extender);
     method public android.os.Bundle getExtras();
+    method public android.app.Notification.Action.Builder setAllowGeneratedReplies(boolean);
   }
 
   public static abstract interface Notification.Action.Extender {
@@ -5338,11 +5339,9 @@
     ctor public Notification.MessagingStyle(java.lang.CharSequence);
     method public android.app.Notification.MessagingStyle addMessage(java.lang.CharSequence, long, java.lang.CharSequence);
     method public android.app.Notification.MessagingStyle addMessage(android.app.Notification.MessagingStyle.Message);
-    method public boolean getAllowGeneratedReplies();
     method public java.lang.CharSequence getConversationTitle();
     method public java.util.List<android.app.Notification.MessagingStyle.Message> getMessages();
     method public java.lang.CharSequence getUserDisplayName();
-    method public android.app.Notification.MessagingStyle setAllowGeneratedReplies(boolean);
     method public android.app.Notification.MessagingStyle setConversationTitle(java.lang.CharSequence);
     field public static final int MAXIMUM_RETAINED_MESSAGES = 25; // 0x19
   }
@@ -5387,6 +5386,7 @@
     method public boolean getContentIntentAvailableOffline();
     method public int getCustomContentHeight();
     method public int getCustomSizePreset();
+    method public java.lang.String getDismissalId();
     method public android.app.PendingIntent getDisplayIntent();
     method public int getGravity();
     method public boolean getHintAmbientBigPicture();
@@ -5404,6 +5404,7 @@
     method public android.app.Notification.WearableExtender setContentIntentAvailableOffline(boolean);
     method public android.app.Notification.WearableExtender setCustomContentHeight(int);
     method public android.app.Notification.WearableExtender setCustomSizePreset(int);
+    method public android.app.Notification.WearableExtender setDismissalId(java.lang.String);
     method public android.app.Notification.WearableExtender setDisplayIntent(android.app.PendingIntent);
     method public android.app.Notification.WearableExtender setGravity(int);
     method public android.app.Notification.WearableExtender setHintAmbientBigPicture(boolean);
@@ -22249,20 +22250,20 @@
     field public static final int VP8Level_Version2 = 4; // 0x4
     field public static final int VP8Level_Version3 = 8; // 0x8
     field public static final int VP8ProfileMain = 1; // 0x1
-    field public static final int VP9Level1 = 0; // 0x0
-    field public static final int VP9Level11 = 1; // 0x1
-    field public static final int VP9Level2 = 2; // 0x2
-    field public static final int VP9Level21 = 4; // 0x4
-    field public static final int VP9Level3 = 8; // 0x8
-    field public static final int VP9Level31 = 16; // 0x10
-    field public static final int VP9Level4 = 32; // 0x20
-    field public static final int VP9Level41 = 64; // 0x40
-    field public static final int VP9Level5 = 128; // 0x80
-    field public static final int VP9Level51 = 256; // 0x100
-    field public static final int VP9Level52 = 512; // 0x200
-    field public static final int VP9Level6 = 1024; // 0x400
-    field public static final int VP9Level61 = 2048; // 0x800
-    field public static final int VP9Level62 = 4096; // 0x1000
+    field public static final int VP9Level1 = 1; // 0x1
+    field public static final int VP9Level11 = 2; // 0x2
+    field public static final int VP9Level2 = 4; // 0x4
+    field public static final int VP9Level21 = 8; // 0x8
+    field public static final int VP9Level3 = 16; // 0x10
+    field public static final int VP9Level31 = 32; // 0x20
+    field public static final int VP9Level4 = 64; // 0x40
+    field public static final int VP9Level41 = 128; // 0x80
+    field public static final int VP9Level5 = 256; // 0x100
+    field public static final int VP9Level51 = 512; // 0x200
+    field public static final int VP9Level52 = 1024; // 0x400
+    field public static final int VP9Level6 = 2048; // 0x800
+    field public static final int VP9Level61 = 4096; // 0x1000
+    field public static final int VP9Level62 = 8192; // 0x2000
     field public static final int VP9Profile0 = 1; // 0x1
     field public static final int VP9Profile1 = 2; // 0x2
     field public static final int VP9Profile2 = 4; // 0x4
@@ -26170,8 +26171,12 @@
     method public static void logEvent(int, long, int, int);
     method public void writeToParcel(android.os.Parcel, int);
     field public static final android.os.Parcelable.Creator<android.net.metrics.ValidationProbeEvent> CREATOR;
-    field public static final int PROBE_HTTP = 0; // 0x0
-    field public static final int PROBE_HTTPS = 1; // 0x1
+    field public static final int DNS_FAILURE = 0; // 0x0
+    field public static final int DNS_SUCCESS = 1; // 0x1
+    field public static final int PROBE_DNS = 0; // 0x0
+    field public static final int PROBE_HTTP = 1; // 0x1
+    field public static final int PROBE_HTTPS = 2; // 0x2
+    field public static final int PROBE_PAC = 3; // 0x3
     field public final long durationMs;
     field public final int netId;
     field public final int probeType;
@@ -27443,6 +27448,7 @@
     method public boolean enableNdefPush();
     method public void enableReaderMode(android.app.Activity, android.nfc.NfcAdapter.ReaderCallback, int, android.os.Bundle);
     method public static android.nfc.NfcAdapter getDefaultAdapter(android.content.Context);
+    method public boolean ignore(android.nfc.Tag, int, android.nfc.NfcAdapter.OnTagRemovedListener, android.os.Handler);
     method public boolean invokeBeam(android.app.Activity);
     method public boolean isEnabled();
     method public boolean isNdefPushEnabled();
@@ -27492,6 +27498,10 @@
     method public abstract void onNdefPushComplete(android.nfc.NfcEvent);
   }
 
+  public static abstract interface NfcAdapter.OnTagRemovedListener {
+    method public abstract void onTagRemoved();
+  }
+
   public static abstract interface NfcAdapter.ReaderCallback {
     method public abstract void onTagDiscovered(android.nfc.Tag);
   }
@@ -27508,7 +27518,6 @@
 
   public final class Tag implements android.os.Parcelable {
     method public int describeContents();
-    method public boolean done(int);
     method public byte[] getId();
     method public java.lang.String[] getTechList();
     method public void writeToParcel(android.os.Parcel, int);
diff --git a/api/test-current.txt b/api/test-current.txt
index a0ca0f4..ae58f36 100644
--- a/api/test-current.txt
+++ b/api/test-current.txt
@@ -2699,7 +2699,7 @@
     method public void addListener(android.accessibilityservice.AccessibilityService.MagnificationController.OnMagnificationChangedListener, android.os.Handler);
     method public float getCenterX();
     method public float getCenterY();
-    method public android.graphics.Region getMagnifiedRegion();
+    method public android.graphics.Region getMagnificationRegion();
     method public float getScale();
     method public boolean removeListener(android.accessibilityservice.AccessibilityService.MagnificationController.OnMagnificationChangedListener);
     method public boolean reset(boolean);
@@ -4924,7 +4924,6 @@
     field public static final int DEFAULT_LIGHTS = 4; // 0x4
     field public static final int DEFAULT_SOUND = 1; // 0x1
     field public static final int DEFAULT_VIBRATE = 2; // 0x2
-    field public static final java.lang.String EXTRA_ALLOW_GENERATED_REPLIES = "android.allowGeneratedReplies";
     field public static final java.lang.String EXTRA_BACKGROUND_IMAGE_URI = "android.backgroundImageUri";
     field public static final java.lang.String EXTRA_BIG_TEXT = "android.bigText";
     field public static final java.lang.String EXTRA_CHRONOMETER_COUNTS_DOWN = "android.chronometerCountsDown";
@@ -5007,6 +5006,7 @@
     ctor public deprecated Notification.Action(int, java.lang.CharSequence, android.app.PendingIntent);
     method public android.app.Notification.Action clone();
     method public int describeContents();
+    method public boolean getAllowGeneratedReplies();
     method public android.os.Bundle getExtras();
     method public android.graphics.drawable.Icon getIcon();
     method public android.app.RemoteInput[] getRemoteInputs();
@@ -5026,6 +5026,7 @@
     method public android.app.Notification.Action build();
     method public android.app.Notification.Action.Builder extend(android.app.Notification.Action.Extender);
     method public android.os.Bundle getExtras();
+    method public android.app.Notification.Action.Builder setAllowGeneratedReplies(boolean);
   }
 
   public static abstract interface Notification.Action.Extender {
@@ -5193,11 +5194,9 @@
     ctor public Notification.MessagingStyle(java.lang.CharSequence);
     method public android.app.Notification.MessagingStyle addMessage(java.lang.CharSequence, long, java.lang.CharSequence);
     method public android.app.Notification.MessagingStyle addMessage(android.app.Notification.MessagingStyle.Message);
-    method public boolean getAllowGeneratedReplies();
     method public java.lang.CharSequence getConversationTitle();
     method public java.util.List<android.app.Notification.MessagingStyle.Message> getMessages();
     method public java.lang.CharSequence getUserDisplayName();
-    method public android.app.Notification.MessagingStyle setAllowGeneratedReplies(boolean);
     method public android.app.Notification.MessagingStyle setConversationTitle(java.lang.CharSequence);
     field public static final int MAXIMUM_RETAINED_MESSAGES = 25; // 0x19
   }
@@ -5242,6 +5241,7 @@
     method public boolean getContentIntentAvailableOffline();
     method public int getCustomContentHeight();
     method public int getCustomSizePreset();
+    method public java.lang.String getDismissalId();
     method public android.app.PendingIntent getDisplayIntent();
     method public int getGravity();
     method public boolean getHintAmbientBigPicture();
@@ -5259,6 +5259,7 @@
     method public android.app.Notification.WearableExtender setContentIntentAvailableOffline(boolean);
     method public android.app.Notification.WearableExtender setCustomContentHeight(int);
     method public android.app.Notification.WearableExtender setCustomSizePreset(int);
+    method public android.app.Notification.WearableExtender setDismissalId(java.lang.String);
     method public android.app.Notification.WearableExtender setDisplayIntent(android.app.PendingIntent);
     method public android.app.Notification.WearableExtender setGravity(int);
     method public android.app.Notification.WearableExtender setHintAmbientBigPicture(boolean);
@@ -20797,20 +20798,20 @@
     field public static final int VP8Level_Version2 = 4; // 0x4
     field public static final int VP8Level_Version3 = 8; // 0x8
     field public static final int VP8ProfileMain = 1; // 0x1
-    field public static final int VP9Level1 = 0; // 0x0
-    field public static final int VP9Level11 = 1; // 0x1
-    field public static final int VP9Level2 = 2; // 0x2
-    field public static final int VP9Level21 = 4; // 0x4
-    field public static final int VP9Level3 = 8; // 0x8
-    field public static final int VP9Level31 = 16; // 0x10
-    field public static final int VP9Level4 = 32; // 0x20
-    field public static final int VP9Level41 = 64; // 0x40
-    field public static final int VP9Level5 = 128; // 0x80
-    field public static final int VP9Level51 = 256; // 0x100
-    field public static final int VP9Level52 = 512; // 0x200
-    field public static final int VP9Level6 = 1024; // 0x400
-    field public static final int VP9Level61 = 2048; // 0x800
-    field public static final int VP9Level62 = 4096; // 0x1000
+    field public static final int VP9Level1 = 1; // 0x1
+    field public static final int VP9Level11 = 2; // 0x2
+    field public static final int VP9Level2 = 4; // 0x4
+    field public static final int VP9Level21 = 8; // 0x8
+    field public static final int VP9Level3 = 16; // 0x10
+    field public static final int VP9Level31 = 32; // 0x20
+    field public static final int VP9Level4 = 64; // 0x40
+    field public static final int VP9Level41 = 128; // 0x80
+    field public static final int VP9Level5 = 256; // 0x100
+    field public static final int VP9Level51 = 512; // 0x200
+    field public static final int VP9Level52 = 1024; // 0x400
+    field public static final int VP9Level6 = 2048; // 0x800
+    field public static final int VP9Level61 = 4096; // 0x1000
+    field public static final int VP9Level62 = 8192; // 0x2000
     field public static final int VP9Profile0 = 1; // 0x1
     field public static final int VP9Profile1 = 2; // 0x2
     field public static final int VP9Profile2 = 4; // 0x4
@@ -25079,6 +25080,7 @@
     method public deprecated void enableForegroundNdefPush(android.app.Activity, android.nfc.NdefMessage);
     method public void enableReaderMode(android.app.Activity, android.nfc.NfcAdapter.ReaderCallback, int, android.os.Bundle);
     method public static android.nfc.NfcAdapter getDefaultAdapter(android.content.Context);
+    method public boolean ignore(android.nfc.Tag, int, android.nfc.NfcAdapter.OnTagRemovedListener, android.os.Handler);
     method public boolean invokeBeam(android.app.Activity);
     method public boolean isEnabled();
     method public boolean isNdefPushEnabled();
@@ -25121,6 +25123,10 @@
     method public abstract void onNdefPushComplete(android.nfc.NfcEvent);
   }
 
+  public static abstract interface NfcAdapter.OnTagRemovedListener {
+    method public abstract void onTagRemoved();
+  }
+
   public static abstract interface NfcAdapter.ReaderCallback {
     method public abstract void onTagDiscovered(android.nfc.Tag);
   }
@@ -25137,7 +25143,6 @@
 
   public final class Tag implements android.os.Parcelable {
     method public int describeContents();
-    method public boolean done(int);
     method public byte[] getId();
     method public java.lang.String[] getTechList();
     method public void writeToParcel(android.os.Parcel, int);
diff --git a/cmds/app_process/Android.mk b/cmds/app_process/Android.mk
index 3ae9e12..fae0400 100644
--- a/cmds/app_process/Android.mk
+++ b/cmds/app_process/Android.mk
@@ -53,7 +53,6 @@
     libutils \
     liblog \
     libbinder \
-    libnativeloader \
     libandroid_runtime \
     $(app_process_common_shared_libs) \
 
diff --git a/cmds/app_process/app_main.cpp b/cmds/app_process/app_main.cpp
index 7590325..2e02382 100644
--- a/cmds/app_process/app_main.cpp
+++ b/cmds/app_process/app_main.cpp
@@ -21,7 +21,6 @@
 #include <cutils/properties.h>
 #include <cutils/trace.h>
 #include <android_runtime/AndroidRuntime.h>
-#include <nativeloader/native_loader.h>
 #include <private/android_filesystem_config.h>  // for AID_SYSTEM
 
 namespace android {
@@ -305,7 +304,6 @@
     }
 
     if (zygote) {
-        InitializeNativeLoader();
         runtime.start("com.android.internal.os.ZygoteInit", args, zygote);
     } else if (className) {
         runtime.start("com.android.internal.os.RuntimeInit", args, zygote);
diff --git a/core/java/android/accessibilityservice/AccessibilityService.java b/core/java/android/accessibilityservice/AccessibilityService.java
index 56728ad..8b277b2 100644
--- a/core/java/android/accessibilityservice/AccessibilityService.java
+++ b/core/java/android/accessibilityservice/AccessibilityService.java
@@ -925,18 +925,25 @@
         }
 
         /**
-         * Returns the region of the screen currently being magnified. If
-         * magnification is not enabled, the returned region will be empty.
+         * Returns the region of the screen currently active for magnification. Changes to
+         * magnification scale and center only affect this portion of the screen. The rest of the
+         * screen, for example input methods, cannot be magnified. This region is relative to the
+         * unscaled screen and is independent of the scale and center point.
+         * <p>
+         * The returned region will be empty if magnification is not active. Magnification is active
+         * if magnification gestures are enabled or if a service is running that can control
+         * magnification.
          * <p>
          * <strong>Note:</strong> If the service is not yet connected (e.g.
          * {@link AccessibilityService#onServiceConnected()} has not yet been
          * called) or the service has been disconnected, this method will
          * return an empty region.
          *
-         * @return the screen-relative bounds of the magnified region
+         * @return the region of the screen currently active for magnification, or an empty region
+         * if magnification is not active.
          */
         @NonNull
-        public Region getMagnifiedRegion() {
+        public Region getMagnificationRegion() {
             final IAccessibilityServiceConnection connection =
                     AccessibilityInteractionClient.getInstance().getConnection(
                             mService.mConnectionId);
@@ -1049,11 +1056,12 @@
              * Called when the magnified region, scale, or center changes.
              *
              * @param controller the magnification controller
-             * @param region the new magnified region, may be empty if
-             *               magnification is not enabled (e.g. scale is 1)
+             * @param region the magnification region
              * @param scale the new scale
-             * @param centerX the new X coordinate around which magnification is focused
-             * @param centerY the new Y coordinate around which magnification is focused
+             * @param centerX the new X coordinate, in unscaled coordinates, around which
+             * magnification is focused
+             * @param centerY the new Y coordinate, in unscaled coordinates, around which
+             * magnification is focused
              */
             void onMagnificationChanged(@NonNull MagnificationController controller,
                     @NonNull Region region, float scale, float centerX, float centerY);
diff --git a/core/java/android/accessibilityservice/GestureDescription.java b/core/java/android/accessibilityservice/GestureDescription.java
index e18a34d..fc9581e 100644
--- a/core/java/android/accessibilityservice/GestureDescription.java
+++ b/core/java/android/accessibilityservice/GestureDescription.java
@@ -18,7 +18,6 @@
 
 import android.annotation.IntRange;
 import android.annotation.NonNull;
-import android.graphics.Matrix;
 import android.graphics.Path;
 import android.graphics.PathMeasure;
 import android.graphics.RectF;
@@ -26,10 +25,8 @@
 import android.view.MotionEvent;
 import android.view.MotionEvent.PointerCoords;
 import android.view.MotionEvent.PointerProperties;
-import android.view.ViewConfiguration;
 
 import java.util.ArrayList;
-import java.util.Arrays;
 import java.util.List;
 
 /**
@@ -160,9 +157,10 @@
         private final List<StrokeDescription> mStrokes = new ArrayList<>();
 
         /**
-         * Add a stroke to the gesture description. Up to {@code MAX_STROKE_COUNT} paths may be
-         * added to a gesture, and the total gesture duration (earliest path start time to latest path
-         * end time) may not exceed {@code MAX_GESTURE_DURATION_MS}.
+         * Add a stroke to the gesture description. Up to
+         * {@link GestureDescription#getMaxStrokeCount()} paths may be
+         * added to a gesture, and the total gesture duration (earliest path start time to latest
+         * path end time) may not exceed {@link GestureDescription#getMaxGestureDuration()}.
          *
          * @param strokeDescription the stroke to add.
          *
@@ -201,10 +199,13 @@
         long mEndTime;
         private float mTimeToLengthConversion;
         private PathMeasure mPathMeasure;
+        // The tap location is only set for zero-length paths
+        float[] mTapLocation;
 
         /**
-         * @param path The path to follow. Must have exactly one contour, and that contour must
-         * have nonzero length. The bounds of the path must not be negative.
+         * @param path The path to follow. Must have exactly one contour. The bounds of the path
+         * must not be negative. The path must not be empty. If the path has zero length
+         * (for example, a single {@code moveTo()}), the stroke is a touch that doesn't move.
          * @param startTime The time, in milliseconds, from the time the gesture starts to the
          * time the stroke should start. Must not be negative.
          * @param duration The duration, in milliseconds, the stroke takes to traverse the path.
@@ -225,10 +226,18 @@
                     || (bounds.left < 0)) {
                 throw new IllegalArgumentException("Path bounds must not be negative");
             }
+            if (path.isEmpty()) {
+                throw new IllegalArgumentException("Path is empty");
+            }
             mPath = new Path(path);
             mPathMeasure = new PathMeasure(path, false);
             if (mPathMeasure.getLength() == 0) {
-                throw new IllegalArgumentException("Path has zero length");
+                // Treat zero-length paths as taps
+                Path tempPath = new Path(path);
+                tempPath.lineTo(-1, -1);
+                mTapLocation = new float[2];
+                PathMeasure pathMeasure = new PathMeasure(tempPath, false);
+                pathMeasure.getPosTan(0, mTapLocation, null);
             }
             if (mPathMeasure.nextContour()) {
                 throw new IllegalArgumentException("Path has more than one contour");
@@ -237,12 +246,10 @@
              * Calling nextContour has moved mPathMeasure off the first contour, which is the only
              * one we care about. Set the path again to go back to the first contour.
              */
-            mPathMeasure.setPath(path, false);
+            mPathMeasure.setPath(mPath, false);
             mStartTime = startTime;
             mEndTime = startTime + duration;
-            if (duration > 0) {
-                mTimeToLengthConversion = getLength() / duration;
-            }
+            mTimeToLengthConversion = getLength() / duration;
         }
 
         /**
@@ -278,6 +285,11 @@
 
         /* Assumes hasPointForTime returns true */
         boolean getPosForTime(long time, float[] pos) {
+            if (mTapLocation != null) {
+                pos[0] = mTapLocation[0];
+                pos[1] = mTapLocation[1];
+                return true;
+            }
             if (time == mEndTime) {
                 // Close to the end time, roundoff can be a problem
                 return mPathMeasure.getPosTan(getLength(), pos, null);
diff --git a/core/java/android/animation/ObjectAnimator.java b/core/java/android/animation/ObjectAnimator.java
index 542ecf4..1d10860 100644
--- a/core/java/android/animation/ObjectAnimator.java
+++ b/core/java/android/animation/ObjectAnimator.java
@@ -585,6 +585,11 @@
      * 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
+     * affect the values on the animator. If the objects will be mutated externally after
+     * this method is called, callers should pass a copy of those objects instead.
+     *
      * @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
      * the value of the <code>propertyName</code> parameter.
@@ -635,6 +640,11 @@
      * 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
+     * affect the values on the animator. If the objects will be mutated externally after
+     * this method is called, callers should pass a copy of those objects instead.
+     *
      * @param target The object whose property is to be animated.
      * @param property The property being animated.
      * @param evaluator A TypeEvaluator that will be called on each animation frame to
@@ -663,6 +673,11 @@
      * 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
+     * objects, which means that changes to those objects after this method is called will
+     * affect the values on the animator. If the objects will be mutated externally after
+     * this method is called, callers should pass a copy of those objects instead.
+     *
      * @param target The object whose property is to be animated.
      * @param property The property being animated.
      * @param converter Converts the animated object to the Property type.
diff --git a/core/java/android/animation/PropertyValuesHolder.java b/core/java/android/animation/PropertyValuesHolder.java
index ffea6f5..224823e 100644
--- a/core/java/android/animation/PropertyValuesHolder.java
+++ b/core/java/android/animation/PropertyValuesHolder.java
@@ -388,6 +388,11 @@
      * set of Object values. This variant also takes a TypeEvaluator because the system
      * cannot automatically interpolate between objects of unknown type.
      *
+     * <p><strong>Note:</strong> The Object values are stored as references to the original
+     * objects, which means that changes to those objects after this method is called will
+     * affect the values on the PropertyValuesHolder. If the objects will be mutated externally
+     * after this method is called, callers should pass a copy of those objects instead.
+     *
      * @param propertyName The name of the property being animated.
      * @param evaluator A TypeEvaluator that will be called on each animation frame to
      * provide the necessary interpolation between the Object values to derive the animated
@@ -433,6 +438,11 @@
      * set of Object values. This variant also takes a TypeEvaluator because the system
      * cannot automatically interpolate between objects of unknown type.
      *
+     * <p><strong>Note:</strong> The Object values are stored as references to the original
+     * objects, which means that changes to those objects after this method is called will
+     * affect the values on the PropertyValuesHolder. If the objects will be mutated externally
+     * after this method is called, callers should pass a copy of those objects instead.
+     *
      * @param property The property being animated. Should not be null.
      * @param evaluator A TypeEvaluator that will be called on each animation frame to
      * provide the necessary interpolation between the Object values to derive the animated
@@ -458,6 +468,11 @@
      * must be a {@link android.animation.BidirectionalTypeConverter} to retrieve the current
      * value.
      *
+     * <p><strong>Note:</strong> The Object values are stored as references to the original
+     * objects, which means that changes to those objects after this method is called will
+     * affect the values on the PropertyValuesHolder. If the objects will be mutated externally
+     * after this method is called, callers should pass a copy of those objects instead.
+     *
      * @param property The property being animated. Should not be null.
      * @param converter Converts the animated object to the Property type.
      * @param evaluator A TypeEvaluator that will be called on each animation frame to
@@ -636,7 +651,12 @@
      * {@link ObjectAnimator}, and with a getter function
      * derived automatically from <code>propertyName</code>, since otherwise PropertyValuesHolder has
      * no way of determining what the value should be.
-     * 
+     *
+     * <p><strong>Note:</strong> The Object values are stored as references to the original
+     * objects, which means that changes to those objects after this method is called will
+     * affect the values on the PropertyValuesHolder. If the objects will be mutated externally
+     * after this method is called, callers should pass a copy of those objects instead.
+     *
      * @param values One or more values that the animation will animate between.
      */
     public void setObjectValues(Object... values) {
diff --git a/core/java/android/animation/ValueAnimator.java b/core/java/android/animation/ValueAnimator.java
index 31035a7..0a9b5de 100644
--- a/core/java/android/animation/ValueAnimator.java
+++ b/core/java/android/animation/ValueAnimator.java
@@ -353,6 +353,11 @@
      * from the target object and property being animated). Therefore, there should typically
      * be two or more values.
      *
+     * <p><strong>Note:</strong> The Object values are stored as references to the original
+     * objects, which means that changes to those objects after this method is called will
+     * affect the values on the animator. If the objects will be mutated externally after
+     * this method is called, callers should pass a copy of those objects instead.
+     *
      * <p>Since ValueAnimator does not know how to animate between arbitrary Objects, this
      * factory method also takes a TypeEvaluator object that the ValueAnimator will use
      * to perform that interpolation.
@@ -434,6 +439,11 @@
      * from the target object and property being animated). Therefore, there should typically
      * be two or more values.
      *
+     * <p><strong>Note:</strong> The Object values are stored as references to the original
+     * objects, which means that changes to those objects after this method is called will
+     * affect the values on the animator. If the objects will be mutated externally after
+     * this method is called, callers should pass a copy of those objects instead.
+     *
      * <p>If there are already multiple sets of values defined for this ValueAnimator via more
      * than one PropertyValuesHolder object, this method will set the values for the first
      * of those objects.</p>
diff --git a/core/java/android/app/ActivityManager.java b/core/java/android/app/ActivityManager.java
index d440017..ff8cf66 100644
--- a/core/java/android/app/ActivityManager.java
+++ b/core/java/android/app/ActivityManager.java
@@ -3430,6 +3430,8 @@
     public static final int FLAG_AND_LOCKED = 1 << 1;
     /** {@hide} */
     public static final int FLAG_AND_UNLOCKED = 1 << 2;
+    /** {@hide} */
+    public static final int FLAG_AND_UNLOCKING_OR_UNLOCKED = 1 << 3;
 
     /**
      * Return whether the given user is actively running.  This means that
@@ -3449,26 +3451,6 @@
     }
 
     /** {@hide} */
-    public boolean isUserRunningAndLocked(int userId) {
-        try {
-            return ActivityManagerNative.getDefault().isUserRunning(userId,
-                    ActivityManager.FLAG_AND_LOCKED);
-        } catch (RemoteException e) {
-            throw e.rethrowFromSystemServer();
-        }
-    }
-
-    /** {@hide} */
-    public boolean isUserRunningAndUnlocked(int userId) {
-        try {
-            return ActivityManagerNative.getDefault().isUserRunning(userId,
-                    ActivityManager.FLAG_AND_UNLOCKED);
-        } catch (RemoteException e) {
-            throw e.rethrowFromSystemServer();
-        }
-    }
-
-    /** {@hide} */
     public boolean isVrModePackageEnabled(ComponentName component) {
         try {
             return ActivityManagerNative.getDefault().isVrModePackageEnabled(component);
diff --git a/core/java/android/app/ActivityOptions.java b/core/java/android/app/ActivityOptions.java
index 2846798..051295e 100644
--- a/core/java/android/app/ActivityOptions.java
+++ b/core/java/android/app/ActivityOptions.java
@@ -160,6 +160,12 @@
     private static final String KEY_LAUNCH_TASK_ID = "android.activity.launchTaskId";
 
     /**
+     * See {@link #setAvoidMoveToFront}.
+     * @hide
+     */
+    private static final String KEY_DONT_MOVE_TO_FRONT = "android.activity.dontMoveToFront";
+
+    /**
      * Where the docked stack should be positioned.
      * @hide
      */
@@ -232,6 +238,7 @@
     private int mLaunchStackId = INVALID_STACK_ID;
     private int mLaunchTaskId = -1;
     private int mDockCreateMode = DOCKED_STACK_CREATE_MODE_TOP_OR_LEFT;
+    private boolean mAvoidMoveToFront;
     private AppTransitionAnimationSpec mAnimSpecs[];
 
     /**
@@ -774,6 +781,7 @@
         }
         mLaunchStackId = opts.getInt(KEY_LAUNCH_STACK_ID, INVALID_STACK_ID);
         mLaunchTaskId = opts.getInt(KEY_LAUNCH_TASK_ID, -1);
+        mAvoidMoveToFront = opts.getBoolean(KEY_DONT_MOVE_TO_FRONT, false);
         mDockCreateMode = opts.getInt(KEY_DOCK_CREATE_MODE, DOCKED_STACK_CREATE_MODE_TOP_OR_LEFT);
         if (opts.containsKey(KEY_ANIM_SPECS)) {
             Parcelable[] specs = opts.getParcelableArray(KEY_ANIM_SPECS);
@@ -950,6 +958,23 @@
         return mLaunchTaskId;
     }
 
+    /**
+     * Set's whether the task should be moved to the front. This is different from
+     * {@link #getLaunchTaskBehind()} as we don't want to have an animation at all when launching
+     * an activity that shouldn't be moved to the front.
+     * @hide
+     */
+    public void setAvoidMoveToFront(boolean avoidMoveToFront) {
+        mAvoidMoveToFront = avoidMoveToFront;
+    }
+
+    /**
+     * @hide
+     */
+    public boolean getAvoidMoveToFront() {
+        return mAvoidMoveToFront;
+    }
+
     /** @hide */
     public int getDockCreateMode() {
         return mDockCreateMode;
@@ -1103,6 +1128,7 @@
         }
         b.putInt(KEY_LAUNCH_STACK_ID, mLaunchStackId);
         b.putInt(KEY_LAUNCH_TASK_ID, mLaunchTaskId);
+        b.putBoolean(KEY_DONT_MOVE_TO_FRONT, mAvoidMoveToFront);
         b.putInt(KEY_DOCK_CREATE_MODE, mDockCreateMode);
         if (mAnimSpecs != null) {
             b.putParcelableArray(KEY_ANIM_SPECS, mAnimSpecs);
diff --git a/core/java/android/app/ActivityThread.java b/core/java/android/app/ActivityThread.java
index 0764ff4..6d805ed 100644
--- a/core/java/android/app/ActivityThread.java
+++ b/core/java/android/app/ActivityThread.java
@@ -3479,7 +3479,9 @@
                     // the decor view we have to notify the view root that the
                     // callbacks may have changed.
                     ViewRootImpl impl = decor.getViewRootImpl();
-                    impl.notifyChildRebuilt();
+                    if (impl != null) {
+                        impl.notifyChildRebuilt();
+                    }
                 }
                 if (a.mVisibleFromClient && !a.mWindowAdded) {
                     a.mWindowAdded = true;
@@ -4615,16 +4617,7 @@
             // onConfigurationChanged
             int diff = activity.mCurrentConfig.diff(newConfig);
             if (diff != 0) {
-                // If this activity doesn't handle any of the config changes then don't bother
-                // calling onConfigurationChanged as we're going to destroy it.
-                // Except in the case where the configuration changed on the activity manager side,
-                // but wasn't big enough to cause a resource change so the activity wasn't destroyed.
-                // In this case we still want to change the configuration of the activity but not
-                // report it to the app.
-                if ((~activity.mActivityInfo.getRealConfigChanged() & diff) == 0
-                        || !reportToActivity) {
-                    shouldChangeConfig = true;
-                }
+                shouldChangeConfig = true;
             }
         }
 
diff --git a/core/java/android/app/Notification.java b/core/java/android/app/Notification.java
index d7705b9..0c2e3c1 100644
--- a/core/java/android/app/Notification.java
+++ b/core/java/android/app/Notification.java
@@ -939,14 +939,6 @@
     public static final String EXTRA_SELF_DISPLAY_NAME = "android.selfDisplayName";
 
     /**
-     * {@link #extras} key: a boolean describing whether the platform should automatically
-     * generate possible replies to
-     * {@link android.app.Notification.MessagingStyle.Message} objects provided by a
-     * {@link android.app.Notification.MessagingStyle} notification.
-     */
-    public static final String EXTRA_ALLOW_GENERATED_REPLIES = "android.allowGeneratedReplies";
-
-    /**
      * {@link #extras} key: a {@link String} to be displayed as the title to a conversation
      * represented by a {@link android.app.Notification.MessagingStyle}
      */
@@ -996,6 +988,7 @@
         private final Bundle mExtras;
         private Icon mIcon;
         private final RemoteInput[] mRemoteInputs;
+        private boolean mAllowGeneratedReplies = false;
 
         /**
          * Small icon representing the action.
@@ -1029,6 +1022,7 @@
             }
             mExtras = Bundle.setDefusable(in.readBundle(), true);
             mRemoteInputs = in.createTypedArray(RemoteInput.CREATOR);
+            mAllowGeneratedReplies = in.readInt() == 1;
         }
 
         /**
@@ -1036,11 +1030,11 @@
          */
         @Deprecated
         public Action(int icon, CharSequence title, PendingIntent intent) {
-            this(Icon.createWithResource("", icon), title, intent, new Bundle(), null);
+            this(Icon.createWithResource("", icon), title, intent, new Bundle(), null, false);
         }
 
         private Action(Icon icon, CharSequence title, PendingIntent intent, Bundle extras,
-                RemoteInput[] remoteInputs) {
+                RemoteInput[] remoteInputs, boolean allowGeneratedReplies) {
             this.mIcon = icon;
             if (icon != null && icon.getType() == Icon.TYPE_RESOURCE) {
                 this.icon = icon.getResId();
@@ -1049,6 +1043,7 @@
             this.actionIntent = intent;
             this.mExtras = extras != null ? extras : new Bundle();
             this.mRemoteInputs = remoteInputs;
+            this.mAllowGeneratedReplies = allowGeneratedReplies;
         }
 
         /**
@@ -1070,6 +1065,14 @@
         }
 
         /**
+         * Return whether the platform should automatically generate possible replies for this
+         * {@link Action}
+         */
+        public boolean getAllowGeneratedReplies() {
+            return mAllowGeneratedReplies;
+        }
+
+        /**
          * Get the list of inputs to be collected from the user when this action is sent.
          * May return null if no remote inputs were added.
          */
@@ -1084,6 +1087,7 @@
             private final Icon mIcon;
             private final CharSequence mTitle;
             private final PendingIntent mIntent;
+            private boolean mAllowGeneratedReplies;
             private final Bundle mExtras;
             private ArrayList<RemoteInput> mRemoteInputs;
 
@@ -1169,6 +1173,20 @@
             }
 
             /**
+             * Set whether the platform should automatically generate possible replies to add to
+             * {@link RemoteInput#getChoices()}. If the {@link Action} doesn't have a
+             * {@link RemoteInput}, this has no effect.
+             * @param allowGeneratedReplies {@code true} to allow generated replies, {@code false}
+             * otherwise
+             * @return this object for method chaining
+             * The default value is {@code false}
+             */
+            public Builder setAllowGeneratedReplies(boolean allowGeneratedReplies) {
+                mAllowGeneratedReplies = allowGeneratedReplies;
+                return this;
+            }
+
+            /**
              * Apply an extender to this action builder. Extenders may be used to add
              * metadata or change options on this builder.
              */
@@ -1185,7 +1203,8 @@
             public Action build() {
                 RemoteInput[] remoteInputs = mRemoteInputs != null
                         ? mRemoteInputs.toArray(new RemoteInput[mRemoteInputs.size()]) : null;
-                return new Action(mIcon, mTitle, mIntent, mExtras, remoteInputs);
+                return new Action(mIcon, mTitle, mIntent, mExtras, remoteInputs,
+                        mAllowGeneratedReplies);
             }
         }
 
@@ -1196,7 +1215,8 @@
                     title,
                     actionIntent, // safe to alias
                     new Bundle(mExtras),
-                    getRemoteInputs());
+                    getRemoteInputs(),
+                    getAllowGeneratedReplies());
         }
         @Override
         public int describeContents() {
@@ -1220,6 +1240,7 @@
             }
             out.writeBundle(mExtras);
             out.writeTypedArray(mRemoteInputs, flags);
+            out.writeInt(mAllowGeneratedReplies ? 1 : 0);
         }
         public static final Parcelable.Creator<Action> CREATOR =
                 new Parcelable.Creator<Action>() {
@@ -3351,7 +3372,8 @@
         }
 
         private void resetStandardTemplateWithActions(RemoteViews big) {
-            big.setViewVisibility(R.id.actions_container, View.GONE);
+            // actions_container is only reset when there are no actions to avoid focus issues with
+            // remote inputs.
             big.setViewVisibility(R.id.actions, View.GONE);
             big.removeAllViews(R.id.actions);
 
@@ -3396,6 +3418,8 @@
                     }
                     big.addView(R.id.actions, button);
                 }
+            } else {
+                big.setViewVisibility(R.id.actions_container, View.GONE);
             }
 
             CharSequence[] replyText = mN.extras.getCharSequenceArray(EXTRA_REMOTE_INPUT_HISTORY);
@@ -4265,15 +4289,19 @@
         public RemoteViews makeBigContentView() {
 
             // Nasty
-            CharSequence oldBuilderContentText =
-                    mBuilder.getAllExtras().getCharSequence(EXTRA_TEXT);
+            CharSequence text = mBuilder.getAllExtras().getCharSequence(EXTRA_TEXT);
             mBuilder.getAllExtras().putCharSequence(EXTRA_TEXT, null);
 
             RemoteViews contentView = getStandardView(mBuilder.getBigTextLayoutResource());
 
-            mBuilder.getAllExtras().putCharSequence(EXTRA_TEXT, oldBuilderContentText);
+            mBuilder.getAllExtras().putCharSequence(EXTRA_TEXT, text);
 
             CharSequence bigTextText = mBuilder.processLegacyText(mBigText);
+            if (TextUtils.isEmpty(bigTextText)) {
+                // In case the bigtext is null / empty fall back to the normal text to avoid a weird
+                // 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);
@@ -4326,7 +4354,6 @@
 
         CharSequence mUserDisplayName;
         CharSequence mConversationTitle;
-        boolean mAllowGeneratedReplies = true;
         List<Message> mMessages = new ArrayList<>();
 
         MessagingStyle() {
@@ -4350,25 +4377,6 @@
         }
 
         /**
-         * Set whether the platform should automatically generate possible replies from messages.
-         * @param allowGeneratedReplies {@code true} to allow generated replies, {@code false}
-         * otherwise
-         * @return this object for method chaining
-         * The default value is {@code true}
-         */
-        public MessagingStyle setAllowGeneratedReplies(boolean allowGeneratedReplies) {
-            mAllowGeneratedReplies = allowGeneratedReplies;
-            return this;
-        }
-
-        /**
-         * Return whether the platform should automatically generate possible replies from messages.
-         */
-        public boolean getAllowGeneratedReplies() {
-            return mAllowGeneratedReplies;
-        }
-
-        /**
          * Sets the title to be displayed on this conversation. This should only be used for
          * group messaging and left unset for one-on-one conversations.
          * @param conversationTitle
@@ -4442,7 +4450,6 @@
             if (mConversationTitle != null) {
                 extras.putCharSequence(EXTRA_CONVERSATION_TITLE, mConversationTitle);
             }
-            extras.putBoolean(EXTRA_ALLOW_GENERATED_REPLIES, mAllowGeneratedReplies);
             if (!mMessages.isEmpty()) { extras.putParcelableArray(EXTRA_MESSAGES,
                     Message.getBundleArrayForMessages(mMessages));
             }
@@ -4458,11 +4465,9 @@
             mMessages.clear();
             mUserDisplayName = extras.getString(EXTRA_SELF_DISPLAY_NAME);
             mConversationTitle = extras.getString(EXTRA_CONVERSATION_TITLE);
-            mAllowGeneratedReplies = extras.getBoolean(EXTRA_ALLOW_GENERATED_REPLIES,
-                    mAllowGeneratedReplies);
             Parcelable[] parcelables = extras.getParcelableArray(EXTRA_MESSAGES);
-            if (parcelables != null && parcelables instanceof Bundle[]) {
-                mMessages = Message.getMessagesFromBundleArray((Bundle[]) parcelables);
+            if (parcelables != null && parcelables instanceof Parcelable[]) {
+                mMessages = Message.getMessagesFromBundleArray(parcelables);
             }
         }
 
@@ -4558,6 +4563,25 @@
             return sb;
         }
 
+        /**
+         * @hide
+         */
+        @Override
+        public RemoteViews makeHeadsUpContentView() {
+            Message m = findLatestIncomingMessage();
+            CharSequence title = mConversationTitle != null
+                    ? mConversationTitle
+                    : (m == null) ? null : m.mSender;
+            CharSequence text = (m == null)
+                    ? null
+                    : mConversationTitle != null ? makeMessageLine(m) : m.mText;
+
+            return mBuilder.applyStandardTemplateWithActions(mBuilder.getBigBaseLayoutResource(),
+                    false /* hasProgress */,
+                    title,
+                    text);
+        }
+
         private static TextAppearanceSpan makeFontColorSpan(int color) {
             return new TextAppearanceSpan(null, 0, 0,
                     ColorStateList.valueOf(color), null);
@@ -4691,12 +4715,14 @@
                 return bundles;
             }
 
-            static List<Message> getMessagesFromBundleArray(Bundle[] bundles) {
+            static List<Message> getMessagesFromBundleArray(Parcelable[] bundles) {
                 List<Message> messages = new ArrayList<>(bundles.length);
                 for (int i = 0; i < bundles.length; i++) {
-                    Message message = getMessageFromBundle(bundles[i]);
-                    if (message != null) {
-                        messages.add(message);
+                    if (bundles[i] instanceof Bundle) {
+                        Message message = getMessageFromBundle((Bundle)bundles[i]);
+                        if (message != null) {
+                            messages.add(message);
+                        }
                     }
                 }
                 return messages;
@@ -5460,6 +5486,7 @@
         private static final String KEY_CUSTOM_CONTENT_HEIGHT = "customContentHeight";
         private static final String KEY_GRAVITY = "gravity";
         private static final String KEY_HINT_SCREEN_TIMEOUT = "hintScreenTimeout";
+        private static final String KEY_DISMISSAL_ID = "dismissalId";
 
         // Flags bitwise-ored to mFlags
         private static final int FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE = 0x1;
@@ -5488,6 +5515,7 @@
         private int mCustomContentHeight;
         private int mGravity = DEFAULT_GRAVITY;
         private int mHintScreenTimeout;
+        private String mDismissalId;
 
         /**
          * Create a {@link android.app.Notification.WearableExtender} with default
@@ -5524,6 +5552,7 @@
                 mCustomContentHeight = wearableBundle.getInt(KEY_CUSTOM_CONTENT_HEIGHT);
                 mGravity = wearableBundle.getInt(KEY_GRAVITY, DEFAULT_GRAVITY);
                 mHintScreenTimeout = wearableBundle.getInt(KEY_HINT_SCREEN_TIMEOUT);
+                mDismissalId = wearableBundle.getString(KEY_DISMISSAL_ID);
             }
         }
 
@@ -5574,6 +5603,9 @@
             if (mHintScreenTimeout != 0) {
                 wearableBundle.putInt(KEY_HINT_SCREEN_TIMEOUT, mHintScreenTimeout);
             }
+            if (mDismissalId != null) {
+                wearableBundle.putString(KEY_DISMISSAL_ID, mDismissalId);
+            }
 
             builder.getExtras().putBundle(EXTRA_WEARABLE_EXTENSIONS, wearableBundle);
             return builder;
@@ -5594,6 +5626,7 @@
             that.mCustomContentHeight = this.mCustomContentHeight;
             that.mGravity = this.mGravity;
             that.mHintScreenTimeout = this.mHintScreenTimeout;
+            that.mDismissalId = this.mDismissalId;
             return that;
         }
 
@@ -6081,6 +6114,29 @@
             return (mFlags & FLAG_HINT_CONTENT_INTENT_LAUNCHES_ACTIVITY) != 0;
         }
 
+        /**
+         * When you post a notification, if you set the dismissal id field, then when that
+         * notification is canceled, notifications on other wearables and the paired Android phone
+         * having that same dismissal id will also be canceled.  Note that this only works if you
+         * have notification bridge mode set to NO_BRIDGING in your Wear app manifest.  See
+         * <a href="{@docRoot}wear/notifications/index.html">Adding Wearable Features to
+         * Notifications</a> for more information on how to use the bridge mode feature.
+         * @param dismissalId the dismissal id of the notification.
+         * @return this object for method chaining
+         */
+        public WearableExtender setDismissalId(String dismissalId) {
+            mDismissalId = dismissalId;
+            return this;
+        }
+
+        /**
+         * Returns the dismissal id of the notification.
+         * @return the dismissal id of the notification or null if it has not been set.
+         */
+        public String getDismissalId() {
+            return mDismissalId;
+        }
+
         private void setFlag(int mask, boolean value) {
             if (value) {
                 mFlags |= mask;
diff --git a/core/java/android/app/job/JobInfo.java b/core/java/android/app/job/JobInfo.java
index ecfc527..c475575 100644
--- a/core/java/android/app/job/JobInfo.java
+++ b/core/java/android/app/job/JobInfo.java
@@ -16,6 +16,8 @@
 
 package android.app.job;
 
+import static android.util.TimeUtils.formatDuration;
+
 import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.content.ComponentName;
@@ -24,7 +26,6 @@
 import android.os.Parcelable;
 import android.os.PersistableBundle;
 import android.util.Log;
-import static android.util.TimeUtils.formatDuration;
 
 import java.util.ArrayList;
 
@@ -154,6 +155,20 @@
      */
     public static final int PRIORITY_ADJ_ALWAYS_RUNNING = -80;
 
+    /**
+     * Indicates that the implementation of this job will be using
+     * {@link JobService#startForeground(int, android.app.Notification)} to run
+     * in the foreground.
+     * <p>
+     * When set, the internal scheduling of this job will ignore any background
+     * network restrictions for the requesting app. Note that this flag alone
+     * doesn't actually place your {@link JobService} in the foreground; you
+     * still need to post the notification yourself.
+     *
+     * @hide
+     */
+    public static final int FLAG_WILL_BE_FOREGROUND = 1 << 0;
+
     private final int jobId;
     private final PersistableBundle extras;
     private final ComponentName service;
@@ -174,6 +189,7 @@
     private final long initialBackoffMillis;
     private final int backoffPolicy;
     private final int priority;
+    private final int flags;
 
     /**
      * Unique job id associated with this class. This is assigned to your job by the scheduler.
@@ -201,6 +217,11 @@
         return priority;
     }
 
+    /** @hide */
+    public int getFlags() {
+        return flags;
+    }
+
     /**
      * Whether this job needs the device to be plugged in.
      */
@@ -356,6 +377,7 @@
         hasEarlyConstraint = in.readInt() == 1;
         hasLateConstraint = in.readInt() == 1;
         priority = in.readInt();
+        flags = in.readInt();
     }
 
     private JobInfo(JobInfo.Builder b) {
@@ -381,6 +403,7 @@
         hasEarlyConstraint = b.mHasEarlyConstraint;
         hasLateConstraint = b.mHasLateConstraint;
         priority = b.mPriority;
+        flags = b.mFlags;
     }
 
     @Override
@@ -410,6 +433,7 @@
         out.writeInt(hasEarlyConstraint ? 1 : 0);
         out.writeInt(hasLateConstraint ? 1 : 0);
         out.writeInt(priority);
+        out.writeInt(this.flags);
     }
 
     public static final Creator<JobInfo> CREATOR = new Creator<JobInfo>() {
@@ -504,6 +528,7 @@
         private PersistableBundle mExtras = PersistableBundle.EMPTY;
         private ComponentName mJobService;
         private int mPriority = PRIORITY_DEFAULT;
+        private int mFlags;
         // Requirements.
         private boolean mRequiresCharging;
         private boolean mRequiresDeviceIdle;
@@ -539,14 +564,18 @@
             mJobId = jobId;
         }
 
-        /**
-         * @hide
-         */
+        /** @hide */
         public Builder setPriority(int priority) {
             mPriority = priority;
             return this;
         }
 
+        /** @hide */
+        public Builder setFlags(int flags) {
+            mFlags = flags;
+            return this;
+        }
+
         /**
          * Set optional extras. This is persisted, so we only allow primitive types.
          * @param extras Bundle containing extras you want the scheduler to hold on to for you.
diff --git a/core/java/android/app/usage/NetworkStats.java b/core/java/android/app/usage/NetworkStats.java
index 6d5c81b..9963eab 100644
--- a/core/java/android/app/usage/NetworkStats.java
+++ b/core/java/android/app/usage/NetworkStats.java
@@ -64,6 +64,11 @@
     private int mUidOrUidIndex;
 
     /**
+     * Tag id in case if was specified in the query.
+     */
+    private int mTag = android.net.NetworkStats.TAG_NONE;
+
+    /**
      * The session while the query requires it, null if all the stats have been collected or close()
      * has been called.
      */
@@ -434,7 +439,7 @@
             mHistory = mSession.getHistoryIntervalForUid(mTemplate, uid,
                     android.net.NetworkStats.SET_ALL, tag,
                     NetworkStatsHistory.FIELD_ALL, mStartTimeStamp, mEndTimeStamp);
-            setSingleUid(uid);
+            setSingleUidTag(uid, tag);
         } catch (RemoteException e) {
             Log.w(TAG, e);
             // Leaving mHistory null
@@ -538,6 +543,7 @@
                 mRecycledHistoryEntry = mHistory.getValues(mEnumerationIndex++,
                         mRecycledHistoryEntry);
                 bucketOut.mUid = Bucket.convertUid(getUid());
+                bucketOut.mTag = Bucket.convertTag(mTag);
                 bucketOut.mState = Bucket.STATE_ALL;
                 bucketOut.mRoaming = Bucket.ROAMING_ALL;
                 bucketOut.mBeginTimeStamp = mRecycledHistoryEntry.bucketStart;
@@ -579,8 +585,9 @@
         return mUidOrUidIndex;
     }
 
-    private void setSingleUid(int uid) {
+    private void setSingleUidTag(int uid, int tag) {
         mUidOrUidIndex = uid;
+        mTag = tag;
     }
 
     private void stepUid() {
diff --git a/core/java/android/content/ContentResolver.java b/core/java/android/content/ContentResolver.java
index 4db4567..aeda7a2 100644
--- a/core/java/android/content/ContentResolver.java
+++ b/core/java/android/content/ContentResolver.java
@@ -1748,7 +1748,7 @@
      *
      * @hide
      */
-    public void notifyChange(Uri uri, ContentObserver observer, boolean syncToNetwork,
+    public void notifyChange(@NonNull Uri uri, ContentObserver observer, boolean syncToNetwork,
             @UserIdInt int userHandle) {
         try {
             getContentService().notifyChange(
@@ -1765,7 +1765,7 @@
      *
      * @hide
      */
-    public void notifyChange(Uri uri, ContentObserver observer, @NotifyFlags int flags,
+    public void notifyChange(@NonNull Uri uri, ContentObserver observer, @NotifyFlags int flags,
             @UserIdInt int userHandle) {
         try {
             getContentService().notifyChange(
diff --git a/core/java/android/content/Loader.java b/core/java/android/content/Loader.java
index e9d82af..c5e0ea7 100644
--- a/core/java/android/content/Loader.java
+++ b/core/java/android/content/Loader.java
@@ -484,7 +484,7 @@
      */
     public void rollbackContentChanged() {
         if (mProcessingChange) {
-            mContentChanged = true;
+            onContentChanged();
         }
     }
 
diff --git a/core/java/android/content/pm/ActivityInfo.java b/core/java/android/content/pm/ActivityInfo.java
index 167befc..bdea1e0 100644
--- a/core/java/android/content/pm/ActivityInfo.java
+++ b/core/java/android/content/pm/ActivityInfo.java
@@ -188,7 +188,7 @@
      * See {@link android.R.attr#resizeableActivity}.
      * @hide
      */
-    public int resizeMode;
+    public int resizeMode = RESIZE_MODE_RESIZEABLE;
 
     /**
      * Name of the VrListenerService component to run for this activity.
diff --git a/core/java/android/content/pm/IPackageManager.aidl b/core/java/android/content/pm/IPackageManager.aidl
index 0c79312..03f83d6 100644
--- a/core/java/android/content/pm/IPackageManager.aidl
+++ b/core/java/android/content/pm/IPackageManager.aidl
@@ -222,7 +222,7 @@
             in String installerPackageName,
             int userId);
 
-    void finishPackageInstall(int token);
+    void finishPackageInstall(int token, boolean didLaunch);
 
     void setInstallerPackageName(in String targetPackage, in String installerPackageName);
 
diff --git a/core/java/android/hardware/location/ContextHubInfo.java b/core/java/android/hardware/location/ContextHubInfo.java
index 194b9ee..aaf6c57 100644
--- a/core/java/android/hardware/location/ContextHubInfo.java
+++ b/core/java/android/hardware/location/ContextHubInfo.java
@@ -357,6 +357,7 @@
       retVal += "\n\tPeakMips : " + mPeakMips;
       retVal += ", StoppedPowerDraw : " + mStoppedPowerDrawMw + " mW";
       retVal += ", PeakPowerDraw : " + mPeakPowerDrawMw + " mW";
+      retVal += ", MaxPacketLength : " + mMaxPacketLengthBytes + " Bytes";
       retVal += "\n\tSupported sensors : " + Arrays.toString(mSupportedSensors);
       retVal += "\n\tMemory Regions : " + Arrays.toString(mMemoryRegions);
 
@@ -375,6 +376,7 @@
         mStoppedPowerDrawMw = in.readFloat();
         mSleepPowerDrawMw = in.readFloat();
         mPeakPowerDrawMw = in.readFloat();
+        mMaxPacketLengthBytes = in.readInt();
 
         int numSupportedSensors = in.readInt();
         mSupportedSensors = new int[numSupportedSensors];
@@ -398,6 +400,7 @@
         out.writeFloat(mStoppedPowerDrawMw);
         out.writeFloat(mSleepPowerDrawMw);
         out.writeFloat(mPeakPowerDrawMw);
+        out.writeInt(mMaxPacketLengthBytes);
 
         out.writeInt(mSupportedSensors.length);
         out.writeIntArray(mSupportedSensors);
@@ -414,4 +417,4 @@
             return new ContextHubInfo[size];
         }
     };
-}
\ No newline at end of file
+}
diff --git a/core/java/android/net/ConnectivityManager.java b/core/java/android/net/ConnectivityManager.java
index faf5c64..933dddf 100644
--- a/core/java/android/net/ConnectivityManager.java
+++ b/core/java/android/net/ConnectivityManager.java
@@ -774,8 +774,13 @@
      * @hide
      */
     public Network getActiveNetworkForUid(int uid) {
+        return getActiveNetworkForUid(uid, false);
+    }
+
+    /** {@hide} */
+    public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
         try {
-            return mService.getActiveNetworkForUid(uid);
+            return mService.getActiveNetworkForUid(uid, ignoreBlocked);
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
         }
@@ -836,8 +841,13 @@
      * {@hide}
      */
     public NetworkInfo getActiveNetworkInfoForUid(int uid) {
+        return getActiveNetworkInfoForUid(uid, false);
+    }
+
+    /** {@hide} */
+    public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
         try {
-            return mService.getActiveNetworkInfoForUid(uid);
+            return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
         }
@@ -880,8 +890,13 @@
      *        is not valid.
      */
     public NetworkInfo getNetworkInfo(Network network) {
+        return getNetworkInfoForUid(network, Process.myUid(), false);
+    }
+
+    /** {@hide} */
+    public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
         try {
-            return mService.getNetworkInfoForNetwork(network);
+            return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
         }
diff --git a/core/java/android/net/IConnectivityManager.aidl b/core/java/android/net/IConnectivityManager.aidl
index c897c45..aec6b3e 100644
--- a/core/java/android/net/IConnectivityManager.aidl
+++ b/core/java/android/net/IConnectivityManager.aidl
@@ -44,11 +44,11 @@
 interface IConnectivityManager
 {
     Network getActiveNetwork();
-    Network getActiveNetworkForUid(int uid);
+    Network getActiveNetworkForUid(int uid, boolean ignoreBlocked);
     NetworkInfo getActiveNetworkInfo();
-    NetworkInfo getActiveNetworkInfoForUid(int uid);
+    NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked);
     NetworkInfo getNetworkInfo(int networkType);
-    NetworkInfo getNetworkInfoForNetwork(in Network network);
+    NetworkInfo getNetworkInfoForUid(in Network network, int uid, boolean ignoreBlocked);
     NetworkInfo[] getAllNetworkInfo();
     Network getNetworkForType(int networkType);
     Network[] getAllNetworks();
diff --git a/core/java/android/net/INetworkPolicyManager.aidl b/core/java/android/net/INetworkPolicyManager.aidl
index a57fac3..224ff5b 100644
--- a/core/java/android/net/INetworkPolicyManager.aidl
+++ b/core/java/android/net/INetworkPolicyManager.aidl
@@ -38,6 +38,9 @@
 
     boolean isUidForeground(int uid);
 
+    /** Higher priority listener before general event dispatch */
+    void setConnectivityListener(INetworkPolicyListener listener);
+
     void registerListener(INetworkPolicyListener listener);
     void unregisterListener(INetworkPolicyListener listener);
 
@@ -52,6 +55,9 @@
     void setRestrictBackground(boolean restrictBackground);
     boolean getRestrictBackground();
 
+    /** Callback used to change internal state on tethering */
+    void onTetheringChanged(String iface, boolean tethering);
+
     /** Control which applications can be exempt from background data restrictions */
     void addRestrictBackgroundWhitelistedUid(int uid);
     void removeRestrictBackgroundWhitelistedUid(int uid);
diff --git a/core/java/android/net/metrics/ValidationProbeEvent.java b/core/java/android/net/metrics/ValidationProbeEvent.java
index 5c8ea65..751c35f 100644
--- a/core/java/android/net/metrics/ValidationProbeEvent.java
+++ b/core/java/android/net/metrics/ValidationProbeEvent.java
@@ -29,8 +29,13 @@
 @SystemApi
 public final class ValidationProbeEvent extends IpConnectivityEvent implements Parcelable {
 
-    public static final int PROBE_HTTP  = 0;
-    public static final int PROBE_HTTPS = 1;
+    public static final int PROBE_DNS   = 0;
+    public static final int PROBE_HTTP  = 1;
+    public static final int PROBE_HTTPS = 2;
+    public static final int PROBE_PAC   = 3;
+
+    public static final int DNS_FAILURE = 0;
+    public static final int DNS_SUCCESS = 1;
 
     public final int netId;
     public final long durationMs;
@@ -73,6 +78,11 @@
         }
     };
 
+    /** @hide */
+    public static String getProbeName(int probeType) {
+        return Decoder.constants.get(probeType, "PROBE_???");
+    }
+
     public static void logEvent(int netId, long durationMs, int probeType, int returnCode) {
         logEvent(new ValidationProbeEvent(netId, durationMs, probeType, returnCode));
     }
@@ -80,7 +90,7 @@
     @Override
     public String toString() {
         return String.format("ValidationProbeEvent(%d, %s:%d, %dms)",
-                netId, Decoder.constants.get(probeType), returnCode, durationMs);
+                netId, getProbeName(probeType), returnCode, durationMs);
     }
 
     final static class Decoder {
diff --git a/core/java/android/nfc/INfcAdapter.aidl b/core/java/android/nfc/INfcAdapter.aidl
index 940565f..f991efe 100644
--- a/core/java/android/nfc/INfcAdapter.aidl
+++ b/core/java/android/nfc/INfcAdapter.aidl
@@ -28,6 +28,7 @@
 import android.nfc.INfcCardEmulation;
 import android.nfc.INfcFCardEmulation;
 import android.nfc.INfcUnlockHandler;
+import android.nfc.ITagRemovedCallback;
 import android.os.Bundle;
 
 /**
@@ -55,6 +56,8 @@
     oneway void invokeBeam();
     oneway void invokeBeamInternal(in BeamShareData shareData);
 
+    boolean ignore(int nativeHandle, int debounceMs, ITagRemovedCallback callback);
+
     void dispatch(in Tag tag);
 
     void setReaderMode (IBinder b, IAppCallback callback, int flags, in Bundle extras);
diff --git a/core/java/android/nfc/INfcTag.aidl b/core/java/android/nfc/INfcTag.aidl
index 26d2bec..539fd4a 100644
--- a/core/java/android/nfc/INfcTag.aidl
+++ b/core/java/android/nfc/INfcTag.aidl
@@ -31,7 +31,6 @@
     boolean isNdef(int nativeHandle);
     boolean isPresent(int nativeHandle);
     TransceiveResult transceive(int nativeHandle, in byte[] data, boolean raw);
-    boolean done(int nativeHandle, int debounceMs);
 
     NdefMessage ndefRead(int nativeHandle);
     int ndefWrite(int nativeHandle, in NdefMessage msg);
diff --git a/core/java/android/nfc/ITagRemovedCallback.aidl b/core/java/android/nfc/ITagRemovedCallback.aidl
new file mode 100644
index 0000000..2a06ff3
--- /dev/null
+++ b/core/java/android/nfc/ITagRemovedCallback.aidl
@@ -0,0 +1,8 @@
+package android.nfc;
+
+/**
+ * @hide
+ */
+oneway interface ITagRemovedCallback {
+    void onTagRemoved();
+}
diff --git a/core/java/android/nfc/NfcAdapter.java b/core/java/android/nfc/NfcAdapter.java
index 6f911ce..8406bcf 100644
--- a/core/java/android/nfc/NfcAdapter.java
+++ b/core/java/android/nfc/NfcAdapter.java
@@ -35,11 +35,14 @@
 import android.nfc.tech.NfcA;
 import android.nfc.tech.NfcF;
 import android.os.Bundle;
+import android.os.Handler;
 import android.os.IBinder;
 import android.os.RemoteException;
 import android.os.ServiceManager;
 import android.util.Log;
 
+import java.io.IOException;
+
 /**
  * Represents the local NFC adapter.
  * <p>
@@ -315,6 +318,8 @@
     final HashMap<NfcUnlockHandler, INfcUnlockHandler> mNfcUnlockHandlers;
     final Object mLock;
 
+    ITagRemovedCallback mTagRemovedListener; // protected by mLock
+
     /**
      * A callback to be invoked when the system finds a tag while the foreground activity is
      * operating in reader mode.
@@ -386,6 +391,13 @@
     }
 
     /**
+     * A callback that is invoked when a tag is removed from the field.
+     */
+    public interface OnTagRemovedListener {
+        void onTagRemoved();
+    }
+
+    /**
      * A callback to be invoked when an application has registered as a
      * handler to unlock the device given an NFC tag at the lockscreen.
      * @hide
@@ -541,6 +553,7 @@
         mContext = context;
         mNfcActivityManager = new NfcActivityManager(this);
         mNfcUnlockHandlers = new HashMap<NfcUnlockHandler, INfcUnlockHandler>();
+        mTagRemovedListener = null;
         mLock = new Object();
     }
 
@@ -1494,6 +1507,75 @@
     }
 
     /**
+     * Signals that you are no longer interested in communicating with an NFC tag
+     * for as long as it remains in range.
+     *
+     * All future attempted communication to this tag will fail with {@link IOException}.
+     * The NFC controller will be put in a low-power polling mode, allowing the device
+     * to save power in cases where it's "attached" to a tag all the time (e.g. a tag in
+     * car dock).
+     *
+     * Additionally the debounceMs parameter allows you to specify for how long the tag needs
+     * to have gone out of range, before it will be dispatched again.
+     *
+     * Note: the NFC controller typically polls at a pretty slow interval (100 - 500 ms).
+     * This means that if the tag repeatedly goes in and out of range (for example, in
+     * case of a flaky connection), and the controller happens to poll every time the
+     * tag is out of range, it *will* re-dispatch the tag after debounceMs, despite the tag
+     * having been "in range" during the interval.
+     *
+     * Note 2: if a tag with another UID is detected after this API is called, its effect
+     * will be cancelled; if this tag shows up before the amount of time specified in
+     * debounceMs, it will be dispatched again.
+     *
+     * Note 3: some tags have a random UID, in which case this API won't work reliably.
+     *
+     * @param tag        the {@link android.nfc.Tag Tag} to ignore.
+     * @param debounceMs minimum amount of time the tag needs to be out of range before being
+     *                   dispatched again.
+     * @param tagRemovedListener listener to be called when the tag is removed from the field.
+     *                           Note that this will only be called if the tag has been out of range
+     *                           for at least debounceMs, or if another tag came into range before
+     *                           debounceMs. May be null in case you don't want a callback.
+     * @param handler the {@link android.os.Handler Handler} that will be used for delivering
+     *                the callback. if the handler is null, then the thread used for delivering
+     *                the callback is unspecified.
+     * @return false if the tag couldn't be found (or has already gone out of range), true otherwise
+     */
+    public boolean ignore(final Tag tag, int debounceMs,
+                          final OnTagRemovedListener tagRemovedListener, final Handler handler) {
+        ITagRemovedCallback.Stub iListener = null;
+        if (tagRemovedListener != null) {
+            iListener = new ITagRemovedCallback.Stub() {
+                @Override
+                public void onTagRemoved() throws RemoteException {
+                    if (handler != null) {
+                        handler.post(new Runnable() {
+                            @Override
+                            public void run() {
+                                tagRemovedListener.onTagRemoved();
+                            }
+                        });
+                    } else {
+                        tagRemovedListener.onTagRemoved();
+                    }
+                    synchronized (mLock) {
+                        mTagRemovedListener = null;
+                    }
+                }
+            };
+        }
+        synchronized (mLock) {
+            mTagRemovedListener = iListener;
+        }
+        try {
+            return sService.ignore(tag.getServiceHandle(), debounceMs, iListener);
+        } catch (RemoteException e) {
+            return false;
+        }
+    }
+
+    /**
      * Inject a mock NFC tag.<p>
      * Used for testing purposes.
      * <p class="note">Requires the
diff --git a/core/java/android/nfc/Tag.java b/core/java/android/nfc/Tag.java
index 40d5a8db..154d5a1 100644
--- a/core/java/android/nfc/Tag.java
+++ b/core/java/android/nfc/Tag.java
@@ -214,42 +214,6 @@
         return techIntList;
     }
 
-    /**
-     * Signals that you are no longer interested in communicating with this tag
-     * for as long as it remains in range.
-     *
-     * All future attempted communication to this tag will fail with {@link IOException}.
-     * The NFC controller will be put in a low-power polling mode, allowing the device
-     * to save power in cases where it's "attached" to a tag all the time (eg a tag in
-     * car dock).
-     *
-     * Additionally the debounceMs parameter allows you to specify for how long the tag needs
-     * to have gone out of range, before it will be dispatched again.
-     *
-     * Note: the NFC controller typically polls at a pretty slow interval (100 - 500 ms).
-     * This means that if the tag repeatedly goes in and out of range (for example, in
-     * case of a flaky connection), and the controller happens to poll every time the
-     * tag is out of range, it *will* re-dispatch the tag after debounceMs, despite the tag
-     * having been "in range" during the interval.
-     *
-     * Note 2: if a tag with another UID is detected after this API is called, its effect
-     * will be cancelled; if this tag shows up before the amount of time specified in
-     * debounceMs, it will be dispatched again.
-     *
-     * Note 3: some tags have a random UID, in which case this API won't work.
-     *
-     * @param debounceMs minimum amount of time the tag needs to be out of range before being
-     *                   dispatched again.
-     * @return false if the Tag couldn't be found (or has gone out of range), true otherwise
-     */
-    public boolean done(int debounceMs) {
-        try {
-            return mTagService.done(getServiceHandle(), debounceMs);
-        } catch (RemoteException e) {
-            return false;
-        }
-    }
-
     private static HashMap<String, Integer> getTechStringToCodeMap() {
         HashMap<String, Integer> techStringToCodeMap = new HashMap<String, Integer>();
 
diff --git a/core/java/android/os/BatteryStats.java b/core/java/android/os/BatteryStats.java
index b9a3cff..959b309 100644
--- a/core/java/android/os/BatteryStats.java
+++ b/core/java/android/os/BatteryStats.java
@@ -1070,6 +1070,9 @@
         public int statSoftIrqTime;
         public int statIdlTime;
 
+        // Platform-level low power state stats
+        public String statPlatformIdleState;
+
         public HistoryStepDetails() {
             clear();
         }
@@ -1099,6 +1102,7 @@
             out.writeInt(statIrqTime);
             out.writeInt(statSoftIrqTime);
             out.writeInt(statIdlTime);
+            out.writeString(statPlatformIdleState);
         }
 
         public void readFromParcel(Parcel in) {
@@ -1119,6 +1123,7 @@
             statIrqTime = in.readInt();
             statSoftIrqTime = in.readInt();
             statIdlTime = in.readInt();
+            statPlatformIdleState = in.readString();
         }
     }
 
@@ -1152,6 +1157,8 @@
         
         public short batteryTemperature;
         public char batteryVoltage;
+
+        public int batteryChargeCoulombs;
         
         // Constants from SCREEN_BRIGHTNESS_*
         public static final int STATE_BRIGHTNESS_SHIFT = 0;
@@ -1176,6 +1183,8 @@
         public static final int STATE_WIFI_SCAN_FLAG = 1<<27;
         public static final int STATE_WIFI_RADIO_ACTIVE_FLAG = 1<<26;
         public static final int STATE_MOBILE_RADIO_ACTIVE_FLAG = 1<<25;
+        // Do not use, this is used for coulomb delta count.
+        private static final int STATE_RESERVED_0 = 1<<24;
         // These are on the lower bits used for the command; if they change
         // we need to write another int of data.
         public static final int STATE_SENSOR_ON_FLAG = 1<<23;
@@ -1347,6 +1356,7 @@
             bat = (((int)batteryTemperature)&0xffff)
                     | ((((int)batteryVoltage)<<16)&0xffff0000);
             dest.writeInt(bat);
+            dest.writeInt(batteryChargeCoulombs);
             dest.writeInt(states);
             dest.writeInt(states2);
             if (wakelockTag != null) {
@@ -1375,6 +1385,7 @@
             int bat2 = src.readInt();
             batteryTemperature = (short)(bat2&0xffff);
             batteryVoltage = (char)((bat2>>16)&0xffff);
+            batteryChargeCoulombs = src.readInt();
             states = src.readInt();
             states2 = src.readInt();
             if ((bat&0x10000000) != 0) {
@@ -1414,6 +1425,7 @@
             batteryPlugType = 0;
             batteryTemperature = 0;
             batteryVoltage = 0;
+            batteryChargeCoulombs = 0;
             states = 0;
             states2 = 0;
             wakelockTag = null;
@@ -1441,6 +1453,7 @@
             batteryPlugType = o.batteryPlugType;
             batteryTemperature = o.batteryTemperature;
             batteryVoltage = o.batteryVoltage;
+            batteryChargeCoulombs = o.batteryChargeCoulombs;
             states = o.states;
             states2 = o.states2;
             if (o.wakelockTag != null) {
@@ -1472,6 +1485,7 @@
                     && batteryPlugType == o.batteryPlugType
                     && batteryTemperature == o.batteryTemperature
                     && batteryVoltage == o.batteryVoltage
+                    && batteryChargeCoulombs == o.batteryChargeCoulombs
                     && states == o.states
                     && states2 == o.states2
                     && currentTime == o.currentTime;
@@ -4522,6 +4536,7 @@
         int oldPlug = -1;
         int oldTemp = -1;
         int oldVolt = -1;
+        int oldCharge = -1;
         long lastTime = -1;
 
         void reset() {
@@ -4532,6 +4547,7 @@
             oldPlug = -1;
             oldTemp = -1;
             oldVolt = -1;
+            oldCharge = -1;
         }
 
         public void printNextItem(PrintWriter pw, HistoryItem rec, long baseTime, boolean checkin,
@@ -4693,6 +4709,11 @@
                     pw.print(checkin ? ",Bv=" : " volt=");
                     pw.print(oldVolt);
                 }
+                if (oldCharge != rec.batteryChargeCoulombs) {
+                    oldCharge = rec.batteryChargeCoulombs;
+                    pw.print(checkin ? ",Bcc=" : " charge=");
+                    pw.print(oldCharge);
+                }
                 printBitDescriptions(pw, oldState, rec.states, rec.wakelockTag,
                         HISTORY_STATE_DESCRIPTIONS, !checkin);
                 printBitDescriptions(pw, oldState2, rec.states2, null,
@@ -4788,6 +4809,8 @@
                             pw.print(sb);
                             pw.print(")");
                         }
+                        pw.print(", PlatformIdleStat ");
+                        pw.print(rec.stepDetails.statPlatformIdleState);
                         pw.println();
                     } else {
                         pw.print(BATTERY_STATS_CHECKIN_VERSION); pw.print(',');
@@ -4821,6 +4844,8 @@
                         pw.print(rec.stepDetails.statSoftIrqTime);
                         pw.print(',');
                         pw.print(rec.stepDetails.statIdlTime);
+                        pw.print(',');
+                        pw.print(rec.stepDetails.statPlatformIdleState);
                         pw.println();
                     }
                 }
diff --git a/core/java/android/os/FileUtils.java b/core/java/android/os/FileUtils.java
index 7d74a12..fa32848 100644
--- a/core/java/android/os/FileUtils.java
+++ b/core/java/android/os/FileUtils.java
@@ -72,8 +72,13 @@
     public static final int S_IWOTH = 00002;
     public static final int S_IXOTH = 00001;
 
-    /** Regular expression for safe filenames: no spaces or metacharacters */
-    private static final Pattern SAFE_FILENAME_PATTERN = Pattern.compile("[\\w%+,./=_-]+");
+    /** Regular expression for safe filenames: no spaces or metacharacters.
+      *
+      * Use a preload holder so that FileUtils can be compile-time initialized.
+      */
+    private static class NoImagePreloadHolder {
+        public static final Pattern SAFE_FILENAME_PATTERN = Pattern.compile("[\\w%+,./=_-]+");
+    }
 
     private static final File[] EMPTY = new File[0];
 
@@ -243,7 +248,7 @@
         // Note, we check whether it matches what's known to be safe,
         // rather than what's known to be unsafe.  Non-ASCII, control
         // characters, etc. are all unsafe by default.
-        return SAFE_FILENAME_PATTERN.matcher(file.getPath()).matches();
+        return NoImagePreloadHolder.SAFE_FILENAME_PATTERN.matcher(file.getPath()).matches();
     }
 
     /**
diff --git a/core/java/android/os/INetworkManagementService.aidl b/core/java/android/os/INetworkManagementService.aidl
index 68b0a9f..b546da0 100644
--- a/core/java/android/os/INetworkManagementService.aidl
+++ b/core/java/android/os/INetworkManagementService.aidl
@@ -324,6 +324,11 @@
     void removeIdleTimer(String iface);
 
     /**
+     * Configure name servers, search paths, and resolver parameters for the given network.
+     */
+    void setDnsConfigurationForNetwork(int netId, in String[] servers, String domains);
+
+    /**
      * Bind name servers to a network in the DNS resolver.
      */
     void setDnsServersForNetwork(int netId, in String[] servers, String domains);
diff --git a/core/java/android/os/UserManager.java b/core/java/android/os/UserManager.java
index dd53cbb..d55201f 100644
--- a/core/java/android/os/UserManager.java
+++ b/core/java/android/os/UserManager.java
@@ -36,7 +36,6 @@
 import android.graphics.BitmapFactory;
 import android.graphics.Rect;
 import android.graphics.drawable.Drawable;
-import android.os.storage.StorageManager;
 import android.provider.Settings;
 import android.telephony.TelephonyManager;
 import android.view.WindowManager.LayoutParams;
@@ -984,10 +983,27 @@
 
     /** {@hide} */
     public boolean isUserUnlocked(@UserIdInt int userId) {
-        // TODO: eventually pivot this back to look at ActivityManager state,
-        // but there is race where we can start a non-encryption-aware launcher
-        // before that lifecycle has entered the running unlocked state.
-        return mContext.getSystemService(StorageManager.class).isUserKeyUnlocked(userId);
+        try {
+            return ActivityManagerNative.getDefault().isUserRunning(userId,
+                    ActivityManager.FLAG_AND_UNLOCKED);
+        } catch (RemoteException re) {
+            throw re.rethrowFromSystemServer();
+        }
+    }
+
+    /** {@hide} */
+    public boolean isUserUnlockingOrUnlocked(UserHandle user) {
+        return isUserUnlockingOrUnlocked(user.getIdentifier());
+    }
+
+    /** {@hide} */
+    public boolean isUserUnlockingOrUnlocked(@UserIdInt int userId) {
+        try {
+            return ActivityManagerNative.getDefault().isUserRunning(userId,
+                    ActivityManager.FLAG_AND_UNLOCKING_OR_UNLOCKED);
+        } catch (RemoteException re) {
+            throw re.rethrowFromSystemServer();
+        }
     }
 
     /**
diff --git a/core/java/android/os/storage/StorageManager.java b/core/java/android/os/storage/StorageManager.java
index f68e227..fbf7b26 100644
--- a/core/java/android/os/storage/StorageManager.java
+++ b/core/java/android/os/storage/StorageManager.java
@@ -25,6 +25,7 @@
 import android.content.Context;
 import android.content.pm.IPackageMoveObserver;
 import android.content.pm.PackageManager;
+import android.os.Binder;
 import android.os.Environment;
 import android.os.FileUtils;
 import android.os.Handler;
@@ -1062,11 +1063,20 @@
     }
 
     /** {@hide} */
-    public boolean isUserKeyUnlocked(int userId) {
+    public static boolean isUserKeyUnlocked(int userId) {
+        final IMountService mount = IMountService.Stub
+                .asInterface(ServiceManager.getService("mount"));
+        if (mount == null) {
+            Slog.w(TAG, "Early during boot, assuming locked");
+            return false;
+        }
+        final long token = Binder.clearCallingIdentity();
         try {
-            return mMountService.isUserKeyUnlocked(userId);
+            return mount.isUserKeyUnlocked(userId);
         } catch (RemoteException e) {
-            throw e.rethrowFromSystemServer();
+            throw e.rethrowAsRuntimeException();
+        } finally {
+            Binder.restoreCallingIdentity(token);
         }
     }
 
diff --git a/core/java/android/provider/CallLog.java b/core/java/android/provider/CallLog.java
index 8a0759f..893eb37 100644
--- a/core/java/android/provider/CallLog.java
+++ b/core/java/android/provider/CallLog.java
@@ -824,6 +824,8 @@
                 UserHandle user, ContentValues values) {
             final ContentResolver resolver = context.getContentResolver();
 
+            // Since we're doing this operation on behalf of an app, we only
+            // want to use the actual "unlocked" state.
             final Uri uri = ContentProvider.maybeAddUserId(
                     userManager.isUserUnlocked(user) ? CONTENT_URI : SHADOW_CONTENT_URI,
                     user.getIdentifier());
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index 4ca1b97..700c2d2 100755
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -726,18 +726,18 @@
             "android.settings.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS";
 
     /**
-     * Activity Action: Show screen for controlling which apps can ignore background data
-     * restrictions.
+     * Activity Action: Show screen for controlling background data
+     * restrictions for a particular application.
      * <p>
-     * Input: if the Intent's data URI is set with an application name (using the "package" schema,
-     * like "package:com.my.app"), then when the screen is displayed it will focus on such app. If
-     * the data is not set, it will just open the screen.
+     * Input: Intent's data URI set with an application name, using the
+     * "package" schema (like "package:com.my.app").
+     *
      * <p>
      * Output: Nothing.
      * <p>
      * Applications can also use {@link android.net.ConnectivityManager#getRestrictBackgroundStatus
-     * ConnectivityManager#getRestrictBackgroundStatus()} to determine the status of the background
-     * data restrictions for them.
+     * ConnectivityManager#getRestrictBackgroundStatus()} to determine the
+     * status of the background data restrictions for them.
      */
     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
     public static final String ACTION_IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS =
@@ -6869,14 +6869,6 @@
                "hdmi_control_auto_device_off_enabled";
 
        /**
-        * Whether to use the DHCP client from Lollipop and earlier instead of the newer Android DHCP
-        * client.
-        * (0 = false, 1 = true)
-        * @hide
-        */
-       public static final String LEGACY_DHCP_CLIENT = "legacy_dhcp_client";
-
-       /**
         * Whether TV will switch to MHL port when a mobile device is plugged in.
         * (0 = false, 1 = true)
         * @hide
@@ -6982,6 +6974,33 @@
        public static final String STORAGE_BENCHMARK_INTERVAL = "storage_benchmark_interval";
 
        /**
+        * Sample validity in seconds to configure for the system DNS resolver.
+        * {@hide}
+        */
+       public static final String DNS_RESOLVER_SAMPLE_VALIDITY_SECONDS =
+               "dns_resolver_sample_validity_seconds";
+
+       /**
+        * Success threshold in percent for use with the system DNS resolver.
+        * {@hide}
+        */
+       public static final String DNS_RESOLVER_SUCCESS_THRESHOLD_PERCENT =
+                "dns_resolver_success_threshold_percent";
+
+       /**
+        * Minimum number of samples needed for statistics to be considered meaningful in the
+        * system DNS resolver.
+        * {@hide}
+        */
+       public static final String DNS_RESOLVER_MIN_SAMPLES = "dns_resolver_min_samples";
+
+       /**
+        * Maximum number taken into account for statistics purposes in the system DNS resolver.
+        * {@hide}
+        */
+       public static final String DNS_RESOLVER_MAX_SAMPLES = "dns_resolver_max_samples";
+
+       /**
         * Whether to disable the automatic scheduling of system updates.
         * 1 = system updates won't be automatically scheduled (will always
         * present notification instead).
@@ -7706,6 +7725,15 @@
         public static final String CAPTIVE_PORTAL_SERVER = "captive_portal_server";
 
         /**
+         * Whether to use HTTPS for network validation. This is enabled by default and the setting
+         * needs to be set to 0 to disable it. This setting is a misnomer because captive portals
+         * don't actually use HTTPS, but it's consistent with the other settings.
+         *
+         * @hide
+         */
+        public static final String CAPTIVE_PORTAL_USE_HTTPS = "captive_portal_use_https";
+
+        /**
          * Whether network service discovery is enabled.
          *
          * @hide
diff --git a/core/java/android/service/notification/NotificationListenerService.java b/core/java/android/service/notification/NotificationListenerService.java
index e708b0a..cf783d2 100644
--- a/core/java/android/service/notification/NotificationListenerService.java
+++ b/core/java/android/service/notification/NotificationListenerService.java
@@ -764,9 +764,9 @@
         }
         mSystemContext = context;
         INotificationManager noMan = getNotificationInterface();
-        noMan.registerListener(mWrapper, componentName, currentUser);
-        mCurrentUser = currentUser;
         mHandler = new MyHandler(context.getMainLooper());
+        mCurrentUser = currentUser;
+        noMan.registerListener(mWrapper, componentName, currentUser);
     }
 
     /**
diff --git a/core/java/android/view/DisplayInfo.java b/core/java/android/view/DisplayInfo.java
index 27fe687c..8aeeffd 100644
--- a/core/java/android/view/DisplayInfo.java
+++ b/core/java/android/view/DisplayInfo.java
@@ -380,7 +380,7 @@
         for (int i = 0; i < nColorTransforms; i++) {
             supportedColorTransforms[i] = Display.ColorTransform.CREATOR.createFromParcel(source);
         }
-        hdrCapabilities = Display.HdrCapabilities.CREATOR.createFromParcel(source);
+        hdrCapabilities = source.readParcelable(null);
         logicalDensityDpi = source.readInt();
         physicalXDpi = source.readFloat();
         physicalYDpi = source.readFloat();
@@ -424,7 +424,7 @@
         for (int i = 0; i < supportedColorTransforms.length; i++) {
             supportedColorTransforms[i].writeToParcel(dest, flags);
         }
-        hdrCapabilities.writeToParcel(dest, flags);
+        dest.writeParcelable(hdrCapabilities, flags);
         dest.writeInt(logicalDensityDpi);
         dest.writeFloat(physicalXDpi);
         dest.writeFloat(physicalYDpi);
diff --git a/core/java/android/view/ViewRootImpl.java b/core/java/android/view/ViewRootImpl.java
index a0384f2..edf05ba 100644
--- a/core/java/android/view/ViewRootImpl.java
+++ b/core/java/android/view/ViewRootImpl.java
@@ -389,6 +389,8 @@
     /** Set to true once doDie() has been called. */
     private boolean mRemoved;
 
+    private boolean mNeedsHwRendererSetup;
+
     /**
      * Consistency verifier for debugging purposes.
      */
@@ -915,6 +917,11 @@
                 mWindowAttributes.surfaceInsets.set(
                         oldInsetLeft, oldInsetTop, oldInsetRight, oldInsetBottom);
                 mWindowAttributes.hasManualSurfaceInsets = oldHasManualSurfaceInsets;
+            } else if (mWindowAttributes.surfaceInsets.left != oldInsetLeft
+                    || mWindowAttributes.surfaceInsets.top != oldInsetTop
+                    || mWindowAttributes.surfaceInsets.right != oldInsetRight
+                    || mWindowAttributes.surfaceInsets.bottom != oldInsetBottom) {
+                mNeedsHwRendererSetup = true;
             }
 
             applyKeepScreenOnFlag(mWindowAttributes);
@@ -1959,9 +1966,11 @@
             if (hardwareRenderer != null && hardwareRenderer.isEnabled()) {
                 if (hwInitialized
                         || mWidth != hardwareRenderer.getWidth()
-                        || mHeight != hardwareRenderer.getHeight()) {
+                        || mHeight != hardwareRenderer.getHeight()
+                        || mNeedsHwRendererSetup) {
                     hardwareRenderer.setup(mWidth, mHeight, mAttachInfo,
                             mWindowAttributes.surfaceInsets);
+                    mNeedsHwRendererSetup = false;
                 }
             }
 
diff --git a/core/java/android/view/WindowManagerInternal.java b/core/java/android/view/WindowManagerInternal.java
index 3ad730b..4b188c4 100644
--- a/core/java/android/view/WindowManagerInternal.java
+++ b/core/java/android/view/WindowManagerInternal.java
@@ -54,13 +54,12 @@
     public interface MagnificationCallbacks {
 
         /**
-         * Called when the bounds of the screen content that is magnified changed.
-         * Note that not the entire screen is magnified.
+         * Called when the region where magnification operates changes. Note that this isn't the
+         * entire screen. For example, IMEs are not magnified.
          *
-         * @param magnifiedBounds the currently magnified region
-         * @param availableBounds the region available for magnification
+         * @param magnificationRegion the current magnification region
          */
-        public void onMagnifiedBoundsChanged(Region magnifiedBounds, Region availableBounds);
+        public void onMagnificationRegionChanged(Region magnificationRegion);
 
         /**
          * Called when an application requests a rectangle on the screen to allow
@@ -158,13 +157,11 @@
     public abstract void setMagnificationSpec(MagnificationSpec spec);
 
     /**
-     * Obtains the magnified and available regions.
+     * Obtains the magnification regions.
      *
-     * @param outMagnified the currently magnified region
-     * @param outAvailable the region available for magnification
+     * @param magnificationRegion the current magnification region
      */
-    public abstract void getMagnificationRegions(@NonNull Region outMagnified,
-            @NonNull Region outAvailable);
+    public abstract void getMagnificationRegion(@NonNull Region magnificationRegion);
 
     /**
      * Gets the magnification and translation applied to a window given its token.
diff --git a/core/java/android/webkit/WebChromeClient.java b/core/java/android/webkit/WebChromeClient.java
index 4737e9b..2d3b6ab 100644
--- a/core/java/android/webkit/WebChromeClient.java
+++ b/core/java/android/webkit/WebChromeClient.java
@@ -284,6 +284,13 @@
      * currently set for that origin. The host application should invoke the
      * specified callback with the desired permission state. See
      * {@link GeolocationPermissions} for details.
+     *
+     * <p>Note that for applications targeting Android N and later SDKs
+     * (API level > {@link android.os.Build.VERSION_CODES#M})
+     * this method is only called for requests originating from secure
+     * origins such as https. On non-secure origins geolocation requests
+     * are automatically denied.</p>
+     *
      * @param origin The origin of the web content attempting to use the
      *               Geolocation API.
      * @param callback The callback to use to set the permission state for the
diff --git a/core/java/android/webkit/WebView.java b/core/java/android/webkit/WebView.java
index ada7731..f54edf1 100644
--- a/core/java/android/webkit/WebView.java
+++ b/core/java/android/webkit/WebView.java
@@ -255,6 +255,16 @@
  * is loading.
  * </p>
  *
+ * <h3>HTML5 Geolocation API support</h3>
+ *
+ * <p>For applications targeting Android N and later releases
+ * (API level > {@link android.os.Build.VERSION_CODES#M}) the geolocation api is only supported on
+ * secure origins such as https. For such applications requests to geolocation api on non-secure
+ * origins are automatically denied without invoking the corresponding
+ * {@link WebChromeClient#onGeolocationPermissionsShowPrompt(String, GeolocationPermissions.Callback)}
+ * method.
+ * </p>
+ *
  * <h3>Layout size</h3>
  * <p>
  * It is recommended to set the WebView layout height to a fixed value or to
diff --git a/core/java/android/widget/AbsSpinner.java b/core/java/android/widget/AbsSpinner.java
index 1cb7f2a..18db54e 100644
--- a/core/java/android/widget/AbsSpinner.java
+++ b/core/java/android/widget/AbsSpinner.java
@@ -356,10 +356,18 @@
                     return mFirstPosition + i;
                 }
             }
-        } 
+        }
         return INVALID_POSITION;
     }
-    
+
+    @Override
+    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
+        super.dispatchRestoreInstanceState(container);
+        // Restores the selected position when Spinner gets restored,
+        // rather than wait until the next measure/layout pass to do it.
+        handleDataChanged();
+    }
+
     static class SavedState extends BaseSavedState {
         long selectedId;
         int position;
diff --git a/core/java/android/widget/AdapterView.java b/core/java/android/widget/AdapterView.java
index 6ed7ab8..2cfefba 100644
--- a/core/java/android/widget/AdapterView.java
+++ b/core/java/android/widget/AdapterView.java
@@ -815,7 +815,6 @@
     @Override
     protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
         dispatchThawSelfOnly(container);
-        handleDataChanged();
     }
 
     class AdapterDataSetObserver extends DataSetObserver {
diff --git a/core/java/android/widget/ListView.java b/core/java/android/widget/ListView.java
index bfc87f2..bb1ffcb 100644
--- a/core/java/android/widget/ListView.java
+++ b/core/java/android/widget/ListView.java
@@ -1308,7 +1308,7 @@
 
         // Include the padding of the list
         int returnedHeight = mListPadding.top + mListPadding.bottom;
-        final int dividerHeight = ((mDividerHeight > 0) && mDivider != null) ? mDividerHeight : 0;
+        final int dividerHeight = mDividerHeight;
         // The previous height value that was less than maxHeight and contained
         // no partial children
         int prevHeightWithoutPartialChild = 0;
diff --git a/core/java/android/widget/TimePickerClockDelegate.java b/core/java/android/widget/TimePickerClockDelegate.java
index b6200a1..c21f1df 100644
--- a/core/java/android/widget/TimePickerClockDelegate.java
+++ b/core/java/android/widget/TimePickerClockDelegate.java
@@ -38,6 +38,7 @@
 import android.view.accessibility.AccessibilityEvent;
 import android.view.accessibility.AccessibilityNodeInfo;
 import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
+import android.widget.RadialTimePickerView.OnValueSelectedListener;
 
 import com.android.internal.R;
 import com.android.internal.widget.NumericTextView;
@@ -48,8 +49,7 @@
 /**
  * A delegate implementing the radial clock-based TimePicker.
  */
-class TimePickerClockDelegate extends TimePicker.AbstractTimePickerDelegate implements
-        RadialTimePickerView.OnValueSelectedListener {
+class TimePickerClockDelegate extends TimePicker.AbstractTimePickerDelegate {
     /**
      * Delay in milliseconds before valid but potentially incomplete, for
      * example "1" but not "12", keyboard edits are propagated from the
@@ -88,8 +88,8 @@
 
     private boolean mIsEnabled = true;
     private boolean mAllowAutoAdvance;
-    private int mInitialHourOfDay;
-    private int mInitialMinute;
+    private int mCurrentHour;
+    private int mCurrentMinute;
     private boolean mIs24Hour;
     private boolean mIsAmPmAtStart;
 
@@ -189,8 +189,7 @@
 
         mRadialTimePickerView = (RadialTimePickerView) mainView.findViewById(R.id.radial_picker);
         mRadialTimePickerView.applyAttributes(attrs, defStyleAttr, defStyleRes);
-
-        setupListeners();
+        mRadialTimePickerView.setOnValueSelectedListener(mOnValueSelectedListener);
 
         mAllowAutoAdvance = true;
 
@@ -324,28 +323,24 @@
     }
 
     private void initialize(int hourOfDay, int minute, boolean is24HourView, int index) {
-        mInitialHourOfDay = hourOfDay;
-        mInitialMinute = minute;
+        mCurrentHour = hourOfDay;
+        mCurrentMinute = minute;
         mIs24Hour = is24HourView;
         updateUI(index);
     }
 
-    private void setupListeners() {
-        mRadialTimePickerView.setOnValueSelectedListener(this);
-    }
-
     private void updateUI(int index) {
         updateHeaderAmPm();
-        updateHeaderHour(mInitialHourOfDay, false);
+        updateHeaderHour(mCurrentHour, false);
         updateHeaderSeparator();
-        updateHeaderMinute(mInitialMinute, false);
+        updateHeaderMinute(mCurrentMinute, false);
         updateRadialPicker(index);
 
         mDelegator.invalidate();
     }
 
     private void updateRadialPicker(int index) {
-        mRadialTimePickerView.initialize(mInitialHourOfDay, mInitialMinute, mIs24Hour);
+        mRadialTimePickerView.initialize(mCurrentHour, mCurrentMinute, mIs24Hour);
         setCurrentItemShowing(index, false, true);
     }
 
@@ -358,7 +353,7 @@
             final boolean isAmPmAtStart = dateTimePattern.startsWith("a");
             setAmPmAtStart(isAmPmAtStart);
 
-            updateAmPmLabelStates(mInitialHourOfDay < 12 ? AM : PM);
+            updateAmPmLabelStates(mCurrentHour < 12 ? AM : PM);
         }
     }
 
@@ -388,15 +383,25 @@
      */
     @Override
     public void setHour(int hour) {
-        if (mInitialHourOfDay != hour) {
-            mInitialHourOfDay = hour;
-            updateHeaderHour(hour, true);
-            updateHeaderAmPm();
-            mRadialTimePickerView.setCurrentHour(hour);
-            mRadialTimePickerView.setAmOrPm(mInitialHourOfDay < 12 ? AM : PM);
-            mDelegator.invalidate();
-            onTimeChanged();
+        setHourInternal(hour, false, true);
+    }
+
+    private void setHourInternal(int hour, boolean isFromPicker, boolean announce) {
+        if (mCurrentHour == hour) {
+            return;
         }
+
+        mCurrentHour = hour;
+        updateHeaderHour(hour, announce);
+        updateHeaderAmPm();
+
+        if (!isFromPicker) {
+            mRadialTimePickerView.setCurrentHour(hour);
+            mRadialTimePickerView.setAmOrPm(hour < 12 ? AM : PM);
+        }
+
+        mDelegator.invalidate();
+        onTimeChanged();
     }
 
     /**
@@ -421,13 +426,23 @@
      */
     @Override
     public void setMinute(int minute) {
-        if (mInitialMinute != minute) {
-            mInitialMinute = minute;
-            updateHeaderMinute(minute, true);
-            mRadialTimePickerView.setCurrentMinute(minute);
-            mDelegator.invalidate();
-            onTimeChanged();
+        setMinuteInternal(minute, false);
+    }
+
+    private void setMinuteInternal(int minute, boolean isFromPicker) {
+        if (mCurrentMinute == minute) {
+            return;
         }
+
+        mCurrentMinute = minute;
+        updateHeaderMinute(minute, true);
+
+        if (!isFromPicker) {
+            mRadialTimePickerView.setCurrentMinute(minute);
+        }
+
+        mDelegator.invalidate();
+        onTimeChanged();
     }
 
     /**
@@ -448,7 +463,7 @@
     public void setIs24Hour(boolean is24Hour) {
         if (mIs24Hour != is24Hour) {
             mIs24Hour = is24Hour;
-            mInitialHourOfDay = getHour();
+            mCurrentHour = getHour();
 
             updateHourFormat();
             updateUI(mRadialTimePickerView.getCurrentItemShowing());
@@ -563,34 +578,6 @@
     }
 
     /**
-     * Called by the picker for updating the header display.
-     */
-    @Override
-    public void onValueSelected(int pickerIndex, int newValue, boolean autoAdvance) {
-        switch (pickerIndex) {
-            case HOUR_INDEX:
-                if (mAllowAutoAdvance && autoAdvance) {
-                    updateHeaderHour(newValue, false);
-                    setCurrentItemShowing(MINUTE_INDEX, true, false);
-                    mDelegator.announceForAccessibility(newValue + ". " + mSelectMinutes);
-                } else {
-                    updateHeaderHour(newValue, true);
-                }
-                break;
-            case MINUTE_INDEX:
-                updateHeaderMinute(newValue, true);
-                break;
-            case AMPM_INDEX:
-                updateAmPmLabelStates(newValue);
-                break;
-        }
-
-        if (mOnTimeChangedListener != null) {
-            mOnTimeChangedListener.onTimeChanged(mDelegator, getHour(), getMinute());
-        }
-    }
-
-    /**
      * Converts hour-of-day (0-23) time into a localized hour number.
      * <p>
      * The localized value may be in the range (0-23), (1-24), (0-11), or
@@ -702,11 +689,43 @@
     private void setAmOrPm(int amOrPm) {
         updateAmPmLabelStates(amOrPm);
 
-        if (mRadialTimePickerView.setAmOrPm(amOrPm) && mOnTimeChangedListener != null) {
-            mOnTimeChangedListener.onTimeChanged(mDelegator, getHour(), getMinute());
+        if (mRadialTimePickerView.setAmOrPm(amOrPm)) {
+            mCurrentHour = getHour();
+
+            if (mOnTimeChangedListener != null) {
+                mOnTimeChangedListener.onTimeChanged(mDelegator, getHour(), getMinute());
+            }
         }
     }
 
+    /** Listener for RadialTimePickerView interaction. */
+    private final OnValueSelectedListener mOnValueSelectedListener = new OnValueSelectedListener() {
+        @Override
+        public void onValueSelected(int pickerIndex, int newValue, boolean autoAdvance) {
+            switch (pickerIndex) {
+                case HOUR_INDEX:
+                    final boolean isTransition = mAllowAutoAdvance && autoAdvance;
+                    setHourInternal(newValue, true, !isTransition);
+                    if (isTransition) {
+                        setCurrentItemShowing(MINUTE_INDEX, true, false);
+                        mDelegator.announceForAccessibility(newValue + ". " + mSelectMinutes);
+                    }
+                    break;
+                case MINUTE_INDEX:
+                    setMinuteInternal(newValue, true);
+                    break;
+                case AMPM_INDEX:
+                    updateAmPmLabelStates(newValue);
+                    break;
+            }
+
+            if (mOnTimeChangedListener != null) {
+                mOnTimeChangedListener.onTimeChanged(mDelegator, getHour(), getMinute());
+            }
+        }
+    };
+
+    /** Listener for keyboard interaction. */
     private final OnValueChangedListener mDigitEnteredListener = new OnValueChangedListener() {
         @Override
         public void onValueChanged(NumericTextView view, int value,
diff --git a/core/java/com/android/internal/app/IBatteryStats.aidl b/core/java/com/android/internal/app/IBatteryStats.aidl
index a2a135b..42b89d5 100644
--- a/core/java/com/android/internal/app/IBatteryStats.aidl
+++ b/core/java/com/android/internal/app/IBatteryStats.aidl
@@ -122,7 +122,8 @@
     void noteNetworkInterfaceType(String iface, int type);
     void noteNetworkStatsEnabled();
     void noteDeviceIdleMode(int mode, String activeReason, int activeUid);
-    void setBatteryState(int status, int health, int plugType, int level, int temp, int volt);
+    void setBatteryState(int status, int health, int plugType, int level, int temp, int volt,
+            int chargeCount);
     long getAwakeTimeBattery();
     long getAwakeTimePlugged();
 
diff --git a/core/java/com/android/internal/content/PackageMonitor.java b/core/java/com/android/internal/content/PackageMonitor.java
index 7bd64e5..c6b6a7fb 100644
--- a/core/java/com/android/internal/content/PackageMonitor.java
+++ b/core/java/com/android/internal/content/PackageMonitor.java
@@ -45,6 +45,7 @@
         sPackageFilt.addAction(Intent.ACTION_PACKAGE_CHANGED);
         sPackageFilt.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
         sPackageFilt.addAction(Intent.ACTION_PACKAGE_RESTARTED);
+        sPackageFilt.addAction(Intent.ACTION_PACKAGE_DATA_CLEARED);
         sPackageFilt.addDataScheme("package");
         sNonDataFilt.addAction(Intent.ACTION_UID_REMOVED);
         sNonDataFilt.addAction(Intent.ACTION_USER_STOPPED);
@@ -275,6 +276,9 @@
     public void onFinishPackageChanges() {
     }
 
+    public void onPackageDataCleared(String packageName, int uid) {
+    }
+
     public int getChangingUserId() {
         return mChangeUserId;
     }
@@ -365,6 +369,12 @@
                 }
                 onPackageModified(pkg);
             }
+        } else if (Intent.ACTION_PACKAGE_DATA_CLEARED.equals(action)) {
+            String pkg = getPackageName(intent);
+            int uid = intent.getIntExtra(Intent.EXTRA_UID, 0);
+            if (pkg != null) {
+                onPackageDataCleared(pkg, uid);
+            }
         } else if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
             mDisappearingPackages = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
             mChangeType = PACKAGE_TEMPORARY_CHANGE;
diff --git a/core/java/com/android/internal/os/BatteryStatsImpl.java b/core/java/com/android/internal/os/BatteryStatsImpl.java
index e69ed35..654a4f1 100644
--- a/core/java/com/android/internal/os/BatteryStatsImpl.java
+++ b/core/java/com/android/internal/os/BatteryStatsImpl.java
@@ -108,7 +108,7 @@
     private static final int MAGIC = 0xBA757475; // 'BATSTATS'
 
     // Current on-disk Parcel version
-    private static final int VERSION = 142 + (USE_OLD_HISTORY ? 1000 : 0);
+    private static final int VERSION = 144 + (USE_OLD_HISTORY ? 1000 : 0);
 
     // Maximum number of items we will record in the history.
     private static final int MAX_HISTORY_ITEMS = 2000;
@@ -150,6 +150,13 @@
         public void batterySendBroadcast(Intent intent);
     }
 
+    public interface PlatformIdleStateCallback {
+        public String getPlatformLowPowerStats();
+    }
+
+    private final PlatformIdleStateCallback mPlatformIdleStateCallback;
+
+
     final class MyHandler extends Handler {
         public MyHandler(Looper looper) {
             super(looper, null, true);
@@ -569,6 +576,7 @@
         mDailyFile = null;
         mHandler = null;
         mExternalSync = null;
+        mPlatformIdleStateCallback = null;
         clearHistoryLocked();
     }
 
@@ -2081,27 +2089,111 @@
         tag.poolIdx = index;
     }
 
+    /*
+        The history delta format uses flags to denote further data in subsequent ints in the parcel.
+
+        There is always the first token, which may contain the delta time, or an indicator of
+        the length of the time (int or long) following this token.
+
+        First token: always present,
+        31              23              15               7             0
+        █M|L|K|J|I|H|G|F█E|D|C|B|A|T|T|T█T|T|T|T|T|T|T|T█T|T|T|T|T|T|T|T█
+
+        T: the delta time if it is <= 0x7fffd. Otherwise 0x7fffe indicates an int immediately
+           follows containing the time, and 0x7ffff indicates a long immediately follows with the
+           delta time.
+        A: battery level changed and an int follows with battery data.
+        B: state changed and an int follows with state change data.
+        C: state2 has changed and an int follows with state2 change data.
+        D: wakelock/wakereason has changed and an wakelock/wakereason struct follows.
+        E: event data has changed and an event struct follows.
+        F: battery charge in coulombs has changed and an int with the charge follows.
+        G: state flag denoting that the mobile radio was active.
+        H: state flag denoting that the wifi radio was active.
+        I: state flag denoting that a wifi scan occurred.
+        J: state flag denoting that a wifi full lock was held.
+        K: state flag denoting that the gps was on.
+        L: state flag denoting that a wakelock was held.
+        M: state flag denoting that the cpu was running.
+
+        Time int/long: if T in the first token is 0x7ffff or 0x7fffe, then an int or long follows
+        with the time delta.
+
+        Battery level int: if A in the first token is set,
+        31              23              15               7             0
+        █L|L|L|L|L|L|L|T█T|T|T|T|T|T|T|T█T|V|V|V|V|V|V|V█V|V|V|V|V|V|V|D█
+
+        D: indicates that extra history details follow.
+        V: the battery voltage.
+        T: the battery temperature.
+        L: the battery level (out of 100).
+
+        State change int: if B in the first token is set,
+        31              23              15               7             0
+        █S|S|S|H|H|H|P|P█F|E|D|C|B| | |A█ | | | | | | | █ | | | | | | | █
+
+        A: wifi multicast was on.
+        B: battery was plugged in.
+        C: screen was on.
+        D: phone was scanning for signal.
+        E: audio was on.
+        F: a sensor was active.
+
+        State2 change int: if C in the first token is set,
+        31              23              15               7             0
+        █M|L|K|J|I|H|H|G█F|E|D|C| | | | █ | | | | | | | █ |B|B|B|A|A|A|A█
+
+        A: 4 bits indicating the wifi supplicant state: {@link BatteryStats#WIFI_SUPPL_STATE_NAMES}.
+        B: 3 bits indicating the wifi signal strength: 0, 1, 2, 3, 4.
+        C: a bluetooth scan was active.
+        D: the camera was active.
+        E: bluetooth was on.
+        F: a phone call was active.
+        G: the device was charging.
+        H: 2 bits indicating the device-idle (doze) state: off, light, full
+        I: the flashlight was on.
+        J: wifi was on.
+        K: wifi was running.
+        L: video was playing.
+        M: power save mode was on.
+
+        Wakelock/wakereason struct: if D in the first token is set,
+        TODO(adamlesinski): describe wakelock/wakereason struct.
+
+        Event struct: if E in the first token is set,
+        TODO(adamlesinski): describe the event struct.
+
+        History step details struct: if D in the battery level int is set,
+        TODO(adamlesinski): describe the history step details struct.
+
+        Battery charge int: if F in the first token is set, an int representing the battery charge
+        in coulombs follows.
+     */
+
     // Part of initial delta int that specifies the time delta.
     static final int DELTA_TIME_MASK = 0x7ffff;
     static final int DELTA_TIME_LONG = 0x7ffff;   // The delta is a following long
     static final int DELTA_TIME_INT = 0x7fffe;    // The delta is a following int
     static final int DELTA_TIME_ABS = 0x7fffd;    // Following is an entire abs update.
     // Flag in delta int: a new battery level int follows.
-    static final int DELTA_BATTERY_LEVEL_FLAG   = 0x00080000;
+    static final int DELTA_BATTERY_LEVEL_FLAG               = 0x00080000;
     // Flag in delta int: a new full state and battery status int follows.
-    static final int DELTA_STATE_FLAG           = 0x00100000;
+    static final int DELTA_STATE_FLAG                       = 0x00100000;
     // Flag in delta int: a new full state2 int follows.
-    static final int DELTA_STATE2_FLAG          = 0x00200000;
+    static final int DELTA_STATE2_FLAG                      = 0x00200000;
     // Flag in delta int: contains a wakelock or wakeReason tag.
-    static final int DELTA_WAKELOCK_FLAG        = 0x00400000;
+    static final int DELTA_WAKELOCK_FLAG                    = 0x00400000;
     // Flag in delta int: contains an event description.
-    static final int DELTA_EVENT_FLAG           = 0x00800000;
+    static final int DELTA_EVENT_FLAG                       = 0x00800000;
+    // Flag in delta int: contains a coulomb charge count.
+    static final int DELTA_BATTERY_CHARGE_COULOMBS_FLAG     = 0x01000000;
     // These upper bits are the frequently changing state bits.
-    static final int DELTA_STATE_MASK           = 0xff000000;
+    static final int DELTA_STATE_MASK                       = 0xfe000000;
 
     // These are the pieces of battery state that are packed in to the upper bits of
     // the state int that have been packed in to the first delta int.  They must fit
-    // in DELTA_STATE_MASK.
+    // in STATE_BATTERY_MASK.
+    static final int STATE_BATTERY_MASK         = 0xff000000;
     static final int STATE_BATTERY_STATUS_MASK  = 0x00000007;
     static final int STATE_BATTERY_STATUS_SHIFT = 29;
     static final int STATE_BATTERY_HEALTH_MASK  = 0x00000007;
@@ -2157,6 +2249,12 @@
         if (cur.eventCode != HistoryItem.EVENT_NONE) {
             firstToken |= DELTA_EVENT_FLAG;
         }
+
+        final boolean batteryChargeCoulombsChanged = cur.batteryChargeCoulombs
+                != last.batteryChargeCoulombs;
+        if (batteryChargeCoulombsChanged) {
+            firstToken |= DELTA_BATTERY_CHARGE_COULOMBS_FLAG;
+        }
         dest.writeInt(firstToken);
         if (DEBUG) Slog.i(TAG, "WRITE DELTA: firstToken=0x" + Integer.toHexString(firstToken)
                 + " deltaTime=" + deltaTime);
@@ -2220,6 +2318,12 @@
                     + cur.eventTag.string);
         }
         if (computeStepDetails) {
+            if (mPlatformIdleStateCallback != null) {
+                mCurHistoryStepDetails.statPlatformIdleState =
+                        mPlatformIdleStateCallback.getPlatformLowPowerStats();
+                if (DEBUG) Slog.i(TAG, "WRITE PlatformIdleState:" +
+                        mCurHistoryStepDetails.statPlatformIdleState);
+            }
             computeHistoryStepDetails(mCurHistoryStepDetails, mLastHistoryStepDetails);
             if (includeStepDetails != 0) {
                 mCurHistoryStepDetails.writeToParcel(dest);
@@ -2233,6 +2337,12 @@
             mLastHistoryStepDetails = null;
         }
         mLastHistoryStepLevel = cur.batteryLevel;
+
+        if (batteryChargeCoulombsChanged) {
+            if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryChargeCoulombs="
+                    + cur.batteryChargeCoulombs);
+            dest.writeInt(cur.batteryChargeCoulombs);
+        }
     }
 
     private int buildBatteryLevelInt(HistoryItem h) {
@@ -2259,7 +2369,7 @@
         return ((h.batteryStatus&STATE_BATTERY_STATUS_MASK)<<STATE_BATTERY_STATUS_SHIFT)
                 | ((h.batteryHealth&STATE_BATTERY_HEALTH_MASK)<<STATE_BATTERY_HEALTH_SHIFT)
                 | ((plugType&STATE_BATTERY_PLUG_MASK)<<STATE_BATTERY_PLUG_SHIFT)
-                | (h.states&(~DELTA_STATE_MASK));
+                | (h.states&(~STATE_BATTERY_MASK));
     }
 
     private void computeHistoryStepDetails(final HistoryStepDetails out,
@@ -2398,7 +2508,7 @@
 
         if ((firstToken&DELTA_STATE_FLAG) != 0) {
             int stateInt = src.readInt();
-            cur.states = (firstToken&DELTA_STATE_MASK) | (stateInt&(~DELTA_STATE_MASK));
+            cur.states = (firstToken&DELTA_STATE_MASK) | (stateInt&(~STATE_BATTERY_MASK));
             cur.batteryStatus = (byte)((stateInt>>STATE_BATTERY_STATUS_SHIFT)
                     & STATE_BATTERY_STATUS_MASK);
             cur.batteryHealth = (byte)((stateInt>>STATE_BATTERY_HEALTH_SHIFT)
@@ -2424,7 +2534,7 @@
                     + " batteryPlugType=" + cur.batteryPlugType
                     + " states=0x" + Integer.toHexString(cur.states));
         } else {
-            cur.states = (firstToken&DELTA_STATE_MASK) | (cur.states&(~DELTA_STATE_MASK));
+            cur.states = (firstToken&DELTA_STATE_MASK) | (cur.states&(~STATE_BATTERY_MASK));
         }
 
         if ((firstToken&DELTA_STATE2_FLAG) != 0) {
@@ -2479,6 +2589,10 @@
         } else {
             cur.stepDetails = null;
         }
+
+        if ((firstToken&DELTA_BATTERY_CHARGE_COULOMBS_FLAG) != 0) {
+            cur.batteryChargeCoulombs = src.readInt();
+        }
     }
 
     @Override
@@ -5597,12 +5711,12 @@
                 mWifiControllerActivity.reset(false);
             }
 
-            if (mBsi.mBluetoothActivity != null) {
-                mBsi.mBluetoothActivity.reset(false);
+            if (mBluetoothControllerActivity != null) {
+                mBluetoothControllerActivity.reset(false);
             }
 
-            if (mBsi.mModemActivity != null) {
-                mBsi.mModemActivity.reset(false);
+            if (mModemControllerActivity != null) {
+                mModemControllerActivity.reset(false);
             }
 
             mUserCpuTime.reset(false);
@@ -7372,11 +7486,16 @@
     }
 
     public BatteryStatsImpl(File systemDir, Handler handler, ExternalStatsSync externalSync) {
-        this(new SystemClocks(), systemDir, handler, externalSync);
+        this(new SystemClocks(), systemDir, handler, externalSync, null);
+    }
+
+    public BatteryStatsImpl(File systemDir, Handler handler, ExternalStatsSync externalSync,
+                            PlatformIdleStateCallback cb) {
+        this(new SystemClocks(), systemDir, handler, externalSync, cb);
     }
 
     public BatteryStatsImpl(Clocks clocks, File systemDir, Handler handler,
-            ExternalStatsSync externalSync) {
+            ExternalStatsSync externalSync, PlatformIdleStateCallback cb) {
         init(clocks);
 
         if (systemDir != null) {
@@ -7462,6 +7581,7 @@
         initDischarge();
         clearHistoryLocked();
         updateDailyDeadlineLocked();
+        mPlatformIdleStateCallback = cb;
     }
 
     public BatteryStatsImpl(Parcel p) {
@@ -7477,6 +7597,7 @@
         mExternalSync = null;
         clearHistoryLocked();
         readFromParcel(p);
+        mPlatformIdleStateCallback = null;
     }
 
     public void setPowerProfile(PowerProfile profile) {
@@ -9189,7 +9310,7 @@
     public static final int BATTERY_PLUGGED_NONE = 0;
 
     public void setBatteryStateLocked(int status, int health, int plugType, int level,
-            int temp, int volt) {
+            int temp, int volt, int chargeCount) {
         final boolean onBattery = plugType == BATTERY_PLUGGED_NONE;
         final long uptime = mClocks.uptimeMillis();
         final long elapsedRealtime = mClocks.elapsedRealtime();
@@ -9233,6 +9354,7 @@
         if (mDischargePlugLevel < 0) {
             mDischargePlugLevel = level;
         }
+
         if (onBattery != mOnBattery) {
             mHistoryCur.batteryLevel = (byte)level;
             mHistoryCur.batteryStatus = (byte)status;
@@ -9240,6 +9362,7 @@
             mHistoryCur.batteryPlugType = (byte)plugType;
             mHistoryCur.batteryTemperature = (short)temp;
             mHistoryCur.batteryVoltage = (char)volt;
+            mHistoryCur.batteryChargeCoulombs = chargeCount;
             setOnBatteryLocked(elapsedRealtime, uptime, onBattery, oldStatus, level);
         } else {
             boolean changed = false;
@@ -9273,6 +9396,11 @@
                 mHistoryCur.batteryVoltage = (char)volt;
                 changed = true;
             }
+            if (chargeCount >= (mHistoryCur.batteryChargeCoulombs+10)
+                    || chargeCount <= (mHistoryCur.batteryChargeCoulombs-10)) {
+                mHistoryCur.batteryChargeCoulombs = chargeCount;
+                changed = true;
+            }
             long modeBits = (((long)mInitStepMode) << STEP_LEVEL_INITIAL_MODE_SHIFT)
                     | (((long)mModStepMode) << STEP_LEVEL_MODIFIED_MODE_SHIFT)
                     | (((long)(level&0xff)) << STEP_LEVEL_LEVEL_SHIFT);
diff --git a/core/java/com/android/internal/policy/DecorView.java b/core/java/com/android/internal/policy/DecorView.java
index 645ffda..68a1378 100644
--- a/core/java/com/android/internal/policy/DecorView.java
+++ b/core/java/com/android/internal/policy/DecorView.java
@@ -78,6 +78,7 @@
 
 import static android.app.ActivityManager.StackId;
 import static android.app.ActivityManager.StackId.FULLSCREEN_WORKSPACE_STACK_ID;
+import static android.app.ActivityManager.StackId.PINNED_STACK_ID;
 import static android.app.ActivityManager.StackId.INVALID_STACK_ID;
 import static android.content.res.Configuration.ORIENTATION_PORTRAIT;
 import static android.os.Build.VERSION_CODES.M;
@@ -2060,8 +2061,11 @@
         if (StackId.hasWindowShadow(mStackId) && !isResizing()) {
             elevation = hasWindowFocus() ?
                     DECOR_SHADOW_FOCUSED_HEIGHT_IN_DIP : DECOR_SHADOW_UNFOCUSED_HEIGHT_IN_DIP;
+            // Add a maximum shadow height value to the top level view.
+            // Note that pinned stack doesn't have focus
+            // so maximum shadow height adjustment isn't needed.
             // TODO(skuhne): Remove this if clause once b/22668382 got fixed.
-            if (!mAllowUpdateElevation) {
+            if (!mAllowUpdateElevation && mStackId != PINNED_STACK_ID) {
                 elevation = DECOR_SHADOW_FOCUSED_HEIGHT_IN_DIP;
             }
             // Convert the DP elevation into physical pixels.
diff --git a/core/java/com/android/internal/view/FloatingActionMode.java b/core/java/com/android/internal/view/FloatingActionMode.java
index b44baa2..ccdb024 100644
--- a/core/java/com/android/internal/view/FloatingActionMode.java
+++ b/core/java/com/android/internal/view/FloatingActionMode.java
@@ -24,6 +24,8 @@
 import android.view.MenuItem;
 import android.view.View;
 import android.view.ViewConfiguration;
+import android.view.ViewGroup;
+import android.view.ViewParent;
 
 import com.android.internal.R;
 import com.android.internal.util.Preconditions;
@@ -165,7 +167,17 @@
         checkToolbarInitialized();
 
         mContentRectOnScreen.set(mContentRect);
-        mContentRectOnScreen.offset(mViewPositionOnScreen[0], mViewPositionOnScreen[1]);
+
+        // Offset the content rect into screen coordinates, taking into account any transformations
+        // that may be applied to the originating view or its ancestors.
+        final ViewParent parent = mOriginatingView.getParent();
+        if (parent instanceof ViewGroup) {
+            ((ViewGroup) parent).getChildVisibleRect(
+                    mOriginatingView, mContentRectOnScreen, null /* offset */);
+            mContentRectOnScreen.offset(mRootViewPositionOnScreen[0], mRootViewPositionOnScreen[1]);
+        } else {
+            mContentRectOnScreen.offset(mViewPositionOnScreen[0], mViewPositionOnScreen[1]);
+        }
 
         if (isContentRectWithinBounds()) {
             mFloatingToolbarVisibilityHelper.setOutOfBounds(false);
diff --git a/core/java/com/android/internal/widget/FloatingToolbar.java b/core/java/com/android/internal/widget/FloatingToolbar.java
index 1848fe8..bc12391 100644
--- a/core/java/com/android/internal/widget/FloatingToolbar.java
+++ b/core/java/com/android/internal/widget/FloatingToolbar.java
@@ -592,9 +592,11 @@
         private void refreshCoordinatesAndOverflowDirection(Rect contentRectOnScreen) {
             refreshViewPort();
 
-            int x = contentRectOnScreen.centerX() - mPopupWindow.getWidth() / 2;
-            // Update x so that the toolbar isn't rendered behind the nav bar in landscape.
-            x = Math.max(0, Math.min(x, mViewPortOnScreen.right - mPopupWindow.getWidth()));
+            // Initialize x ensuring that the toolbar isn't rendered behind the nav bar in
+            // landscape.
+            final int x = Math.min(
+                    contentRectOnScreen.centerX() - mPopupWindow.getWidth() / 2,
+                    mViewPortOnScreen.right - mPopupWindow.getWidth());
 
             final int y;
 
@@ -684,7 +686,8 @@
             int rootViewTopOnWindow = mTmpCoords[1];
             int windowLeftOnScreen = rootViewLeftOnScreen - rootViewLeftOnWindow;
             int windowTopOnScreen = rootViewTopOnScreen - rootViewTopOnWindow;
-            mCoordsOnWindow.set(x - windowLeftOnScreen, y - windowTopOnScreen);
+            mCoordsOnWindow.set(
+                    Math.max(0, x - windowLeftOnScreen), Math.max(0, y - windowTopOnScreen));
         }
 
         /**
diff --git a/core/jni/android_hardware_SensorManager.cpp b/core/jni/android_hardware_SensorManager.cpp
index 9793cdb..f4237d2 100644
--- a/core/jni/android_hardware_SensorManager.cpp
+++ b/core/jni/android_hardware_SensorManager.cpp
@@ -13,28 +13,25 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 #define LOG_TAG "SensorManager"
 
-#include <map>
+#include "JNIHelp.h"
+#include "android_os_MessageQueue.h"
+#include "core_jni_helpers.h"
+#include "jni.h"
 
 #include <ScopedUtfChars.h>
 #include <ScopedLocalRef.h>
-
+#include <android_runtime/AndroidRuntime.h>
+#include <gui/Sensor.h>
+#include <gui/SensorEventQueue.h>
+#include <gui/SensorManager.h>
 #include <utils/Log.h>
 #include <utils/Looper.h>
 #include <utils/Vector.h>
 
-#include <gui/Sensor.h>
-#include <gui/SensorManager.h>
-#include <gui/SensorEventQueue.h>
-
-#include "jni.h"
-#include "JNIHelp.h"
-#include "android_os_MessageQueue.h"
-#include <android_runtime/AndroidRuntime.h>
-
-#include "core_jni_helpers.h"
+#include <endian.h>   // htobe64
+#include <map>
 
 namespace {
 
diff --git a/core/jni/android_hardware_location_ContextHubService.cpp b/core/jni/android_hardware_location_ContextHubService.cpp
index 5c961d9..98d6b24 100644
--- a/core/jni/android_hardware_location_ContextHubService.cpp
+++ b/core/jni/android_hardware_location_ContextHubService.cpp
@@ -44,7 +44,6 @@
 static constexpr int HEADER_FIELD_HUB_HANDLE=2;
 static constexpr int HEADER_FIELD_APP_INSTANCE=3;
 
-
 namespace android {
 
 namespace {
@@ -164,9 +163,20 @@
     return db.hubInfo.hubs[hubHandle].hub_id;
 }
 
+static int get_app_instance_for_app_id(uint64_t app_id) {
+    auto end = db.appInstances.end();
+    for (auto current = db.appInstances.begin(); current != end; ++current) {
+        if (current->second.appInfo.app_name.id == app_id) {
+            return current->first;
+        }
+    }
+    ALOGD("Cannot find app for app instance %" PRIu64 ".", app_id);
+    return -1;
+}
+
 static int set_dest_app(hub_message_t *msg, int id) {
     if (!db.appInstances.count(id)) {
-        ALOGD("%s: Cannod find app for app instance %d", __FUNCTION__, id);
+        ALOGD("%s: Cannot find app for app instance %d", __FUNCTION__, id);
         return -1;
     }
 
@@ -301,7 +311,7 @@
     }
 }
 
-static int onMessageReceipt(int *header, int headerLen, char *msg, int msgLen) {
+static int onMessageReceipt(uint32_t *header, size_t headerLen, char *msg, size_t msgLen) {
     JNIEnv *env;
 
     if ((db.jniInfo.vm)->AttachCurrentThread(&env, nullptr) != JNI_OK) {
@@ -396,14 +406,9 @@
 int context_hub_callback(uint32_t hubId,
                          const struct hub_message_t *msg,
                          void *cookie) {
-    int msgHeader[MSG_HEADER_SIZE];
-
     if (!msg) {
         return -1;
     }
-
-    msgHeader[HEADER_FIELD_MSG_TYPE] = msg->message_type;
-
     if (!sanity_check_cookie(cookie, hubId)) {
         ALOGW("Incorrect cookie %" PRId32 " for cookie %p! Bailing",
               hubId, cookie);
@@ -411,17 +416,22 @@
         return -1;
     }
 
-    msgHeader[HEADER_FIELD_HUB_HANDLE] = *(uint32_t*)cookie;
+    uint32_t messageType = msg->message_type;
+    uint32_t hubHandle = *(uint32_t*) cookie;
 
-    if (msgHeader[HEADER_FIELD_MSG_TYPE] < CONTEXT_HUB_TYPE_PRIVATE_MSG_BASE &&
-        msgHeader[HEADER_FIELD_MSG_TYPE] != 0 ) {
-        handle_os_message(msgHeader[HEADER_FIELD_MSG_TYPE],
-                          msgHeader[HEADER_FIELD_HUB_HANDLE],
-                          (char *)msg->message,
-                          msg->message_len);
+    if (messageType < CONTEXT_HUB_TYPE_PRIVATE_MSG_BASE) {
+        handle_os_message(messageType, hubHandle, (char*) msg->message, msg->message_len);
     } else {
-        onMessageReceipt(msgHeader, sizeof(msgHeader),
-                         (char *)msg->message, msg->message_len);
+        int appHandle = get_app_instance_for_app_id(msg->app_name.id);
+        if (appHandle < 0) {
+            ALOGE("Filtering out message due to invalid App Instance.");
+        } else {
+            uint32_t msgHeader[MSG_HEADER_SIZE] = {};
+            msgHeader[HEADER_FIELD_MSG_TYPE] = messageType;
+            msgHeader[HEADER_FIELD_HUB_HANDLE] = hubHandle;
+            msgHeader[HEADER_FIELD_APP_INSTANCE] = appHandle;
+            onMessageReceipt(msgHeader, MSG_HEADER_SIZE, (char*) msg->message, msg->message_len);
+        }
     }
 
     return 0;
diff --git a/core/jni/android_os_Debug.cpp b/core/jni/android_os_Debug.cpp
index f870a89..e0bfecb 100644
--- a/core/jni/android_os_Debug.cpp
+++ b/core/jni/android_os_Debug.cpp
@@ -597,6 +597,13 @@
 
 static long get_allocated_vmalloc_memory() {
     char line[1024];
+    // Ignored tags that don't actually consume memory (ie remappings)
+    static const char* const ignored_tags[] = {
+            "ioremap",
+            "map_lowmem",
+            "vm_map_ram",
+            NULL
+    };
     long size, vmalloc_allocated_size = 0;
     FILE* fp = fopen("/proc/vmallocinfo", "r");
     if (fp == NULL) {
@@ -606,12 +613,17 @@
         if (fgets(line, 1024, fp) == NULL) {
             break;
         }
-
-        if (!strstr(line, "ioremap") && !strstr(line, "map_lowmem")) {
-            // Ignore ioremap and map_lowmem regions, since they don't actually consume memory
-            if (sscanf(line, "%*x-%*x %ld", &size) == 1) {
-                vmalloc_allocated_size += size;
+        bool valid_line = true;
+        int i = 0;
+        while (ignored_tags[i]) {
+            if (strstr(line, ignored_tags[i]) != NULL) {
+                valid_line = false;
+                break;
             }
+            i++;
+        }
+        if (valid_line && (sscanf(line, "%*x-%*x %ld", &size) == 1)) {
+            vmalloc_allocated_size += size;
         }
     }
     fclose(fp);
diff --git a/core/res/res/drawable-nodpi/default_wallpaper.png b/core/res/res/drawable-nodpi/default_wallpaper.png
index e9c4d5c..91ad252 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-sw600dp-nodpi/default_wallpaper.png b/core/res/res/drawable-sw600dp-nodpi/default_wallpaper.png
index 9f3efa5..af8e251 100644
--- a/core/res/res/drawable-sw600dp-nodpi/default_wallpaper.png
+++ b/core/res/res/drawable-sw600dp-nodpi/default_wallpaper.png
Binary files differ
diff --git a/core/res/res/drawable-sw720dp-nodpi/default_wallpaper.png b/core/res/res/drawable-sw720dp-nodpi/default_wallpaper.png
index 8199e70..cb00d82 100644
--- a/core/res/res/drawable-sw720dp-nodpi/default_wallpaper.png
+++ b/core/res/res/drawable-sw720dp-nodpi/default_wallpaper.png
Binary files differ
diff --git a/core/res/res/layout-sw600dp/date_picker_dialog.xml b/core/res/res/layout-sw600dp/date_picker_dialog.xml
index f18485f..5e3ca14 100644
--- a/core/res/res/layout-sw600dp/date_picker_dialog.xml
+++ b/core/res/res/layout-sw600dp/date_picker_dialog.xml
@@ -21,4 +21,5 @@
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:spinnersShown="true"
-    android:calendarViewShown="true" />
+    android:calendarViewShown="true"
+    android:datePickerMode="@integer/date_picker_mode" />
diff --git a/core/res/res/layout/date_picker_dialog.xml b/core/res/res/layout/date_picker_dialog.xml
index 64ac1b9..8f36e95 100644
--- a/core/res/res/layout/date_picker_dialog.xml
+++ b/core/res/res/layout/date_picker_dialog.xml
@@ -21,4 +21,5 @@
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:spinnersShown="true"
-    android:calendarViewShown="false" />
+    android:calendarViewShown="false"
+    android:datePickerMode="@integer/date_picker_mode" />
diff --git a/core/res/res/layout/time_picker_dialog.xml b/core/res/res/layout/time_picker_dialog.xml
index 30fe910..d1f3902 100644
--- a/core/res/res/layout/time_picker_dialog.xml
+++ b/core/res/res/layout/time_picker_dialog.xml
@@ -21,4 +21,5 @@
     android:id="@+id/timePicker"
     android:layout_gravity="center_horizontal"
     android:layout_width="wrap_content"
-    android:layout_height="wrap_content" />
+    android:layout_height="wrap_content"
+    android:timePickerMode="@integer/time_picker_mode" />
diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml
index d36da9f..dffab2c 100644
--- a/core/res/res/values/strings.xml
+++ b/core/res/res/values/strings.xml
@@ -626,7 +626,7 @@
     <!-- Title for the capability of an accessibility service to request touch exploration. -->
     <string name="capability_title_canRequestTouchExploration">Turn on Explore by Touch</string>
     <!-- Description for the capability of an accessibility service to request touch exploration. -->
-    <string name="capability_desc_canRequestTouchExploration">Touched items will be spoken aloud
+    <string name="capability_desc_canRequestTouchExploration">Tapped items will be spoken aloud
         and the screen can be explored using gestures.</string>
 
     <!-- Title for the capability of an accessibility service to request enhanced web accessibility. -->
@@ -1708,7 +1708,7 @@
     <string name="keyguard_password_enter_pin_prompt">New PIN code</string>
 
     <!-- Displayed as hint in passwordEntry EditText on PasswordUnlockScreen [CHAR LIMIT=30]-->
-    <string name="keyguard_password_entry_touch_hint"><font size="17">Touch to type password</font></string>
+    <string name="keyguard_password_entry_touch_hint"><font size="17">Tap to type password</font></string>
 
     <!-- Instructions telling the user to enter their text password to unlock the keyguard.
          Displayed in one line in a large font.  -->
@@ -2428,41 +2428,49 @@
 
     <!-- Phrase describing a time duration using minutes that is as short as possible, preferrably one character. If the language needs a space in between the integer and the unit, please also integrate it in the string, but preferably it should not have a space in between.[CHAR LIMIT=6] -->
     <plurals name="duration_minutes_shortest">
+        <item quantity="one"><xliff:g example="1" id="count">%d</xliff:g>m</item>
         <item quantity="other"><xliff:g example="2" id="count">%d</xliff:g>m</item>
     </plurals>
 
     <!-- Phrase describing a time duration using hours that is as short as possible, preferrably one character. If the language needs a space in between the integer and the unit, please also integrate it in the string, but preferably it should not have a space in between.[CHAR LIMIT=6] -->
     <plurals name="duration_hours_shortest">
+        <item quantity="one"><xliff:g example="1" id="count">%d</xliff:g>h</item>
         <item quantity="other"><xliff:g example="2" id="count">%d</xliff:g>h</item>
     </plurals>
 
     <!-- Phrase describing a time duration using days that is as short as possible, preferrably one character. If the language needs a space in between the integer and the unit, please also integrate it in the string, but preferably it should not have a space in between.[CHAR LIMIT=6] -->
     <plurals name="duration_days_shortest">
+        <item quantity="one"><xliff:g example="1" id="count">%d</xliff:g>d</item>
         <item quantity="other"><xliff:g example="2" id="count">%d</xliff:g>d</item>
     </plurals>
 
     <!-- Phrase describing a time duration using years that is as short as possible, preferrably one character. If the language needs a space in between the integer and the unit, please also integrate it in the string, but preferably it should not have a space in between.[CHAR LIMIT=6] -->
     <plurals name="duration_years_shortest">
+        <item quantity="one"><xliff:g example="1" id="count">%d</xliff:g>y</item>
         <item quantity="other"><xliff:g example="2" id="count">%d</xliff:g>y</item>
     </plurals>
 
     <!-- Phrase describing a time duration using minutes that is as short as possible, preferrably one character. This version should be a future point in time. If the language needs a space in between the integer and the unit, please also integrate it in the string, but preferably it should not have a space in between.[CHAR LIMIT=14] -->
     <plurals name="duration_minutes_shortest_future">
+        <item quantity="one">in <xliff:g example="1" id="count">%d</xliff:g>m</item>
         <item quantity="other">in <xliff:g example="2" id="count">%d</xliff:g>m</item>
     </plurals>
 
     <!-- Phrase describing a time duration using hours that is as short as possible, preferrably one character. This version should be a future point in time. If the language needs a space in between the integer and the unit, please also integrate it in the string, but preferably it should not have a space in between.[CHAR LIMIT=14] -->
     <plurals name="duration_hours_shortest_future">
+        <item quantity="one">in <xliff:g example="1" id="count">%d</xliff:g>h</item>
         <item quantity="other">in <xliff:g example="2" id="count">%d</xliff:g>h</item>
     </plurals>
 
     <!-- Phrase describing a time duration using days that is as short as possible, preferrably one character. This version should be a future point in time. If the language needs a space in between the integer and the unit, please also integrate it in the string, but preferably it should not have a space in between.[CHAR LIMIT=14] -->
     <plurals name="duration_days_shortest_future">
+        <item quantity="one">in <xliff:g example="1" id="count">%d</xliff:g>d</item>
         <item quantity="other">in <xliff:g example="2" id="count">%d</xliff:g>d</item>
     </plurals>
 
     <!-- Phrase describing a time duration using years that is as short as possible, preferrably one character. This version should be a future point in time. If the language needs a space in between the integer and the unit, please also integrate it in the string, but preferably it should not have a space in between.[CHAR LIMIT=14] -->
     <plurals name="duration_years_shortest_future">
+        <item quantity="one">in <xliff:g example="1" id="count">%d</xliff:g>y</item>
         <item quantity="other">in <xliff:g example="2" id="count">%d</xliff:g>y</item>
     </plurals>
 
@@ -2569,7 +2577,7 @@
         is running</string>
     <!-- [CHAR LIMIT=NONE] Stub notification text for an app running a service that has provided
          a bad bad notification for itself. -->
-    <string name="app_running_notification_text">Touch for more information
+    <string name="app_running_notification_text">Tap for more information
         or to stop the app.</string>
 
     <!-- Preference framework strings. -->
@@ -2753,7 +2761,7 @@
     <string name="heavy_weight_notification"><xliff:g id="app">%1$s</xliff:g> running</string>
 
     <!-- Notification details to tell the user that a heavy-weight application is running. -->
-    <string name="heavy_weight_notification_detail">Touch to switch to app</string>
+    <string name="heavy_weight_notification_detail">Tap to switch to app</string>
 
     <!-- Title of dialog prompting whether user wants to switch between heavy-weight apps. -->
     <string name="heavy_weight_switcher_title">Switch apps?</string>
@@ -2774,7 +2782,7 @@
 
     <!-- Notification details to tell the user that a process has exceeded its memory limit. -->
     <string name="dump_heap_notification_detail">Heap dump has been collected;
-        touch to share</string>
+        tap to share</string>
 
     <!-- Title of dialog prompting the user to share a heap dump. -->
     <string name="dump_heap_title">Share heap dump?</string>
@@ -2857,7 +2865,7 @@
     <string name="wifi_no_internet">Wi-Fi has no Internet access</string>
 
     <!-- A notification is shown when the user connects to a Wi-Fi network and the system detects that that network has no Internet access. This is the notification's message. -->
-    <string name="wifi_no_internet_detailed">Touch for options</string>
+    <string name="wifi_no_internet_detailed">Tap for options</string>
 
      <!-- A notification is shown when a user's selected SSID is later disabled due to connectivity problems.  This is the notification's title / ticker. -->
      <string name="wifi_watchdog_network_disabled">Couldn\'t connect to Wi-Fi</string>
@@ -2879,7 +2887,7 @@
     <string name="wifi_p2p_turnon_message">Start Wi-Fi Direct. This will turn off Wi-Fi client/hotspot.</string>
     <string name="wifi_p2p_failed_message">Couldn\'t start Wi-Fi Direct.</string>
     <string name="wifi_p2p_enabled_notification_title">Wi-Fi Direct is on</string>
-    <string name="wifi_p2p_enabled_notification_message">Touch for settings</string>
+    <string name="wifi_p2p_enabled_notification_message">Tap for settings</string>
 
     <string name="accept">Accept</string>
     <string name="decline">Decline</string>
@@ -2987,12 +2995,12 @@
     <!-- USB_PREFERENCES: Notification for when a USB accessory is attached.  This is the title -->
     <string name="usb_accessory_notification_title">Connected to a USB accessory</string>
     <!-- See USB_PREFERENCES. This is the message. -->
-    <string name="usb_notification_message">Touch for more options.</string>
+    <string name="usb_notification_message">Tap for more options.</string>
 
     <!-- Title of notification shown when ADB is actively connected to the phone. -->
     <string name="adb_active_notification_title">USB debugging connected</string>
     <!-- Message of notification shown when ADB is actively connected to the phone. -->
-    <string name="adb_active_notification_message">Touch to disable USB debugging.</string>
+    <string name="adb_active_notification_message">Tap to disable USB debugging.</string>
 
     <!-- Title of notification shown to indicate that bug report is being collected. -->
     <string name="taking_remote_bugreport_notification_title">Taking bug report\u2026</string>
@@ -3049,12 +3057,12 @@
     <!-- Notification title when external media is unmountable (corrupt) [CHAR LIMIT=30] -->
     <string name="ext_media_unmountable_notification_title">Corrupted <xliff:g id="name" example="SD card">%s</xliff:g></string>
     <!-- Notification body when external media is unmountable (corrupt) [CHAR LIMIT=NONE] -->
-    <string name="ext_media_unmountable_notification_message"><xliff:g id="name" example="SD card">%s</xliff:g> is corrupt. Touch to fix.</string>
+    <string name="ext_media_unmountable_notification_message"><xliff:g id="name" example="SD card">%s</xliff:g> is corrupt. Tap to fix.</string>
 
     <!-- Notification title when external media is unsupported [CHAR LIMIT=30] -->
     <string name="ext_media_unsupported_notification_title">Unsupported <xliff:g id="name" example="SD card">%s</xliff:g></string>
     <!-- Notification body when external media is unsupported [CHAR LIMIT=NONE] -->
-    <string name="ext_media_unsupported_notification_message">This device doesn\u2019t support this <xliff:g id="name" example="SD card">%s</xliff:g>. Touch to set up in a supported format.</string>
+    <string name="ext_media_unsupported_notification_message">This device doesn\u2019t support this <xliff:g id="name" example="SD card">%s</xliff:g>. Tap to set up in a supported format.</string>
 
     <!-- Notification title when external media is unsafely removed [CHAR LIMIT=30] -->
     <string name="ext_media_badremoval_notification_title"><xliff:g id="name" example="SD card">%s</xliff:g> unexpectedly removed</string>
@@ -3140,7 +3148,7 @@
     <string name="permdesc_requestInstallPackages">Allows an application to request installation of packages.</string>
 
     <!-- Shown in the tutorial for tap twice for zoom control. -->
-    <string name="tutorial_double_tap_to_zoom_message_short">Touch twice for zoom control</string>
+    <string name="tutorial_double_tap_to_zoom_message_short">Tap twice for zoom control</string>
 
 
     <!-- Shown in gadget hosts (e.g. the home screen) when there was an error inflating
@@ -3227,9 +3235,9 @@
     <!-- The title of the notification when VPN is active with an application name. -->
     <string name="vpn_title_long">VPN is activated by <xliff:g id="app" example="FooVPN client">%s</xliff:g></string>
     <!-- The text of the notification when VPN is active. -->
-    <string name="vpn_text">Touch to manage the network.</string>
+    <string name="vpn_text">Tap to manage the network.</string>
     <!-- The text of the notification when VPN is active with a session name. -->
-    <string name="vpn_text_long">Connected to <xliff:g id="session" example="office">%s</xliff:g>. Touch to manage the network.</string>
+    <string name="vpn_text_long">Connected to <xliff:g id="session" example="office">%s</xliff:g>. Tap to manage the network.</string>
 
     <!-- Notification title when connecting to lockdown VPN. -->
     <string name="vpn_lockdown_connecting">Always-on VPN connecting\u2026</string>
@@ -3238,7 +3246,7 @@
     <!-- Notification title when error connecting to lockdown VPN. -->
     <string name="vpn_lockdown_error">Always-on VPN error</string>
     <!-- Notification body that indicates user can touch to configure lockdown VPN connection. -->
-    <string name="vpn_lockdown_config">Touch to configure</string>
+    <string name="vpn_lockdown_config">Tap to configure</string>
 
     <!-- Localized strings for WebView -->
     <!-- Label for button in a WebView that will open a chooser to choose a file to upload -->
@@ -3253,12 +3261,12 @@
     <!-- Strings for car mode notification -->
     <!-- Shown when car mode is enabled -->
     <string name="car_mode_disable_notification_title">Car mode enabled</string>
-    <string name="car_mode_disable_notification_message">Touch to exit car mode.</string>
+    <string name="car_mode_disable_notification_message">Tap to exit car mode.</string>
 
     <!-- Strings for tethered notification -->
     <!-- Shown when the device is tethered -->
     <string name="tethered_notification_title">Tethering or hotspot active</string>
-    <string name="tethered_notification_message">Touch to set up.</string>
+    <string name="tethered_notification_message">Tap to set up.</string>
 
     <!--  Strings for possible PreferenceActivity Back/Next buttons -->
     <string name="back_button_label">Back</string>
@@ -3344,7 +3352,7 @@
     <!-- Description of the button to decrease the NumberPicker value. [CHAR LIMIT=NONE] -->
     <string name="number_picker_decrement_button">Decrease</string>
     <!-- Description of the tap and hold action to get into scroll mode in NumberPicker. [CHAR LIMIT=NONE] -->
-    <string name="number_picker_increment_scroll_mode"><xliff:g id="value" example="3">%s</xliff:g> touch and hold.</string>
+    <string name="number_picker_increment_scroll_mode"><xliff:g id="value" example="3">%s</xliff:g> touch &amp; hold.</string>
     <!-- Description of the scrolling action in NumberPicker. [CHAR LIMIT=NONE] -->
     <string name="number_picker_increment_scroll_action">Slide up to increase and down to decrease.</string>
 
@@ -3462,7 +3470,7 @@
     <!-- Notification title when data usage has exceeded warning threshold. [CHAR LIMIT=32] -->
     <string name="data_usage_warning_title">Data usage warning</string>
     <!-- Notification body when data usage has exceeded warning threshold. [CHAR LIMIT=32] -->
-    <string name="data_usage_warning_body">Touch to view usage and settings.</string>
+    <string name="data_usage_warning_body">Tap to view usage and settings.</string>
 
     <!-- Notification title when 2G-3G data usage has exceeded limit threshold, and has been disabled. [CHAR LIMIT=32] -->
     <string name="data_usage_3g_limit_title">2G-3G data limit reached</string>
@@ -3489,7 +3497,7 @@
     <!-- Notification title when background data usage is limited. [CHAR LIMIT=32] -->
     <string name="data_usage_restricted_title">Background data restricted</string>
     <!-- Notification body when background data usage is limited. [CHAR LIMIT=32] -->
-    <string name="data_usage_restricted_body">Touch to remove restriction.</string>
+    <string name="data_usage_restricted_body">Tap to remove restriction.</string>
 
     <!-- SSL Certificate dialogs -->
     <!-- Title for an SSL Certificate dialog -->
@@ -4072,9 +4080,9 @@
     <string name="date_picker_day_typeface">sans-serif-medium</string>
 
     <!-- Notify use that they are in Lock-to-app -->
-    <string name="lock_to_app_toast">To unpin this screen, touch and hold Back.</string>
+    <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 and hold Overview.</string>
+    <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. -->
diff --git a/core/res/res/values/styles_material.xml b/core/res/res/values/styles_material.xml
index 8a33406..6752e3c 100644
--- a/core/res/res/values/styles_material.xml
+++ b/core/res/res/values/styles_material.xml
@@ -660,7 +660,7 @@
     </style>
 
     <style name="Widget.Material.TimePicker">
-        <item name="timePickerMode">@integer/time_picker_mode</item>
+        <item name="timePickerMode">clock</item>
         <item name="legacyLayout">@layout/time_picker_legacy_material</item>
         <!-- Attributes for new-style TimePicker. -->
         <item name="internalLayout">@layout/time_picker_material</item>
@@ -674,7 +674,7 @@
     </style>
 
     <style name="Widget.Material.DatePicker">
-        <item name="datePickerMode">@integer/date_picker_mode</item>
+        <item name="datePickerMode">calendar</item>
         <item name="legacyLayout">@layout/date_picker_legacy_holo</item>
         <item name="calendarViewShown">true</item>
         <!-- Attributes for new-style DatePicker. -->
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index 4d86a92..14c17f3 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -2530,6 +2530,9 @@
   <java-symbol type="string" name="profile_encrypted_message" />
   <java-symbol type="drawable" name="ic_user_secure" />
 
+  <java-symbol type="string" name="android_upgrading_notification_title" />
+  <java-symbol type="string" name="android_upgrading_notification_body" />
+
   <java-symbol type="string" name="usb_mtp_launch_notification_title" />
   <java-symbol type="string" name="usb_mtp_launch_notification_description" />
 
diff --git a/core/res/res/values/themes_holo.xml b/core/res/res/values/themes_holo.xml
index 34c89fc..677051a 100644
--- a/core/res/res/values/themes_holo.xml
+++ b/core/res/res/values/themes_holo.xml
@@ -466,6 +466,9 @@
 
         <item name="editTextColor">?attr/textColorPrimary</item>
         <item name="editTextBackground">@drawable/edit_text_holo_light</item>
+        <item name="textEditSuggestionItemLayout">@layout/text_edit_suggestion_item</item>
+        <item name="textEditSuggestionContainerLayout">@layout/text_edit_suggestion_container</item>
+        <item name="textEditSuggestionHighlightStyle">@style/TextAppearance.Holo.SuggestionHighlight</item>
 
         <item name="candidatesTextStyleSpans">@string/candidates_style</item>
 
diff --git a/data/etc/platform.xml b/data/etc/platform.xml
index 8a7d39b..a26850f 100644
--- a/data/etc/platform.xml
+++ b/data/etc/platform.xml
@@ -172,6 +172,10 @@
          access while in power save mode, even if they aren't in the foreground. -->
     <allow-in-power-save-except-idle package="com.android.providers.downloads" />
 
+    <!-- These are the standard packages that are white-listed to always have internet
+         access while in data mode, even if they aren't in the foreground. -->
+    <allow-in-data-usage-save package="com.android.providers.downloads" />
+
     <!-- These are the packages that are white-listed to be able to run as system user -->
     <system-user-whitelisted-app package="com.android.settings" />
 
diff --git a/data/sounds/alarms/material/ogg/Awaken_OG7_1ch_48k.ogg b/data/sounds/alarms/material/ogg/Awaken_OG7_1ch_48k.ogg
new file mode 100755
index 0000000..47b1d34
--- /dev/null
+++ b/data/sounds/alarms/material/ogg/Awaken_OG7_1ch_48k.ogg
Binary files differ
diff --git a/data/sounds/alarms/material/ogg/Bounce_OG7_1ch_48k.ogg b/data/sounds/alarms/material/ogg/Bounce_OG7_1ch_48k.ogg
new file mode 100755
index 0000000..6af4d70
--- /dev/null
+++ b/data/sounds/alarms/material/ogg/Bounce_OG7_1ch_48k.ogg
Binary files differ
diff --git a/data/sounds/alarms/material/ogg/Drip_OG7_1ch_48k.ogg b/data/sounds/alarms/material/ogg/Drip_OG7_1ch_48k.ogg
new file mode 100755
index 0000000..de3eec2
--- /dev/null
+++ b/data/sounds/alarms/material/ogg/Drip_OG7_1ch_48k.ogg
Binary files differ
diff --git a/data/sounds/alarms/material/ogg/Gallop_OG7_1ch_48k.ogg b/data/sounds/alarms/material/ogg/Gallop_OG7_1ch_48k.ogg
new file mode 100755
index 0000000..98549b3
--- /dev/null
+++ b/data/sounds/alarms/material/ogg/Gallop_OG7_1ch_48k.ogg
Binary files differ
diff --git a/data/sounds/alarms/material/ogg/Nudge_OG7_1ch_48k.ogg b/data/sounds/alarms/material/ogg/Nudge_OG7_1ch_48k.ogg
new file mode 100755
index 0000000..7a3d7ed
--- /dev/null
+++ b/data/sounds/alarms/material/ogg/Nudge_OG7_1ch_48k.ogg
Binary files differ
diff --git a/data/sounds/alarms/material/ogg/Orbit_OG7_1ch_48k.ogg b/data/sounds/alarms/material/ogg/Orbit_OG7_1ch_48k.ogg
new file mode 100755
index 0000000..52e3918
--- /dev/null
+++ b/data/sounds/alarms/material/ogg/Orbit_OG7_1ch_48k.ogg
Binary files differ
diff --git a/data/sounds/alarms/material/ogg/Rise_OG7_1ch_48k.ogg b/data/sounds/alarms/material/ogg/Rise_OG7_1ch_48k.ogg
new file mode 100755
index 0000000..a2d00cc
--- /dev/null
+++ b/data/sounds/alarms/material/ogg/Rise_OG7_1ch_48k.ogg
Binary files differ
diff --git a/data/sounds/alarms/material/ogg/Sway_OG7_1ch_48k.ogg b/data/sounds/alarms/material/ogg/Sway_OG7_1ch_48k.ogg
new file mode 100755
index 0000000..273728a
--- /dev/null
+++ b/data/sounds/alarms/material/ogg/Sway_OG7_1ch_48k.ogg
Binary files differ
diff --git a/data/sounds/alarms/material/ogg/Wag_OG7_1ch_48k.ogg b/data/sounds/alarms/material/ogg/Wag_OG7_1ch_48k.ogg
new file mode 100755
index 0000000..f61d5b9
--- /dev/null
+++ b/data/sounds/alarms/material/ogg/Wag_OG7_1ch_48k.ogg
Binary files differ
diff --git a/docs/html/_redirects.yaml b/docs/html/_redirects.yaml
index adb31b8..545923f 100644
--- a/docs/html/_redirects.yaml
+++ b/docs/html/_redirects.yaml
@@ -24,11 +24,11 @@
 - from: /tools/debugging/debugging-projects-cmdline.html
   to: /tools/debugging/index.html
 - from: /sdk/compatibility-library.html
-  to: /tools/support-library/index.html
+  to: /go/libraries/support-library/index.html
 - from: /tools/extras/support-library.html
-  to: /tools/support-library/index.html
+  to: /go/libraries/support-library/index.html
 - from: /training/basics/fragments/support-lib.html
-  to: /tools/support-library/setup.html
+  to: /go/libraries/support-library/setup.html
 - from: /sdk/eclipse-adt.html
   to: /tools/sdk/eclipse-adt.html
 - from: /sdk/RELEASENOTES.html
@@ -72,13 +72,11 @@
 - from: /tools/publishing/app-signing-eclipse.html
   to: /tools/help/adt.html
 - from: /tools/help/uiautomator/.*
-  to: /tools/testing-support-library/index.html
+  to: /go/libraries/testing-support/library/
 - from: /tools/testing/testing_ui.html
   to: /training/testing/ui-testing/index.html
 - from: /tools/testing/activity_test.html
   to: /training/testing/ui-testing/index.html
-- from: /tools/data-binding/index.html
-  to: /tools/data-binding/guide.html
 - from: /tools/testing/what_to_test.html
   to: /distribute/essentials/quality/core.html
 - from: /tools/testing/testing_accessibility.html
@@ -725,3 +723,14 @@
   to: https://commondatastorage.googleapis.com/androiddevelopers/shareables/
 - from: /downloads/
   to: https://commondatastorage.googleapis.com/androiddevelopers/
+
+# Redirects for the new go/libraries/ area
+
+- from: /tools/support-library
+  to: /go/libraries/support-library
+
+- from: /tools/data-binding/...
+  to: /go/libraries/data-binding
+
+- from: /tools/testing-support-library
+  to: /go/libraries/testing-support-library
diff --git a/docs/html/about/_book.yaml b/docs/html/about/_book.yaml
index 04150bd..fdbe53f 100644
--- a/docs/html/about/_book.yaml
+++ b/docs/html/about/_book.yaml
@@ -16,13 +16,19 @@
     path: /about/versions/android-5.1.html
   - title: Android 5.0 APIs
     path: /about/versions/android-5.0.html
-    custom_link_attributes:
-    - es-lang="API de Android 5.0"
-    - ja-lang="Android 5.0 API"
-    - ko-lang="Android 5.0 API"
-    - ru-lang="API для Android 5.0"
-    - zh-cn-lang="Android 5.0 API"
-    - zh-tw-lang="Android 5.0 API"
+    path_attributes:
+    - name: es-lang
+      value: API de Android 5.0
+    - name: ja-lang
+      value: Android 5.0 API
+    - name: ko-lang
+      value: Android 5.0 API
+    - name: ru-lang
+      value: API для Android 5.0
+    - name: zh-cn-lang
+      value: Android 5.0 API
+    - name: zh-tw-lang
+      value: Android 5.0 API
   - title: Android 5.0 Changes
     path: /about/versions/android-5.0-changes.html
 
diff --git a/docs/html/design/_book.yaml b/docs/html/design/_book.yaml
index 4575475..df5406f 100644
--- a/docs/html/design/_book.yaml
+++ b/docs/html/design/_book.yaml
@@ -4,24 +4,35 @@
   section:
   - title: Design Principles
     path: /design/get-started/principles.html
-    custom_link_attributes:
-    - es-lang="Principios de diseño para Android"
-    - ja-lang="Android デザイン指針"
-    - ko-lang="Android 디자인 원칙"
-    - pt-br-lang="Princípios de projeto para Android"
-    - ru-lang="Принципы проектирования Android"
-    - zh-cn-lang="Android 设计原则"
-    - zh-tw-lang="Android 設計原則"
+    path_attributes:
+    - name: es-lang
+      value: Principios de diseño para Android
+    - name: ja-lang
+      value: Android デザイン指針
+    - name: ko-lang
+      value: Android 디자인 원칙
+    - name: pt-br-lang
+      value: Princípios de projeto para Android
+    - name: ru-lang
+      value: Принципы проектирования Android
+    - name: zh-cn-lang
+      value: Android 设计原则
+    - name: zh-tw-lang
+      value: Android 設計原則
   - title: New in Android
     path: /design/patterns/new.html
 
 - title: Material for Android
   path: /design/material/index.html
-  custom_link_attributes:
-  - ja-lang="マテリアル デザイン"
-  - ko-lang="머티어리얼 디자인"
-  - zh-cn-lang="材料设计"
-  - zh-tw-lang="材料設計"
+  path_attributes:
+  - name: ja-lang
+    value: マテリアル デザイン
+  - name: ko-lang
+    value: 머티어리얼 디자인
+  - name: zh-cn-lang
+    value: 材料设计
+  - name: zh-tw-lang
+    value: 材料設計
 
 - title: Devices
   path: /design/devices.html
@@ -64,24 +75,38 @@
     path: /design/style/devices-displays.html
   - title: Navigation
     path: /design/patterns/navigation.html
-    custom_link_attributes:
-    - es-lang="Navegación con los botones Back y Up"
-    - ja-lang="Back と Up を使用したナビゲーション"
-    - ko-lang="뒤로 및 위로 탐색 기능이 포함된 탐색"
-    - pt-br-lang="Navegação com Voltar e Para cima"
-    - ru-lang="Навигация с помощью кнопок \"Назад\" и \"Вверх\""
-    - zh-cn-lang="使用返回和向上导航"
-    - zh-tw-lang="使用 [返回] 及 [上一層] 導覽"
+    path_attributes:
+    - name: es-lang
+      value: Navegación con los botones Back y Up
+    - name: ja-lang
+      value: Back と Up を使用したナビゲーション
+    - name: ko-lang
+      value: 뒤로 및 위로 탐색 기능이 포함된 탐색
+    - name: pt-br-lang
+      value: Navegação com Voltar e Para cima
+    - name: ru-lang
+      value: Навигация с помощью кнопок "Назад" и "Вверх"
+    - name: zh-cn-lang
+      value: 使用返回和向上导航
+    - name: zh-tw-lang
+      value: 使用 [返回] 及 [上一層] 導覽
   - title: Notifications
     path: /design/patterns/notifications.html
-    custom_link_attributes:
-    - es-lang="Notificaciones"
-    - ja-lang="通知"
-    - ko-lang="알림"
-    - pt-br-lang="Notificações"
-    - ru-lang="Уведомления"
-    - zh-cn-lang="通知"
-    - zh-tw-lang="通知"
+    path_attributes:
+    - name: es-lang
+      value: Notificaciones
+    - name: ja-lang
+      value: 通知
+    - name: ko-lang
+      value: 알림
+    - name: pt-br-lang
+      value: Notificações
+    - name: ru-lang
+      value: Уведомления
+    - name: zh-cn-lang
+      value: 通知
+    - name: zh-tw-lang
+      value: 通知
   - title: Widgets
     path: /design/patterns/widgets.html
   - title: Swipe Views
@@ -90,14 +115,21 @@
     path: /design/patterns/fullscreen.html
   - title: Confirming & Acknowledging
     path: /design/patterns/confirming-acknowledging.html
-    custom_link_attributes:
-    - es-lang="Confirmación y reconocimiento"
-    - ja-lang="確認と通知"
-    - ko-lang="확인 및 승인하기"
-    - pt-br-lang="Confirmação e reconhecimento"
-    - ru-lang="Подтверждение и уведомление"
-    - zh-cn-lang="确认和确知"
-    - zh-tw-lang="確認及確認完成"
+    path_attributes:
+    - name: es-lang
+      value: Confirmación y reconocimiento
+    - name: ja-lang
+      value: 確認と通知
+    - name: ko-lang
+      value: 확인 및 승인하기
+    - name: pt-br-lang
+      value: Confirmação e reconhecimento
+    - name: ru-lang
+      value: Подтверждение и уведомление
+    - name: zh-cn-lang
+      value: 确认和确知
+    - name: zh-tw-lang
+      value: 確認及確認完成
   - title: Pure Android
     path: /design/patterns/pure-android.html
   - title: Compatibility
diff --git a/docs/html/distribute/essentials/_book.yaml b/docs/html/distribute/essentials/_book.yaml
index e8b7811..6a2c8f5 100644
--- a/docs/html/distribute/essentials/_book.yaml
+++ b/docs/html/distribute/essentials/_book.yaml
@@ -1,13 +1,15 @@
 toc:
 - title: Core App Quality
   path: /distribute/essentials/quality/core.html
-  custom_link_attributes:
-  - zh-cn-lang="应用的核心质量"
+  path_attributes:
+  - name: zh-cn-lang
+    value: 应用的核心质量
 
 - title: Tablet App Quality
   path: /distribute/essentials/quality/tablets.html
-  custom_link_attributes:
-  - zh-cn-lang="平板电脑应用的质量"
+  path_attributes:
+  - name: zh-cn-lang
+    value: 平板电脑应用的质量
 
 - title: Wear App Quality
   path: /distribute/essentials/quality/wear.html
@@ -20,31 +22,36 @@
 
 - title: Launch Checklist
   path: /distribute/tools/launch-checklist.html
-  custom_link_attributes:
-  - zh-cn-lang="发布检查清单"
+  path_attributes:
+  - name: zh-cn-lang
+    value: 发布检查清单
 
 - title: Localization Checklist
   path: /distribute/tools/localization-checklist.html
-  custom_link_attributes:
-  - zh-cn-lang="本地化检查清单"
+  path_attributes:
+  - name: zh-cn-lang
+    value: 本地化检查清单
 
 - title: Brand Guidelines
   path: /distribute/tools/promote/brand.html
-  custom_link_attributes:
-  - zh-cn-lang="品牌指南"
+  path_attributes:
+  - name: zh-cn-lang
+    value: 品牌指南
 
 - title: Device Art Generator
   path: /distribute/tools/promote/device-art.html
 
 - title: Google Play Badges
   path: https://play.google.com/intl/en_us/badges/
-  custom_link_attributes:
-  - zh-cn-lang="Google Play 徽章生成器"
+  path_attributes:
+  - name: zh-cn-lang
+    value: Google Play 徽章生成器
 
 - title: Linking to Your Products
   path: /distribute/tools/promote/linking.html
-  custom_link_attributes:
-  - zh-cn-lang="链接到您的商品"
+  path_attributes:
+  - name: zh-cn-lang
+    value: 链接到您的商品
 
 - title: Alternative Distribution
   path: /distribute/tools/open-distribution.html
diff --git a/docs/html/distribute/googleplay/_book.yaml b/docs/html/distribute/googleplay/_book.yaml
index 009d1c07..ede18f4 100644
--- a/docs/html/distribute/googleplay/_book.yaml
+++ b/docs/html/distribute/googleplay/_book.yaml
@@ -1,75 +1,119 @@
 toc:
 - title: The Google Play Opportunity
   path: /distribute/googleplay/about.html
-  custom_link_attributes:
-  - es-lang="La oportunidad de Google Play"
-  - ja-lang="Google Play の可能性"
-  - ko-lang="Google Play 활용 기회"
-  - pt-br-lang="A oportunidade do Google Play"
-  - ru-lang="Возможности Google Play"
-  - zh-cn-lang="Google Play 蕴藏的机会"
-  - zh-tw-lang="Google Play商機"
+  path_attributes:
+  - name: es-lang
+    value: La oportunidad de Google Play
+  - name: ja-lang
+    value: Google Play の可能性
+  - name: ko-lang
+    value: Google Play 활용 기회
+  - name: pt-br-lang
+    value: A oportunidade do Google Play
+  - name: ru-lang
+    value: Возможности Google Play
+  - name: zh-cn-lang
+    value: Google Play 蕴藏的机会
+  - name: zh-tw-lang
+    value: Google Play商機
 
 - title: Get Started with Publishing
   path: /distribute/googleplay/start.html
-  custom_link_attributes:
-  - es-lang="Comienza a publicar"
-  - ja-lang="アプリを公開する"
-  - ko-lang="게시 시작하기"
-  - pt-br-lang="Introdução à publicação"
-  - ru-lang="Первые шаги в публикациях"
-  - zh-cn-lang="开始发布"
-  - zh-tw-lang="開始發行"
+  path_attributes:
+  - name: es-lang
+    value: Comienza a publicar
+  - name: ja-lang
+    value: アプリを公開する
+  - name: ko-lang
+    value: 게시 시작하기
+  - name: pt-br-lang
+    value: Introdução à publicação
+  - name: ru-lang
+    value: Первые шаги в публикациях
+  - name: zh-cn-lang
+    value: 开始发布
+  - name: zh-tw-lang
+    value: 開始發行
 
 - title: Developer Console
   path: /distribute/googleplay/developer-console.html
-  custom_link_attributes:
-  - es-lang="Consola para desarrolladores"
-  - ja-lang="デベロッパー コンソール"
-  - ko-lang="개발자 콘솔"
-  - pt-br-lang="Console do Desenvolvedor"
-  - ru-lang="Консоль разработчика"
-  - zh-cn-lang="开发者控制台"
+  path_attributes:
+  - name: es-lang
+    value: Consola para desarrolladores
+  - name: ja-lang
+    value: デベロッパー コンソール
+  - name: ko-lang
+    value: 개발자 콘솔
+  - name: pt-br-lang
+    value: Console do Desenvolvedor
+  - name: ru-lang
+    value: Консоль разработчика
+  - name: zh-cn-lang
+    value: 开发者控制台
 
 - title: Distribute to Android Wear
   path: /distribute/googleplay/wear.html
-  custom_link_attributes:
-  - es-lang="Distribución para Android Wear"
-  - ja-lang="Android Wear への配布"
-  - ko-lang="Android Wear에 배포"
-  - pt-br-lang="Distribuindo para Android Wear"
-  - ru-lang="Распространение приложений Android Wear"
-  - zh-cn-lang="分发到 Android Wear"
-  - zh-tw-lang="散佈至 Android Wear"
+  path_attributes:
+  - name: es-lang
+    value: Distribución para Android Wear
+  - name: ja-lang
+    value: Android Wear への配布
+  - name: ko-lang
+    value: Android Wear에 배포
+  - name: pt-br-lang
+    value: Distribuindo para Android Wear
+  - name: ru-lang
+    value: Распространение приложений Android Wear
+  - name: zh-cn-lang
+    value: 分发到 Android Wear
+  - name: zh-tw-lang
+    value: 散佈至 Android Wear
 
 - title: Distribute to Android TV
   path: /distribute/googleplay/tv.html
-  custom_link_attributes:
-  - es-lang="Distribución para Android TV"
-  - ja-lang="Android TV への配布"
-  - ko-lang="Android TV에 배포"
-  - pt-br-lang="Distribuindo para Android TV"
-  - ru-lang="Распространение приложений в Android TV"
-  - zh-cn-lang="分发到 Android TV"
-  - zh-tw-lang="散佈至 Android 電視"
+  path_attributes:
+  - name: es-lang
+    value: Distribución para Android TV
+  - name: ja-lang
+    value: Android TV への配布
+  - name: ko-lang
+    value: Android TV에 배포
+  - name: pt-br-lang
+    value: Distribuindo para Android TV
+  - name: ru-lang
+    value: Распространение приложений в Android TV
+  - name: zh-cn-lang
+    value: 分发到 Android TV
+  - name: zh-tw-lang
+    value: 散佈至 Android 電視
 
 - title: Distribute to Android Auto
   path: /distribute/googleplay/auto.html
-  custom_link_attributes:
-  - es-lang="Distribución para Android Auto"
-  - ja-lang="Android Auto への配布"
-  - ko-lang="Android Auto에 배포"
-  - pt-br-lang="Distribuindo para o Android Auto"
-  - ru-lang="Распространение приложений для Android Auto"
-  - zh-cn-lang="分发到 Android Auto"
-  - zh-tw-lang="散佈至 Android Auto"
+  path_attributes:
+  - name: es-lang
+    value: Distribución para Android Auto
+  - name: ja-lang
+    value: Android Auto への配布
+  - name: ko-lang
+    value: Android Auto에 배포
+  - name: pt-br-lang
+    value: Distribuindo para o Android Auto
+  - name: ru-lang
+    value: Распространение приложений для Android Auto
+  - name: zh-cn-lang
+    value: 分发到 Android Auto
+  - name: zh-tw-lang
+    value: 散佈至 Android Auto
 
 - title: Designed for Families
   path: /distribute/googleplay/families/about.html
-  custom_link_attributes:
-  - es-lang="Diseñado para la familia"
-  - ru-lang="Для всей семьи"
-  - zh-cn-lang="为家庭设计"
+  path_attributes:
+  - name: es-lang
+    value: Diseñado para la familia
+  - name: ru-lang
+    value: Для всей семьи
+  - name: zh-cn-lang
+    value: 为家庭设计
 
 - title: Google Play for Work
   path: /distribute/googleplay/work/about.html
@@ -90,11 +134,18 @@
 
 - title: Find Success on Google Play
   path: /distribute/googleplay/guide.html
-  custom_link_attributes:
-  - es-lang="Cómo tener éxito en Google Play"
-  - ja-lang="Google Play で成功を手にする"
-  - ko-lang="Google Play에서 성공 모색"
-  - pt-br-lang="Obtendo sucesso no Google Play"
-  - ru-lang="Найдите свой путь к успеху в Google Play"
-  - zh-cn-lang="在 Google Play 上取得成功"
-  - zh-tw-lang="在 Google Play 上尋找成功"
+  path_attributes:
+  - name: es-lang
+    value: Cómo tener éxito en Google Play
+  - name: ja-lang
+    value: Google Play で成功を手にする
+  - name: ko-lang
+    value: Google Play에서 성공 모색
+  - name: pt-br-lang
+    value: Obtendo sucesso no Google Play
+  - name: ru-lang
+    value: Найдите свой путь к успеху в Google Play
+  - name: zh-cn-lang
+    value: 在 Google Play 上取得成功
+  - name: zh-tw-lang
+    value: 在 Google Play 上尋找成功
diff --git a/docs/html/distribute/tools/_book.yaml b/docs/html/distribute/tools/_book.yaml
index 57e03ba..4064c34 100644
--- a/docs/html/distribute/tools/_book.yaml
+++ b/docs/html/distribute/tools/_book.yaml
@@ -1,31 +1,36 @@
 toc:
 - title: Launch Checklist
   path: /distribute/tools/launch-checklist.html
-  custom_link_attributes:
-  - zh-cn-lang="发布检查清单"
+  path_attributes:
+  - name: zh-cn-lang
+    value: 发布检查清单
 
 - title: Localization Checklist
   path: /distribute/tools/localization-checklist.html
-  custom_link_attributes:
-  - zh-cn-lang="本地化检查清单"
+  path_attributes:
+  - name: zh-cn-lang
+    value: 本地化检查清单
 
 - title: Device Art Generator
   path: /distribute/tools/promote/device-art.html
 
 - title: Google Play Badges
   path: /distribute/tools/promote/badges.html
-  custom_link_attributes:
-  - zh-cn-lang="Google Play 徽章生成器"
+  path_attributes:
+  - name: zh-cn-lang
+    value: Google Play 徽章生成器
 
 - title: Linking to Your Products
   path: /distribute/tools/promote/linking.html
-  custom_link_attributes:
-  - zh-cn-lang="链接到您的商品"
+  path_attributes:
+  - name: zh-cn-lang
+    value: 链接到您的商品
 
 - title: Brand Guidelines
   path: /distribute/tools/promote/brand.html
-  custom_link_attributes:
-  - zh-cn-lang="品牌指南"
+  path_attributes:
+  - name: zh-cn-lang
+    value: 品牌指南
 
 - title: Alternative Distribution
   path: /distribute/tools/open-distribution.html
diff --git a/docs/html/go/libraries/_book.yaml b/docs/html/go/libraries/_book.yaml
new file mode 100644
index 0000000..209dae5
--- /dev/null
+++ b/docs/html/go/libraries/_book.yaml
@@ -0,0 +1,17 @@
+toc:
+- title: Support Library
+  path: /tools/support-library/index.html
+  section:
+  - title: Features
+    path: /tools/support-library/features.html
+  - title: Setup
+    path: /tools/support-library/setup.html
+
+- title: Data Binding Library
+  path: /tools/data-binding/guide.html
+
+- title: Testing Support Library
+  path: /tools/testing-support-library/index.html
+  section:
+  - title: API Reference
+    path: /reference/android/support/test/package-summary.html
diff --git a/docs/html/tools/data-binding/guide.jd b/docs/html/go/libraries/data-binding/index.jd
similarity index 99%
rename from docs/html/tools/data-binding/guide.jd
rename to docs/html/go/libraries/data-binding/index.jd
index 8bbd833..ca8784e 100644
--- a/docs/html/tools/data-binding/guide.jd
+++ b/docs/html/go/libraries/data-binding/index.jd
@@ -1,4 +1,5 @@
-page.title=Data Binding Guide
+page.title=Data Binding Library
+page.metaDescription=The Data Binding Library enables you to write declarative layouts.
 page.tags="databinding", "layouts"
 @jd:body
 
diff --git a/docs/html/go/libraries/index.jd b/docs/html/go/libraries/index.jd
new file mode 100644
index 0000000..2831d15
--- /dev/null
+++ b/docs/html/go/libraries/index.jd
@@ -0,0 +1,14 @@
+page.title=Android Libraries
+
+@jd:body
+
+<p>This section describes several useful Android libraries that are not
+included with the Android Framework.</p>
+
+<div class="dynamic-grid">
+  <div class="resource-widget resource-flow-layout landing col-12"
+    data-query="collection:go/libraries"
+    data-cardSizes="6x6"
+    data-maxResults="6">
+  </div>
+</div>
diff --git a/docs/html/tools/support-library/features.jd b/docs/html/go/libraries/support-library/features.jd
similarity index 98%
rename from docs/html/tools/support-library/features.jd
rename to docs/html/go/libraries/support-library/features.jd
index a5f343e..089357a 100755
--- a/docs/html/tools/support-library/features.jd
+++ b/docs/html/go/libraries/support-library/features.jd
@@ -34,11 +34,11 @@
 
     <h2>See also</h2>
     <ol>
-      <li><a href="{@docRoot}tools/support-library/index.html#revisions">
+      <li><a href="{@docRoot}go/libraries/support-library/index.html#revisions">
         Support Library Revisions</a></li>
-      <li><a href="{@docRoot}tools/support-library/setup.html">
+      <li><a href="{@docRoot}go/libraries/support-library/setup.html">
         Support Library Setup</a></li>
-      <li><a href="{@docRoot}tools/testing-support-library/index.html">
+      <li><a href="{@docRoot}go/libraries/testing-support-library/index.html">
         Testing Support Library</a></li>
     </ol>
 
diff --git a/docs/html/tools/support-library/index.jd b/docs/html/go/libraries/support-library/index.jd
similarity index 93%
rename from docs/html/tools/support-library/index.jd
rename to docs/html/go/libraries/support-library/index.jd
index 3afd7ac..61f0bc2 100644
--- a/docs/html/tools/support-library/index.jd
+++ b/docs/html/go/libraries/support-library/index.jd
@@ -1,4 +1,5 @@
 page.title=Support Library
+page.metaDescription=The Android Support Library offers backward-compatible versions of a number of features that are not built into the framework.
 
 @jd:body
 
@@ -8,7 +9,11 @@
     <h2>In this document</h2>
     <ol>
       <li><a href="#overview">Overview</a></li>
-      <li><a href="#revisions">Revisions</a></li>
+      <li><a href="#backward">Backward Compatibility</a></li>
+      <li><a href="#layout-patterns">Support for General Layout Patterns</a></li>
+      <li><a href="#form-factors">Support for Different Form Factors</a></li>
+      <li><a href="#utils">General Utilities</a></li>
+      <li><a href="#revisions">Support Library Revision History</a></li>
     </ol>
 
     <h2>See also</h2>
@@ -22,39 +27,161 @@
   </div>
 </div>
 
-<p>The Android Support Library package is a set of code libraries that provide
-  backward-compatible versions of Android framework APIs as well as features that are only available
-  through the library APIs. Each Support Library is backward-compatible to a specific Android API
-  level. This design means that your applications can use the libraries' features and still be
-  compatible with devices running Android 1.6 (API level 4) and up.</p>
-
-<p>This guide provides information about what features are enabled by the Support Libraries,
-  how to use them in your development environment and information about library releases.</p>
-
+<p>
+  The Android Support Library offers a number of features that are not built
+  into the framework. These libraries offer backward-compatible versions of
+  new features, provide useful UI elements that are not included in the
+  framework, and provide a range of utilities that apps can draw on.
+</p>
 
 <h2 id="overview">Overview</h2>
 
-<p>Including the Support Libraries in your Android project is considered a best practice for
-  application developers, depending on the range of platform versions your app is targeting
-  and the APIs that it uses. Using the features the libraries provide can help you improve the look
-  of your application, increase performance and broaden the reach of your application to more users.
-  If you use the Android
-  <a href="{@docRoot}tools/projects/templates.html">code template</a> tools, you will notice that
-  all the Android application templates include one or more of the Support Libraries by default.</p>
+<p>
+  In many cases, a feature may be valuable to many app developers, but not
+  appropriate to include in the Android framework itself. For example, an app
+  might only need a feature for specialized use cases, such as to smooth the
+  transition between different versions of the Android system.
+</p>
 
-<p>The Support Libraries each target a base Android API level and each provides a different set
-  of features. In order to effectively use the libraries, it is important to consider what features
-  you want to support and understand what features are supported by each library at what Android
-  API level. To get started, review the
-  <a href="{@docRoot}tools/support-library/features.html">Support Library Features</a> guide.
-  After that, go to the
-  <a href="{@docRoot}tools/support-library/setup.html">Support Library Setup</a> topic to
-  learn how to incorporate the Support Libraries into your application. For more details
-  about Support Library APIs, see the {@link android.support.v4.app android.support}
-  packages in the API reference.</p>
+<p>
+  To address these situations, the Android SDK includes several libraries
+  collectively called the <em>Android Support Library</em>. App developers
+  can include any of these libraries if they want to incorporate the
+  library functionality into their apps.
+</p>
+
+<p>
+  Support libraries provide a range of different features:
+</p>
+
+<ul>
+  <li>
+    <a href="#backward">Backward-compatible</a> versions of framework
+    components.
+  </li>
+
+  <li>UI elements to implement the recommended Android <a href=
+  "#layout-patterns">layout patterns</a>.
+  </li>
+
+  <li>Support for different <a href="#form-factors">form factors</a>.
+  </li>
+
+  <li>Miscellaneous <a href="#utils">utility</a> functions.
+  </li>
+</ul>
+
+<h2 id="backward">Backward Compatibility</h2>
+
+<div class="figure" style="width:300px">
+  <img src="{@docRoot}images/tools/support-library/appbar-kitkat.png"
+    srcset="{@docRoot}images/tools/support-library/appbar-kitkat.png 1x,
+        {@docRoot}images/tools/support-library/appbar-kitkat_2x.png 2x"
+    alt="" width="300">
+  <p class="img-caption">
+    <strong>Figure 1.</strong> Because this app uses support library UI
+    elements its interface incorporates material design principles, even though
+    it is running on Android 4.4, which does not include native support for
+    material design.
+  </p>
+</div>
+
+<p>
+  Support libraries allow apps running on older versions of the Android
+  platform to support features made available on newer versions of the
+  platform. For example, an app running on a version of Android lower than 5.0
+  (API level 21) that relies on framework classes cannot display
+  material-design elements, as that version of the Android framework doesn't
+  support material design. However, if the app incorporates the Support
+  Library's <a href="{@docRoot}tools/support-library/features.html">appcompat
+  library</a>, the app has access to many of the features available in API
+  level 21, including support for material design. As a result, your app can
+  deliver a more consistent experience across a broader range of platform
+  versions.
+</p>
 
 
-<h2 id="revisions">Revisions</h2>
+<p>
+  In some cases, the support library version of a class depends as much as
+  possible on the functionality that the framework provides. In these cases,
+  if an app calls one of the support class's methods, the support library's
+  behavior depends on what version of Android the app is running on. If the
+  framework provides the necessary functionality, the support library calls on
+  the framework to perform the task. If the app is running on an earlier
+  version of Android, and the framework doesn't expose the needed
+  functionality, the support library may try to provide the functionality
+  itself, or may act as a no-op. In either case, the app generally doesn't
+  need to check what version of Android it's running on; instead, the app
+  can rely on the support library to do those checks and choose appropriate
+  behavior. Generally, classes whose names end in
+  <code>…Compat</code> (like {@link android.support.v4.app.ActivityCompat})
+  behave this way.
+</p>
+
+<p>
+  In other cases, the support library class provides a complete, standalone
+  version of a framework class that does not rely on the availability of
+  any framework APIs. These
+  methods provide consistent behavior across all supported platforms.
+</p>
+
+<p>
+  In either case, the app does not need to check the system version at run
+  time. The app can rely on the support library class to do the appropriate
+  system checks, and modify its behavior as necessary.
+</p>
+
+<h2 id="layout-patterns">Support for General Layout Patterns</h2>
+
+<p>
+  Support libraries provide user interface elements not offered by
+  the Android framework. For example, the Android Support Library offers additional
+  layout classes, like {@link android.support.v4.widget.DrawerLayout}. These
+  classes follow recommended Android design practices; for example, the Design
+  Library follows the principles of material design in a way that works across
+  many versions of Android.
+</p>
+
+<p>
+  By using these support library classes, you can avoid having to reinvent the
+  wheel; if your app has a particular user interface requirement, you can draw
+  on existing code, which provides a user interface that users will already be
+  familiar with. These elements also help you build an app that looks and feels
+  like a part of the Android ecosystem. For example, many apps need to display
+  arbitrarily long lists of elements, and need to be able to quickly and
+  efficiently reuse those elements as the list changes; this might be a list of
+  emails, contacts, music albums, and so on. Those apps can use the support
+  library {@link android.support.v7.widget.RecyclerView} widget to display the
+  list. This saves the app developer from having to develop the list from
+  scratch, and also ensures that the user will see a list that looks and
+  behaves like lists in other apps.
+</p>
+
+<h2 id="form-factors">Support for Different Form Factors</h2>
+
+<p>
+  The Android SDK provides libraries for a number of different form factors,
+  such as TV and wearables. An app can depend on the appropriate support
+  library to provide functionality across a wide range of platform versions,
+  and can provide content on external screens, speakers, and other destination
+  devices.
+</p>
+
+<h2 id="utils">General Utilities</h2>
+
+<p>
+  The Android Support Library provides backward-compatible utility functions.
+  Apps can use these utility functions to provide an appropriate user
+  experience across a wide range of Android system versions. For example,
+  support library permission methods behave appropriately depending on what
+  platform version your app is running on. If the platform supports the
+  runtime permissions model, these methods request the appropriate permission
+  from the user; on platform versions that do not support the runtime
+  permissions model, the methods check whether the appropriate permission was
+  granted at install time.
+</p>
+
+<h2 id="revisions">Support Library Revision History</h2>
 
 <p>This section provides details about the Support Library package releases.</p>
 
diff --git a/docs/html/tools/support-library/setup.jd b/docs/html/go/libraries/support-library/setup.jd
similarity index 100%
rename from docs/html/tools/support-library/setup.jd
rename to docs/html/go/libraries/support-library/setup.jd
diff --git a/docs/html/tools/testing-support-library/index.jd b/docs/html/go/libraries/testing-support-library/index.jd
similarity index 99%
rename from docs/html/tools/testing-support-library/index.jd
rename to docs/html/go/libraries/testing-support-library/index.jd
index 35a3c7d..f69a35b7 100644
--- a/docs/html/tools/testing-support-library/index.jd
+++ b/docs/html/go/libraries/testing-support-library/index.jd
@@ -1,4 +1,5 @@
 page.title=Testing Support Library
+page.metaDescription=The Android Testing Support Library provides an extensive framework for testing Android apps.
 page.image=images/tools/studio-test-module.png
 
 @jd:body
diff --git a/docs/html/google/_book.yaml b/docs/html/google/_book.yaml
index 01efa4f..92357e9 100644
--- a/docs/html/google/_book.yaml
+++ b/docs/html/google/_book.yaml
@@ -1,17 +1,20 @@
 toc:
 - title: Google Play In-app Billing
   path: /google/play/billing/index.html
-  custom_link_attributes:
-  - zh-cn-lang="应用内结算"
+  path_attributes:
+  - name: zh-cn-lang
+    value: 应用内结算
   section:
   - title: Overview
     path: /google/play/billing/billing_overview.html
-    custom_link_attributes:
-    - zh-cn-lang="应用内结算概述"
+    path_attributes:
+    - name: zh-cn-lang
+      value: 应用内结算概述
   - title: Version 3 API
     path: /google/play/billing/api.html
-    custom_link_attributes:
-    - zh-cn-lang="应用内结算 API"
+    path_attributes:
+    - name: zh-cn-lang
+      value: 应用内结算 API
     section:
     - title: Implementing the API
       path: /google/play/billing/billing_integrate.html
@@ -23,29 +26,39 @@
     path: /google/play/billing/billing_promotions.html
   - title: Security and Design
     path: /google/play/billing/billing_best_practices.html
-    custom_link_attributes:
-    - zh-cn-lang="安全性和设计"
+    path_attributes:
+    - name: zh-cn-lang
+      value: 安全性和设计
   - title: Testing In-app Billing
     path: /google/play/billing/billing_testing.html
-    custom_link_attributes:
-    - zh-cn-lang="测试应用内结算"
+    path_attributes:
+    - name: zh-cn-lang
+      value: 测试应用内结算
   - title: Administering In-app Billing
     path: /google/play/billing/billing_admin.html
-    custom_link_attributes:
-    - zh-cn-lang="管理应用内结算"
+    path_attributes:
+    - name: zh-cn-lang
+      value: 管理应用内结算
   - title: Version Notes
     path: /google/play/billing/versions.html
 
 - title: Filters on Google Play
   path: /google/play/filters.html
-  custom_link_attributes:
-  - es-lang="Filtros en Google Play"
-  - ja-lang="Google Play 上のフィルタ"
-  - ko-lang="Google Play 필터"
-  - pt-br-lang="Filtros no Google Play"
-  - ru-lang="Фильтры в Google Play"
-  - zh-cn-lang="Google Play 上的筛选器"
-  - zh-tw-lang="Google Play 上的篩選器"
+  path_attributes:
+  - name: es-lang
+    value: Filtros en Google Play
+  - name: ja-lang
+    value: Google Play 上のフィルタ
+  - name: ko-lang
+    value: Google Play 필터
+  - name: pt-br-lang
+    value: Filtros no Google Play
+  - name: ru-lang
+    value: Фильтры в Google Play
+  - name: zh-cn-lang
+    value: Google Play 上的筛选器
+  - name: zh-tw-lang
+    value: Google Play 上的篩選器
 
 - title: Google Play Developer API
   path: /google/play/developer-api.html
diff --git a/docs/html/guide/_book.yaml b/docs/html/guide/_book.yaml
index 5017376..4163f0f 100644
--- a/docs/html/guide/_book.yaml
+++ b/docs/html/guide/_book.yaml
@@ -365,6 +365,12 @@
   - title: App Install Location
     path: /guide/topics/data/install-location.html
 
+
+- title: Libraries
+  path: /go/libraries/index.html
+  section:
+  - include: /go/libraries/_book.yaml
+
 - title: Administration
   path: /guide/topics/admin/index.html
   section:
@@ -387,14 +393,21 @@
 
 - title: Best Practices
   path: /guide/practices/index.html
-  custom_link_attributes:
-  - de-lang="Bewährte Verfahren"
-  - es-lang="Prácticas recomendadas"
-  - fr-lang="Meilleures pratiques"
-  - it-lang="Best practice"
-  - ja-lang="ベスト プラクティス"
-  - zh-cn-lang="最佳实践"
-  - zh-tw-lang="最佳實務"
+  path_attributes:
+  - name: de-lang
+    value: Bewährte Verfahren
+  - name: es-lang
+    value: Prácticas recomendadas
+  - name: fr-lang
+    value: Meilleures pratiques
+  - name: it-lang
+    value: Best practice
+  - name: ja-lang
+    value: ベスト プラクティス
+  - name: zh-cn-lang
+    value: 最佳实践
+  - name: zh-tw-lang
+    value: 最佳實務
   section:
   - title: Supporting Multiple Screens
     path: /guide/practices/screens_support.html
diff --git a/docs/html/guide/guide_toc.cs b/docs/html/guide/guide_toc.cs
index 549a1b6..9257a76 100644
--- a/docs/html/guide/guide_toc.cs
+++ b/docs/html/guide/guide_toc.cs
@@ -121,7 +121,7 @@
       <li><a href="<?cs var:toroot ?>guide/topics/resources/overview.html">
           <span class="en">Overview</span>
         </a></li>
-        <li><a href="<?cs var:toroot ?>guide/topics/resources/providing-resources.html">
+      <li><a href="<?cs var:toroot ?>guide/topics/resources/providing-resources.html">
           <span class="en">Providing Resources</span>
         </a></li>
       <li><a href="<?cs var:toroot ?>guide/topics/resources/accessing-resources.html">
@@ -129,10 +129,13 @@
         </a></li>
       <li><a href="<?cs var:toroot ?>guide/topics/resources/runtime-changes.html">
             <span class="en">Handling Runtime Changes</span>
-          </a></li>
+        </a></li>
       <li><a href="<?cs var:toroot ?>guide/topics/resources/localization.html">
           <span class="en">Localization</span>
         </a></li>
+      <li><a href="<?cs var:toroot ?>guide/topics/resources/complex-xml-resources.html">
+          <span class="en">Complex XML Resources</span>
+        </a></li>
       <li class="nav-section">
         <div class="nav-section-header"><a href="<?cs var:toroot ?>guide/topics/resources/available-resources.html">
             <span class="en">Resource Types</span>
diff --git a/docs/html/guide/topics/resources/complex-xml-resources.jd b/docs/html/guide/topics/resources/complex-xml-resources.jd
new file mode 100644
index 0000000..66dcb58
--- /dev/null
+++ b/docs/html/guide/topics/resources/complex-xml-resources.jd
@@ -0,0 +1,117 @@
+page.title=Inline Complex XML Resources
+parent.title=Application Resources
+parent.link=index.html
+@jd:body
+
+<p>Certain resource types are a composition of multiple complex resources represented by XML files.
+One example is an animated vector drawable, which is a drawable resource encapsulating a vector
+drawable and an animation. This requires the use of at least three XML files.</p>
+
+<dl>
+
+<dt><code>res/drawable/avd.xml</code></dt>
+<dd>
+<pre class="stx">
+&lt;?xml version="1.0" encoding="utf-8"?&gt;
+&lt;animated-vector xmlns:android="http://schemas.android.com/apk/res/android"
+    android:drawable="@drawable/vectordrawable" &gt;
+    &lt;target
+        android:name="rotationGroup"
+        android:animation="@anim/rotation" /&gt;
+&lt;/animated-vector&gt;
+</pre>
+</dd>
+
+<dt><code>res/drawable/vectordrawable.xml</code></dt>
+<dd>
+<pre class="stx">
+&lt;?xml version="1.0" encoding="utf-8"?&gt;
+&lt;vector xmlns:android="http://schemas.android.com/apk/res/android"
+    android:height="64dp"
+    android:width="64dp"
+    android:viewportHeight="600"
+    android:viewportWidth="600" &gt;
+
   &lt;group
+        android:name="rotationGroup"
+        android:pivotX="300.0"
+        android:pivotY="300.0"
+        android:rotation="45.0" &gt;
+        &lt;path
+            android:fillColor="#000000"
+            android:pathData="M300,70 l 0,-70 70,70 0,0 -70,70z" /&gt;
+
   &lt;/group&gt;
+&lt;/vector&gt;
+</pre>
+</dd>
+
+<dt><code>res/anim/rotation.xml</code></dt>
+<dd>
+<pre class="stx">
+&lt;?xml version="1.0" encoding="utf-8"?&gt;
+&lt;objectAnimator xmlns:android="http://schemas.android.com/apk/android"
+    android:duration="6000"
+    android:propertyName="rotation"
+    android:valueFrom="0"
+
   android:valueTo="360" /&gt;
+</pre>
+</dd>
+
+</dl>
+
+<p>There are a lot of files here just to make a single animated vector drawable!
+If the vector drawable and animations are re-used elsewhere, this is the best way to implement an
+animated vector drawable. If they’re only ever used for this animated vector drawable, then there is
+a more compact way to implement them.</p>
+
+<p>Using AAPT’s inline resource format, you can define all three resources in the same XML file.
+Since we’re making an animated vector drawable, we put the file under <code>res/drawable/</code>.</p>
+
+<dl>
+
+<dt><code>res/drawable/avd.xml</code></dt>
+<dd>
+<pre class="stx">
+&lt;?xml version="1.0" encoding="utf-8"?&gt;
+&lt;animated-vector xmlns:android="http://schemas.android.com/apk/res/android"
+    <strong>xmlns:aapt="http://schemas.android.com/aapt"</strong> &gt;
+
+    <strong>&lt;aapt:attr name="android:drawable" &gt;</strong>
+        &lt;vector
+            android:height="64dp"
+            android:width="64dp"
+            android:viewportHeight="600"
+            android:viewportWidth="600" &gt;
+
           &lt;group
+                android:name="rotationGroup"
+                android:pivotX="300.0"
+                android:pivotY="300.0"
+                android:rotation="45.0" &gt;
+                &lt;path
+                    android:fillColor="#000000"
+                    android:pathData="M300,70 l 0,-70 70,70 0,0 -70,70z" /&gt;
+
           &lt;/group&gt;
+        &lt;/vector&gt;
+    <strong>&lt;aapt:attr /&gt;</strong>
+
+    &lt;target
+        android:name="rotationGroup" /&gt;
+        <strong>&lt;aapt:attr name="android:animation" &gt;</strong>
+            &lt;objectAnimator
+                android:duration="6000"
+                android:propertyName="rotation"
+                android:valueFrom="0"
+
               android:valueTo="360" /&gt;
+        <strong>&lt;aapt:attr&gt;</strong>
+&lt;/animated-vector&gt;
+</pre>
+</dd>
+
+</dl>
+
+<p>The XML tag <code>&lt;aapt:attr &gt;</code> tells AAPT that the tag’s child shall be treated as a
+resource and extracted into its own resource file. The value in the attribute name specifies where
+to use the inline resource within the parent tag.</p>
+
+<p>AAPT will generate resource files and names for all of the inline resources.
+Applications built using this inline format are compatible with all versions of Android.</p>
+
diff --git a/docs/html/guide/topics/resources/overview.jd b/docs/html/guide/topics/resources/overview.jd
index c3bd0bf..c496797 100644
--- a/docs/html/guide/topics/resources/overview.jd
+++ b/docs/html/guide/topics/resources/overview.jd
@@ -9,6 +9,7 @@
     <li><a href="accessing-resources.html">Accessing Resources</a></li>
     <li><a href="runtime-changes.html">Handling Runtime Changes</a></li>
     <li><a href="localization.html">Localization</a></li>
+    <li><a href="complex-xml-resources.html">Complex XML Resources</a></li>
   </ol>
 
   <h2>Reference</h2>
@@ -79,6 +80,9 @@
   <dd>A bottom-up guide to localizing your application using alternative resources. While this is
 just one specific use of alternative resources, it is very important in order to reach more
 users.</dd>
+  <dt><strong><a href="complex-xml-resources.html">Complex XML Resources</a></strong></dt>
+  <dd>An XML format for building complex resources like animated vector drawables in a single
+XML file.</dd>
   <dt><strong><a href="available-resources.html">Resource Types</a></strong></dt>
   <dd>A reference of various resource types you can provide, describing their XML elements,
 attributes, and syntax. For example, this reference shows you how to create a resource for
diff --git a/docs/html/images/tools/am-androidmon2.png b/docs/html/images/tools/am-androidmon2.png
new file mode 100644
index 0000000..a4a7571
--- /dev/null
+++ b/docs/html/images/tools/am-androidmon2.png
Binary files differ
diff --git a/docs/html/images/tools/am-cpumon2.png b/docs/html/images/tools/am-cpumon2.png
new file mode 100644
index 0000000..6ac6e02
--- /dev/null
+++ b/docs/html/images/tools/am-cpumon2.png
Binary files differ
diff --git a/docs/html/images/tools/am-dumpalloc2.png b/docs/html/images/tools/am-dumpalloc2.png
new file mode 100644
index 0000000..d936aa8
--- /dev/null
+++ b/docs/html/images/tools/am-dumpalloc2.png
Binary files differ
diff --git a/docs/html/images/tools/am-gc2.png b/docs/html/images/tools/am-gc2.png
new file mode 100644
index 0000000..a5e8b6e
--- /dev/null
+++ b/docs/html/images/tools/am-gc2.png
Binary files differ
diff --git a/docs/html/images/tools/am-gpumon2.png b/docs/html/images/tools/am-gpumon2.png
new file mode 100644
index 0000000..5cf51d9
--- /dev/null
+++ b/docs/html/images/tools/am-gpumon2.png
Binary files differ
diff --git a/docs/html/images/tools/am-icaptures.png b/docs/html/images/tools/am-icaptures.png
new file mode 100644
index 0000000..cf288d6
--- /dev/null
+++ b/docs/html/images/tools/am-icaptures.png
Binary files differ
diff --git a/docs/html/images/tools/am-igraphic.png b/docs/html/images/tools/am-igraphic.png
new file mode 100644
index 0000000..a3c43fa
--- /dev/null
+++ b/docs/html/images/tools/am-igraphic.png
Binary files differ
diff --git a/docs/html/images/tools/am-imaximize.png b/docs/html/images/tools/am-imaximize.png
new file mode 100644
index 0000000..38a6c6c
--- /dev/null
+++ b/docs/html/images/tools/am-imaximize.png
Binary files differ
diff --git a/docs/html/images/tools/am-imaxlogcat.png b/docs/html/images/tools/am-imaxlogcat.png
new file mode 100644
index 0000000..4522bd4
--- /dev/null
+++ b/docs/html/images/tools/am-imaxlogcat.png
Binary files differ
diff --git a/docs/html/images/tools/am-iminimize.png b/docs/html/images/tools/am-iminimize.png
new file mode 100644
index 0000000..d0bbe4c
--- /dev/null
+++ b/docs/html/images/tools/am-iminimize.png
Binary files differ
diff --git a/docs/html/images/tools/am-imovedown.png b/docs/html/images/tools/am-imovedown.png
new file mode 100644
index 0000000..802c13b
--- /dev/null
+++ b/docs/html/images/tools/am-imovedown.png
Binary files differ
diff --git a/docs/html/images/tools/am-imoveup.png b/docs/html/images/tools/am-imoveup.png
new file mode 100644
index 0000000..95f6ef3
--- /dev/null
+++ b/docs/html/images/tools/am-imoveup.png
Binary files differ
diff --git a/docs/html/images/tools/am-logcatmon2.png b/docs/html/images/tools/am-logcatmon2.png
new file mode 100644
index 0000000..5635935
--- /dev/null
+++ b/docs/html/images/tools/am-logcatmon2.png
Binary files differ
diff --git a/docs/html/images/tools/am-networkmon.png b/docs/html/images/tools/am-networkmon.png
index 95b3a5b..f55f853 100644
--- a/docs/html/images/tools/am-networkmon.png
+++ b/docs/html/images/tools/am-networkmon.png
Binary files differ
diff --git a/docs/html/images/tools/am-networkmon2.png b/docs/html/images/tools/am-networkmon2.png
new file mode 100644
index 0000000..d05fcd4
--- /dev/null
+++ b/docs/html/images/tools/am-networkmon2.png
Binary files differ
diff --git a/docs/html/images/tools/am-screenshot.png b/docs/html/images/tools/am-screenshot.png
new file mode 100644
index 0000000..5c27617
--- /dev/null
+++ b/docs/html/images/tools/am-screenshot.png
Binary files differ
diff --git a/docs/html/images/tools/am-sysinfo.png b/docs/html/images/tools/am-sysinfo.png
new file mode 100644
index 0000000..9b5cd17
--- /dev/null
+++ b/docs/html/images/tools/am-sysinfo.png
Binary files differ
diff --git a/docs/html/images/tools/am-video.png b/docs/html/images/tools/am-video.png
new file mode 100644
index 0000000..9787ef8
--- /dev/null
+++ b/docs/html/images/tools/am-video.png
Binary files differ
diff --git a/docs/html/images/tools/sdk-iadd.png b/docs/html/images/tools/sdk-iadd.png
new file mode 100644
index 0000000..7e35521
--- /dev/null
+++ b/docs/html/images/tools/sdk-iadd.png
Binary files differ
diff --git a/docs/html/images/tools/studio-sdk-manager-packages.png b/docs/html/images/tools/studio-sdk-manager-packages.png
index 356073e..79ea912 100644
--- a/docs/html/images/tools/studio-sdk-manager-packages.png
+++ b/docs/html/images/tools/studio-sdk-manager-packages.png
Binary files differ
diff --git a/docs/html/images/tools/support-library/appbar-kitkat.png b/docs/html/images/tools/support-library/appbar-kitkat.png
new file mode 100644
index 0000000..c89fd87
--- /dev/null
+++ b/docs/html/images/tools/support-library/appbar-kitkat.png
Binary files differ
diff --git a/docs/html/images/tools/support-library/appbar-kitkat_2x.png b/docs/html/images/tools/support-library/appbar-kitkat_2x.png
new file mode 100644
index 0000000..c9718e6
--- /dev/null
+++ b/docs/html/images/tools/support-library/appbar-kitkat_2x.png
Binary files differ
diff --git a/docs/html/jd_collections.js b/docs/html/jd_collections.js
index 48c923d..ecd374b 100644
--- a/docs/html/jd_collections.js
+++ b/docs/html/jd_collections.js
@@ -1699,6 +1699,37 @@
       "https://www.youtube.com/watch?v=j3QC6hcpy90"
     ]
   },
+"tools/help/log": {
+    "title": "",
+    "resources": [
+       "tools/help/am-logcat.html"
+    ]
+  },
+"tools/help/monitor": {
+    "title": "",
+    "resources": [
+       "tools/help/am-memory.html",
+       "tools/help/am-cpu.html",
+       "tools/help/am-gpu.html",
+       "tools/help/am-network.html"
+    ]
+  },
+ "tools/help/data": {
+    "title": "",
+    "resources": [
+       "tools/help/am-hprof.html",
+       "tools/help/am-allocation.html",
+       "tools/help/am-methodtrace.html",
+       "tools/help/am-sysinfo.html"
+    ]
+  },
+  "tools/help/shot": {
+    "title": "",
+    "resources": [
+       "tools/help/am-screenshot.html",
+       "tools/help/am-video.html"
+    ]
+  },
   "tools/performance/rendering": {
     "title": "",
     "resources": [
diff --git a/docs/html/jd_extras_en.js b/docs/html/jd_extras_en.js
index 53f0703..b1d7efc 100644
--- a/docs/html/jd_extras_en.js
+++ b/docs/html/jd_extras_en.js
@@ -3530,7 +3530,6 @@
       "distribute/googleplay/index.html#opportunities",
       "distribute/analyze/improve-roi.html",
       "distribute/users/expand-to-new-markets.html",
-      "distribute/users/promote-with-ads.html",
       "distribute/analyze/index.html",
       "distribute/users/app-invites.html",
       "distribute/users/ota-installs.html",
@@ -4457,6 +4456,14 @@
       "https://support.google.com/googleplay/answer/2651410"
     ]
   },
+  "go/libraries": {
+    "title": "",
+    "resources": [
+      "go/libraries/support-library/index.html",
+      "go/libraries/testing-support-library/index.html",
+      "go/libraries/data-binding/index.html"
+    ]
+  },
   "autolanding": {
     "title": "",
     "resources": [
diff --git a/docs/html/ndk/guides/_book.yaml b/docs/html/ndk/guides/_book.yaml
index fdcfe46..287a92d 100644
--- a/docs/html/ndk/guides/_book.yaml
+++ b/docs/html/ndk/guides/_book.yaml
@@ -61,5 +61,14 @@
   - title: OpenSL ES for Android
     path: /ndk/guides/audio/opensl-for-android.html
 
-- title: Graphics
+- title: Vulkan
   path: /ndk/guides/graphics/index.html
+  section:
+  - title: Getting Started
+    path: /ndk/guides/graphics/getting-started.html
+  - title: Design Guidelines
+    path: /ndk/guides/graphics/design-notes.html
+  - title: Shader Compilers
+    path: /ndk/guides/graphics/shader-compilers.html
+  - title: Validation Layers
+    path: /ndk/guides/graphics/validation-layer.html
diff --git a/docs/html/ndk/guides/graphics/validation-layer.jd b/docs/html/ndk/guides/graphics/validation-layer.jd
index 3a61f18..beac1c0 100644
--- a/docs/html/ndk/guides/graphics/validation-layer.jd
+++ b/docs/html/ndk/guides/graphics/validation-layer.jd
@@ -109,10 +109,37 @@
 </li>
 
 <li>
-Prepare to build by following the preparation instructions for your platform. These instructions
-are in the {@code BUILD.md} file contained in the local instance of the repository you cloned.
+Begin preparation for building by entering the following commands on the command line:
+<ul>
+   <li>For Linux or OS X:
+   <ul>
+      <li>
+      <pre class="no-pretty-print">
+$ cd build-android
+$ ./android-generate</pre>
+      </li>
+   </ul>
+   </li>
+
+   <li>For Windows:
+   <ul>
+      <li>
+<pre class="no-pretty-print">
+&gt; cd build-android
+&gt; android-generate.bat</pre>
+      </li>
+   </ul>
+   </li>
+</ul>
 </li>
 
+<li>
+Continue by following the build instructions for your platform.
+These instructions are in the {@code BUILD.md} file contained in the local instance of the
+repository you cloned.
+</li>
+</ul>
+
 </ol>
 
 <h3 id="ias">Android Studio Integration</h3>
@@ -205,12 +232,10 @@
 <p>
 To build validation layers on Linux or OS X, enter these commands on the command line:
 </p>
-<ol>
+<ul>
 <li>
 Using Gradle:
 <pre class="no-pretty-print">
-$ cd build-android
-$ ./android-generate
 $ cd generated/gradle-build
 $ # configure SDK and NDK path in local.properties
 $ gradlew assembleAllDebug
@@ -219,22 +244,17 @@
 <li>
 Using Android makefiles:
 <pre class="no-pretty-print">
-$ cd build-android
-$ ./android-generate
-$ ndk-build
-</pre>
+$ ndk-build</pre>
 </li>
-</ol>
+</ul>
 
 <p>
 To build validation layers on Windows, enter these commands on the command line:
 </p>
-<ol>
+<ul>
 <li>
 Using Gradle:
 <pre class="no-pretty-print">
-&gt; cd build-android
-&gt; android-generate.bat
 &gt; cd generated\gradle-build
 &gt; REM configure SDK and NDK path in local.properties
 &gt; gradlew.bat assembleAllDebug
@@ -243,12 +263,10 @@
 <li>
 Using Android makefiles:
 <pre class="no-pretty-print">
-&gt; cd build-android
-&gt; android-generate.bat
 &gt; ndk-build.cmd
 </pre>
 </li>
-</ol>
+</ul>
 
 
 
diff --git a/docs/html/preview/_book.yaml b/docs/html/preview/_book.yaml
index 9f53866..cac6d13 100644
--- a/docs/html/preview/_book.yaml
+++ b/docs/html/preview/_book.yaml
@@ -1,96 +1,342 @@
 toc:
 - title: Program Overview
   path: /preview/overview.html
-  custom_link_attributes:
-  - es-lang="Información general del programa"
-  - ja-lang="プログラム概要"
-  - ko-lang="프로그램 개요"
-  - pt-br-lang="Visão geral do programa"
-  - ru-lang="Обзор программы"
-  - zh-cn-lang="计划概览"
-  - zh-tw-lang="程式總覽"
+  path_attributes:
+  - name: es-lang
+    value: Información general del programa
+  - name: in-lang
+    value: Ikhtisar Program
+  - name: ja-lang
+    value: プログラム概要
+  - name: ko-lang
+    value: 프로그램 개요
+  - name: pt-br-lang
+    value: Visão geral do programa
+  - name: ru-lang
+    value: Обзор программы
+  - name: vi-lang
+    value: Tổng quan về Chương trình
+  - name: zh-cn-lang
+    value: 计划概览
+  - name: zh-tw-lang
+    value: 程式總覽
 
 - title: Support and Release Notes
   path: /preview/support.html
 
 - title: Set Up to Develop
   path: /preview/setup-sdk.html
-  custom_link_attributes:
-  - es-lang="Configurar el SDK de la versión preliminar"
-  - ja-lang="Preview SDK のセットアップ"
-  - ko-lang="미리 보기 SDK 설정하기"
-  - pt-br-lang="Configuração do Preview SDK"
-  - ru-lang="Настройка пакета SDK Preview"
-  - zh-cn-lang="设置预览版 SDK"
-  - zh-tw-lang="設定預覽版 SDK"
+  path_attributes:
+  - name: es-lang
+    value: Configurar el SDK de la versión preliminar
+  - name: in-lang
+    value: Menyiapkan Preview
+  - name: ja-lang
+    value: Preview SDK のセットアップ
+  - name: ko-lang
+    value: 미리 보기 SDK 설정하기
+  - name: pt-br-lang
+    value: Configuração do Preview SDK
+  - name: ru-lang
+    value: Настройка пакета SDK Preview
+  - name: vi-lang
+    value: Kiểm thử trên Thiết bị
+  - name: zh-cn-lang
+    value: 设置预览版 SDK
+  - name: zh-tw-lang
+    value: 設定預覽版 SDK
 
 - title: Test on a Device
   path: /preview/download.html
+  path_attributes:
+  - name: es-lang
+    value: Pruebe en un dispositivo
+  - name: in-lang
+    value: Menguji pada Perangkat
+  - name: ja-lang
+    value: デバイス上でテストする
+  - name: ko-lang
+    value: 기기에서 테스트
+  - name: pt-br-lang
+    value: Testar em um dispositivo
+  - name: ru-lang
+    value: Тестирование на устройстве
+  - name: vi-lang
+    value: Kiểm thử trên Thiết bị
+  - name: zh-cn-lang
+    value: 在设备上测试
+  - name: zh-tw-lang
+    value: 在裝置上測試
 
 - title: Behavior Changes
   path: /preview/behavior-changes.html
-  custom_link_attributes:
-  - es-lang="Cambios en los comportamientos"
-  - ja-lang="動作の変更点"
-  - ko-lang="동작 변경"
-  - pt-br-lang="Mudanças de comportamento"
-  - ru-lang="Изменения в работе"
-  - zh-cn-lang="行为变更"
-  - zh-tw-lang="行為變更"
+  path_attributes:
+  - name: es-lang
+    value: Cambios en los comportamientos
+  - name: in-lang
+    value: Perubahan Perilaku
+  - name: ja-lang
+    value: 動作の変更点
+  - name: ko-lang
+    value: 동작 변경
+  - name: pt-br-lang
+    value: Mudanças de comportamento
+  - name: ru-lang
+    value: Изменения в работе
+  - name: vi-lang
+    value: Các thay đổi Hành vi
+  - name: zh-cn-lang
+    value: 行为变更
+  - name: zh-tw-lang
+    value: 行為變更
   section:
   - title: Background Optimizations
     path: /preview/features/background-optimization.html
+    path_attributes:
+    - name: es-lang
+      value: Optimizaciones en segundo plano
+    - name: in-lang
+      value: Optimisasi Latar Belakang
+    - name: ja-lang
+      value: バックグラウンド処理の最適化
+    - name: ko-lang
+      value: 백그라운드 최적화
+    - name: pt-br-lang
+      value: Otimizações em segundo plano
+    - name: ru-lang
+      value: Оптимизация фоновых процессов
+    - name: vi-lang
+      value: Tối ưu hóa Chạy ngầm
+    - name: zh-cn-lang
+      value: 后台优化
+    - name: zh-tw-lang
+      value: 背景最佳化
   - title: Language and Locale
     path: /preview/features/multilingual-support.html
+    path_attributes:
+    - name: es-lang
+      value: Idioma y configuración regional
+    - name: in-lang
+      value: Bahasa dan Lokal
+    - name: ja-lang
+      value: 言語とロケール
+    - name: ko-lang
+      value: 언어 및 로케일
+    - name: pt-br-lang
+      value: Idioma e localidade
+    - name: ru-lang
+      value: Язык и языковой стандарт
+    - name: vi-lang
+      value: Ngôn ngữ và Bản địa
+    - name: zh-cn-lang
+      value: 语言和区域设置
+    - name: zh-tw-lang
+      value: 語言和地區設定
 
 - title: Android N for Developers
   path: /preview/api-overview.html
-  custom_link_attributes:
-  - es-lang="Información general de la API"
-  - ja-lang="API の概要"
-  - ko-lang="API 개요"
-  - pt-br-lang="Visão geral da API"
-  - ru-lang="Обзор API-интерфейсов"
-  - zh-cn-lang="API 概览"
-  - zh-tw-lang="API 總覽"
+  path_attributes:
+  - name: es-lang
+    value: Información general de la API
+  - name: in-lang
+    value: Android N untuk Pengembang
+  - name: ja-lang
+    value: API の概要
+  - name: ko-lang
+    value: API 개요
+  - name: pt-br-lang
+    value: Visão geral da API
+  - name: ru-lang
+    value: Обзор API-интерфейсов
+  - name: vi-lang
+    value: Android N cho Nhà phát triển
+  - name: zh-cn-lang
+    value: API 概览
+  - name: zh-tw-lang
+    value: API 總覽
   section:
   - title: Multi-Window Support
     path: /preview/features/multi-window.html
+    path_attributes:
+    - name: es-lang
+      value: Compatibilidad con ventanas múltiples
+    - name: in-lang
+      value: Dukungan Multi-Jendela
+    - name: ja-lang
+      value: マルチ ウィンドウのサポート
+    - name: ko-lang
+      value: 다중 창 지원
+    - name: pt-br-lang
+      value: Suporte a várias janelas
+    - name: ru-lang
+      value: Поддержка многооконного режима
+    - name: vi-lang
+      value: Hỗ trợ đa cửa sổ
+    - name: zh-cn-lang
+      value: 多窗口支持
+    - name: zh-tw-lang
+      value: 多視窗支援
   - title: Notifications
     path: /preview/features/notification-updates.html
+    path_attributes:
+    - name: es-lang
+      value: Notificaciones
+    - name: in-lang
+      value: Pemberitahuan
+    - name: ja-lang
+      value: 通知
+    - name: ko-lang
+      value: 알림
+    - name: pt-br-lang
+      value: Notificações
+    - name: ru-lang
+      value: Уведомления
+    - name: vi-lang
+      value: Thông báo
+    - name: zh-cn-lang
+      value: 通知
+    - name: zh-tw-lang
+      value: 通知
   - title: Data Saver
     path: /preview/features/data-saver.html
   - title: TV Recording
     path: /preview/features/tv-recording-api.html
+    path_attributes:
+    - name: es-lang
+      value: Grabación de TV
+    - name: in-lang
+      value: Perekaman TV
+    - name: ja-lang
+      value: TV の録画
+    - name: ko-lang
+      value: TV 녹화
+    - name: pt-br-lang
+      value: Gravação para TV
+    - name: ru-lang
+      value: Запись ТВ
+    - name: vi-lang
+      value: Ghi lại TV
+    - name: zh-cn-lang
+      value: TV 录制
+    - name: zh-tw-lang
+      value: 電視錄製
   - title: Network Security Configuration
     path: /preview/features/security-config.html
+    path_attributes:
+    - name: es-lang
+      value: Configuración de seguridad de la red
+    - name: ja-lang
+      value: ネットワーク セキュリティ構成
+    - name: ko-lang
+      value: 네트워크 보안 구성
+    - name: pt-br-lang
+      value: Configurações de segurança de rede
+    - name: ru-lang
+      value: Конфигурация сетевой безопасности
+    - name: vi-lang
+      value: Cấu hình Bảo mật mạng
+    - name: zh-cn-lang
+      value: 网络安全配置
+    - name: zh-tw-lang
+      value: 網路安全性設定
   - title: ICU4J Support
     path: /preview/features/icu4j-framework.html
+    path_attributes:
+    - name: es-lang
+      value: API de ICU4J del framework de Android
+    - name: in-lang
+      value: ICU4J Android Framework API
+    - name: ja-lang
+      value: ICU4J Android フレームワーク API
+    - name: ko-lang
+      value: ICU4J Android 프레임워크 API
+    - name: pt-br-lang
+      value: APIs de estrutura do Android para ICU4J
+    - name: ru-lang
+      value: API-интерфейсы ICU4J в платформе Android
+    - name: vi-lang
+      value: API Khuôn khổ Android ICU4J
+    - name: zh-cn-lang
+      value: ICU4J Android 框架 API
+    - name: zh-tw-lang
+      value: ICU4J Android 架構 API
   - title: Java 8 Language Features
     path: /preview/j8-jack.html
+    path_attributes:
+    - name: es-lang
+      value: Funciones del lenguaje Java 8
+    - name: in-lang
+      value: Fitur Bahasa Java 8
+    - name: ja-lang
+      value: Java 8 の機能
+    - name: ko-lang
+      value: Java 8 언어 기능
+    - name: pt-br-lang
+      value: Recursos de linguagem do Java 8
+    - name: ru-lang
+      value: Возможности языка Java 8
+    - name: vi-lang
+      value: Tính năng của Ngôn ngữ Java 8
+    - name: zh-cn-lang
+      value: Java 8 语言功能
+    - name: zh-tw-lang
+      value: Java 8 語言功能
   - title: Android for Work Updates
     path: /preview/features/afw.html
   - title: Scoped Directory Access
     path: /preview/features/scoped-folder-access.html
+    path_attributes:
+    - name: es-lang
+      value: Acceso a directorios determinados
+    - name: ja-lang
+      value: 特定のディレクトリへのアクセス
+    - name: ko-lang
+      value: 범위가 지정된 디렉터리 액세스
+    - name: pt-br-lang
+      value: Acesso a diretórios com escopo
+    - name: ru-lang
+      value: Доступ к выделенным каталогам
+    - name: vi-lang
+      value: Truy cập Thư mục theo Phạm vi
+    - name: zh-cn-lang
+      value: 作用域目录访问
+    - name: zh-tw-lang
+      value: 限定範圍目錄存取
 
 - title: Samples
   path: /preview/samples.html
-  custom_link_attributes:
-  - es-lang="Ejemplos"
-  - ja-lang="サンプル"
-  - ko-lang="샘플"
-  - pt-br-lang="Exemplos"
-  - ru-lang="Примеры"
-  - zh-cn-lang="示例"
-  - zh-tw-lang="範例"
+  path_attributes:
+  - name: es-lang
+    value: Ejemplos
+  - name: in-lang
+    value: Contoh
+  - name: ja-lang
+    value: サンプル
+  - name: ko-lang
+    value: 샘플
+  - name: pt-br-lang
+    value: Exemplos
+  - name: ru-lang
+    value: Примеры
+  - name: zh-cn-lang
+    value: 示例
+  - name: zh-tw-lang
+    value: 範例
 
 - title: License Agreement
   path: /preview/license.html
-  custom_link_attributes:
-  - es-lang="Contrato de licencia"
-  - ja-lang="使用許諾契約"
-  - ko-lang="라이선스 계약"
-  - pt-br-lang="Contrato de licença"
-  - ru-lang="Лицензионное соглашение"
-  - zh-cn-lang="许可协议"
-  - zh-tw-lang="授權協議"
+  path_attributes:
+  - name: es-lang
+    value: Contrato de licencia
+  - name: ja-lang
+    value: 使用許諾契約
+  - name: ko-lang
+    value: 라이선스 계약
+  - name: pt-br-lang
+    value: Contrato de licença
+  - name: ru-lang
+    value: Лицензионное соглашение
+  - name: zh-cn-lang
+    value: 许可协议
+  - name: zh-tw-lang
+    value: 授權協議
diff --git a/docs/html/preview/behavior-changes.jd b/docs/html/preview/behavior-changes.jd
index 0cf5bc9..7c8bfe8 100644
--- a/docs/html/preview/behavior-changes.jd
+++ b/docs/html/preview/behavior-changes.jd
@@ -215,11 +215,17 @@
 
 <ul>
   <li>
-    Private files’ file permissions can no longer be relaxed by the owner, and
-    an attempt to do so using
+    Private files’ file permissions should no longer be relaxed by the owner,
+    and an attempt to do so using
     {@link android.content.Context#MODE_WORLD_READABLE} and/or
     {@link android.content.Context#MODE_WORLD_WRITEABLE}, will trigger a
     {@link java.lang.SecurityException}.
+    <p class="note">
+      <strong>Note:</strong> As of yet, this restriction is not fully enforced.
+      Apps may still modify permissions to their private directory using
+      native APIs or the {@link java.io.File File} API. However, we strongly
+      discourage relaxing the permissions to the private directory.
+    </p>
   </li>
   <li>
     Passing <code>file://</code> URIs outside the package domain may leave the
diff --git a/docs/html/preview/download-ota.jd b/docs/html/preview/download-ota.jd
index 55139f1..7e70f57 100644
--- a/docs/html/preview/download-ota.jd
+++ b/docs/html/preview/download-ota.jd
@@ -248,10 +248,9 @@
   <tr id="fugu">
     <td>Nexus Player <br>"fugu"</td>
     <td><a href="#top" onclick="onDownload(this)"
-      >fugu-ota-2665432-f0f8fea4.zip</a><br>
-      <strong>Note:</strong> DP2 version not yet available.<br>
-      MD5: 4403af764b57502d89111fd68ecb7da5<br>
-      SHA-1: f0f8fea49ea3874b751cf67462ecc5d8e039875e
+      >fugu-ota-npc91o-b1d73dd5.zip</a><br>
+      MD5: d7fbccde75e0b6d860102320ea76d58f<br>
+      SHA-1: b1d73dd5a6498fb6c66e022bd0a6c8b6a6a2374b
     </td>
   </tr>
 
diff --git a/docs/html/preview/download.jd b/docs/html/preview/download.jd
index 629bd78..b0f5369 100644
--- a/docs/html/preview/download.jd
+++ b/docs/html/preview/download.jd
@@ -347,10 +347,9 @@
   <tr id="fugu">
     <td>Nexus Player <br>"fugu"</td>
     <td><a href="#top" onclick="onDownload(this)"
-      >fugu-npc56r-preview-7027d5b6.tgz</a><br>
-      <strong>Note:</strong> DP2 version not yet available.<br>
-      MD5: f5d3d8f75836ccfe4c70e8162e498be4<br>
-      SHA-1: 7027d5b662bceda4c80a91a0a14ef0e5a7ba795b
+      >fugu-npc91o-factory-3b8e3f56.tgz</a><br>
+      MD5: b88b70ecbfb80c983c90b97cb243628b<br>
+      SHA-1: 3b8e3f56a4c35b559783c2928e740df2aab8b377
     </td>
   </tr>
 
@@ -468,18 +467,12 @@
 <p>You can now launch the Android Emulator with the Android N Preview AVD.</p>
 
 <p>
-For the best experience in the Android Emulator, install
-Android Studio 2.1 Preview, which supports the <a
-href="http://tools.android.com/tech-docs/emulator">Android Emulator 2.0 Beta</a>
-with much faster performance compared to the Emulator in
+For the best experience in the Android Emulator, make sure you're using
+Android Studio 2.1 or higher, which supports <a
+href="http://tools.android.com/tech-docs/emulator">Android Emulator 2.0</a>
+with much faster performance compared to the emulator in
 Android Studio 1.5.</p>
 
-<p class="note"><strong>Note:</strong>
-  If you're currently using Android Studio 2.0 Beta, there's a known issue
-  that prevents you from creating AVDs with the N Preview system images, so
-  you currently need to use the Android Studio 2.1 preview to create AVDs.
-</p>
-
 <p>For more information about creating virtual devices, see <a href=
   "{@docRoot}tools/devices/index.html">Managing Virtual Devices</a>.
 </p>
diff --git a/docs/html/preview/j8-jack.jd b/docs/html/preview/j8-jack.jd
index 44e1af0..1f10efa 100644
--- a/docs/html/preview/j8-jack.jd
+++ b/docs/html/preview/j8-jack.jd
@@ -23,7 +23,7 @@
 </p>
 
 <p>To start using these features, you need to download and set up Android
-Studio 2.1 (preview) and the Android N Preview SDK, which includes the required
+Studio 2.1 and the Android N Preview SDK, which includes the required
 Jack toolchain and updated Android Plugin for Gradle. If you haven't yet
 installed the Android N Preview SDK, see <a href=
 "{@docRoot}preview/setup-sdk.html">Set Up to Develop for Android N</a>.</p>
@@ -58,7 +58,7 @@
   <li>
     <a class="external-link" href=
     "https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html">
-    Lambda expressions</a>
+    Lambda expressions</a> (also available on API level 23 and lower)
   </li>
 
   <li>
@@ -70,10 +70,17 @@
   <li>
     <a class="external-link" href=
     "https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html">
-    Method References</a>
+    Method References</a> (also available on API level 23 and lower)
   </li>
 </ul>
 
+<p class="note">
+  <strong>Note:</strong> To test lambda expressions and method references on
+  earlier versions of Android, go to your {@code build.gradle}
+  file, and set {@code compileSdkVersion} and {@code targetSdkVersion} to 23 or
+  lower. You will still need to <a href="#configuration">enable the Jack
+  toolchain</a> to use these Java 8 features.
+</p>
 
 <p>
   Additionally, the following Java 8 language feature APIs are now available:
@@ -125,15 +132,6 @@
   </li>
 </ul>
 
-<p class="note">
-  <strong>Note:</strong> The Android N bases its implementation of
-  lambda expressions on anonymous classes. This approach allows them to be
-  backwards compatible and executable on earlier versions of Android. To test
-  lambda expressions on earlier versions, remember to go to your {@code
-  build.gradle} file, and set {@code compileSdkVersion} and {@code
-  targetSdkVersion} to 23 or lower.
-</p>
-
 <h2 id="configuration">
   Enabling Java 8 Features and the Jack Toolchain
 </h2>
@@ -166,7 +164,7 @@
 
 <p>
   To enable the Java 8 language features and Jack for your project, enter the
-  following in your module-specific {@code build.gradle} file:
+  following in your module-level {@code build.gradle} file:
 </p>
 
 <pre>
@@ -185,7 +183,7 @@
 }
 </pre>
 
-<h3>
+<h3 id="known-issues">
   Known Issues
 </h3>
 
@@ -209,4 +207,4 @@
 </ul>
 
 <p>If you find other problems while using Jack, <a href=
-"http://tools.android.com/filing-bugs">please report bugs</a>.</p>
\ No newline at end of file
+"http://tools.android.com/filing-bugs">please file a bug</a>.</p>
\ No newline at end of file
diff --git a/docs/html/preview/setup-sdk.jd b/docs/html/preview/setup-sdk.jd
index 9e318cf..60568ac 100644
--- a/docs/html/preview/setup-sdk.jd
+++ b/docs/html/preview/setup-sdk.jd
@@ -32,7 +32,7 @@
 <img src="{@docRoot}preview/images/n-preview-setup.png" width="700" alt="" />
 
 
-<h2 id="get-as13">Get Android Studio 2.1 (preview)</h2>
+<h2 id="get-as13">Get Android Studio 2.1</h2>
 
 <p>The Android N platform adds support for <a
 href="{@docRoot}preview/j8-jack.html">Java 8 language features</a>,
@@ -41,55 +41,14 @@
 use Java 8 language features, you need to use Android Studio 2.1 to
 build your app. Otherwise, you don't need to use the Jack compiler, but you
 still need to update to JDK 8 to compile against the Android N platform,
-as described below.
-</p>
+as described below.</p>
 
-<iframe width="400" height="225" src="//www.youtube.com/embed/SBbWGxXCMqQ?autohide=1&amp;showinfo=0" frameborder="0" allowfullscreen="" style="float: right; margin: 0 0 20px 20px;"></iframe>
+<p>If you already have Android Studio installed, make sure you have Android
+Studio 2.1 or higher by clicking <strong>Help > Check for Update</strong>
+(on Mac, <strong>Android Studio > Check for Updates</strong>).</p>
 
-<p>Android Studio 2.1 is currently available as a preview in the canary
-release channel. If you already
-have Android Studio and don't want to update to the canary channel, you can
-download Android Studio 2.1 as a separate installation and use it
-for development with Android N, leaving your primary Android Studio
-environment unaffected.</p>
-
-<p>To download Android Studio 2.1 as a separate installation, follow these
-steps (or if you want to receive Android Studio 2.1 as an update to your
-existing installation, skip to step 6):</p>
-
-<ol>
-  <li>Edit the name of your
-  existing Android Studio installation and append the version number. This way,
-  when you install the new version, it will not override the existing one.</li>
-  <li>Download the appropriate ZIP file for your operating system from the
-    <a href="http://tools.android.com/download/studio/canary/latest"
-    >canary channel download page</a>.
-  </li>
-  <li>Unzip the package and move the Android Studio 2.1 contents to the
-    appropriate location for applications on your system, then launch it.</li>
-  <li>In the setup wizard, click <strong>Next</strong> a couple times to
-  reach the SDK Components Setup screen. Here,
-  you must set a different path for the <strong>Android SDK Location</strong>.
-  It can be any directory you want, but it must not be the default path, which
-  is the same directory used by your original version of Android Studio (unless
-  you changed that one yourself). The SDK location for Android Studio 2.1
-  must be different because the N Preview SDK packages are not compatible with
-  versions of Android Studio lower than 2.1.</p>
-  </li>
-  <li>Continue with the setup wizard until you reach the Android Studio IDE.</li>
-  <li>Open the Settings dialog
-    (<strong>File &gt; Settings</strong> on Windows/Linux, or
-    <strong>Android Studio &gt; Preferences</strong> on Mac). In the left
-    panel, select <strong>Appearance &amp; Behavior &gt; System Settings &gt;
-    Updates</strong>.
-  </li>
-  <li>On the Updates panel, select the <strong>Automatically
-    check updates for</strong> check box and select
-    <strong>Canary Channel</strong> from the drop-down list.
-  </li>
-</ol>
-
-<p>Keep this settings window open for the next step.</p>
+<p>If you don't have it, <a href="{@docRoot}sdk/">download Android Studio
+2.1 here</a>.</p>
 
 
 <h2 id="get-sdk">Get the N Preview SDK</h2>
@@ -98,17 +57,10 @@
 Android N Preview SDK in Android Studio as follows:</p>
 
 <ol>
-  <li>While still viewing the Updates panel (step 4 from above),
-  select the <strong>Automatically
-    check updates for Android SDK</strong> check box and select
-    <strong>Preview Channel</strong> from the drop-down list.
-  </li>
-  <li>Click <strong>Check Now</strong>.</li>
+  <li>Open the SDK Manager by clicking <strong>Tools > Android >
+  SDK Manager</strong>.</li>
 
-  <li>In the left panel, select <strong>Appearance &amp; Behavior &gt;
-  System Settings &gt; Android SDK</strong>.
-
-  <li>Click the <strong>SDK Platforms</strong> tab, then select the
+  <li>In the <strong>SDK Platforms</strong> tab, select the
   <strong>Android N Preview</strong> check box.</li>
 
   <li>Click the <strong>SDK Tools</strong> tab, then select the
@@ -199,7 +151,7 @@
 <pre>
 android {
   compileSdkVersion <strong>'android-N'</strong>
-  buildToolsVersion <strong>'24.0.0-rc1'</strong>
+  buildToolsVersion <strong>'24.0.0-rc3'</strong>
   ...
 
   defaultConfig {
diff --git a/docs/html/preview/support.jd b/docs/html/preview/support.jd
index 4caa6b2..f0da709 100644
--- a/docs/html/preview/support.jd
+++ b/docs/html/preview/support.jd
@@ -23,7 +23,7 @@
     <div class="col-6of12">
       <p>
         <em>Date: April 2016<br>
-        Builds: NPC91K<br>
+        Builds: NPC91K, NPC91O<br>
         Emulator support: x86 &amp; ARM (32/64-bit)<br>
         Google Play services: 8.4</em>
       </p>
@@ -325,7 +325,7 @@
   </dt>
 
   <dd>
-    Playback of Netflix HD content is known to fail on Nexus Player.
+    Playback of Netflix HD content may fail on Nexus Player.
   </dd>
 
   <dd>
diff --git a/docs/html/samples/_book.yaml b/docs/html/samples/_book.yaml
deleted file mode 100644
index 3fe0d19..0000000
--- a/docs/html/samples/_book.yaml
+++ /dev/null
@@ -1,6 +0,0 @@
-toc:
-- title: About the Samples
-  path: /samples/index.html
-
-- title: What's New
-  path: /samples/new/index.html
diff --git a/docs/html/sdk/index.jd b/docs/html/sdk/index.jd
index ddc6e14..1e7761b 100644
--- a/docs/html/sdk/index.jd
+++ b/docs/html/sdk/index.jd
@@ -34,7 +34,7 @@
 
 <p style="margin-top:24px">
   <a class="landing-button green download-bundle-button"
-    data-modal-toggle="studio_tos">Download Android Studio 2.0<br>
+    data-modal-toggle="studio_tos">Download Android Studio 2.1<br>
   <span class="small"></span></a>
 </p>
 
@@ -55,7 +55,7 @@
 
 
 <!-- start studio download modal -->
-<div data-modal="studio_tos" class="dac-modal" id="langform">
+<div data-modal="studio_tos" class="dac-modal" id="studio_tos">
   <div class="dac-modal-container">
     <div class="dac-modal-window">
       <header class="dac-modal-header">
@@ -534,4 +534,3 @@
 </div>
 
 </section>
-
diff --git a/docs/html/sdk/sdk_vars.cs b/docs/html/sdk/sdk_vars.cs
index 9f220d7..6e58ddd 100644
--- a/docs/html/sdk/sdk_vars.cs
+++ b/docs/html/sdk/sdk_vars.cs
@@ -1,27 +1,28 @@
 <?cs
-set:studio.version='2.0.0.20' ?><?cs
-set:studio.release.date='April 7, 2016' ?><?cs
+set:studio.version='2.1.0.9' ?><?cs
+set:studio.release.date='April 26, 2016' ?><?cs
 
 
-set:studio.linux_bundle_download='android-studio-ide-143.2739321-linux.zip' ?><?cs
-set:studio.linux_bundle_bytes='292106971' ?><?cs
-set:studio.linux_bundle_checksum='b64070ee4ec4868e9dd942b56f76864634cb0c67' ?><?cs
+set:studio.linux_bundle_download='android-studio-ide-143.2790544-linux.zip' ?><?cs
+set:studio.linux_bundle_bytes='298122012' ?><?cs
+set:studio.linux_bundle_checksum='45dad9b76ad0506c354483aaa67ea0e2468d03a5' ?><?cs
 
-set:studio.mac_bundle_download='android-studio-ide-143.2739321-mac.dmg' ?><?cs
-set:studio.mac_bundle_bytes='292574501' ?><?cs
-set:studio.mac_bundle_checksum='0f3d53a08815c00912c13738abc79e82207b20ed' ?><?cs
+set:studio.mac_bundle_download='android-studio-ide-143.2790544-mac.dmg' ?><?cs
+set:studio.mac_bundle_bytes='298589307' ?><?cs
+set:studio.mac_bundle_checksum='d667d93ae2e4e0f3fc1b95743329a46222dbf11d' ?><?cs
 
-set:studio.win_bundle_download='android-studio-ide-143.2739321-windows.zip' ?><?cs
-set:studio.win_bundle_bytes='294612422' ?><?cs
-set:studio.win_bundle_checksum='705c00f52b715d6a845c97979ced6f9b1b3f11c6' ?><?cs
+set:studio.win_bundle_download='android-studio-ide-143.2790544-windows.zip' ?><?cs
+set:studio.win_bundle_bytes='300627540' ?><?cs
+set:studio.win_bundle_checksum='9689ba415e5f09e2dcf5263ea302e7b1d98a8fc6' ?><?cs
 
-set:studio.win_bundle_exe_download='android-studio-bundle-143.2739321-windows.exe' ?><?cs
-set:studio.win_bundle_exe_bytes='1223633080' ?><?cs
-set:studio.win_bundle_exe_checksum='c556debf40de6b5d6f6d65d169a64398e3380183' ?><?cs
+set:studio.win_bundle_exe_download='android-studio-bundle-143.2790544-windows.exe' ?><?cs
+set:studio.win_bundle_exe_bytes='1238568304' ?><?cs
+set:studio.win_bundle_exe_checksum='c6abe7980dbb7d1d9887f7341a2942c9e506f891' ?><?cs
 
-set:studio.win_notools_exe_download='android-studio-ide-143.2739321-windows.exe' ?><?cs
-set:studio.win_notools_exe_bytes='277789224' ?><?cs
-set:studio.win_notools_exe_checksum='3e8c25bd7b7f3aa326f7b2a349c4d67c550d13ac' ?><?cs
+set:studio.win_notools_exe_download='android-studio-ide-143.2790544-windows.exe' ?><?cs
+set:studio.win_notools_exe_bytes='283804056' ?><?cs
+set:studio.win_notools_exe_checksum='a2065ba737ddcfb96f4921fee6a038278f46d2a7' ?><?cs
+
 
 
 set:sdk.linux_download='android-sdk_r24.4.1-linux.tgz' ?><?cs
@@ -40,6 +41,7 @@
 set:sdk.win_installer_checksum='f9b59d72413649d31e633207e31f456443e7ea0b' ?><?cs
 
 
+
 set:ndk.mac64_download='android-ndk-r11c-darwin-x86_64.zip' ?><?cs
 set:ndk.mac64_bytes='772428792' ?><?cs
 set:ndk.mac64_checksum='4ce8e7ed8dfe08c5fe58aedf7f46be2a97564696' ?><?cs
diff --git a/docs/html/tools/_book.yaml b/docs/html/tools/_book.yaml
index 5395cc8..fb257f3 100644
--- a/docs/html/tools/_book.yaml
+++ b/docs/html/tools/_book.yaml
@@ -2,10 +2,8 @@
 - title: Download
   path: /sdk/index.html
   section:
-  - title: Installing the SDK
+  - title: Install Android Studio
     path: /sdk/installing/index.html
-  - title: Adding SDK Packages
-    path: /sdk/installing/adding-packages.html
 
 - title: Workflow
   path: /tools/workflow/index.html
@@ -27,13 +25,15 @@
     path: /tools/debugging/index.html
   - title: Publishing
     path: /tools/publishing/publishing_overview.html
-    custom_link_attributes:
-    - zh-cn-lang="发布概述"
+    path_attributes:
+    - name: zh-cn-lang
+      value: 发布概述
     section:
     - title: Preparing for Release
       path: /tools/publishing/preparing.html
-      custom_link_attributes:
-      - zh-cn-lang="准备发布"
+      path_attributes:
+      - name: zh-cn-lang
+        value: 准备发布
     - title: Versioning Your Apps
       path: /tools/publishing/versioning.html
     - title: Signing Your Apps
@@ -65,7 +65,9 @@
       path: /tools/debugging/improving-w-lint.html
     - title: Improving Code Inspection with Annotations
       path: /tools/debugging/annotations.html
-    - title: Deep Link and App Indexing API Support
+    - title: Shrink Your Code and Resources
+      path: /tools/help/proguard.html
+    - title: Supporting URLs and App Indexing in Android Studio
       path: /tools/help/app-link-indexing.html
   - title: UI Tools
     path: /tools/studio/ui-tools.html
@@ -82,6 +84,11 @@
       path: /tools/help/image-asset-studio.html
   - title: AVD Manager
     path: /tools/devices/managing-avds.html
+  - title: Android Emulator
+    path: /tools/devices/emulator.html
+    section:
+    - title: Android Emulator Command-Line Features
+      path: /tools/help/emulator.html
   - title: Debugging Tools
     path: /tools/debugging/debugging-studio.html
     section:
@@ -152,15 +159,8 @@
       path: /tools/debugging/debugging-log.html
   - title: mksdcard
     path: /tools/help/mksdcard.html
-  - title: ProGuard
-    path: /tools/help/proguard.html
   - title: Tracer for OpenGL ES
     path: /tools/help/gltracer.html
-  - title: Virtual Device Emulator
-    path: /tools/devices/emulator.html
-    section:
-    - title: Command Reference
-      path: /tools/help/emulator.html
   - title: zipalign
     path: /tools/help/zipalign.html
 
diff --git a/docs/html/tools/building/building-studio.jd b/docs/html/tools/building/building-studio.jd
index 7ba716f..2b18b66 100644
--- a/docs/html/tools/building/building-studio.jd
+++ b/docs/html/tools/building/building-studio.jd
@@ -394,11 +394,10 @@
         <li>Change the app manifest
         </li>
 
-        <li>Change resources reference by the app manifest
+        <li>Change resources referenced by the app manifest
         </li>
 
-        <li>Change an Android widget UI element (requires a <a href="#rerun">
-          Clean and Rerun</a>)
+        <li>Change an Android widget UI element
         </li>
       </ul>
     </td>
@@ -415,8 +414,17 @@
         If your build process automatically updates any part of the app manifest,
         such as automatically iterating <code>versionCode</code> or
         <code>versionName</code>, you will not be able to benefit from the full
-        performance of Instant Run. We recommend that you disable automatic updates
-        to any part in the app manifest in your debug build variants.
+        performance of Instant Run. When using Instant Run, you should disable
+        automatic updates to any part in the app manifest in your debug build
+        variants.
+      </p>
+
+      <p>
+        When updating an Android widget UI element, you need to perform a <a href=
+        "#rerun">Clean and Rerun</a> to see your changes. Alternatively, because
+        performing clean builds may take longer while using Instant Run, you can
+        temporarily <a href="#disable-ir">disable Instant Run</a> while making
+        updates to your widget UI.
       </p>
     </td>
   </tr>
@@ -608,7 +616,49 @@
 <p>
   You should experiment with these settings by incrementing their values and
   observing the effect on your build times. You could experience a negative
-  impact to performance if you allocate too many resources to the DEX'ing process.
+  impact to performance if you allocate too many resources to the dexing process.
+</p>
+
+<h4>
+  Enabling dexing-in-process and incremental Java compilation
+</h4>
+
+<p>
+  <a href="{@docRoot}tools/revisions/gradle-plugin.html#revisions">Android
+  Plugin for Gradle version 2.1.0</a> and higher features additional build
+  process improvements, including incremental Java compilation and
+  dexing-in-process. Incremental Java compilation is enabled by default and
+  reduces compilation time during development by only recompiling portions of
+  the source that have changed or need to be recompiled.
+</p>
+
+<p>
+  Dexing-in-process performs dexing within the build process rather than in a
+  separate, external VM processes. This not only makes incremental builds much
+  faster, but also significantly speeds up full builds. To enable this feature,
+  you need to set the Gradle daemon's maximum heap size to at least 2048 MB. You
+  can do this by including the following in your project's
+  <code>gradle.properties</code> file:
+
+<pre>
+org.gradle.jvmargs = -Xmx2048m
+</pre>
+
+</p>
+
+<p>
+  If you have defined a value for <a class="external-link" href=
+  "http://google.github.io/android-gradle-dsl/current/com.android.build.gradle.internal.dsl.DexOptions.html#com.android.build.gradle.internal.dsl.DexOptions:javaMaxHeapSize">
+  <code>javaMaxHeapSize</code></a> in your module-level <code>build.gradle</code>
+  file, you need to set the daemon's max heap size to the value of
+  <code>javaMaxHeapSize</code> + 1024 MB. For example, if you have set
+  <code>javaMaxHeapSize</code> to "2g", you need to add the following to your
+  project's <code>gradle.properties</code> file:
+
+<pre>
+org.gradle.jvmargs = -Xmx3072m
+</pre>
+
 </p>
 
 <h4 id="windows-defender">
diff --git a/docs/html/tools/device.jd b/docs/html/tools/device.jd
index 60dce3d..2f39402 100644
--- a/docs/html/tools/device.jd
+++ b/docs/html/tools/device.jd
@@ -211,6 +211,10 @@
     <td><code>109b</code></td>
   </tr>
   <tr>
+    <td>HP</td>
+    <td><code>03f0</code></td>
+  </tr>
+  <tr>
     <td>HTC</td>
     <td><code>0bb4</code></td>
   </tr>
diff --git a/docs/html/tools/help/am-allocation.jd b/docs/html/tools/help/am-allocation.jd
new file mode 100644
index 0000000..20570c3
--- /dev/null
+++ b/docs/html/tools/help/am-allocation.jd
@@ -0,0 +1,220 @@
+page.title=Allocation Tracker
+parent.title=Android Monitor
+parent.link=android-monitor.html
+meta.tags="android, performance, profiling, tools, monitor"
+page.tags="android", "performance", "profiling", "tools", "monitor"
+page.metaDescription=Use the Memory Monitor to capture allocation data about your app. The Allocation Tracker displays each method responsible for an allocation, as well as the allocation size and number of instances.
+page.image=tools/help/thumbnails/am_alloctracker.png
+page.article=true
+
+@jd:body
+
+<div id="qv-wrapper">
+<div id="qv">
+  <h2>In this document</h2>
+<ol>
+      <li><a href="#display">Understanding the Allocation Tracker Display</a></li>
+      <li><a href="#alloc-snapshot">Taking and Displaying a Snapshot of Allocation Data</a></li>
+      <li><a href="#alloc-viewing">Viewing a Saved Allocation Tracking File</a></li>
+      <li><a href="#alloc-sorting">Sorting Allocation Data</a></li>
+      <li><a href="#alloc-source">Displaying Java Source</a></li>
+      <li><a href="#alloc-files">Working with Allocation Tracking Files</a></li>
+</ol>
+
+ <h2>See also</h2>
+  <ol>
+    <li><a href="{@docRoot}training/articles/memory.html">Managing Your App's Memory</a></li>
+    <li><a href="{@docRoot}guide/practices/verifying-apps-art.html#GC_Migration">Addressing Garbage Collection Issues</a></li>
+    <li><a href="{@docRoot}tools/debugging/debugging-memory.html">Investigating Your RAM Usage</a></li>
+  </ol>
+
+</div>
+</div>
+
+
+
+
+<p>Android Studio allows you to track memory allocation as it monitors memory use. Tracking memory
+  allocation allows you to monitor where objects are being allocated when you perform certain
+  actions. Knowing these allocations enables you to adjust the method calls related to those actions
+  to optimize app performance and memory use.</p>
+
+<p>The Allocation Tracker does the following:</p>
+<ul>
+<li>Shows when and where your code allocates object types, their size, allocating thread, and stack
+  traces.</li>
+<li>Helps recognize memory churn through recurring allocation/deallocation patterns.</li>
+<li>Helps you track down memory leaks when used in combination with the HPROF Viewer. For example,
+  if you see a bitmap object resident on the heap, you can find its allocation location with
+  Allocation Tracker.</li>
+</ul>
+
+
+<p>However, it takes time and experience to learn to interpret the output from this tool.</p>
+
+<h2 id="display">
+  Understanding the Allocation Tracker Display
+</h2>
+
+<p>
+  The Allocation Tracker looks similar to the following figure:
+</p>
+<img src="{@docRoot}images/tools/am-alloctracker.png" />
+<p>
+
+
+<p>The tool displays the following information: </p>
+
+<table>
+  <tr>
+    <th scope="col">Column</th>
+    <th scope="col">Description</th>
+  </tr>
+
+  <tr>
+    <td><strong>Method</strong></td>
+    <td>The Java method responsible for the allocation.</td>
+  </tr>
+  <tr>
+    <td><strong>Count</strong></td>
+    <td>Total number of instances allocated.</td>
+  </tr>
+  <tr>
+    <td><strong>Size</strong></td>
+    <td>The total amount of allocated memory in bytes.</td>
+  </tr>
+
+</table>
+
+<h2 id="alloc-snapshot">Taking and Displaying a Snapshot of Allocation Data</h2>
+
+<p>To examine allocation data:</p>
+<ol>
+  <li><a href="{@docRoot}tools/help/am-memory.html#displaying">Display a running app in the Memory
+    Monitor</a>.</li>
+<li>Click Start Allocation Tracking
+  <img src="{@docRoot}images/tools/am-ialloctracking.png"
+  style="vertical-align:sub;margin:0;height:17px" alt="Start Allocation Tracking icon" />. </li>
+<li>Click Start Allocation Tracking
+  <img src="{@docRoot}images/tools/am-ialloctracking.png"
+  style="vertical-align:sub;margin:0;height:17px" alt="Start Allocation Tracking icon" /> again to
+  deselect it and end the snapshot. </li>
+
+  <p>The Memory Monitor displays the period when it took the snapshot. In the following
+    figure, you can see the snapshot period, as shown on the left. By comparison, when you dump the
+    Java heap, the Memory Monitor displays just the point where the heap snapshot was taken, as
+    shown on the right.</p>
+    <img src="{@docRoot}images/tools/am-dumpalloc2.png" />
+
+<p>Android Studio creates the heap snapshot file with the
+  filename <code><em>package_yyyy.mm.dd_hh.mm.ss</em>.alloc</code> using the activity package (or
+  project) name, year, month, day,
+  hour, minute, and second of the capture, for example,
+  <code>com.android.calc_2015.11.17_14.58.48.alloc</code>.</p>
+
+  The Allocation Tracker appears.
+</p>
+
+<li>Optionally click the graphic icon <img src="{@docRoot}images/tools/am-igraphic.png"
+style="vertical-align:sub;margin:0;height:17px"
+  alt="graphic icon" /> to display a visual representation of the data.
+  </li>
+
+
+
+
+<li>Select the Group By menu option you want to display: </li>
+<ul>
+<li><strong>Group by Allocator</strong> </li>
+<li><strong>Group by Method</strong></li>
+</ul>
+
+</ol>
+
+
+<h2 id="alloc-viewing">Viewing a Saved Allocation Tracking File</h2>
+<p>After you capture allocation data, Android Studio automatically stores it so
+you can view it again.</p>
+<p>To view an allocation tracking file in the Allocation Tracker:</p>
+
+
+<ol>
+<li>Click
+<img src="{@docRoot}images/tools/am-icaptures.png"
+style="vertical-align:sub;margin:0;height:17px"
+  alt="Captures icon" /> in the main window.</li>
+
+<p>Or select <strong>View</strong> > <strong>Tools Windows</strong> >
+<strong>Captures</strong>.</p>
+<p>The <em>Captures</em> window appears.</p>
+<li>Open the <strong>Allocation Tracking</strong> folder.</li>
+<li>Double-click the file to view it.</li>
+</ol>
+
+<h2 id="alloc-sorting">Sorting Allocation Data</h2>
+
+<p>To sort allocation data:</p>
+<ul>
+<li>In the Allocation Tracker, click a column heading to sort the table by ascending or
+  descending order. </li>
+</ul>
+
+
+<h2 id="alloc-source">Displaying Java Source</h2>
+<p>For some items displayed in the Allocation Tracker, you can view the Java source.</p>
+<p>To display Java source:</p>
+<ul>
+<li>In the Allocation Tracker, right-click a method and then select <strong>Jump to Source</strong>.
+</li>
+<li>In the Allocation Tracker, select a method and then click Jump to Source
+  <img src="{@docRoot}images/tools/am-ijumptosource.png"
+  style="vertical-align:sub;margin:0;height:17px" alt="Jump to Source icon" />. </li>
+</ul>
+
+<p>The source code appears in the Code Editor.</p>
+
+
+<h2 id="alloc-files">Working with Allocation Tracking Files</h2>
+<p>You can rename, locate, and delete an allocation tracking file from within
+Android Studio.</p>
+
+<h3 id="alloc-renaming">Renaming an allocation tracking file</h3>
+
+<p>If you rename a file from within Android Studio, it continues to appear in the <em>Captures</em>
+  window.</p>
+<p>To rename an allocation tracking file:</p>
+<ol>
+<li>In the <em>Captures</em> window, right-click the file and select <strong>Rename</strong>.</li>
+<li>In the <em>Rename</em> dialog, specify the name of the file and click <strong>OK</strong>.</li>
+</ol>
+
+
+<h3 id="alloc-locating">Locating an allocation tracking file</h3>
+<p>You can quickly discover where Android Studio stored allocation tracking files on disk.</p>
+
+
+<p>To locate an allocation tracking file from Android Studio: </p>
+<ul>
+<li>In the <em>Captures</em> window, right-click allocation file and select
+  <strong>Show</strong> or <strong>Reveal</strong>.</li>
+
+<p>Android Studio opens an operating system file browser displaying the location where the file
+  resides.</p>
+</ul>
+
+<p class="note"><strong>Note:</strong> If you move an allocation tracking file, Android Studio
+  no longer displays it in the <em>Captures</em> window. To display the file, use
+  <strong>File</strong>
+  &gt; <strong>Open</strong>. Also, rename the file from the <em>Captures</em>
+  window and not in the operating system file browser. </p>
+
+<h3 id="alloc-deleting">Deleting an allocation tracking file</h3>
+
+
+<p>To delete an allocation tracking file: </p>
+<ul>
+<li>In the <em>Captures</em> window, right-click an allocation tracking file and select
+  <strong>Delete</strong>.</li>
+
+<p>Android Studio deletes the file from the <em>Captures</em> dialog and from disk. </p>
+</ul>
diff --git a/docs/html/tools/help/am-basics.jd b/docs/html/tools/help/am-basics.jd
new file mode 100644
index 0000000..4bacecf
--- /dev/null
+++ b/docs/html/tools/help/am-basics.jd
@@ -0,0 +1,329 @@
+page.title=Android Monitor Basics
+parent.title=Android Monitor
+parent.link=index.html
+page.tags=monitor
+@jd:body
+
+<div id="qv-wrapper">
+<div id="qv">
+  <h2>In this document</h2>
+<ol>
+  <li><a href="#byb">Prerequisites and Dependencies</a></li>
+  <li><a href="#displaying">Displaying Android Monitor</a></li>
+  <li><a href="#profiling">Profiling a Running App in Android Monitor</a></li>
+  <li><a href="#switching">Switching between Devices and Apps</a></li>
+  <li><a href="#rearranging">Rearranging Android Monitor Windows</a></li>
+  <li><a href="#terminating">Terminating an App</a></li>
+  <li><a href="#removing">Removing an App from a Device</a></li>
+  <li><a href="#other">Using Other Main Window Features</a></li>
+</ol>
+
+
+
+
+
+</div>
+</div>
+
+<p>
+  Android Monitor has a main window that contains the logcat, Memory, CPU, GPU, and Network
+  Monitors. From this window, you can select a device and app process to work with, terminate an
+  app, collect <code>dumpsys</code> system information, and create screenshots and videos of the
+  running app.
+</p>
+
+
+<h2 id="byb">
+   Prerequisites and Dependencies
+</h2>
+
+<p>
+   Before you start using Android Monitor, you need to set up your environment, as well as the
+   hardware device or emulator. All of the monitors require the following:
+</p>
+    <ul>
+      <li>If you want to run your app on a hardware device (as opposed to the emulator), connect it
+        to the USB port. Make sure your development computer
+        <a href="{@docRoot}tools/device.html#setting-up">detects your device</a>, which often
+        happens automatically when you connect it.
+  </li>
+      <li>Enable ADB integration by selecting <strong>Tools</strong> &gt; <strong>Android</strong>
+        &gt; <strong>Enable ADB Integration</strong>. <strong>Enable ADB Integration</strong>
+        should have a check mark next to it in the menu to indicate it's enabled.
+      </li>
+  <li>
+    <a href="{@docRoot}tools/help/monitor.html">Android Device Monitor</a> can’t be running.
+  </li>
+    </ul>
+
+  <p>
+   All but the logcat Monitor have these additional requirements:
+</p>
+<ul>
+  <li>
+    <a href="{@docRoot}tools/device.html#device-developer-options">Enable</a> <strong><a href=
+    "{@docRoot}tools/device.html#device-developer-options">USB debugging</a></strong> in
+    <strong>Developer Options</strong> on the device or emulator.
+  </li>
+
+  <li>In your app, set the <code>debuggable</code> property to <code>true</code> in the manifest or
+  <code>build.gradle</code> file (it’s initially set by default).
+  </li>
+</ul>
+
+
+<p>
+   The GPU Monitor has this requirement as well:
+</p>
+<ul>
+  <li>For Android 5.0 (API level 21) and Android 5.1 (API level 22), in <strong>Developer
+  Options</strong> on the device or emulator, set <strong>Profile GPU rendering</strong> to
+  <strong>In adb shell dumpsys gfxinfo</strong>.
+  </li>
+</ul>
+<p>
+   The Network Monitor and the Video Capture tool work with a hardware device
+   only, not the emulator.
+</p>
+
+
+
+<h2 id="displaying">
+  Displaying Android Monitor
+</h2>
+
+<p>
+  Android Monitor is integrated into the Android Studio main window:
+</p>
+
+<ul>
+  <li>To display Android Monitor, click <img src="{@docRoot}images/tools/am-icon.png"
+    style="vertical-align:sub;margin:0;height:17px" alt="Android Monitor icon" />,
+    which by default is at the bottom of the main window.
+  </li>
+
+  <li>To hide Android Monitor, click <img src="{@docRoot}images/tools/am-icon.png"
+    style="vertical-align:sub;margin:0;height:17px" alt="Android Monitor icon" /> again.
+  </li>
+  <li>Or select <strong>View</strong> > <strong>Tool Windows</strong> >
+  <strong>Android Monitor</strong>.</li>
+</ul>
+ <p class="note">
+      <strong>Note:</strong> If you don't see the sidebar buttons, you can
+      display them by selecting <strong>View</strong> >
+      <strong>Tool Buttons</strong>.
+    </p>
+<p>
+  Android Monitor looks like the following figure:
+</p>
+<img src="{@docRoot}images/tools/am-androidmon2.png" style="vertical-align:sub;margin:0" />
+
+<h2 id="profiling">
+  Profiling a Running App in Android Monitor
+</h2>
+
+<p>
+  After you've met the prerequisites and optionally connected a hardware device, you're ready
+  to profile an app in Android Monitor:
+</p>
+
+<ol>
+
+  <li>Open an app project and <a href=
+  "{@docRoot}tools/building/building-studio.html#RunningApp">run the app</a> on a device or
+  emulator.
+  </li>
+
+  <li>Display Android Monitor and click the tab for the monitor you want to view.
+  </li>
+  <li>Follow the instructions about using the monitor:
+  </li>
+    <ul>
+      <li><a href="{@docRoot}tools/help/am-logcat.html">logcat Monitor</a>
+      </li>
+
+      <li><a href="{@docRoot}tools/help/am-memory.html">Memory Monitor</a>
+      </li>
+
+      <li><a href="{@docRoot}tools/help/am-cpu.html">CPU Monitor</a>
+      </li>
+
+      <li><a href="{@docRoot}tools/help/am-gpu.html">GPU Monitor</a>
+      </li>
+
+      <li>
+        <a href="{@docRoot}tools/help/am-network.html">Network Monitor</a>
+      </li>
+    </ul>
+</ol>
+    <h2 id="switching">
+      Switching between Devices and Apps
+    </h2>
+
+    <p>
+      By default, Android Monitor displays data for your most recently run app. You can switch to
+      another device and app as needed. In addition to currently running apps, you can view
+      information about apps that are no longer running so you can continue to see any information
+      about them that you gathered previously.
+    </p>
+
+    <p>
+      At the top of the Android Monitor main window are two menus listing devices and processes. To
+      switch to another device, process, or both:
+    </p>
+
+    <ol>
+      <li>Select the device or emulator.
+      </li>
+
+    <p>
+      The Device menu lists the devices and emulators that are running or have run during your
+      current session. There are various status messages that can appear in the Device menu:
+    </p>
+
+    <ul>
+      <li>
+        <strong>DISCONNECTED</strong> - You closed an emulator or unplugged a device from the
+        computer.
+      </li>
+
+      <li>
+        <strong>UNAUTHORIZED</strong> - A device needs you to accept the incoming computer
+        connection. For example, if the connected device displays an <em>Allow USB Debugging</em>
+        dialog, click <strong>OK</strong> to allow the connection.
+      </li>
+
+      <li>
+        <strong>OFFLINE</strong> - Android Monitor can’t communicate with a device, even though it
+        has detected that device.
+      </li>
+    </ul>
+
+  <li>Select the process.
+  </li>
+  <p>
+  The Process menu lists the processes that are running or have run during your current session. If
+  a process is no longer running, the menu displays a status of <strong>DEAD</strong>.
+</p>
+</ol>
+
+
+
+
+<h2 id="rearranging">
+  Rearranging Android Monitor Windows
+</h2>
+
+<p>
+  You can rearrange the Android Monitor windows for optimal viewing during your
+  tests:
+</p>
+<ul>
+  <li>To move a monitor up or down, click Move Monitor Up
+  <img src="{@docRoot}images/tools/am-imoveup.png" style="vertical-align:sub;margin:0;height:17px"
+    alt="Move Monitor Up icon" /> or Move Monitor Down
+    <img src="{@docRoot}images/tools/am-imovedown.png" style="vertical-align:sub;margin:0;height:17px"
+    alt="Move Monitor Down icon" />.
+  </li>
+  <li>To minimize or maximize a monitor, click Minimize Monitor
+  <img src="{@docRoot}images/tools/am-iminimize.png" style="vertical-align:sub;margin:0;height:17px"
+    alt="Minimize Monitor icon" />
+    or Maximize Monitor
+    <img src="{@docRoot}images/tools/am-imaximize.png" style="vertical-align:sub;margin:0;height:17px"
+    alt="Maximize Monitor icon" />.
+  </li>
+</ul>
+
+<p>
+  To rearrange the <strong>logcat</strong> and <strong>Monitors</strong> tabs:
+</p>
+<ul>
+  <li>To reorder the logcat or monitor group, move the tabs back and forth.
+  </li>
+
+  <li>To move the logcat or monitor group to a standalone window, drag a tab
+  to a different location on the screen. Or, select
+  <img src="{@docRoot}images/tools/am-igear.png" style="vertical-align:sub;margin:0;height:17px"
+  alt="Gear menu icon" /> &gt; <strong>Floating Mode</strong>.
+  </li>
+
+
+  <li>To dock a standalone window, drag it to the Android Monitor
+  tab area.</li>
+
+
+  <li>To combine the logcat and monitor group displays together, drag a tab and
+  move it onto another monitor.
+  </li>
+
+  <li>To hide a tab, click the
+    <img src="{@docRoot}images/tools/am-ihide.png" style="vertical-align:sub;margin:0;height:17px"
+    alt="Hide icon" /> icon. To make it reappear, click Restore Monitors View
+    <img src="{@docRoot}images/tools/am-imaximize.png" style="vertical-align:sub;margin:0;height:17px"
+    alt="Restore Monitors View icon" />
+    or the Restore logcat View
+    <img src="{@docRoot}images/tools/am-imaxlogcat.png" style="vertical-align:sub;margin:0;height:17px"
+    alt="Restore logcat View icon" />
+    on the far right of the row of tabs.
+  </li>
+</ul>
+
+<h2 id="terminating">
+  Terminating an App
+</h2>
+
+<p>
+  To stop an app you’ve run from Android Studio:
+</p>
+
+<ol>
+  <li>
+    <a href="#switching">Select the device and the process</a> in the Android Monitor
+    menus, if needed.
+  </li>
+
+  <li>Click Terminate Application <img src="{@docRoot}images/tools/am-iterminate.png"
+    style="vertical-align:sub;margin:0;height:17px" alt="Terminate App icon" />.
+  </li>
+
+
+<p>
+  The process status changes to <strong>DEAD</strong> in the Processes menu. The emulator or device
+  continues to run, but the app closes. Any running monitors in Android Monitor stop.
+</p>
+</ol>
+
+<h2 id="removing">
+  Removing an App from a Device
+</h2>
+
+<p>
+  To remove an app from a device you use for development, use the normal uninstall procedure on the
+  device.
+</p>
+
+<p>
+  If you run a new version of an app from Android Studio that’s been already installed on a
+  hardware device, the device displays an <em>Application Installation Failed</em> dialog. Click
+  <strong>OK</strong> to install the new version of the app.
+</p>
+
+<h2 id="other">
+  Using Other Main Window Features
+</h2>
+<p>
+  From the Android Monitor main window, you can also do the following:
+</p>
+
+<ul>
+  <li>
+    <a href="{@docRoot}tools/help/am-sysinfo.html">Examine <code>dumpsys</code> system information</a>.
+  </li>
+  <li>
+    <a href="{@docRoot}tools/help/am-screenshot.html">Take a screen capture of the device</a>.
+  </li>
+  <li>
+    <a href="{@docRoot}tools/help/am-video.html">Record a video from the screen</a>.
+  </li>
+</ul>
+
diff --git a/docs/html/tools/help/am-cpu.jd b/docs/html/tools/help/am-cpu.jd
index 62b3590..420d6f8 100644
--- a/docs/html/tools/help/am-cpu.jd
+++ b/docs/html/tools/help/am-cpu.jd
@@ -1,7 +1,12 @@
 page.title=CPU Monitor
 parent.title=Android Monitor
 parent.link=android-monitor.html
-page.tags=monitor
+meta.tags="android, performance, profiling, tools, monitor"
+page.tags="android", "performance", "profiling", "tools", "monitor"
+page.metaDescription=Use the CPU Monitor to display CPU usage in real time and the percentage of total CPU time (including all cores) used in user and kernel mode.
+page.image=tools/help/thumbnails/am-cpumon.png
+page.article=true
+
 @jd:body
 
 <div id="qv-wrapper">
@@ -9,63 +14,9 @@
   <h2>In this document</h2>
 <ol>
   <li><a href="#running">Displaying a Running App in the CPU Monitor</a></li>
-  <li><a href="#trace">Performing a Method Trace in the CPU Monitor</a></li>
-  <li><a href="#viewtrace">Viewing a Saved Method Trace</a></li>
-  <li><a href="#sorttrace">Sorting Method Trace Data</a></li>
-  <li><a href="#renametrace">Renaming a Method Trace File</a></li>
-  <li><a href="#locatetrace">Locating a Method Trace File on Disk</a></li>
-  <li><a href="#deletetrace">Deleting a Method Trace File</a></li>
+  <li><a href="#snapshot">Recording Call Stack Changes</a></li>
 </ol>
 
- <h2>See also</h2>
-  <ol>
-    <li>
-        <a href="{@docRoot}tools/help/android-monitor.html">Android Monitor</a>
-      </li>
-    <li><a href="{@docRoot}tools/help/am-logcat.html">logcat Monitor</a>
-      </li>
-
-      <li><a href="{@docRoot}tools/help/am-memory.html">Memory Monitor</a>
-      </li>
-
-      <li><a href="{@docRoot}tools/help/am-gpu.html">GPU Monitor</a>
-      </li>
-
-      <li>
-        <a href="{@docRoot}tools/help/am-network.html">Network Monitor</a>
-      </li>
-  </ol>
-
-
-<h2>
-  Dependencies and Prerequisites
-</h2>
-
-<ul>
-  <li>Make sure your development computer detects your hardware device, which often happens
-  automatically when you connect it to a USB port.
-  </li>
-
-  <li>
-    <a href="{@docRoot}tools/device.html#device-developer-options">Enable</a> <strong><a href=
-    "{@docRoot}tools/device.html#device-developer-options">USB debugging</a></strong> in
-    <strong>Developer Options</strong> on the device or emulator.
-  </li>
-
-  <li>In your app, set the <code>debuggable</code> property to <code>true</code> in the manifest or
-  <code>build.gradle</code> file (it’s initially set by default).
-  </li>
-
-<li>Enable ADB integration through <strong>Tools</strong> &gt; <strong>Android</strong> &gt;
-  <strong>Enable ADB Integration</strong>.
-  </li>
-
-  <li>
-    <a href="{@docRoot}tools/help/monitor.html">Android Device Monitor</a> can’t be running.
-  </li>
-
-</ul>
-
 </div>
 </div>
 
@@ -73,253 +24,66 @@
 <p>
   The CPU Monitor lets you easily monitor the central processing unit (CPU) usage of your app. It
   displays CPU usage in real time and displays the percentage of total CPU time (including all cores)
-  used by user and kernel mode. In user mode, the code must use system APIs to access hardware or
-  memory, and crashes are usually recoverable. In kernel mode, the code can directly access
-  hardware, including memory addresses; crashes halt the device.
+  used in user and kernel mode. In user mode, the code must use system APIs to access hardware or
+  memory, has access to virtual memory addresses only, and crashes are usually
+  recoverable. In kernel mode, the code can directly access
+  hardware, including physical memory addresses; crashes halt the device.
 </p>
 
+
 <h2 id="running">
   Displaying a Running App in the CPU Monitor
 </h2>
 
 <p>
-  Follow these steps:
+  To display an app running on a particular device or emulator in the CPU Monitor:
 </p>
 
 <ol>
-  <li>Optionally connect a hardware device.
+  <li>Meet the <a href=
+  "{@docRoot}tools/help/am-basics.html#byb">prerequisites and dependencies</a>.
   </li>
-
-  <li>
-    <a href="{@docRoot}tools/help/android-monitor.html#displaying">Display Android Monitor</a>.
+ <li>Open an app project.
   </li>
-
-  <li>Click the <strong>CPU</strong> tab.
-  </li>
-
-  <li>Open an app project and <a href=
-  "{@docRoot}tools/building/building-studio.html#RunningApp">run it</a> on a hardware device or
+  <li><a href=
+  "{@docRoot}tools/building/building-studio.html#RunningApp">Run the app</a> on a hardware device or
   emulator.
   </li>
+  <li>
+    <a href="{@docRoot}tools/help/am-basics.html#displaying">Display Android Monitor</a>.
+  </li>
+  <li>Click the <strong>Monitors</strong> tab and <a href=
+  "{@docRoot}tools/help/am-basics.html#rearranging">display the CPU Monitor</a>.
+  </li>
+
 
   <li>Enable the CPU Monitor by clicking Pause <img src="{@docRoot}images/tools/am-ipause.png"
-    style="vertical-align:sub;margin:0;height:17px" alt="Pause icon" /> to deselect
-  it.
+    style="vertical-align:sub;margin:0;height:17px" alt="Pause icon" /> to deselect it.
   </li>
 
+
 <p>
   The CPU Monitor starts to display any CPU usage.
   In the graph, the y-axis displays the percentage of CPU used. The x-axis records the time elapsed
   and starts with seconds, and then minutes and seconds, and so on.
 </p>
-<img src="{@docRoot}images/tools/am-cpumon.png" style="vertical-align:sub;margin:0;width:450px" />
+<img src="{@docRoot}images/tools/am-cpumon2.png" style="vertical-align:sub;margin:0" />
   <li>To stop the CPU Monitor, click Pause <img src="{@docRoot}images/tools/am-ipause.png"
     style="vertical-align:sub;margin:0;height:17px" alt="Pause icon" /> again to select
   it.
   </li>
 </ol>
 
-
-<h2 id="trace">
-  Performing a Method Trace in the CPU Monitor
+<h2 id="snapshot">
+  Recording Call Stack Changes
 </h2>
 
 <p>
-  Follow these steps:
-</p>
-
-<ol>
-  <li>
-    <a href="{@docRoot}tools/help/android-monitor.html#displaying">Display a running app in the CPU
-    Monitor</a>.
-  </li>
-
-  <li>Start a trace by clicking Start Method Tracing <img src="{@docRoot}images/tools/am-imethodtrace.png"
-    style="vertical-align:sub;margin:0;height:17px" alt="Start Method Tracing icon" /> to
-  select it.
-  </li>
-
-  <li>To stop the trace, click Stop Method Tracing <img src="{@docRoot}images/tools/am-imethodtrace.png"
-    style="vertical-align:sub;margin:0;height:17px" alt="Stop Method Tracing icon" /> to
-  deselect it.
-  </li>
-
-<p>
-  The method trace appears in the Code Editor area:
-</p>
-<img src="{@docRoot}images/tools/am-methodtrace.png" alt="Method Trace" />
-<p>
-  Android Studio creates the method trace file
-  with the filename <code>Trace_<em>yyyy.mm.dd_hh.mm.ss</em>.trace</code>
-  using the year, month, day, hour, minute, and second of the capture, for example,
-  <code>Trace_2015.11.17_14.58.48.trace</code>.
-</p>
-  <li>Specify display options:
-    <ul>
-      <li>Select a <strong>Thread</strong>.
-      </li>
-
-      <li>Select an <strong>x-axis</strong> time for the graphic and the method list:
-      </li>
-
-        <ul>
-          <li>
-            <strong>Wall Clock Time</strong> - Total CPU time elapsed between the method call and
-            return.
-          </li>
-
-          <li>
-            <strong>Thread Time</strong> - Total time during which the JRE scheduled the
-            thread during call processing. It’s less than or equal to the Wall Clock Time: less if
-            the JRE interrupted the thread, and equal if it didn’t.
-            The thread might not run continuously; when it’s not executing, that time is excluded.
-            If threads are interrupted often and it’s not by design, the interruptions affect app
-            performance. However, an example of a by-design use is synchronous operations that take
-            a long time, such as file transfers and reads from disk, where the method could be the
-            asynchronous wrapper for the synchronous reader.
-          </li>
-       </ul>
-
-        <li>
-          Optionally select <strong>Color by inclusive time</strong>.
-        </li>
-        </ul>
-
-        <p>
-          The display shows the following information:
-        </p>
-<table>
-  <tr>
-    <th scope="col">Field</th>
-    <th scope="col">Description</th>
-  </tr>
-
-  <tr>
-    <td><strong>Name</strong></td>
-    <td>The name of the method.</td>
-  </tr>
-
-  <tr>
-    <td><strong>Invocation Count</strong></td>
-    <td>How many times the method was called.</td>
-  </tr>
-
-  <tr>
-    <td><strong>Inclusive Time (microseconds)</strong></td>
-    <td>Time spent in the method and all of its children, either wall clock or thread time,
-          depending on your selection in the <strong>x-axis</strong> menu.</td>
-  </tr>
-
-  <tr>
-    <td><strong>Exclusive Time (microseconds)</strong></td>
-    <td>Time spent just in the method (excluding time spent in its children), either wall clock
-          or thread time, depending on your selection in the <strong>x-axis</strong> menu.</td>
-  </tr>
-</table>
-<p class="note"><strong>Note:</strong> Running the method trace significantly affects CPU timings.
-  Use the method trace to understand the flow of the program, but not for performance timings.</p>
-        <p>
-          The graphic represents the wall clock or thread time for each method. Hover the cursor
-          over the display to receive information about the method. This information also appears
-          in the table.
-        </p>
-</ol>
-        <h2 id="viewtrace">
-          Viewing a Saved Method Trace
-        </h2>
-
-        <p>
-          After you do a method trace, Android Studio automatically stores it so you can view it
-          again. To examine the trace, follow these steps:
-        </p>
-
-        <ol>
-          <li>Click <strong>Captures</strong> in the main window.
-          </li>
-
-        <p>
-          The <em>Captures</em> window appears.
-        </p>
-
-      <li>Open the <strong>Methods Tracing</strong> folder.
-      </li>
-
-      <li>Double-click the file to view it.
-      </li>
-</ol>
-
-<h2 id="sorttrace">
-  Sorting Method Trace Data
-</h2>
-
-<p>
-  You can sort the data by method name, count, inclusive time, and exclusive time. Follow this step:
-</p>
-
-
-<ul>
-  <li>Click a column heading to sort the table by ascending or descending order.
-  </li>
-</ul>
-
-<h2 id="renametrace">
-  Renaming a Method Trace File
-</h2>
-
-<p>
-  Rename a method trace file from within Android Studio so it
-  continues to appear in the <em>Captures</em> window. Follow these steps:
-</p>
-
-<ol>
-  <li>In the <em>Captures</em> window, right-click the file and select <strong>Rename</strong>.
-  </li>
-
-  <li>In the dialog, specify the name of the file and click <strong>OK</strong>.
-  </li>
-</ol>
-
-<h2 id="locatetrace">
-  Locating a Method Trace File on Disk
-</h2>
-
-<p>
-  You can quickly discover where Android Studio stored method trace files on disk. Follow this step:
+  You can capture a record of the changes on the call stack during a particular
+  time period while the CPU Monitor is running. For more information, see
+  <a href="{@docRoot}tools/help/am-methodtrace.html">Method Trace</a>.
 </p>
 
 
 
-<ul>
-  <li>In the <em>Captures</em> window, right-click a method trace file and select <strong>Show in
-  files</strong>.
-  </li>
 
-<p>
-  Android Studio opens an operating system file browser displaying the location where the file
-  resides.
-</p>
-</ul>
-<p class="note">
-  <strong>Note:</strong> If you move a method trace file, Android Studio no longer displays the file
-  in the <em>Captures</em> window. To display it, use <strong>File</strong> &gt;
-  <strong>Open</strong>. Also, rename a file from the <em>Captures</em>
-  window and not in the operating system file browser.
-</p>
-
-<h2 id="deletetrace">
-  Deleting a Method Trace File
-</h2>
-
-<p>
-  Follow this step in Android Studio:
-</p>
-
-<ul>
-  <li>In the <em>Captures</em> window, right-click a method trace file and select
-  <strong>Delete</strong>.
-  </li>
-</ul>
-
-<p>
-  Android Studio deletes the file from the <em>Captures</em> dialog and from disk.
-</p>
\ No newline at end of file
diff --git a/docs/html/tools/help/am-gpu.jd b/docs/html/tools/help/am-gpu.jd
index a244b22..fb140ad 100644
--- a/docs/html/tools/help/am-gpu.jd
+++ b/docs/html/tools/help/am-gpu.jd
@@ -1,7 +1,12 @@
 page.title=GPU Monitor
 parent.title=Android Monitor
 parent.link=android-monitor.html
-page.tags=monitor
+meta.tags="android, performance, profiling, tools, monitor"
+page.tags="android", "performance", "profiling", "tools", "monitor"
+page.metaDescription=Use the GPU Monitor for a visual representation of how much time it takes to render the frames of a UI window. Use this information to optimize the code that displays graphics and conserve memory.
+page.image=tools/help/thumbnails/am-gpumon.png
+page.article=true
+
 @jd:body
 
 <div id="qv-wrapper">
@@ -11,59 +16,6 @@
   <li><a href="#running">Displaying a Running App in the GPU Monitor</a></li>
 </ol>
 
- <h2>See also</h2>
-  <ol>
-    <li>
-        <a href="{@docRoot}tools/help/android-monitor.html">Android Monitor</a>
-      </li>
-    <li><a href="{@docRoot}tools/help/am-logcat.html">logcat Monitor</a>
-      </li>
-
-      <li><a href="{@docRoot}tools/help/am-memory.html">Memory Monitor</a>
-      </li>
-
-      <li><a href="{@docRoot}tools/help/am-cpu.html">CPU Monitor</a>
-      </li>
-
-      <li>
-        <a href="{@docRoot}tools/help/am-network.html">Network Monitor</a>
-      </li>
-  </ol>
-
-<h2>
-  Dependencies and Prerequisites
-</h2>
-
-<ul>
-  <li>Make sure your development computer detects your hardware device, which often happens
-  automatically when you connect it to a USB port.
-  </li>
-
-  <li>
-    <a href="{@docRoot}tools/device.html#device-developer-options">Enable</a> <strong><a href=
-    "{@docRoot}tools/device.html#device-developer-options">USB debugging</a></strong> in
-    <strong>Developer Options</strong> on the device or emulator.
-  </li>
-
-  <li>For Android 5.0 (API level 21) and Android 5.1 (API level 22), in <strong>Developer
-  Options</strong> on the device or emulator, set <strong>Profile GPU rendering</strong> to
-  <strong>In adb shell dumpsys gfxinfo</strong>.
-  </li>
-
-  <li>In your app, set the <code>debuggable</code> property to <code>true</code> in the manifest or
-  <code>build.gradle</code> file (it’s initially set by default).
-  </li>
-
-
-  <li>Enable ADB integration through <strong>Tools</strong> &gt; <strong>Android</strong> &gt;
-  <strong>Enable ADB Integration</strong>.
-  </li>
-
-   <li>
-    <a href="{@docRoot}tools/help/monitor.html">Android Device Monitor</a> can’t be running.
-  </li>
-</ul>
-
 </div>
 </div>
 
@@ -96,33 +48,34 @@
 </h2>
 
 <p>
-  Follow these steps:
+  To display an app running on a particular device or emulator in the GPU Monitor:
 </p>
 
 <ol>
-  <li>Optionally connect a hardware device.
+  <li>Meet the <a href=
+  "{@docRoot}tools/help/am-basics.html#byb">prerequisites and dependencies</a>.
   </li>
-
-  <li>
-    <a href="{@docRoot}tools/help/android-monitor.html#displaying">Display Android Monitor</a>.
+ <li>Open an app project.
   </li>
-
-  <li>Click the <strong>GPU</strong> tab.
-  </li>
-
-  <li>Open an app project and <a href=
-  "{@docRoot}tools/building/building-studio.html#RunningApp">run it</a> on a hardware device or
+  <li><a href=
+  "{@docRoot}tools/building/building-studio.html#RunningApp">Run the app</a> on a hardware device or
   emulator.
   </li>
+  <li>
+    <a href="{@docRoot}tools/help/am-basics.html#displaying">Display Android Monitor</a>.
+  </li>
+  <li>Click the <strong>Monitors</strong> tab and <a href=
+  "{@docRoot}tools/help/am-basics.html#rearranging">display the GPU Monitor</a>.
+  </li>
 
-  <li>Enable the GPU Monitor by clicking Pause <img src="{@docRoot}images/tools/am-ipause.png" style="vertical-align:sub;margin:0;height:17px" alt="Pause icon" /> to deselect
-  it.
+  <li>Enable the GPU Monitor by clicking Pause <img src="{@docRoot}images/tools/am-ipause.png"
+    style="vertical-align:sub;margin:0;height:17px" alt="Pause icon" /> to deselect it.
   </li>
 
   <p>
   Any GPU usage begins to appear in the GPU Monitor:
 </p>
-  <img src="{@docRoot}images/tools/am-gpumon.png" style="vertical-align:sub;margin:0;width:450px" />
+  <img src="{@docRoot}images/tools/am-gpumon2.png" style="vertical-align:sub;margin:0" />
 
 <p>
   The y-axis is the amount of time it takes the GPU to execute, process, prepare, and draw frames,
diff --git a/docs/html/tools/help/am-hprof.jd b/docs/html/tools/help/am-hprof.jd
new file mode 100644
index 0000000..1eef6ab
--- /dev/null
+++ b/docs/html/tools/help/am-hprof.jd
@@ -0,0 +1,355 @@
+page.title=HPROF Viewer and Analyzer
+parent.title=Android Monitor
+parent.link=android-monitor.html
+meta.tags="android, performance, profiling, tools, monitor"
+page.tags="android", "performance", "profiling", "tools", "monitor"
+page.metaDescription=Use the Memory Monitor to dump the Java heap to an HPROF file. The HPROF Viewer displays classes, instances of each class, and a reference tree to help you track memory usage and find memory leaks.
+page.image=tools/help/thumbnails/am_hprofviewer.png
+page.article=true
+
+@jd:body
+
+<div id="qv-wrapper">
+<div id="qv">
+  <h2>In this document</h2>
+<ol>
+      <li><a href="#why">Why Look at the Java Heap?</a></li>
+      <li><a href="#display">Understanding the HPROF Viewer Display</a></li>
+      <li><a href="#hprof-snapshot">Taking a Snapshot of the Java Heap</a></li>
+      <li><a href="#hprof-viewing">Viewing a Saved HPROF File</a></li>
+      <li><a href="#hprof-diving">Diving into Heap Dump Data in the HPROF Viewer</a></li>
+      <li><a href="#hprof-analyzing">Analyzing Heap Dump Data in the HPROF Analyzer</a></li>
+      <li><a href="#hprof-sorting">Sorting Heap Dump Data</a></li>
+      <li><a href="#hprof-source">Displaying Java Source</a></li>
+      <li><a href="#hprof-files">Working with HPROF Files</a></li>
+
+</ol>
+
+ <h2>See also</h2>
+  <ol>
+    <li><a href="{@docRoot}training/articles/memory.html">Managing Your App's Memory</a></li>
+    <li><a href="{@docRoot}guide/practices/verifying-apps-art.html#GC_Migration">Addressing Garbage Collection Issues</a></li>
+    <li><a href="{@docRoot}tools/debugging/debugging-memory.html">Investigating Your RAM Usage</a></li>
+  </ol>
+
+</div>
+</div>
+
+
+<p>
+  When you're monitoring memory usage in the Memory Monitor you can, at the same time, dump a
+  snapshot of the Java heap to an Android-specific Heap/CPU Profiling (HPROF) file. The HPROF Viewer
+  displays classes, instances of each class, and a reference tree to help you track memory usage
+  and find memory leaks. HPROF is a binary heap dump format originally supported by J2SE.
+</p>
+<h2 id="why">
+  Why Look at the Java Heap?
+</h2>
+<p>The Java heap display does the following:</p>
+
+<ul>
+  <li>Shows snapshots of a number of objects allocated by type.
+  </li>
+
+  <li>Samples data every time a garbage collection event occurs naturally or is triggered by you.
+  </li>
+
+  <li>Helps identify which object types might be involved in memory leaks.
+  </li>
+</ul>
+
+<p>
+  However, you have to look for changes over time yourself by tracking what's happening in the
+  graph.
+</p>
+
+<p>
+  The HPROF Analyzer finds the following potential issues:
+</p>
+
+<ul>
+  <li>All destroyed activity instances that are reachable from garbage collection roots.
+  </li>
+
+  <li>Where the target program has strings that repeat values.
+  </li>
+</ul>
+
+<p>
+  A dominator is at the top of a tree. If you remove it, you also remove the branches of the tree
+  it dominates, so it’s a potential way to free memory.
+</p>
+
+<h2 id="display">
+  Understanding the HPROF Viewer Display
+</h2>
+
+<p>
+  The HPROF Viewer looks similar to the following figure:
+</p>
+<img src="{@docRoot}images/tools/am-hprofviewer.png" />
+<p>
+  The tool displays the following information:
+</p>
+
+<table>
+  <tr>
+    <th scope="col">Column</th>
+    <th scope="col">Description</th>
+  </tr>
+
+  <tr>
+    <td><strong>Class Name</strong></td>
+    <td>The Java class responsible for the memory.</td>
+  </tr>
+
+  <tr>
+    <td><strong>Total Count</strong></td>
+    <td>Total number of instances outstanding.</td>
+  </tr>
+  <tr>
+    <td><strong>Heap Count</strong></td>
+    <td>Number of instances in the selected heap.</td>
+  </tr>
+  <tr>
+    <td><strong>Sizeof</strong></td>
+    <td>Size of the instances (currently, 0 if the size is variable).</td>
+  </tr>
+  <tr>
+    <td><strong>Shallow Size</strong></td>
+    <td>Total size of all instances in this heap.</td>
+  </tr>
+  <tr>
+    <td><strong>Retained Size</strong></td>
+    <td>Size of memory that all instances of this class is dominating.</td>
+  </tr>
+  <tr>
+    <td><strong>Instance</strong></td>
+    <td>A specific instance of the class.</td>
+  </tr>
+  <tr>
+    <td><strong>Reference Tree</strong></td>
+    <td>References that point to the selected instance, as well as references pointing to the
+      references.</td>
+  </tr>
+  <tr>
+    <td><strong>Depth</strong></td>
+    <td>The shortest number of hops from any GC root to the selected instance.</td>
+  </tr>
+  <tr>
+    <td><strong>Shallow Size</strong></td>
+    <td>Size of this instance.</td>
+  </tr>
+  <tr>
+    <td><strong>Dominating Size</strong></td>
+    <td>Size of memory that this instance is dominating.</td>
+  </tr>
+</table>
+
+<p>If you click <strong>Capture Analysis</strong>, the HPROF Analyzer appears: </p>
+<img src="{@docRoot}images/tools/am-hprofanalyzer.png" />
+<p>You can detect leaked activities and find duplicate strings with the HPROF Analyzer.</p>
+
+<h2 id="hprof-snapshot">
+  Taking and Displaying a Snapshot of the Java Heap
+</h2>
+
+<p>
+  To examine a snapshot of the Java heap:
+</p>
+
+<ol>
+  <li><a href="{@docRoot}tools/help/am-memory.html#displaying">Display a running app in the Memory
+    Monitor</a>.</li>
+  <li>Click Dump Java Heap
+    <img src="{@docRoot}images/tools/am-idump.png"
+    style="vertical-align:sub;margin:0;height:17px" alt="Dump Java Heap icon" />.
+  </li>
+
+
+<p>
+  When the icon on the Memory Monitor display changes from
+  <img src="{@docRoot}images/tools/am-idumpstart.png"
+  style="vertical-align:sub;margin:0;height:17px" alt="Dump Java Heap Start icon" /> to
+  <img src="{@docRoot}images/tools/am-idumpend.png" style="vertical-align:sub;margin:0;height:17px"
+  alt="Dump Java Heap End icon" />, the file is ready. Android Studio creates the heap snapshot
+  file with the
+  filename <code><em>package_yyyy.mm.dd_hh.mm.ss</em>.hprof</code> using
+  the activity package (or project) name, year, month, day, hour, minute, and second of the
+  capture, for example,
+  <code>com.android.calc_2015.11.17_14.58.48.hprof</code>.
+</p>
+<p>
+  The HPROF Viewer appears.
+</p>
+</ol>
+
+<h2 id="hprof-viewing">Viewing a Saved HPROF File</h2>
+<p>After you do a heap dump, Android Studio automatically stores it so you can view it again.
+ </p>
+ <p>To view an HPROF file in the HPROF Viewer:</p>
+
+<ol>
+<li>Click
+<img src="{@docRoot}images/tools/am-icaptures.png"
+style="vertical-align:sub;margin:0;height:17px"
+  alt="Captures icon" /> in the main window.</li>
+<p>Or select <strong>View</strong> > <strong>Tools Windows</strong> >
+<strong>Captures</strong>.</p>
+<p>The <em>Captures</em> window appears.</p>
+<li>Open the <strong>Heap Snapshot</strong> folder.</li>
+
+
+  <li>Double-click the file to view it in the HPROF Viewer.
+  </li>
+<p>
+  The HPROF Viewer appears.
+</p>
+
+
+  <li>Select the Heap menu option you want to display:
+    <ul>
+      <li>
+        <strong>App heap</strong> - The heap used by the current app.
+      </li>
+
+      <li><strong>Image heap</strong> - The memory mapped copy of the
+      current app on disk.
+      </li>
+
+
+  <li>
+    <strong>Zygote heap</strong> - The common set of libraries and runtime classes and data that
+    all apps are forked
+    from. The zygote space is created during device startup and is never allocated into.
+  </li>
+
+    </ul>
+
+      <li>Select the View menu option you want to display:
+        <ul>
+          <li>
+            <strong>Class List View</strong>
+          </li>
+
+              <li>
+                <strong>Package Tree View</strong>
+              </li>
+            </ul>
+    </ol>
+
+
+<h2 id="hprof-diving">
+  Diving into Heap Dump Data in the HPROF Viewer
+</h2>
+<p>The following steps outline the typical workflow:</p>
+<ol>
+<li>In the HPROF Viewer, select a class name. </li>
+<li>Select an instance of that class.</li>
+<li>Examine the reference tree.</li>
+<li>Right-click an item to <strong>Jump to source</strong> or <strong>Go to instance</strong>,
+  as needed.</li>
+</ol>
+
+
+
+<h2 id="hprof-analyzing">Analyzing Heap Dump Data in the HPROF Analyzer</h2>
+<p>You can detect leaked activities and find duplicate strings with the HPROF Analyzer.
+ </p>
+ <p>To use the HPROF Analyzer:</p>
+<ol>
+<li>In the <em>Captures</em> window, double-click an <code>.hprof</code> file to display it in the
+  HPROF Viewer. </li>
+<li>Click <strong>Capture Analysis</strong> on the right side of the main Android Studio window.</li>
+
+
+<p>The HPROF Analyzer appears to the right of the HPROF Analyzer, by default.</p>
+
+
+
+<li>In the <strong>Analyzer Tasks</strong> list, select the items you want to find.</li>
+<li>Click Perform Analysis <img src="{@docRoot}images/tools/am-iperformanalysis.png"
+  style="vertical-align:sub;margin:0;height:17px" alt="Perform Analysis icon" />.</li>
+<li>Examine the items in <strong>Analysis Results</strong>. Click an item to display it in the
+  HPROF Viewer.</li>
+</ol>
+
+
+
+<h2 id="hprof-sorting">Sorting Heap Dump Data</h2>
+<p>To sort heap dump data:</p>
+<ul>
+<li>In the HPROF Viewer, click a column heading to sort the table by ascending or descending
+  order. </li>
+</ul>
+
+
+<h2 id="hprof-source">Displaying Java Source</h2>
+<p>For some items displayed in the HPROF Viewer, you can go straight to its
+source code.
+</p>
+<p>To display Java source:</p>
+<ul>
+<li>In the HPROF Viewer, right-click a class, instance, or item in the reference tree, and then
+  select <strong>Jump to Source</strong>. </li>
+
+
+<p>The source code appears in the Code Editor.</p>
+</ul>
+
+<h2 id="hprof-files">Working with HPROF Files</h2>
+<p>You can rename, locate, and delete an HPROF file from within Android Studio.
+You can also convert it to standard HPROF format to use with other analysis
+tools.</p>
+
+<h3 id="hprof-renaming">Renaming an HPROF file</h3>
+
+<p>If you rename a file from within Android Studio, it continues to appear in
+the <em>Captures</em> window.</p>
+<p>To rename an HPROF file:</p>
+<ol>
+<li>In the <em>Captures</em> window, right-click the file and select <strong>Rename</strong>. </li>
+<li>In the dialog, specify the name of the file and click <strong>OK</strong>.</li>
+</ol>
+
+
+<h3 id="hprof-locating">Locating a heap dump file on disk</h3>
+<p>You can quickly discover where Android Studio stored HPROF files on disk.</p>
+
+
+<p>To locate an HPROF file on disk: </p>
+<ul>
+<li>In the <em>Captures</em> window, right-click a heap snapshot file and select
+  <strong>Show</strong> or <strong>Reveal</strong>.</li>
+
+<p>Android Studio opens an operating system file browser displaying the location where the file
+  resides.</p>
+</ul>
+<p class="note"><strong>Note:</strong> If you move an HPROF file, Android Studio no longer
+  displays it in the <em>Captures</em> window. To display it, use
+  <strong>File</strong> &gt; <strong>Open</strong>. Also, if you want to rename the file, do it
+  from the <em>Captures</em> window and not in the operating system file browser. </p>
+
+<h3 id="hprof-deleting">Deleting a heap dump file</h3>
+
+<p>To delete a heap dump file: </p>
+<ul>
+<li>In the <em>Captures</em> window, right-click a heap snapshot file and select
+  <strong>Delete</strong>.</li>
+
+<p>Android Studio deletes the file from the <em>Captures</em> dialog and from disk. </p>
+</ul>
+
+<h3 id="hprof-converting">Converting a heap dump file to standard HPROF format</h3>
+<p>You can convert an HPROF file to standard format so you can use it outside of Android Studio with
+  other analysis tools. </p>
+  <p>To convert an HPROF file:</p>
+<ol>
+<li>In the <em>Captures</em> window, right-click a heap snapshot file and select <strong>Export to
+  standard .hprof</strong>.</li>
+<li>In the <em>Convert Android Java Heap Dump</em> dialog, specify a filename and click
+  <strong>OK</strong>.</li>
+
+
+<p>Android Studio creates a binary HPROF file in the location you specified.</p>
+</ol>
diff --git a/docs/html/tools/help/am-logcat.jd b/docs/html/tools/help/am-logcat.jd
index 57da848..9e26bca 100644
--- a/docs/html/tools/help/am-logcat.jd
+++ b/docs/html/tools/help/am-logcat.jd
@@ -1,7 +1,12 @@
 page.title=logcat Monitor
 parent.title=Android Monitor
 parent.link=android-monitor.html
-page.tags=monitor
+meta.tags="android, performance, profiling, tools, monitor"
+page.tags="android", "performance", "profiling", "tools", "monitor"
+page.metaDescription=Use the logcat Monitor to view system and user-defined log messages. You can filter the messages to display just the items that interest you.
+page.image=tools/help/thumbnails/am-logcatmon2.png
+page.article=true
+
 @jd:body
 <div id="qv-wrapper">
   <div id="qv">
@@ -43,16 +48,13 @@
       </li>
 
       <li>
-        <a href="#printing">Printing the Log</a>
+        <a href="#printing">Printing and Writing to a File</a>
       </li>
 
       <li>
-        <a href="#clearing">Clearing the Log</a>
+        <a href="#clearing">Clearing and Restarting the Log</a>
       </li>
 
-      <li>
-        <a href="#restarting">Restarting the Log</a>
-      </li>
     </ol>
 
     <h2>
@@ -63,58 +65,31 @@
       <li>
         <a href="{@docRoot}tools/debugging/debugging-log.html">Reading and Writing Logs</a>
       </li>
-      <li>
-        <a href="{@docRoot}tools/help/android-monitor.html">Android Monitor</a>
-      </li>
-
-      <li><a href="{@docRoot}tools/help/am-memory.html">Memory Monitor</a>
-      </li>
-
-      <li><a href="{@docRoot}tools/help/am-cpu.html">CPU Monitor</a>
-      </li>
-
-      <li><a href="{@docRoot}tools/help/am-gpu.html">GPU Monitor</a>
-      </li>
-
-      <li>
-        <a href="{@docRoot}tools/help/am-network.html">Network Monitor</a>
-      </li>
     </ol>
 
-    <h2>
-      Dependencies and Prerequisites
-    </h2>
-
-    <ul>
-      <li>Enable ADB integration through <strong>Tools</strong> &gt; <strong>Android</strong> &gt;
-      <strong>Enable ADB Integration</strong>.
-      </li>
-  <li>
-    <a href="{@docRoot}tools/help/monitor.html">Android Device Monitor</a> can’t be running.
-  </li>
-    </ul>
   </div>
 </div>
 
 <p>
   The Android logging system provides a mechanism for collecting and viewing system debug output.
-  logcat Monitor displays messages that you added to your app by using the <a href=
-  "{@docRoot}reference/android/util/Log.html">Log</a> class, as well as system
-  messages, such as stack traces when the emulator throws an error or a garbage collection occurs.
-  The monitor displays messages in real time and also keeps a history so you can view older
+  The logcat Monitor displays system messages, such as when a garbage collection occurs, as well as
+  messages that you added to your app by using the <a href=
+  "{@docRoot}reference/android/util/Log.html">Log</a> class.
+  It displays messages in real time and also keeps a history so you can view older
   messages.
 </p>
 
 <p>
   To display just the information of interest, you can create filters, modify how much information
   is displayed in messages, set priority levels, display messages produced by app code
-  only, and search the log. By default, logcat Monitor shows the log output related to the running
-  application only.
+  only, and search the log. By default, the logcat Monitor shows the log output related to the
+  most recently run app only.
 </p>
 
 <p>
-  You can traverse the stack trace when your app throws an exception, as well as view the
-  associated code. This feature can help you fix exceptions and improve app operation.
+  When an app throws an exception, the logcat Monitor shows a message followed by the associated
+  stack trace containing links to
+  the code. This feature can help you fix errors and improve app operation.
 </p>
 
 <h2 id="format">
@@ -125,9 +100,9 @@
   Every Android log message has a tag and a priority associated with it. The tag of a system
   log message
   is a short string indicating the system component from which the message originates (for example,
-  <code>ActivityManager</code>). A user-defined tag can be any string that you find helpful, such
-  as the name of the current class (the recommended tag). You define it in a <code>Log</code>
-  method call, for example:
+  {@link android.app.ActivityManager}). A user-defined tag can be any string that you find helpful,
+  such as the name of the current class (the recommended tag). You define it in a
+  {@link android.util.Log} method call, for example:
 </p>
 
 <pre>
@@ -189,31 +164,38 @@
 </h2>
 
 <p>
-  Follow these steps:
+  To display the log messages for a particular app:
 </p>
 
 <ol>
-  <li>Optionally connect a hardware device.
+  <li>Meet the <a href=
+  "{@docRoot}tools/help/am-basics.html#byb">prerequisites and dependencies</a>.
   </li>
-
+ <li>Open an app project.
+  </li>
+  <li><a href=
+  "{@docRoot}tools/building/building-studio.html#RunningApp">Run the app</a> on a hardware device or
+  emulator.
+  </li>
   <li>
-    <a href="{@docRoot}tools/help/android-monitor.html#displaying">Display Android Monitor</a>.
+    <a href="{@docRoot}tools/help/am-basics.html#displaying">Display Android Monitor</a>.
   </li>
 
   <li>Click the <strong>logcat</strong> tab.
   </li>
 
-  <li>Open an app project and <a href=
-  "{@docRoot}tools/building/building-studio.html#RunningApp">run it</a> on a hardware device or
-  emulator.
-  </li>
+
 <p>
-  By default, the logcat Monitor displays messages for the app running on the device or emulator:
+  By default, the logcat Monitor displays just the log messages for your app running on the
+  device or emulator:
 </p>
-<img src="{@docRoot}images/tools/am-logcatmon.png" />
+<img src="{@docRoot}images/tools/am-logcatmon2.png" />
 <p>
   To change this default, see <a href="#filtering">Filtering logcat Messages</a>.
 </p>
+<li>Optionally <a href=
+  "{@docRoot}tools/help/am-basics.html#switching">select a different device, emulator, or process</a>.
+  </li>
 </ol>
 
 <h2 id="level">
@@ -221,17 +203,17 @@
 </h2>
 
 <p>
-  You can control how many messages appear in logcat Monitor by setting the log level. You can
+  You can control how many messages appear in the logcat Monitor by setting the log level. You can
   display all messages, or just the messages indicating the most severe conditions.
 </p>
 
 <p>
-  Remember that logcat Monitor continues to collect all messages regardless of the log level setting.
-  The setting just determines what logcat Monitor displays.
+  Remember that the logcat Monitor continues to collect all messages regardless of the log level setting.
+  The setting just determines what the logcat Monitor displays.
 </p>
 
 <p>
-  Follow this step:
+  To set the log level:
 </p>
 
 <ul>
@@ -259,7 +241,7 @@
       </li>
 
       <li>
-        <strong>Error</strong> - Show issues that have caused errors, as well as the message levels
+        <strong>Error</strong> - Show issues that have caused errors, as well as the message level
         lower in this list.
       </li>
 
@@ -275,7 +257,7 @@
     </h2>
 
     <p>
-      You can search the messages currently displayed in logcat Monitor. Follow these steps:
+      To search the messages currently displayed in the logcat Monitor:
     </p>
 
     <ol>
@@ -292,7 +274,7 @@
     </p>
   </li>
 
-  <li>Press <strong>Enter</strong> to store the sequence in the menu during this session.
+  <li>Press Enter to store the search string in the menu during this session.
   </li>
 
   <li>To repeat a search, choose it from the search menu. Select or deselect
@@ -310,12 +292,12 @@
 
     <p class="note">
       <strong>Note:</strong> The filter applies to your full logcat history, not just those messages
-      currently displayed in logcat Monitor. Make sure your other display options are set
+      currently displayed in the logcat Monitor. Make sure your other display options are set
       appropriately so you can see the filter output you want to examine.
     </p>
 
     <p>
-      To define and apply a filter, follow these steps:
+      To define and apply a filter:
     </p>
 
     <ol>
@@ -323,15 +305,18 @@
         <ul>
           <li>
             <strong>Show only selected application</strong> - Display the messages produced by the
-            app code only.
+            app code only (the default). The logcat Monitor filters the log messages using the PID
+            of the active app.
           </li>
 
           <li>
-            <strong>No Filters</strong> - Apply no filters (the default).
+            <strong>No Filters</strong> - Apply no filters. The logcat Monitor
+            displays all log messages from the device, regardless of which process you selected.
           </li>
 
           <li>
-            <strong>Edit Filter Configuration</strong> - Create or modify a custom filter.
+            <strong>Edit Filter Configuration</strong> - Create or modify a custom filter. For
+            example, you could create a filter to view log messages from two apps at the same time.
           </li>
         </ul>
 
@@ -386,7 +371,7 @@
             </ul>
 
             <li>
-              Click <strong>+</strong> to add it to the left pane.
+              Click <strong>+</strong> to add the filter definition to the left pane.
             </li>
 
             <p>
@@ -398,6 +383,14 @@
               <strong>Cancel</strong>, any filter additions or modifications are lost.
             </li>
             </ol>
+            <li>
+              Make sure you see the log messages you want to examine.
+            </li>
+             <p>
+              If you don't think you see the log messages you want, try selecting
+              <strong>No filters</strong> and <a href="#searching">searching</a> for particular
+              log messages.
+            </p>
             </ol>
 
             <h2 id="logheader">
@@ -405,7 +398,7 @@
             </h2>
 
             <p>
-              You can customize the header display to show just the information you’re interested
+              To customize the header display to show just the information you’re interested
               in:
             </p>
 
@@ -440,7 +433,9 @@
               in the Code Editor. If needed (and possible), the decompiler derives source code that
               you can view.
             </p>
-
+             <p>
+              To move up and down the stack trace, and view the associated code in the Code Editor:
+            </p>
             <ul>
               <li>Click Up the Stack Trace <img src="{@docRoot}images/tools/am-iupstack.png"
                 style="vertical-align:sub;margin:0;height:17px" alt="Up the Stack Trace icon" />
@@ -460,8 +455,11 @@
             </h2>
 
             <p>
-              Clicking a particular message stops the display of messages. You can quickly move to
-              the end of the log to see the real-time message flow.
+              Clicking a particular message stops the display of messages.
+            </p>
+            <p>
+              To quickly move to
+              the end of the log to see the real-time message flow:
             </p>
 
 <ul>
@@ -477,25 +475,48 @@
 </ul>
 
 <h2 id="printing">
-  Printing the Log
+  Printing and Writing to a File
 </h2>
 <p>
-  Follow these steps:
+  To preserve log information, you can send the log to a printer, write the log to a PDF file, or
+  copy and paste the log into a text file.
+</p>
+<p>
+  To print the log or write it to a PDF file:
 </p>
 <ol>
   <li>Click Print <img src="{@docRoot}images/tools/am-iprint.png"
     style="vertical-align:sub;margin:0;height:17px" alt="Print icon" />.
   </li>
   <li>
-    In the <em>Print</em> dialog, optionally change print parameters, and then click
+    In the Android Studio <em>Print</em> dialog, optionally change print parameters, and then click
     <strong>Print</strong>.
+  </li>
+  <li>
+    In the operating system <em>Print</em> dialog, optionally change print parameters, and then click
+    <strong>Print</strong>.
+  </li>
+  <p>
+  You can set the parameters to send the log to a printer or write it to a PDF file.
+</p>
+</ol>
+<p>
+  To copy the log to a text file:
+</p>
+<ol>
+  <li>In the logcat Monitor, select and then copy log text.
+  </li>
+  <p>Press Ctrl+A (⌘A) to select all.</p>
+  <li>
+    Open a text editor and paste the text into a file.
+  </li>
 </ol>
 
 <h2 id="clearing">
-  Clearing the Log
+  Clearing and Restarting the Log
 </h2>
 <p>
-  To clear (flush) the entire log, follow this step:
+  To clear (flush) the entire log:
 </p>
 <ul>
   <li>Click Clear logcat <img src="{@docRoot}images/tools/am-iclear.png"
@@ -504,14 +525,8 @@
 </ul>
 
 
-
-<h2 id="restarting">
-  Restarting the Log
-</h2>
-
 <p>
-  If there is a problem and the log is no longer progressing, you can restart the log. Follow this
-  step:
+  If there's a problem and the log is no longer progressing, you can restart the log:
 </p>
 
 <ul>
diff --git a/docs/html/tools/help/am-memory.jd b/docs/html/tools/help/am-memory.jd
index 24006cd..20c6934 100644
--- a/docs/html/tools/help/am-memory.jd
+++ b/docs/html/tools/help/am-memory.jd
@@ -1,7 +1,12 @@
 page.title=Memory Monitor
 parent.title=Android Monitor
 parent.link=android-monitor.html
-page.tags=monitor
+meta.tags="android, performance, profiling, tools, monitor"
+page.tags="android", "performance", "profiling", "tools", "monitor"
+page.metaDescription=Use the Memory Monitor to evaluate memory usage and find deallocated objects, locate memory leaks, and track the amount of memory the connected device is using.
+page.image=tools/help/thumbnails/am-memorymon.png
+page.article=true
+
 @jd:body
 
 <div id="qv-wrapper">
@@ -17,31 +22,7 @@
   </li>
   <li><a href="#displaying">Displaying a Running App in the Memory Monitor</a></li>
   <li><a href="#forcing">Forcing a Garbage Collection Event</a></li>
-  <li><a href="#dumping">Dumping and Analyzing the Java Heap</a>
-    <ol>
-      <li><a href="#hprof-snapshot">Taking and displaying a snapshot of the Java heap</a></li>
-      <li><a href="#hprof-diving">Diving into heap dump data in the HPROF Viewer</a></li>
-      <li><a href="#hprof-analyzing">Analyzing heap dump data in the HPROF Analyzer</a></li>
-      <li><a href="#hprof-sorting">Sorting heap dump data</a></li>
-      <li><a href="#hprof-source">Displaying Java source</a></li>
-      <li><a href="#hprof-viewing">Viewing a saved HPROF file</a></li>
-      <li><a href="#hprof-renaming">Renaming an HPROF file</a></li>
-      <li><a href="#hprof-locating">Locating a heap dump file on disk</a></li>
-      <li><a href="#hprof-deleting">Deleting a heap dump file</a></li>
-      <li><a href="#hprof-converting">Converting a heap dump file to standard HPROF format</a></li>
-    </ol>
-    </li>
-  <li><a href="#tracking">Tracking and Analyzing Memory Allocation</a>
-      <ol>
-      <li><a href="#alloc-snapshot">Taking and displaying a snapshot of allocation data</a></li>
-      <li><a href="#alloc-sorting">Sorting allocation data</a></li>
-      <li><a href="#alloc-source">Displaying Java source</a></li>
-      <li><a href="#alloc-viewing">Viewing a saved allocation tracking file</a></li>
-      <li><a href="#alloc-renaming">Renaming an allocation tracking file</a></li>
-      <li><a href="#alloc-locating">Locating an allocation tracking file</a></li>
-      <li><a href="#alloc-deleting">Deleting an allocation tracking file</a></li>
-    </ol>
-    </li>
+  <li><a href="#snapshot">Taking a Snapshot of the Java Heap and Memory Allocation</a></li>
 </ol>
 
  <h2>See also</h2>
@@ -49,53 +30,8 @@
     <li><a href="{@docRoot}training/articles/memory.html">Managing Your App's Memory</a></li>
     <li><a href="{@docRoot}guide/practices/verifying-apps-art.html#GC_Migration">Addressing Garbage Collection Issues</a></li>
     <li><a href="{@docRoot}tools/debugging/debugging-memory.html">Investigating Your RAM Usage</a></li>
-
-    <li>
-        <a href="{@docRoot}tools/help/android-monitor.html">Android Monitor</a>
-      </li>
-    <li><a href="{@docRoot}tools/help/am-logcat.html">logcat Monitor</a>
-      </li>
-
-      <li><a href="{@docRoot}tools/help/am-cpu.html">CPU Monitor</a>
-      </li>
-
-      <li><a href="{@docRoot}tools/help/am-gpu.html">GPU Monitor</a>
-      </li>
-
-      <li>
-        <a href="{@docRoot}tools/help/am-network.html">Network Monitor</a>
-      </li>
   </ol>
 
-
-<h2>
-  Dependencies and Prerequisites
-</h2>
-
-<ul>
-  <li>
-    Make sure your development computer detects your hardware device, which often happens
-  automatically when you connect it to a USB port.
-  </li>
-<li>
-    <a href="{@docRoot}tools/device.html#device-developer-options">Enable</a> <strong><a href=
-    "{@docRoot}tools/device.html#device-developer-options">USB debugging</a></strong> in
-    <strong>Developer Options</strong> on the device or emulator.
-  </li>
-
-  <li>In your app, set the <code>debuggable</code> property to <code>true</code> in the manifest or
-  <code>build.gradle</code> file (it’s initially set by default).
-  </li>
-
-  <li>Enable ADB integration through <strong>Tools</strong> &gt; <strong>Android</strong> &gt;
-  <strong>Enable ADB Integration</strong>.
-  </li>
-
-   <li>
-    <a href="{@docRoot}tools/help/monitor.html">Android Device Monitor</a> can’t be running.
-  </li>
-</ul>
-
 </div>
 </div>
 
@@ -107,7 +43,7 @@
 </p>
 
 <ul>
-  <li>Show a graph of available and allocated memory over time.
+  <li>Show a graph of available and allocated Java memory over time.
   </li>
 <li>Show garbage collection (GC) events
   over time.
@@ -227,10 +163,7 @@
 
 <p>
   One way to optimize memory usage is to analyze large arrays. For example, can you reduce the size
-  of individual elements in the array to save memory? Does a dominator object point to
-  an element in the array, preventing it from being garbage-collected? If the dominator object
-  directly points to an element in the array, the dominator is either the contiguous memory
-  representing the underlying data of the array, some part of the array, or the array itself.
+  of individual elements in the array to save memory?
 </p>
 
 <p>
@@ -347,25 +280,26 @@
 </h2>
 
 <p>
-  Follow these steps:
+  To display an app running on a particular device or emulator in the Memory Monitor:
 </p>
 
 <ol>
-  <li>Optionally connect a hardware device.
+  <li>Meet the <a href=
+  "{@docRoot}tools/help/am-basics.html#byb">prerequisites and dependencies</a>.
   </li>
-
+ <li>Open an app project.
+  </li>
+  <li><a href=
+  "{@docRoot}tools/building/building-studio.html#RunningApp">Run the app</a> on a hardware device or
+  emulator.
+  </li>
   <li>
-    <a href=
-    "{@docRoot}tools/help/android-monitor.html#displaying">Display Android Monitor</a>.
+    <a href="{@docRoot}tools/help/am-basics.html#displaying">Display Android Monitor</a>.
+  </li>
+  <li>Click the <strong>Monitors</strong> tab and <a href=
+  "{@docRoot}tools/help/am-basics.html#rearranging">display the Memory Monitor</a>.
   </li>
 
-  <li>Click the <strong>Memory</strong> tab.
-  </li>
-
-  <li>Open an app project and <a href=
-  "{@docRoot}tools/building/building-studio.html#RunningApp">run it</a> on a
-  hardware device or emulator.
-  </li>
 
   <li>Enable the Memory Monitor by clicking Pause <img src="{@docRoot}images/tools/am-ipause.png"
     style="vertical-align:sub;margin:0;height:17px" alt="Pause icon" /> to deselect it.
@@ -389,10 +323,10 @@
   <p>In the following figure, the VM initiated the first garbage collection event, while the
     developer forced the second.
 </p>
-<img src="{@docRoot}images/tools/am-gc.png" />
+<img src="{@docRoot}images/tools/am-gc2.png" />
 
   <li>Interact with your app and watch how it affects memory usage in the Memory Monitor. You can
-  identify garbage collection patterns for your app and determine whether they are healthy and what
+  identify garbage collection patterns for your app and determine whether they're healthy and what
   you expect.
   </li>
 
@@ -452,465 +386,20 @@
   </li>
 </ul>
 
-<h2 id="dumping">
-  Dumping and Analyzing the Java Heap
+<h2 id="snapshot">
+  Taking a Snapshot of the Java Heap and Memory Allocation
 </h2>
 
 <p>
-  When you're monitoring memory usage in Android Studio you can, at the same time, dump the Java
-  heap to a heap snapshot in an Android-specific HPROF binary format file. The HPROF Viewer
-  displays classes, instances of each class, and a reference tree to help you track memory usage
-  and find memory leaks. HPROF is a heap dump format originally supported by J2SE.
-</p>
-<p>The Java heap display does the following:</p>
-
-<ul>
-  <li>Shows snapshots of a number of objects allocated by type.
-  </li>
-
-  <li>Samples data every time a garbage collection event occurs naturally or is triggered by you.
-  </li>
-
-  <li>Helps identify which object types might be involved in memory leaks.
-  </li>
-</ul>
-
-<p>
-  However, you have to look for changes over time yourself by tracking what's happening in the
-  graph.
-</p>
-
-<p>
-  The HPROF Analyzer finds the following potential issues:
+  You can take snapshots while the Memory Monitor is running or paused:
 </p>
 
 <ul>
-  <li>All destroyed activity instances that are reachable from garbage collection roots.
+  <li>To take and display a snapshot of the Java heap, see <a href=
+  "{@docRoot}tools/help/am-hprof.html">HPROF Viewer and Analyzer</a>.
   </li>
-
-  <li>Where the target program has strings that repeat values.
+  <li>To take and display a snapshot of memory allocation, see <a href=
+  "{@docRoot}tools/help/am-allocation.html">Allocation Tracker</a>.
   </li>
 </ul>
 
-<p>
-  A dominator is at the top of a tree. If you remove it, you also remove the branches of the tree
-  it dominates, so it’s a potential way to free memory.
-</p>
-
-<h3 id="hprof-snapshot">
-  Taking and displaying a snapshot of the Java heap
-</h3>
-
-<p>
-  To see a snapshot of the Java heap, follow these steps:
-</p>
-
-<ol>
-  <li>While the Memory Monitor is running, click Dump Java Heap
-    <img src="{@docRoot}images/tools/am-idump.png"
-    style="vertical-align:sub;margin:0;height:17px" alt="Dump Java Heap icon" />.
-  </li>
-
-
-<p>
-  When the icon on the Memory Monitor display changes from
-  <img src="{@docRoot}images/tools/am-idumpstart.png"
-  style="vertical-align:sub;margin:0;height:17px" alt="Dump Java Heap Start icon" /> to
-  <img src="{@docRoot}images/tools/am-idumpend.png" style="vertical-align:sub;margin:0;height:17px"
-  alt="Dump Java Heap End icon" />, the file is ready. Android Studio creates the heap snapshot
-  file with the
-  filename <code>Snapshot_<em>yyyy.mm.dd_hh.mm.ss</em>.hprof</code> using
-  the year, month, day, hour, minute, and second of the capture, for example,
-  <code>Snapshot_2015.11.17_14.58.48.hprof</code>.
-</p>
-
-  <li>Click <strong>Captures</strong> in the main window.
-  </li>
-
-<p>
-  The <em>Captures</em> window appears.
-</p>
-
-  <li>Double-click the file to view it in the HPROF Viewer.
-  </li>
-
-<p>
-  The HPROF Viewer appears:
-</p>
-<img src="{@docRoot}images/tools/am-hprofviewer.png" />
-<p>
-  The tool displays the following information:
-</p>
-
-<table>
-  <tr>
-    <th scope="col">Column</th>
-    <th scope="col">Description</th>
-  </tr>
-
-  <tr>
-    <td><strong>Class Name</strong></td>
-    <td>The Java class responsible for the memory.</td>
-  </tr>
-
-  <tr>
-    <td><strong>Total Count</strong></td>
-    <td>Total number of instances outstanding.</td>
-  </tr>
-  <tr>
-    <td><strong>Heap Count</strong></td>
-    <td>Number of instances in the selected heap.</td>
-  </tr>
-  <tr>
-    <td><strong>Sizeof</strong></td>
-    <td>Size of the instances (currently, 0 if the size is variable).</td>
-  </tr>
-  <tr>
-    <td><strong>Shallow Size</strong></td>
-    <td>Total size of all instances in this heap.</td>
-  </tr>
-  <tr>
-    <td><strong>Retained Size</strong></td>
-    <td>Size of memory that all instances of this class is dominating.</td>
-  </tr>
-  <tr>
-    <td><strong>Instance</strong></td>
-    <td>A specific instance of the class.</td>
-  </tr>
-  <tr>
-    <td><strong>Reference Tree</strong></td>
-    <td>References that point to the selected instance, as well as references pointing to the
-      references.</td>
-  </tr>
-  <tr>
-    <td><strong>Depth</strong></td>
-    <td>The shortest number of hops from any GC root to the selected instance.</td>
-  </tr>
-  <tr>
-    <td><strong>Shallow Size</strong></td>
-    <td>Size of this instance.</td>
-  </tr>
-  <tr>
-    <td><strong>Dominating Size</strong></td>
-    <td>Size of memory that this instance is dominating.</td>
-  </tr>
-</table>
-
-  <li>Select the Heap menu option you want to display:
-    <ul>
-      <li>
-        <strong>App heap</strong> - The heap used by the current app.
-      </li>
-
-      <li><strong>Image heap</strong> - The memory mapped copy of the
-      current app on disk.
-      </li>
-
-
-  <li>
-    <strong>Zygote heap</strong> - The common set of libraries and runtime classes and data that
-    all apps are forked
-    from. The zygote space is created during device startup and is never allocated into.
-  </li>
-
-    </ul>
-
-      <li>Select the View menu option you want to display:
-        <ul>
-          <li>
-            <strong>Class List View</strong>
-          </li>
-
-              <li>
-                <strong>Package Tree View</strong>
-              </li>
-            </ul>
-    </ol>
-
-
-<h3 id="hprof-diving">
-  Diving into heap dump data in the HPROF Viewer
-</h3>
-<p>The following steps outline the typical workflow:</p>
-<ol>
-<li>In the HPROF viewer, select a class name. </li>
-<li>Select an instance of that class.</li>
-<li>Examine the reference tree.</li>
-<li>Right-click an item to <strong>Jump to source</strong> or <strong>Go to instance</strong>,
-  as needed.</li>
-</ol>
-
-
-
-<h3 id="hprof-analyzing">Analyzing heap dump data in the HPROF Analyzer</h3>
-<p>You can detect leaked activities and find duplicate strings with the HPROF Analyzer.
-  Follow these steps: </p>
-<ol>
-<li>In the <em>Captures</em> window, double-click an <code>.hprof</code> file to display it in the
-  HPROF Viewer. </li>
-<li>Click <strong>Capture Analysis</strong> on the right side of the main Android Studio window.</li>
-
-
-<p>The HPROF Analyzer appears to the right of the HPROF Analyzer, by default: </p>
-
-<img src="{@docRoot}images/tools/am-hprofanalyzer.png" />
-
-<li>In the <strong>Analyzer Tasks</strong> list, select the items you want to find.</li>
-<li>Click Perform Analysis <img src="{@docRoot}images/tools/am-iperformanalysis.png"
-  style="vertical-align:sub;margin:0;height:17px" alt="Perform Analysis icon" />.</li>
-<li>Examine the items in <strong>Analysis Results</strong>. Click an item to display it in the
-  HPROF Viewer.</li>
-</ol>
-
-
-
-<h3 id="hprof-sorting">Sorting heap dump data</h3>
-<p>Follow this step:</p>
-<ul>
-<li>In the HPROF Viewer, click a column heading to sort the table by ascending or descending
-  order. </li>
-</ul>
-
-
-<h3 id="hprof-source">Displaying Java source</h3>
-<p>For some items displayed in the HPROF Viewer, you can go straight to its source code.
-  Follow this step:</p>
-<ul>
-<li>In the HPROF Viewer, right-click a class, instance, or item in the reference tree, and then
-  select <strong>Jump to Source</strong>. </li>
-
-
-<p>The source code appears in the Code Editor.</p>
-</ul>
-
-<h3 id="hprof-viewing">Viewing a saved HPROF file</h3>
-<p>After you do a heap dump, Android Studio automatically stores it so you can view it again.
-  Follow these steps:</p>
-
-<ol>
-<li>Click <strong>Captures</strong> in the main window.</li>
-
-<p>The <em>Captures</em> window appears.</p>
-<li>Open the <strong>Heap Snapshot</strong> folder.</li>
-<li>Double-click the file to view it.</li>
-</ol>
-
-
-<h3 id="hprof-renaming">Renaming an HPROF file</h3>
-
-<p>If you rename a file from within Android Studio, it continues to appear in <em>Captures</em>
-  window. Follow these steps:</p>
-<ol>
-<li>In the <em>Captures</em> window, right-click the file and select <strong>Rename</strong>. </li>
-<li>In the dialog, specify the name of the file and click <strong>OK</strong>.</li>
-</ol>
-
-
-<h3 id="hprof-locating">Locating a heap dump file on disk</h3>
-<p>You can quickly discover where Android Studio stored HPROF files on disk.</p>
-
-
-<p>Follow this step in Android Studio: </p>
-<ul>
-<li>In the <em>Captures</em> window, right-click a heap snapshot file and select
-  <strong>Show in files</strong>.</li>
-
-<p>Android Studio opens an operating system file browser displaying the location where the file
-  resides.</p>
-</ul>
-<p class="note"><strong>Note:</strong> If you move an HPROF file, Android Studio no longer
-  displays it in the <em>Captures</em> window. To display it, use
-  <strong>File</strong> &gt; <strong>Open</strong>. Also, if you want to rename the file, do it
-  from the <em>Captures</em> window and not in the operating system file browser. </p>
-
-<h3 id="hprof-deleting">Deleting a heap dump file</h3>
-
-<p>To delete a heap dump file, follow this step: </p>
-<ul>
-<li>In the <em>Captures</em> window, right-click a heap snapshot file and select
-  <strong>Delete</strong>.</li>
-
-<p>Android Studio deletes the file from the <em>Captures</em> dialog and from disk. </p>
-</ul>
-
-<h3 id="hprof-converting">Converting a heap dump file to standard HPROF format</h3>
-<p>You can convert an HPROF file to standard format so you can use it outside of Android Studio with
-  other analysis tools. Follow these steps: </p>
-<ol>
-<li>In the <em>Captures</em> window, right-click a heap snapshot file and select <strong>Export to
-  standard .hprof</strong>.</li>
-<li>In the <em>Convert Android Java Heap Dump</em> dialog, specify a filename and click
-  <strong>OK</strong>.</li>
-
-
-<p>Android Studio creates a binary HPROF file in the location you specified.</p>
-</ol>
-
-<h2 id="tracking">
-  Tracking and Analyzing Memory Allocation
-</h2>
-
-<p>Android Studio allows you to track memory allocation as it monitors memory use. Tracking memory
-  allocation allows you to monitor where objects are being allocated when you perform certain
-  actions. Knowing these allocations enables you to adjust the method calls related to those actions
-  to optimize app performance and memory use.</p>
-
-<p>The Allocation Tracker does the following:</p>
-<ul>
-<li>Shows when and where your code allocates object types, their size, allocating thread, and stack
-  traces.</li>
-<li>Helps recognize memory churn through recurring allocation/deallocation patterns.</li>
-<li>Help you track down memory leaks when used in combination with the HPROF Viewer. For example,
-  if you see a bitmap object resident on the heap, you can find its allocation location with
-  Allocation Tracker.</li>
-</ul>
-
-
-<p>However, it takes time and experience to learn to interpret the output from this tool.</p>
-
-<h3 id="alloc-snapshot">Taking and displaying a snapshot of allocation data</h3>
-
-<p>Follow these steps:</p>
-<ol>
-<li>While the Memory Monitor is running, click Start Allocation Tracking
-  <img src="{@docRoot}images/tools/am-ialloctracking.png"
-  style="vertical-align:sub;margin:0;height:17px" alt="Start Allocation Tracking icon" />. </li>
-<li>Click Start Allocation Tracking
-  <img src="{@docRoot}images/tools/am-ialloctracking.png"
-  style="vertical-align:sub;margin:0;height:17px" alt="Start Allocation Tracking icon" /> again to
-  deselect it and end the snapshot. </li>
-
-  <p>The Memory Monitor displays the period when it took the snapshot. In the following
-    figure, you can see the snapshot period, as shown on the left. By comparison, when you dump the
-    Java heap, the Memory Monitor displays just the point where the heap snapshot was taken, as
-    shown on the right.</p>
-    <img src="{@docRoot}images/tools/am-dumpalloc.png" />
-
-<p>Android Studio creates the heap snapshot file with the
-  filename <code>Allocations_<em>yyyy.mm.dd_hh.mm.ss</em>.alloc</code> using the year, month, day,
-  hour, minute, and second of the capture, for example,
-  <code>Allocations_2015.11.17_14.58.48.alloc</code>.</p>
-<li>Click <strong>Captures</strong> in the main window.</li>
-
-
-<p>The <em>Captures</em> window appears.</p>
-<li>Double-click the file to view it in the Allocation Tracker. </li>
-<li>Optionally click the graphic icon to display a visual representation of the data.
-  </li>
-<p>
-  The Allocation Tracker appears:
-</p>
-<img src="{@docRoot}images/tools/am-alloctracker.png" />
-<p>
-
-
-<p>The tool displays the following information: </p>
-
-<table>
-  <tr>
-    <th scope="col">Column</th>
-    <th scope="col">Description</th>
-  </tr>
-
-  <tr>
-    <td><strong>Method</strong></td>
-    <td>The Java method responsible for the allocation.</td>
-  </tr>
-  <tr>
-    <td><strong>Count</strong></td>
-    <td>Total number of instances allocated.</td>
-  </tr>
-  <tr>
-    <td><strong>Size</strong></td>
-    <td>The total amount of allocated memory in bytes.</td>
-  </tr>
-
-</table>
-
-
-<li>Select the Group By menu option you want to display: </li>
-<ul>
-<li><strong>Group by Allocator</strong> </li>
-<li><strong>Group by Method</strong></li>
-</ul>
-
-</ol>
-
-
-
-<h3 id="alloc-sorting">Sorting allocation data</h3>
-
-<p>Follow this step:</p>
-<ul>
-<li>In the Allocation Tracker, click a column heading to sort the table by ascending or
-  descending order. </li>
-</ul>
-
-
-<h3 id="alloc-source">Displaying Java source</h3>
-<p>For some items displayed in the Allocation Tracker, you can view the Java source. Follow one of
-  these steps:</p>
-<ul>
-<li>In the Allocation Tracker, right-click a method and then select <strong>Jump to Source</strong>.
-</li>
-<li>In the Allocation Tracker, select a method and then click Jump to Source
-  <img src="{@docRoot}images/tools/am-ijumptosource.png"
-  style="vertical-align:sub;margin:0;height:17px" alt="Jump to Source icon" />. </li>
-</ul>
-
-<p>The source code appears in the Code Editor.</p>
-
-<h3 id="alloc-viewing">Viewing a saved allocation tracking file</h3>
-<p>After you monitor allocation tracking, Android Studio automatically stores it so you can view it
-  again. Follow these steps:</p>
-
-
-<ol>
-<li>Click <strong>Captures</strong> in the main window.</li>
-
-
-<p>The <em>Captures</em> window appears.</p>
-<li>Open the <strong>Allocation Tracking</strong> folder.</li>
-<li>Double-click the file to view it.</li>
-</ol>
-
-
-<h3 id="alloc-renaming">Renaming an allocation tracking file</h3>
-
-<p>If you rename a file from within Android Studio, it continues to appear in the <em>Captures</em>
-  window. Follow these steps:</p>
-<ol>
-<li>In the <em>Captures</em> window, right-click the file and select <strong>Rename</strong>.</li>
-<li>In the <em>Rename</em> dialog, specify the name of the file and click <strong>OK</strong>.</li>
-</ol>
-
-
-<h3 id="alloc-locating">Locating an allocation tracking file</h3>
-<p>You can quickly discover where Android Studio stored allocation tracking files on disk.</p>
-
-
-<p>Follow this step in Android Studio: </p>
-<ul>
-<li>In the <em>Captures</em> window, right-click allocation file and select
-  <strong>Show in Files</strong>.</li>
-
-<p>Android Studio opens an operating system file browser displaying the location where the file
-  resides.</p>
-</ul>
-
-<p class="note"><strong>Note:</strong> If you move an allocation tracking file, Android Studio
-  no longer displays it in the <em>Captures</em> window. To display the file, use
-  <strong>File</strong>
-  &gt; <strong>Open</strong>. Also, rename the file from the <em>Captures</em>
-  window and not in the operating system file browser. </p>
-
-<h3 id="alloc-deleting">Deleting an allocation tracking file</h3>
-
-
-<p>Follow this step: </p>
-<ul>
-<li>In the <em>Captures</em> window, right-click an allocation tracking file and select
-  <strong>Delete</strong>.</li>
-
-<p>Android Studio deletes the file from the <em>Captures</em> dialog and from disk. </p>
-</ul>
diff --git a/docs/html/tools/help/am-methodtrace.jd b/docs/html/tools/help/am-methodtrace.jd
new file mode 100644
index 0000000..7d5f070
--- /dev/null
+++ b/docs/html/tools/help/am-methodtrace.jd
@@ -0,0 +1,266 @@
+page.title=Method Trace
+parent.title=Android Monitor
+parent.link=android-monitor.html
+meta.tags="android, performance, profiling, tools, monitor"
+page.tags="android", "performance", "profiling", "tools", "monitor"
+page.metaDescription=Use the CPU Monitor to perform a method trace on your app. View call stack and timing information in the method trace display.
+page.image=tools/help/thumbnails/am_methodtrace.png
+page.article=true
+
+@jd:body
+
+<div id="qv-wrapper">
+<div id="qv">
+  <h2>In this document</h2>
+<ol>
+<li><a href="#display">Understanding the Method Trace Display</a></li>
+  <li><a href="#trace">Performing a Method Trace in the CPU Monitor</a></li>
+  <li><a href="#viewtrace">Viewing a Saved Method Trace</a></li>
+  <li><a href="#sorttrace">Sorting Method Trace Data</a></li>
+  <li><a href="#trace-files">Working with Method Trace Files</a></li>
+</ol>
+
+</div>
+</div>
+
+
+<p>
+  You can start a method trace from the CPU Monitor. It lets you view the call stack and timing
+  information for your app. This information can help you optimize and debug your app.
+</p>
+
+<h2 id="display">
+  Understanding the Method Trace Display
+</h2>
+
+<p>
+  The method trace looks similar to the following figure:
+</p>
+<img src="{@docRoot}images/tools/am-methodtrace.png" alt="Method Trace" />
+<p></p>
+
+<p>The display shows the following information:</p>
+
+<table>
+  <tr>
+    <th scope="col">Field</th>
+    <th scope="col">Description</th>
+  </tr>
+
+  <tr>
+    <td><strong>Name</strong></td>
+    <td>The name of the method.</td>
+  </tr>
+
+  <tr>
+    <td><strong>Invocation Count</strong></td>
+    <td>How many times the method was called.</td>
+  </tr>
+
+  <tr>
+    <td><strong>Inclusive Time (microseconds)</strong></td>
+    <td>Time spent in the method and all of its children, either wall clock or thread time,
+          depending on your selection in the <strong>x-axis</strong> menu.</td>
+  </tr>
+
+  <tr>
+    <td><strong>Exclusive Time (microseconds)</strong></td>
+    <td>Time spent just in the method (excluding time spent in its children), either wall clock
+          or thread time, depending on your selection in the <strong>x-axis</strong> menu.</td>
+  </tr>
+</table>
+
+<p class="note"><strong>Note:</strong> Running the method trace significantly affects CPU timings.
+  Use the method trace to understand the flow of the program, but not for performance timings.</p>
+
+<h2 id="trace">
+  Performing a Method Trace in the CPU Monitor
+</h2>
+
+<p>
+  To perform a method trace:
+</p>
+
+<ol>
+  <li>
+    <a href="{@docRoot}tools/help/am-cpu.html#running">Display a running app in the CPU
+    Monitor</a>.
+  </li>
+
+  <li>Start a trace by clicking Start Method Tracing <img src="{@docRoot}images/tools/am-imethodtrace.png"
+    style="vertical-align:sub;margin:0;height:17px" alt="Start Method Tracing icon" /> to
+  select it.
+  </li>
+
+  <li>To stop the trace, click Stop Method Tracing <img src="{@docRoot}images/tools/am-imethodtrace.png"
+    style="vertical-align:sub;margin:0;height:17px" alt="Stop Method Tracing icon" /> to
+  deselect it.
+  </li>
+
+<p>
+  The method trace appears in the Code Editor area.
+</p>
+
+<p>
+  Android Studio creates the method trace file
+  with the filename <code><em>package_yyyy.mm.dd_hh.mm.ss</em>.trace</code>
+  using the activity package (or project) name, year, month, day, hour, minute, and second of
+  the capture, for example,
+  <code>com.android.calc_2015.11.17_14.58.48.trace</code>.
+</p>
+  <li>Specify display options:
+    <ul>
+      <li>Select a <strong>Thread</strong>.
+      </li>
+
+      <li>Select an <strong>x-axis</strong> time for the graphic and the method list:
+      </li>
+
+        <ul>
+          <li>
+            <strong>Wall Clock Time</strong> - Total CPU time elapsed between the method call and
+            return.
+          </li>
+
+          <li>
+            <strong>Thread Time</strong> - Total time during which the JRE scheduled the
+            thread during call processing. It’s less than or equal to the Wall Clock Time: less if
+            the JRE interrupted the thread, and equal if it didn’t.
+            The thread might not run continuously; when it’s not executing, that time is excluded.
+            If threads are interrupted often and it’s not by design, the interruptions affect app
+            performance. However, an example of a by-design use is synchronous operations that take
+            a long time, such as file transfers and reads from disk, where the method could be the
+            asynchronous wrapper for the synchronous reader.
+          </li>
+       </ul>
+
+        <li>
+          Optionally select <strong>Color by inclusive time</strong>.
+        </li>
+        </ul>
+
+
+
+        <p>
+          The graphic represents the wall clock or thread time for each method. Hover the cursor
+          over the display to receive information about the method. This information also appears
+          in the table.
+        </p>
+</ol>
+        <h2 id="viewtrace">
+          Viewing a Saved Method Trace
+        </h2>
+
+        <p>
+          After you do a method trace, Android Studio automatically stores it so you can view it
+          again.</p>
+
+          <p>To examine a saved method trace:
+        </p>
+
+        <ol>
+          <li>Click
+          <img src="{@docRoot}images/tools/am-icaptures.png"
+          style="vertical-align:sub;margin:0;height:17px"
+          alt="Captures icon" /> in the main window.
+          </li>
+          <p>Or select <strong>View</strong> > <strong>Tools Windows</strong> >
+          <strong>Captures</strong>.</p>
+
+        <p>
+          The <em>Captures</em> window appears.
+        </p>
+
+      <li>Open the <strong>Methods Tracing</strong> folder.
+      </li>
+
+      <li>Double-click the file to view it.
+      </li>
+</ol>
+
+<h2 id="sorttrace">
+  Sorting Method Trace Data
+</h2>
+
+<p>
+  You can sort the data by method name, count, inclusive time, and exclusive
+  time.</p>
+
+  <p>To sort method trace data:</p>
+
+
+<ul>
+  <li>Click a column heading to sort the table by ascending or descending order.
+  </li>
+</ul>
+
+<h2 id="trace-files">Working with Method Trace Files</h2>
+<p>You can rename, locate, and delete a method trace file from within Android
+Studio.</p>
+
+<h3 id="renametrace">
+  Renaming a method trace file
+</h3>
+
+<p>
+  Rename a method trace file from within Android Studio so it
+  continues to appear in the <em>Captures</em> window.</p>
+
+  <p>To rename a method trace file:
+</p>
+
+<ol>
+  <li>In the <em>Captures</em> window, right-click the file and select <strong>Rename</strong>.
+  </li>
+
+  <li>In the dialog, specify the name of the file and click <strong>OK</strong>.
+  </li>
+</ol>
+
+<h3 id="locatetrace">
+  Locating a method trace file on disk
+</h3>
+
+<p>
+  You can quickly discover where Android Studio stored method trace files on
+  disk.</p>
+
+  <p>To locate a method trace file on disk:
+</p>
+
+
+
+<ul>
+  <li>In the <em>Captures</em> window, right-click a method trace file and
+  select <strong>Show</strong> or <strong>Reveal</strong>.
+  </li>
+
+<p>
+  Android Studio opens an operating system file browser displaying the location where the file
+  resides.
+</p>
+</ul>
+<p class="note">
+  <strong>Note:</strong> If you move a method trace file, Android Studio no longer displays the file
+  in the <em>Captures</em> window. To display it, use <strong>File</strong> &gt;
+  <strong>Open</strong>. Also, rename a file from the <em>Captures</em>
+  window and not in the operating system file browser.
+</p>
+
+<h3 id="deletetrace">
+  Deleting a method trace file
+</h3>
+
+<p>
+  To delete a method trace file:
+</p>
+
+<ul>
+  <li>In the <em>Captures</em> window, right-click a method trace file and select
+  <strong>Delete</strong>.
+  </li>
+</ul>
+
+<p>
+  Android Studio deletes the file from the <em>Captures</em> dialog and from disk.
+</p>
\ No newline at end of file
diff --git a/docs/html/tools/help/am-network.jd b/docs/html/tools/help/am-network.jd
index ae116ac..8129992 100644
--- a/docs/html/tools/help/am-network.jd
+++ b/docs/html/tools/help/am-network.jd
@@ -1,7 +1,12 @@
 page.title=Network Monitor
 parent.title=Android Monitor
 parent.link=android-monitor.html
-page.tags=monitor
+meta.tags="android, performance, profiling, tools, monitor"
+page.tags="android", "performance", "profiling", "tools", "monitor"
+page.metaDescription=Use the Network Monitor to analyze network requests, including how and when your app transfers data. Preserve battery life by optimizing network use.
+page.image=tools/help/thumbnails/am-networkmon.png
+page.article=true
+
 @jd:body
 
 <div id="qv-wrapper">
@@ -11,63 +16,12 @@
   <li><a href="#running">Displaying a Running App in the Network Monitor</a></li>
 </ol>
 
- <h2>See also</h2>
-  <ol>
-    <li>
-        <a href="{@docRoot}tools/help/android-monitor.html">Android Monitor</a>
-      </li>
-    <li><a href="{@docRoot}tools/help/am-logcat.html">logcat Monitor</a>
-      </li>
-
-      <li><a href="{@docRoot}tools/help/am-memory.html">Memory Monitor</a>
-      </li>
-
-      <li><a href="{@docRoot}tools/help/am-cpu.html">CPU Monitor</a>
-      </li>
-
-      <li><a href="{@docRoot}tools/help/am-gpu.html">GPU Monitor</a>
-      </li>
-  </ol>
-
 <h2>Video</h2>
   <ol>
     <li><a href="https://www.youtube.com/watch?v=fEEulSk1kNY"
       class="external-link">Battery Drain and Networking</a></li>
   </ol>
 
-<h2>
-  Dependencies and Prerequisites
-</h2>
-
-<ul>
-  <li>
-    <a href="{@docRoot}tools/building/building-studio.html#RunningOnDeviceStudio">Connect a
-    hardware device</a> to your development computer.
-  </li>
-
-  <li>Make sure your development computer detects your hardware device, which often happens
-  automatically when you connect it to a USB port.
-  </li>
-
-  <li>
-    <a href="{@docRoot}tools/device.html#device-developer-options">Enable</a> <strong><a href=
-    "{@docRoot}tools/device.html#device-developer-options">USB debugging</a></strong> in
-    <strong>Developer Options</strong> on the device.
-  </li>
-
-  <li>In your app, set the <code>debuggable</code> property to <code>true</code> in the manifest or
-  <code>build.gradle</code> file (it’s initially set by default).
-  </li>
-
-  <li>Enable ADB integration through <strong>Tools</strong> &gt; <strong>Android</strong> &gt;
-  <strong>Enable ADB Integration</strong>.
-  </li>
-
-  <li>
-    <a href="{@docRoot}tools/help/monitor.html">Android Device Monitor</a> can’t be running.
-  </li>
-</ul>
-
 </div>
 </div>
 
@@ -91,32 +45,35 @@
 </h2>
 
 <p>
-  Follow these steps:
+  To display an app running on a particular device in the Network Monitor:
 </p>
 
 <ol>
-  <li>Connect a hardware device.
+  <li>Meet the <a href=
+  "{@docRoot}tools/help/am-basics.html#byb">prerequisites and dependencies</a>.
   </li>
-
+  <p>Connect a hardware device; the Network Monitor doesn't monitor an emulator.
+  </p>
+ <li>Open an app project.
+  </li>
+  <li><a href=
+  "{@docRoot}tools/building/building-studio.html#RunningApp">Run the app</a> on the hardware device.
+  </li>
   <li>
-    <a href="{@docRoot}tools/help/android-monitor.html#displaying">Display Android Monitor</a>.
+    <a href="{@docRoot}tools/help/am-basics.html#displaying">Display Android Monitor</a>.
+  </li>
+  <li>Click the <strong>Monitors</strong> tab and <a href=
+  "{@docRoot}tools/help/am-basics.html#rearranging">display the Network Monitor</a>.
   </li>
 
-  <li>Click the <strong>Network</strong> tab.
+  <li>Enable the Network Monitor by clicking Pause <img src="{@docRoot}images/tools/am-ipause.png"
+    style="vertical-align:sub;margin:0;height:17px" alt="Pause icon" /> to deselect it.
   </li>
 
-  <li>Open an app project and <a href=
-  "{@docRoot}tools/building/building-studio.html#RunningApp">run it</a> on the hardware device.
-  </li>
-
-  <li>To start the Network Monitor, click Pause <img src="{@docRoot}images/tools/am-ipause.png"
-    style="vertical-align:sub;margin:0;height:17px" alt="Pause icon" /> to
-  deselect it.
-  </li>
 <p>
   Any network traffic begins to appear in the Network Monitor:
 </p>
-  <img src="{@docRoot}images/tools/am-networkmon.png" style="vertical-align:sub;margin:0;width:450px" />
+  <img src="{@docRoot}images/tools/am-networkmon2.png" style="vertical-align:sub;margin:0" />
 <p>
   The Network Monitor adds up the amount of time it takes for the device to transmit and receive
   kilobytes of data.
diff --git a/docs/html/tools/help/am-screenshot.jd b/docs/html/tools/help/am-screenshot.jd
new file mode 100644
index 0000000..322616e
--- /dev/null
+++ b/docs/html/tools/help/am-screenshot.jd
@@ -0,0 +1,89 @@
+page.title=Screen Capture
+parent.title=Android Monitor
+parent.link=android-monitor.html
+meta.tags="android, performance, profiling, tools, monitor"
+page.tags="android", "performance", "profiling", "tools", "monitor"
+page.metaDescription=Use the Screen Capture tool to take a screenshot of the display on a hardware device or the emulator. Optionally display the screenshot within a graphic of a device.
+page.image=tools/help/thumbnails/am_screenshot.png
+page.article=true
+@jd:body
+
+
+<p>
+  You can take a PNG screenshot of the display on a connected device or the emulator. You can use
+  the images for your marketing materials as well as for debugging, for example.
+</p>
+
+
+<h2 id="screencapture">
+  Taking a Screen Capture of the Device
+</h2>
+
+
+<p>
+  To take a screen capture:
+</p>
+<ol>
+  <li>Meet the <a href=
+  "{@docRoot}tools/help/am-basics.html#byb">prerequisites and dependencies</a>.
+  </li>
+ <li>Open an app project.
+  </li>
+  <li><a href=
+  "{@docRoot}tools/building/building-studio.html#RunningApp">Run the app</a> on
+  a hardware device or emulator.
+  </li>
+  <li>
+    <a href="{@docRoot}tools/help/am-basics.html#displaying">Display Android Monitor</a>.
+  </li>
+
+  <li>Interact with the display on the device or emulator to stage the image you want.
+  </li>
+
+  <li>Click Screen Capture <img src="{@docRoot}images/tools/am-iscreencapture.png"
+    style="vertical-align:sub;margin:0;height:17px" alt="Screen Capture icon" /> in the
+    Android Monitor toolbar.
+  </li>
+  <p>The screenshot appears in a <em>Screenshot Editor</em> window.</p>
+
+<img src="{@docRoot}images/tools/am-screenshot.png" alt="Screen Capture" />
+
+  <li>Optionally change the image:
+    <ul>
+      <li>
+        <strong>Recapture</strong> - Click to take a new screenshot.
+      </li>
+
+      <li>
+        <strong>Rotate</strong> - Click to rotate the image 90 degrees clockwise.
+      </li>
+
+      <li>
+        <strong>Frame Screenshot</strong> - Select this option and choose a device to add an image
+        of the device to the outside of the screenshot. Select <strong>Drop Shadow</strong>,
+        <strong>Screen Glare</strong>, or both to add these effects to your image.
+      </li>
+
+      <li>
+        <strong>Chessboard</strong> and <strong>Grid</strong> - Select an option to display these
+        behind your image.
+      </li>
+
+      <li>
+        <strong>Zoom In</strong>, <strong>Zoom Out</strong>, or <strong>Actual Size</strong> -
+        Click these options to get different perspectives of your image without changing the image
+        itself.
+      </li>
+    </ul>
+    </li>
+      <li>Click <strong>Save</strong> to save the image.
+      </li>
+      </li>
+      <li>In the <em>Save as PNG</em> dialog, specify the location and filename,
+      and then click <strong>OK</strong>.
+      </li>
+      <p>The screenshot file appears in the Code Editor area.</p>
+</ol>
+
+
+
diff --git a/docs/html/tools/help/am-sysinfo.jd b/docs/html/tools/help/am-sysinfo.jd
new file mode 100644
index 0000000..166cc08
--- /dev/null
+++ b/docs/html/tools/help/am-sysinfo.jd
@@ -0,0 +1,205 @@
+page.title=System Information
+parent.title=Android Monitor
+parent.link=android-monitor.html
+meta.tags="android, performance, profiling, tools, monitor"
+page.tags="android", "performance", "profiling", "tools", "monitor"
+page.metaDescription=Use the System Information tool to capture <code>dumpsys</code> information about your app. View activity manager, package, memory usage, and graphics state information.
+page.image=tools/help/thumbnails/am_sysinfo.png
+page.article=true
+@jd:body
+<div id="qv-wrapper">
+<div id="qv">
+  <h2>In this document</h2>
+<ol>
+  <li><a href="#sysinfo">Examining System Information for a Running App</a></li>
+  <li><a href="#viewsysinfo">Viewing Saved System Information</a></li>
+  <li><a href="#sysinfo-files">Working with System Information Files</a></li>
+</ol>
+
+</div>
+</div>
+
+<p>
+  You can capture <code>dumpsys</code> output from within Android Monitor and
+  display the file in the Code Editor. The <em>Captures</em> window lists the
+  system information files so you can retrieve the information later for
+  analysis.
+</p>
+
+
+
+<h2 id="sysinfo">
+  Examining System Information for a Running App
+</h2>
+<p>
+  To capture and view a snapshot of system information:
+</p>
+
+<ol>
+  <li>Meet the <a href=
+  "{@docRoot}tools/help/am-basics.html#byb">prerequisites and dependencies</a>.
+  </li>
+ <li>Open an app project.
+  </li>
+  <li><a href=
+  "{@docRoot}tools/building/building-studio.html#RunningApp">Run the app</a> on
+  a hardware device or emulator.
+  </li>
+  <li>
+    <a href="{@docRoot}tools/help/am-basics.html#displaying">Display Android Monitor</a>.
+  </li>
+
+  <li>In the toolbar of the Android Monitor main window, click System Information
+    <img src="{@docRoot}images/tools/am-isysteminfo.png"
+    style="vertical-align:sub;margin:0;height:17px" alt="System Information icon" />
+    and then select a menu item.
+  </li>
+
+<p>
+  The menu items display different types of <code><a href=
+  "https://source.android.com/devices/tech/debug/dumpsys.html">dumpsys</a></code>
+  output:
+</p>
+
+<ul>
+  <li>
+    <strong>Activity Manager State</strong> - <code>dumpsys activity</code>
+  </li>
+
+  <li>
+    <strong>Package Information</strong> - <code>dumpsys package</code>
+  </li>
+
+  <li>
+    <strong>Memory Usage</strong> - <code><a href=
+    "{@docRoot}tools/debugging/debugging-memory.html#ViewingAllocations">dumpsys
+    meminfo</a></code>
+  </li>
+
+  <li>
+    <strong>Memory Use Over Time</strong> - <code><a href=
+    "http://android-developers.blogspot.com/2014/01/process-stats-understanding-how-your.html">dumpsys
+    procstats</a></code>
+  </li>
+
+  <li>
+    <strong>Graphics State</strong> - <code><a href=
+    "{@docRoot}training/testing/performance.html">dumpsys gfxinfo</a></code>
+  </li>
+</ul>
+
+<p>
+  The information appears in an editable text file in the Code Editor.
+</p>
+<img src="{@docRoot}images/tools/am-sysinfo.png" alt="System Information" />
+<p>Android Studio creates the system information file with the
+  filename <code><em>package_yyyy.mm.dd_hh.mm.ss</em>.txt</code> using the
+  activity package (or project) name, year, month, day,
+  hour, minute, and second of the capture, for example,
+  <code>com.android.calc_2015.11.17_14.58.48.txt</code>.</p>
+</ol>
+
+<h2 id="viewsysinfo">
+Viewing Saved System Information
+</h2>
+
+<p>
+After you take a snapshot of system information, Android Studio automatically
+stores it so you can view it again.</p>
+
+<p>To examine a saved system information file:</p>
+
+<ol>
+          <li>Click
+          <img src="{@docRoot}images/tools/am-icaptures.png"
+          style="vertical-align:sub;margin:0;height:17px"
+          alt="Captures icon" /> in the main window.
+          </li>
+          <p>Or select <strong>View</strong> > <strong>Tools Windows</strong> >
+          <strong>Captures</strong>.</p>
+
+        <p>
+          The <em>Captures</em> window appears.
+        </p>
+
+      <li>Open the <strong>System Information</strong> folder.
+      </li>
+
+      <li>Double-click the file to view it.
+      </li>
+</ol>
+
+
+<h2 id="sysinfo-files">Working with System Information Files</h2>
+<p>You can rename, locate, and delete a system information file from within
+Android Studio.</p>
+
+<h3 id="renamesysinfo">
+  Renaming a system information file
+</h3>
+
+<p>
+  Rename a system information file from within Android Studio so it
+  continues to appear in the <em>Captures</em> window.</p>
+
+  <p>To rename a system information file:
+</p>
+
+<ol>
+  <li>In the <em>Captures</em> window, right-click the file and select
+  <strong>Rename</strong>.
+  </li>
+
+  <li>In the dialog, specify the name of the file and click <strong>OK</strong>.
+  </li>
+</ol>
+
+<h3 id="locatesysinfo">
+  Locating a system information file on disk
+</h3>
+
+<p>
+  You can quickly discover where Android Studio stored system information files
+  on disk.</p>
+
+  <p>To locate a system information file on disk:
+</p>
+
+
+
+<ul>
+  <li>In the <em>Captures</em> window, right-click a system information file and
+  select <strong>Show</strong> or <strong>Reveal</strong>.
+  </li>
+
+<p>
+  Android Studio opens an operating system file browser displaying the location
+  where the file resides.
+</p>
+</ul>
+<p class="note">
+  <strong>Note:</strong> If you move a system information file, Android Studio
+  no longer displays the file
+  in the <em>Captures</em> window. To display it, use <strong>File</strong> &gt;
+  <strong>Open</strong>. Also, rename a file from the <em>Captures</em>
+  window and not in the operating system file browser.
+</p>
+
+<h3 id="deletesysinfo">
+  Deleting a system information file
+</h3>
+
+<p>
+  To delete a system information file:
+</p>
+
+<ul>
+  <li>In the <em>Captures</em> window, right-click a system information file
+  and select <strong>Delete</strong>.
+  </li>
+</ul>
+
+<p>
+  Android Studio deletes the file from the <em>Captures</em> dialog and from
+  disk.
+</p>
diff --git a/docs/html/tools/help/am-video.jd b/docs/html/tools/help/am-video.jd
new file mode 100644
index 0000000..5ecdd11
--- /dev/null
+++ b/docs/html/tools/help/am-video.jd
@@ -0,0 +1,78 @@
+page.title=Video Capture
+parent.title=Android Monitor
+parent.link=android-monitor.html
+meta.tags="android, performance, profiling, tools, monitor"
+page.tags="android", "performance", "profiling", "tools", "monitor"
+page.metaDescription=Use the Video tool to make a video of the display on a hardware device.
+page.image=tools/help/thumbnails/am_video.png
+page.article=true
+@jd:body
+
+
+<p>
+  Android Studio lets you record an MP4 video from your hardware device for a maximum of three
+  minutes. You can use the video for your marketing materials as well as for debugging, for
+  example.
+</p>
+<img src="{@docRoot}images/tools/am-video.png" width="230" alt="Device Video" />
+
+
+
+<h2 id="video">
+  Recording a Video from the Screen
+</h2>
+
+<p>
+  To record a video from a hardware device:
+</p>
+<ol>
+  <li>Meet the <a href=
+  "{@docRoot}tools/help/am-basics.html#byb">prerequisites and dependencies</a>.
+  </li>
+ <li>Open an app project.
+  </li>
+  <li><a href=
+  "{@docRoot}tools/building/building-studio.html#RunningApp">Run the app</a> on
+  a hardware device.
+  </li>
+  <li>
+    <a href="{@docRoot}tools/help/am-basics.html#displaying">Display Android Monitor</a>.
+  </li>
+
+  <li>Interact with the display on the hardware device to stage the start of the video.
+  </li>
+
+  <li>Click Screen Record <img src="{@docRoot}images/tools/am-ivideo.png"
+    style="vertical-align:sub;margin:0;height:17px" alt="Screen Record icon" /> in the
+    Android Monitor toolbar.
+  </li>
+  <p>The screenshot appears in a Screenshot Editor window.</p>
+
+  <li>In the <em>Screen Recorder Options</em> dialog, optionally change the recording options:
+  </li>
+<ul>
+  <li>
+    <strong>Bit Rate</strong> - Type a bit rate. The default is 4 Mbps.
+  </li>
+
+  <li>
+    <strong>Resolution</strong> - Type a width and height value in pixels. The value must be a
+    multiple of 16. The default is the resolution of the device.
+  </li>
+</ul>
+  <li>Click <strong>Start Recording</strong> to start the recording.
+  </li>
+
+  <li>Click <strong>Stop Recording</strong> to stop the recording.
+  </li>
+
+  <li>In the <em>Save As</em> dialog, save the MP4 file.
+  </li>
+
+  <li>In the <em>Screen Recorder</em> dialog, click one of the buttons to show the file location,
+  open the recording in a player, or to dismiss the dialog.
+  </li>
+</ol>
+
+
+
diff --git a/docs/html/tools/help/android-monitor.jd b/docs/html/tools/help/android-monitor.jd
index 4c9f80f..2820db8 100644
--- a/docs/html/tools/help/android-monitor.jd
+++ b/docs/html/tools/help/android-monitor.jd
@@ -8,63 +8,16 @@
 <div id="qv">
   <h2>In this document</h2>
 <ol>
-  <li><a href="#displaying">Displaying Android Monitor</a></li>
-  <li><a href="#profiling">Profiling a Running App in Android Monitor</a></li>
-  <li><a href="#switching">Switching between Devices and Apps</a></li>
-  <li><a href="#screencapture">Taking a Screen Capture of the Device</a></li>
-  <li><a href="#video">Recording a Video from the Screen</a></li>
-  <li><a href="#sysinfo">Examining System Information</a></li>
-  <li><a href="#terminating">Terminating the App</a></li>
-  <li><a href="#rearranging">Rearranging Android Monitor Windows</a></li>
-  <li><a href="#removing">Removing an App from a Device</a></li>
+  <li><a href="#logcat">Log Messages</a></li>
+  <li><a href="#monitors">Performance Monitors</a></li>
+  <li><a href="#data">Data Analysis</a></li>
+  <li><a href="#shots">Screen and Video Captures</a></li>
+  <li><a href="#getstarted">Get Started</a></li>
 </ol>
 
- <h2>See also</h2>
-  <ol>
-    <li><a href="{@docRoot}tools/help/am-logcat.html">logcat Monitor</a>
-      </li>
-
-      <li><a href="{@docRoot}tools/help/am-memory.html">Memory Monitor</a>
-      </li>
-
-      <li><a href="{@docRoot}tools/help/am-cpu.html">CPU Monitor</a>
-      </li>
-
-      <li><a href="{@docRoot}tools/help/am-gpu.html">GPU Monitor</a>
-      </li>
-
-      <li>
-        <a href="{@docRoot}tools/help/am-network.html">Network Monitor</a>
-      </li>
-  </ol>
 
 
-<h2>
-  Dependencies and Prerequisites
-</h2>
 
-<ul>
-  <li>In your app, set the <code>debuggable</code> property to <code>true</code> in the manifest or
-  <code>build.gradle</code> file (it’s initially set by default).
-  </li>
-
-    <li>Enable ADB integration through <strong>Tools</strong> &gt; <strong>Android</strong> &gt;
-  <strong>Enable ADB Integration</strong>.
-    </li>
-
-  <li>Make sure your development computer detects your hardware device, which often happens
-  automatically when you connect it to a USB port.
-  </li>
- <li>
-    <a href="{@docRoot}tools/device.html#device-developer-options">Enable</a> <strong><a href=
-    "{@docRoot}tools/device.html#device-developer-options">USB debugging</a></strong> in
-    <strong>Developer Options</strong> on the device or emulator.
-  </li>
-
-  <li>
-    <a href="{@docRoot}tools/help/monitor.html">Android Device Monitor</a> can’t be running.
-  </li>
-</ul>
 
 </div>
 </div>
@@ -72,7 +25,7 @@
 <p>
   Android Monitor helps you to profile the performance of your apps so you can optimize, debug, and
   improve them. It lets you monitor the following aspects of your apps from a hardware device or
-  the Android Studio emulator:
+  the <a href="{@docRoot}tools/devices/emulator.html">Android Emulator</a>:
 </p>
 
 <ul>
@@ -88,375 +41,66 @@
   </li>
 </ul>
 
-<p>
-  Android Monitor contains the logcat, Memory, CPU, GPU, and Network Monitors that you can use
-  separately to examine these aspects of your apps.
-</p>
 
+<p>Android Monitor provides various tools that provide real-time information about your app. It
+  lets you capture data as your app runs and stores it in a file that you can analyze in various
+  viewers. You can also capture screen shots and videos of your app as it runs.</p>
 
-<h2 id="displaying">
-  Displaying Android Monitor
-</h2>
+<h2 id="logcat">Log Messages</h2>
 
-<p>
-  Android Monitor is integrated into the Android Studio main window:
-</p>
+<p>View log messages — in real time and historically — which is useful for debugging.</p>
 
-<ul>
-  <li>To display Android Monitor, click <img src="{@docRoot}images/tools/am-icon.png"
-    style="vertical-align:sub;margin:0;height:17px" alt="Android Monitor icon" />, which by default
-  is at the bottom of the main window.
-  </li>
+<div class="dynamic-grid">
+  <div class="resource-widget resource-flow-layout landing col-12"
+    data-query="collection:tools/help/log"
+    data-cardSizes="12x6"
+    data-maxResults="6">
+  </div>
+</div>
 
-  <li>To hide Android Monitor, click <img src="{@docRoot}images/tools/am-icon.png"
-    style="vertical-align:sub;margin:0;height:17px" alt="Android Monitor icon" /> again.
-  </li>
-</ul>
-<img src="{@docRoot}images/tools/am-androidmon.png" style="vertical-align:sub;margin:0;width:480px" />
 
-<h2 id="profiling">
-  Profiling a Running App in Android Monitor
-</h2>
+<h2 id="monitors">Performance Monitors</h2>
 
-<p>
-  Follow these steps:
-</p>
+<p>Visualize the behavior and performance of your app.</p>
 
-<ol>
-  <li>Optionally connect a hardware device.
-  </li>
+<div class="dynamic-grid">
+  <div class="resource-widget resource-flow-layout landing col-12"
+    data-query="collection:tools/help/monitor"
+    data-cardSizes="9x6"
+    data-maxResults="6">
+  </div>
+</div>
 
-  <li>
-    <a href="#displaying">Display Android Monitor</a>.
-  </li>
+<h2 id="data">Data Analysis</h2>
 
-  <li>Open an app project and <a href=
-  "{@docRoot}tools/building/building-studio.html#RunningApp">run the app</a> on a device or
-  emulator.
-  </li>
+<p>Android Monitor lets you capture various types of data about your app while it's running and
+  stores it in a file, which you can access whenever is convenient.
+  It lists these files in the <em>Captures</em> window.</p>
 
-  <li>Click the tab for the monitor you want to view and start the monitor, if needed:
-    <ul>
-      <li><a href="{@docRoot}tools/help/am-logcat.html">logcat Monitor</a>
-      </li>
+<div class="dynamic-grid">
+  <div class="resource-widget resource-flow-layout landing col-12"
+    data-query="collection:tools/help/data"
+    data-cardSizes="9x6"
+    data-maxResults="6">
+  </div>
+</div>
 
-      <li><a href="{@docRoot}tools/help/am-memory.html">Memory Monitor</a>
-      </li>
+<h2 id="shots">Screen and Video Captures</h2>
 
-      <li><a href="{@docRoot}tools/help/am-cpu.html">CPU Monitor</a>
-      </li>
+<p>Create screen captures and videos of your app to help with marketing and debugging.
+  </p>
 
-      <li><a href="{@docRoot}tools/help/am-gpu.html">GPU Monitor</a>
-      </li>
+<div class="dynamic-grid">
+  <div class="resource-widget resource-flow-layout landing col-12"
+    data-query="collection:tools/help/shot"
+    data-cardSizes="9x3"
+    data-maxResults="2">
+  </div>
+</div>
 
-      <li>
-        <a href="{@docRoot}tools/help/am-network.html">Network Monitor</a>
-      </li>
-    </ul>
-</ol>
-    <h2 id="switching">
-      Switching between Devices and Apps
-    </h2>
-
-    <p>
-      By default, Android Monitor displays data for your most recently run app. You can switch to
-      another device and app as needed. In addition to currently running apps, you can view
-      information about apps that are no longer running so you can continue to view any information
-      about them that you gathered previously.
-    </p>
-
-    <p>
-      At the top of the Android Monitor main window are two menus listing devices and processes. To
-      switch to another device, process, or both, follow these steps:
-    </p>
-
-    <ol>
-      <li>Select the device or emulator.
-      </li>
-
-    <p>
-      The Device menu lists the devices and emulators that are running or have run during your
-      current session. There are various status messages that can appear in the Device menu:
-    </p>
-
-    <ul>
-      <li>
-        <strong>DISCONNECTED</strong> - You closed an emulator or unplugged a device from the
-        computer.
-      </li>
-
-      <li>
-        <strong>UNAUTHORIZED</strong> - A device needs you to accept the incoming computer
-        connection. For example, if the connected device displays an <em>Allow USB Debugging</em>
-        dialog, click <strong>OK</strong> to allow the connection.
-      </li>
-
-      <li>
-        <strong>OFFLINE</strong> - Android Monitor can’t communicate with a device, even though it
-        has detected that device.
-      </li>
-    </ul>
-
-  <li>Select the process.
-  </li>
-</ol>
-
-<p>
-  The Process menu lists the processes that are running or have run during your current session. If
-  a process is no longer running, the menu displays a status of <strong>DEAD</strong>.
-</p>
-
-<h2 id="screencapture">
-  Taking a Screen Capture of the Device
-</h2>
-
-<p>
-  You can take a PNG screenshot of the display on a connected device or the emulator. You can use
-  the images for your marketing materials as well as for debugging, for example.
-</p>
-<p>
-  Follow these steps:
-</p>
-<ol>
-  <li>
-    <a href="{@docRoot}training/basics/firstapp/running-app.html">Run your
-    app</a> from within Android Studio.
-  </li>
-
-  <li>
-    <a href="#switching">Select the device and the process</a> in the Android Monitor
-    menus, if needed.
-  </li>
-
-  <li>Interact with the display on the device or emulator to stage the image you want.
-  </li>
-
-  <li>Click Screen Capture <img src="{@docRoot}images/tools/am-iscreencapture.png"
-    style="vertical-align:sub;margin:0;height:17px" alt="Screen Capture icon" /> in the
-    Android Monitor toolbar.
-  </li>
-  <p>The screenshot appears in a <em>Screenshot Editor</em> window.</p>
-
-  <li>Optionally change the image:
-    <ul>
-      <li>
-        <strong>Reload</strong> - Click to take a new screenshot.
-      </li>
-
-      <li>
-        <strong>Rotate</strong> - Click to rotate the image 90 degrees clockwise.
-      </li>
-
-      <li>
-        <strong>Frame Screenshot</strong> - Select this option and choose a device to add an image
-        of the device to the outside of the screenshot. Select <strong>Drop Shadow</strong>,
-        <strong>Screen Glare</strong>, or both to add these effects to your image.
-      </li>
-
-      <li>
-        <strong>Chessboard</strong> and <strong>Grid</strong> - Select an option to display these
-        behind your image.
-      </li>
-
-      <li>
-        <strong>Zoom In</strong>, <strong>Zoom Out</strong>, or <strong>Actual Size</strong> -
-        Click these options to get different perspectives of your image without changing the image
-        itself.
-      </li>
-    </ul>
-    </li>
-      <li>Click <strong>Save</strong> to save the image.
-      </li>
-</ol>
-
-<h2 id="video">
-  Recording a Video from the Screen
-</h2>
-
-<p>
-  Android Studio lets you record an MP4 video from your hardware device for a maximum of three
-  minutes. You can use the video for your marketing materials as well as for debugging, for
-  example.
-</p>
-<p>
-  Follow these steps:
-</p>
-<ol>
-  <li>
-    <a href="{@docRoot}training/basics/firstapp/running-app.html">Run your
-    app</a> from within Android Studio.
-  </li>
-
-  <li>
-    <a href="#switching">Select the device and the process</a> in the Android Monitor
-    menus, if needed.
-  </li>
-
-  <li>Interact with the display on the device or emulator to stage the start of the video.
-  </li>
-
-  <li>Click Screen Record <img src="{@docRoot}images/tools/am-ivideo.png" style="vertical-align:sub;margin:0;height:17px" alt="Screen Record icon" /> in the Android Monitor toolbar.
-  </li>
-  <p>The screenshot appears in a Screenshot Editor window.</p>
-
-  <li>In the <em>Screen Recorder Options</em> dialog, optionally change the recording options:
-  </li>
-<ul>
-  <li>
-    <strong>Bit Rate</strong> - Type a bit rate. The default is 4 Mbps.
-  </li>
-
-  <li>
-    <strong>Resolution</strong> - Type a width and height value in pixels. The value must be a
-    multiple of 16. The default is the resolution of the device.
-  </li>
-</ul>
-  <li>Click <strong>Start Recording</strong> to start the recording.
-  </li>
-
-  <li>Click <strong>Stop Recording</strong> to stop the recording.
-  </li>
-
-  <li>In the <em>Save As</em> dialog, save the MP4 file.
-  </li>
-
-  <li>In the <em>Screen Recorder</em> dialog, click one of the buttons to show the file location,
-  open the recording in a player, or to dismiss the dialog.
-  </li>
-</ol>
-
-<h2 id="sysinfo">
-  Examining System Information
-</h2>
-<p>
-  You can view <code>dumpsys</code> output from within Android Monitor. Follow these steps:
-</p>
-
-<ol>
-  <li>
-    <a href="{@docRoot}training/basics/firstapp/running-app.html">Run your
-    app</a> from within Android Studio.
-  </li>
-
-  <li>
-    <a href="#switching">Select the device and the process</a> in the Android Monitor
-    menus, if needed.
-  </li>
-
-  <li>Click System Information <img src="{@docRoot}images/tools/am-isysteminfo.png"
-    style="vertical-align:sub;margin:0;height:17px" alt="System Information icon" /> and then a
-    menu item in the Android Monitor
-  toolbar.
-  </li>
-
-<p>
-  The menu items display different types of <code><a href=
-  "https://source.android.com/devices/tech/debug/dumpsys.html">dumpsys</a></code> output:
-</p>
-
-<ul>
-  <li>
-    <strong>Activity Manager State</strong> - <code>dumpsys activity</code>
-  </li>
-
-  <li>
-    <strong>Package Information</strong> - <code>dumpsys package</code>
-  </li>
-
-  <li>
-    <strong>Memory Usage</strong> - <code><a href=
-    "{@docRoot}tools/debugging/debugging-memory.html#ViewingAllocations">dumpsys
-    meminfo</a></code>
-  </li>
-
-  <li>
-    <strong>Memory Use Over Time</strong> - <code><a href=
-    "http://android-developers.blogspot.com/2014/01/process-stats-understanding-how-your.html">dumpsys
-    procstats</a></code>
-  </li>
-
-  <li>
-    <strong>Graphics State</strong> - <code><a href=
-    "{@docRoot}training/testing/performance.html">dumpsys gfxinfo</a></code>
-  </li>
-</ul>
-
-<p>
-  The information appears in an editable text file in the Code Editor.
-</p>
-</ol>
-
-<h2 id="terminating">
-  Terminating the App
-</h2>
-
-<p>
-  If you want to stop an app you’ve run from Android Studio, follow these steps:
-</p>
-
-<ol>
-  <li>
-    <a href="#switching">Select the device and the process</a> in the Android Monitor
-    menus, if needed.
-  </li>
-
-  <li>Click Terminate Application <img src="{@docRoot}images/tools/am-iterminate.png"
-    style="vertical-align:sub;margin:0;height:17px" alt="Terminate App icon" />.
-  </li>
-
-
-<p>
-  The process status changes to <strong>DEAD</strong> in the Processes menu. The emulator or device
-  continues to run, but the app closes. Any running monitors in Android Monitor stop.
-</p>
-</ol>
-
-<h2 id="rearranging">
-  Rearranging Android Monitor Windows
-</h2>
-
-<p>
-  You can rearrange the Android Monitor windows for optimal viewing during your tests:
-</p>
-
-<ul>
-  <li>To reorder the monitors, move the tabs back and forth.
-  </li>
-
-  <li>To move a monitor to a standalone window, grab a tab and move it to a different location on
-  the screen. Or, select <img src="{@docRoot}images/tools/am-igear.png" style="vertical-align:sub;margin:0;height:17px" alt="Gear menu icon" /> &gt; <strong>Floating Mode</strong>.
-  </li>
-
-
-  <li>To dock a standalone window, grab it and move it to the Android Monitor area. Or, select
-  <img src="{@docRoot}images/tools/am-igear.png" style="vertical-align:sub;margin:0;height:17px"
-  alt="Gear menu icon"> &gt; <strong>Floating Mode</strong> to deselect it.
-  </li>
-
-
-  <li>To combine two monitor displays together, grab a tab and move it onto another monitor.
-  </li>
-
-  <li>To hide a monitor, click the <img src="{@docRoot}images/tools/am-ihide.png" style="vertical-align:sub;margin:0;height:17px" alt="Hide icon" /> icon. To make it reappear, click the icon of
-  the monitor on the far right of the row of tabs.
-  </li>
-</ul>
-
-<h2 id="removing">
-  Removing an App from a Device
-</h2>
-
-<p>
-  To remove an app from a device you use for development, use the normal uninstall procedure on the
-  device.
-</p>
-
-<p>
-  If you run a new version of an app from Android Studio that’s been already installed on a
-  hardware device, the device displays an <em>Application Installation Failed</em> dialog. Click
-  <strong>OK</strong> to install the new version of the app.
-</p>
-
-
+<h2 id="getstarted">Get Started</h2>
+<p>To begin using Android Monitor, start with <a href=
+  "{@docRoot}tools/help/am-basics.html">Android Monitor Basics</a>.
+  </p>
 
 
diff --git a/docs/html/tools/help/sdk-manager.jd b/docs/html/tools/help/sdk-manager.jd
index aaa1930..36eac07 100755
--- a/docs/html/tools/help/sdk-manager.jd
+++ b/docs/html/tools/help/sdk-manager.jd
@@ -1,26 +1,39 @@
 page.title=SDK Manager
 @jd:body
 
+<div id="qv-wrapper">
+<div id="qv">
+  <h2>In this document</h2>
+<ol>
+  <li><a href="#updatecheck">Enabling Automatic Update Checking</a></li>
+  <li><a href="#run">Running the SDK Manager</a></li>
+  <li><a href="#Recommended">Recommended Packages</a></li>
+  <li><a href="#AddingSites">Adding New Sites</a></li>
+</ol>
+
+</div>
+</div>
 
 <p>The Android SDK Manager separates the SDK tools, platforms, and other components into packages
 for easy access and management. You can also customize which sites the SDK Manager checks for new
 or updated SDK packages and add-on tools. For example, you can configure the SDK Manager
-to automatically check for updates and notify you when an installed SDK Tools package is updated.
+to automatically check for updates and notify you when updates are available.
 When you receive such a notification, you can then quickly decide whether to download the changes.  </p>
 
-<p>By default, Android Studio does not check for Android SDK updates. To enable automatic Android
-SDK checking: </p>
+<h2 id="updatecheck">Enabling Automatic Update Checking</h2>
+<p>To enable automatic update checking: </p>
 <ol>
   <li>Choose <strong>File</strong> &gt; <strong>Settings</strong>
     &gt; <strong>Appearance & Behavior</strong> &gt; <strong>System Settings</strong>
     &gt; <strong>Updates</strong>. </li>
-  <li>Check the <strong>Automatically check updates for Android SDK</strong> checkbox and select an
+  <li>Select the <strong>Automatically check updates for</strong> checkbox and select an
     <ahref="{@docRoot}tools/studio/studio-config.html#update-channel">update channel</a>.</li>
 
 
   <li>Click <strong>OK</strong> or <strong>Apply</strong> to enable the update checking. </li>
 </ol>
 
+<h2 id="run">Running the SDK Manager</h2>
 <p>You can launch the SDK Manager in one of the following ways:</p>
 <ul>
   <li>From the Android Studio <strong>File</strong> menu:  <strong>File</strong> &gt;
@@ -32,13 +45,17 @@
     (<img src="{@docRoot}images/tools/sdk-manager-studio.png" style="vertical-align:sub;margin:0;height:17px" alt="" />)
     in the menu bar.  </li>
 </ul>
+<p>The SDK Manager appears.</p>
+<img src="{@docRoot}images/tools/studio-sdk-manager-packages.png" alt="" />
+<p class="img-caption"><strong>Figure 1.</strong> The Android SDK Manager shows the
+SDK platforms and packages that are available and installed along with the SDK update sites.</p>
 
 <p class="note"><strong>Tip:</strong> The standalone SDK Manager is still available from the
-command line, but we recommend it only for use with standalone SDK installations.</p>
+command line, but we recommend it for use with standalone SDK installations only.</p>
 
-<p>By default, the SDK Manager installs the latest packages and tools. Click the checkbox next to
+<p>Click the checkbox next to
 each additional SDK platform and tool that you want to install. Clear the
-checkbox to uninstall a SDK platform or tool. Click <strong>Apply</strong> or <strong>OK</strong>
+checkbox to uninstall an SDK platform or tool. Click <strong>Apply</strong> or <strong>OK</strong>
 to update the packages and tools. </p>
 
 <p class="note"><strong>Tip:</strong> When an update is available for an installed
@@ -49,16 +66,14 @@
 (<img src="{@docRoot}images/tools/studio-sdk-removal-icon.png" style="vertical-align:sub;margin:0;height:17px" alt="" />) appears next to the checkbox to
 indicate pending removals.</p>
 
-<p>Click the <em>SDK Update Sites</em> tab to manage which SDK sites Android Studio checks for
+<p>Click the <strong>SDK Update Sites</strong> tab to manage which SDK sites Android Studio checks for
 tool and add-on updates. </p>
 
-<img src="{@docRoot}images/tools/studio-sdk-manager-packages.png" alt="" />
-<p class="img-caption"><strong>Figure 1.</strong> The Android SDK Manager shows the
-SDK platforms and packages that are available and installed along with the SDK update sites.</p>
 
-<p>There are several different packages available for the Android SDK. The table below describes
+
+<p>There are several different packages available for the Android SDK. The following section describes
 most of the available packages and where they're located in your SDK directory
-once you download them.</p>
+after you download them.</p>
 
 
 
@@ -76,43 +91,44 @@
     Be sure to respond to the Android Studio update prompts to keep your SDK Platform-tools
     up-to-date.</dd>
   <dt>SDK Platform</dt>
-  <dd><strong>Required.</strong><em> At least one platform</em> is required in your
-environment so you're able to compile your application. In order to provide the best user experience
+  <dd><strong>Required.</strong> At least one platform is required in your
+environment to be able to compile your application. To provide the best user experience
 on the latest devices, we recommend that you use the latest platform version as your build target.
 You'll still be able to run your app on older versions, but you must build against the latest
 version in order to use new features when running on devices with the latest version of Android.
-  <p>The SDK Manager downloads the latest Android version. It also downloads the earliest version
-  of Android (Android 2.2 (API level 8)) that we recommend that your app support. </p></dd>
+  </dd>
   <dt>System Image</dt>
   <dd>Recommended. Although you might have one or more Android-powered devices on which to test
  your app, it's unlikely you have a device for every version of Android your app supports. It's
-a good practice to download system images for all versions of Android your app supports and test
-your app running on them with the
-<a href="{@docRoot}tools/devices/emulator.html">Android emulator</a>. Each SDK platform package
-contains the supported system images. Click <strong>Show Package Details</strong> to display the available
+a good practice to download system images for all versions of Android that your
+app supports and then test
+your app against these Android versions by using the
+<a href="{@docRoot}tools/devices/emulator.html">Android Emulator</a>. Click <strong>Show Package Details</strong> to display the available
 system images for each available platform. You can also download system images when creating
 Android Virtual Devices (AVDs) in the
 <a href="{@docRoot}tools/help/avd-manager.html">AVD Manager</a>. </dd>
 
-  <dt>Android Support Library</dt>
-  <dd>Recommended. Includes a static library that provides an extended set of
-  APIs that are compatible with most versions of Android. It's required for
+
+  <dt>Android Support Repository</dt>
+  <dd>Recommended. Includes a local Maven repository for the Android Data
+  Binding Library, Android Testing Support Library, and Android Support
+  Libraries. The Android Support Libraries provide an extended set of
+  APIs that are compatible with most versions of Android. They're required for
   products such as <a href="{@docRoot}wear/index.html">Android Wear</a>, <a
   href="{@docRoot}tv/index.html">Android TV</a>, and <a
   href="https://developers.google.com/cast/">Google Cast</a>. For more
-  information, read <a href="{@docRoot}tools/support-library/index.html">Support
-  Library</a>.
-  </dd>
-
-  <dt>Android Support Repository</dt>
-  <dd>Recommended. Includes local Maven repository for Support libraries.</dd>
+  information about each of the libraries in the Android Support Repository,
+  see <a href="{@docRoot}tools/data-binding/guide.html">Data Binding Guide</a>,
+  <a href="{@docRoot}tools/testing-support-library/index.html">Testing Support
+  Library</a>, and <a href="{@docRoot}tools/support-library/index.html">Support
+  Library</a>.</dd>
 
   <dt>Google Play services</dt>
   <dd>Recommended. Includes the Google Play services client library, which
-  provides a variety of features and services for your 
+  provides a variety of features and services for your
   apps, such as <a
   href="https://developers.google.com/identity/sign-in/android/">Google
-  sign-in</a>,<a
+  sign-in</a>, <a
   href="https://developers.google.com/maps/documentation/android-api/">Google
   Maps</a>, <a href="https://developers.google.com/games/services/">Games
   achievements and leaderboards</a>, and much more.</dd>
@@ -122,45 +138,44 @@
 
 
 <p class="note"><strong>Tip:</strong> For easy access to the SDK tools from a command line, add the
-location of the SDK's <code>tools/</code> and
+location of the SDK <code>tools/</code> and
 <code>platform-tools</code> to your <code>PATH</code> environment variable.</p>
 
 
-<p>The above list is not comprehensive and you can <a
+<p>The previous list is not comprehensive and you can <a
 href="#AddingSites">add new sites</a> to download additional packages from third parties.</p>
 
 <p>In some cases, an SDK package may require a specific minimum revision of
-another package or SDK tool.
-The development tools will notify you with warnings if there is dependency that you need to
-address. The Android SDK Manager also enforces dependencies by requiring any
-packages that are needed by those you have selected.</p>
+another package or SDK tool. The SDK Manager automatically notifies you of any
+dependencies and downloads the required packages or tools.
+In addition, development tools notify you if there are dependencies that you need to
+address. </p>
 
 
 
 <h2 id="AddingSites">Adding New Sites</h2>
 
-<p>The <em>SDK Update Sites</em> tab displays the sites that Android Studio checks for Android SDK
-and third-party updates. You can add other sites that host their own Android SDK add-ons, then
+<p>The <strong>SDK Update Sites</strong> tab displays the sites that Android Studio checks for Android SDK
+and third-party updates. You can add other sites that host their own Android SDK add-ons, and then
 download the SDK add-ons from those sites.</p>
 
 <p>For example, a mobile carrier or device manufacturer might offer additional
-API libraries that are supported by their own Android-powered devices. In order
-to develop using their libraries, you must install their Android SDK add-on, if it's not already
-available as a <em>third-party add-on</em>. </p>
+API libraries that are supported by their own Android-powered devices.
+To develop using their libraries, you must install their Android SDK add-on, if it's not already
+available as a third-party add-on.</p>
 
 <p>If a carrier or device manufacturer has hosted an SDK add-on repository file
 on their website, follow these steps to add their site to the Android SDK Manager:</p>
 
 <ol>
   <li>Click the <strong>SDK Update Sites</strong> tab.</li>
-  <li>Click the <strong>Add</strong> icon in the tools area and enter the name and URL of the
-    <code>add-on</code> site.</li>
-  <li>Click <strong>OK</strong>.</li>
-  <li>Make sure the checkbox is checked in the <em>Enabled</em> column.</li>
-  <li>Click <strong>OK</strong> or <strong>Apply</strong>.</li>
-</ol>
-<p>Any SDK packages available from the site appear in the <em>SDK Platforms</em> or
-<em>SDK Tools</em> tabs.</p>
+  <li>Click <strong>Add</strong> <img src="{@docRoot}images/tools/sdk-iadd.png" style="vertical-align:sub;margin:0;height:17px" alt="" />. </li>
+  <li>Type the name and URL of the
+    add-on site, and then cick <strong>OK</strong>.</li>
+  <li>Make sure the checkbox is selected in the <strong>Enabled</strong> column.</li>
 
+<p>Any SDK packages available from the site appear in the <strong>SDK Platforms</strong> or
+<strong>SDK Tools</strong> tabs.</p>
+</ol>
 
 
diff --git a/docs/html/tools/help/thumbnails/am-androidmon2.png b/docs/html/tools/help/thumbnails/am-androidmon2.png
new file mode 100644
index 0000000..a4a7571
--- /dev/null
+++ b/docs/html/tools/help/thumbnails/am-androidmon2.png
Binary files differ
diff --git a/docs/html/tools/help/thumbnails/am-cpumon.png b/docs/html/tools/help/thumbnails/am-cpumon.png
new file mode 100644
index 0000000..59908c8
--- /dev/null
+++ b/docs/html/tools/help/thumbnails/am-cpumon.png
Binary files differ
diff --git a/docs/html/tools/help/thumbnails/am-cpumon2.png b/docs/html/tools/help/thumbnails/am-cpumon2.png
new file mode 100644
index 0000000..6ac6e02
--- /dev/null
+++ b/docs/html/tools/help/thumbnails/am-cpumon2.png
Binary files differ
diff --git a/docs/html/tools/help/thumbnails/am-gc2.png b/docs/html/tools/help/thumbnails/am-gc2.png
new file mode 100644
index 0000000..a5e8b6e
--- /dev/null
+++ b/docs/html/tools/help/thumbnails/am-gc2.png
Binary files differ
diff --git a/docs/html/tools/help/thumbnails/am-gpumon.png b/docs/html/tools/help/thumbnails/am-gpumon.png
new file mode 100644
index 0000000..a414fe5
--- /dev/null
+++ b/docs/html/tools/help/thumbnails/am-gpumon.png
Binary files differ
diff --git a/docs/html/tools/help/thumbnails/am-gpumon2.png b/docs/html/tools/help/thumbnails/am-gpumon2.png
new file mode 100644
index 0000000..5cf51d9
--- /dev/null
+++ b/docs/html/tools/help/thumbnails/am-gpumon2.png
Binary files differ
diff --git a/docs/html/tools/help/thumbnails/am-logcatmon2.png b/docs/html/tools/help/thumbnails/am-logcatmon2.png
new file mode 100644
index 0000000..5635935
--- /dev/null
+++ b/docs/html/tools/help/thumbnails/am-logcatmon2.png
Binary files differ
diff --git a/docs/html/tools/help/thumbnails/am-memorymon.png b/docs/html/tools/help/thumbnails/am-memorymon.png
new file mode 100644
index 0000000..0fefb27
--- /dev/null
+++ b/docs/html/tools/help/thumbnails/am-memorymon.png
Binary files differ
diff --git a/docs/html/tools/help/thumbnails/am-networkmon.png b/docs/html/tools/help/thumbnails/am-networkmon.png
new file mode 100644
index 0000000..db9c647
--- /dev/null
+++ b/docs/html/tools/help/thumbnails/am-networkmon.png
Binary files differ
diff --git a/docs/html/tools/help/thumbnails/am_alloctracker.png b/docs/html/tools/help/thumbnails/am_alloctracker.png
new file mode 100644
index 0000000..b94713d
--- /dev/null
+++ b/docs/html/tools/help/thumbnails/am_alloctracker.png
Binary files differ
diff --git a/docs/html/tools/help/thumbnails/am_androidmon.png b/docs/html/tools/help/thumbnails/am_androidmon.png
new file mode 100644
index 0000000..6b05230
--- /dev/null
+++ b/docs/html/tools/help/thumbnails/am_androidmon.png
Binary files differ
diff --git a/docs/html/tools/help/thumbnails/am_cpumon.png b/docs/html/tools/help/thumbnails/am_cpumon.png
new file mode 100644
index 0000000..c8c0415
--- /dev/null
+++ b/docs/html/tools/help/thumbnails/am_cpumon.png
Binary files differ
diff --git a/docs/html/tools/help/thumbnails/am_gpumon.png b/docs/html/tools/help/thumbnails/am_gpumon.png
new file mode 100644
index 0000000..e453e7d
--- /dev/null
+++ b/docs/html/tools/help/thumbnails/am_gpumon.png
Binary files differ
diff --git a/docs/html/tools/help/thumbnails/am_hprofviewer.png b/docs/html/tools/help/thumbnails/am_hprofviewer.png
new file mode 100644
index 0000000..342590f
--- /dev/null
+++ b/docs/html/tools/help/thumbnails/am_hprofviewer.png
Binary files differ
diff --git a/docs/html/tools/help/thumbnails/am_iscreencapture.png b/docs/html/tools/help/thumbnails/am_iscreencapture.png
new file mode 100644
index 0000000..68135a7
--- /dev/null
+++ b/docs/html/tools/help/thumbnails/am_iscreencapture.png
Binary files differ
diff --git a/docs/html/tools/help/thumbnails/am_isysteminfo.png b/docs/html/tools/help/thumbnails/am_isysteminfo.png
new file mode 100644
index 0000000..37d77db
--- /dev/null
+++ b/docs/html/tools/help/thumbnails/am_isysteminfo.png
Binary files differ
diff --git a/docs/html/tools/help/thumbnails/am_ivideo.png b/docs/html/tools/help/thumbnails/am_ivideo.png
new file mode 100644
index 0000000..901eaf1
--- /dev/null
+++ b/docs/html/tools/help/thumbnails/am_ivideo.png
Binary files differ
diff --git a/docs/html/tools/help/thumbnails/am_logcatmon.png b/docs/html/tools/help/thumbnails/am_logcatmon.png
new file mode 100644
index 0000000..ca7063c
--- /dev/null
+++ b/docs/html/tools/help/thumbnails/am_logcatmon.png
Binary files differ
diff --git a/docs/html/tools/help/thumbnails/am_methodtrace.png b/docs/html/tools/help/thumbnails/am_methodtrace.png
new file mode 100644
index 0000000..8d5ca4e
--- /dev/null
+++ b/docs/html/tools/help/thumbnails/am_methodtrace.png
Binary files differ
diff --git a/docs/html/tools/help/thumbnails/am_networkmon2.png b/docs/html/tools/help/thumbnails/am_networkmon2.png
new file mode 100644
index 0000000..f55f853
--- /dev/null
+++ b/docs/html/tools/help/thumbnails/am_networkmon2.png
Binary files differ
diff --git a/docs/html/tools/help/thumbnails/am_screenshot.png b/docs/html/tools/help/thumbnails/am_screenshot.png
new file mode 100644
index 0000000..66afff9
--- /dev/null
+++ b/docs/html/tools/help/thumbnails/am_screenshot.png
Binary files differ
diff --git a/docs/html/tools/help/thumbnails/am_sysinfo.png b/docs/html/tools/help/thumbnails/am_sysinfo.png
new file mode 100644
index 0000000..9b5cd17
--- /dev/null
+++ b/docs/html/tools/help/thumbnails/am_sysinfo.png
Binary files differ
diff --git a/docs/html/tools/help/thumbnails/am_video.png b/docs/html/tools/help/thumbnails/am_video.png
new file mode 100644
index 0000000..209cb0c
--- /dev/null
+++ b/docs/html/tools/help/thumbnails/am_video.png
Binary files differ
diff --git a/docs/html/tools/revisions/gradle-plugin.jd b/docs/html/tools/revisions/gradle-plugin.jd
index 20492f7..f77cfd6 100644
--- a/docs/html/tools/revisions/gradle-plugin.jd
+++ b/docs/html/tools/revisions/gradle-plugin.jd
@@ -73,7 +73,7 @@
   Structure</strong> &gt; <strong>Project</strong> menu in Android Studio, or
   the top-level <code>build.gradle</code> file. The plugin version applies to
   all modules built in that Android Studio project. The following example sets
-  the Android Plugin for Gradle to version 2.0.0 from the
+  the Android Plugin for Gradle to version 2.1.0 from the
   <code>build.gradle</code> file:
 </p>
 
@@ -81,7 +81,7 @@
 buildscript {
   ...
   dependencies {
-    classpath 'com.android.tools.build:gradle:2.0.0'
+    classpath 'com.android.tools.build:gradle:2.1.0'
   }
 }
 </pre>
@@ -138,6 +138,108 @@
 <div class="toggle-content opened">
   <p><a href="#" onclick="return toggleContent(this)">
     <img src="{@docRoot}assets/images/styles/disclosure_up.png" class="toggle-content-img"
+      alt=""/>Android Plugin for Gradle, Revision 2.1.0</a> <em>(April 2016)</em>
+  </p>
+
+  <div class="toggle-content-toggleme">
+    <dl>
+    <dt>Dependencies:</dt>
+
+    <dd>
+      <ul>
+        <li>Gradle 2.10 or higher.
+        </li>
+
+        <li>
+          <a href="{@docRoot}tools/revisions/build-tools.html">Build Tools 23.0.2</a>
+          or higher.
+        </li>
+      </ul>
+    </dd>
+
+    <dt>New:</dt>
+    <dd>
+      <ul>
+        <li>Added support for the N Developer Preview, JDK 8, and <a href=
+        "{@docRoot}preview/j8-jack.html">Java 8 language features</a> using the Jack
+        toolchain. To find out more, read the <a href=
+        "{@docRoot}preview/overview.html">N Preview guide</a>.
+
+          <p class="note">
+            <strong>Note:</strong> <a href=
+            "{@docRoot}tools/building/building-studio.html#instant-run">Instant
+            Run</a> does not currently work with Jack and will be disabled while
+            using the new toolchain. You only need to use Jack if you are developing
+            for the N Preview and want to use the supported Java 8 language features.
+          </p>
+        </li>
+
+        <li>Added default support for incremental Java compilation to reduce
+        compilation time during development. It does this by only recompiling
+        portions of the source that have changed or need to be recompiled. To disable
+        this feature, add the following code to your module-level
+        <code>build.gradle</code> file:
+
+<pre>
+android {
+  ...
+  compileOptions {
+    incremental false
+  }
+}
+</pre>
+        </li>
+
+        <li>
+          <p>
+          Added support for dexing-in-process which performs dexing within the build
+          process rather than in a separate, external VM processes. This not only makes
+          incremental builds faster, but also speeds up full builds. The feature is
+          enabled by default for projects that have set the Gradle daemon's maximum heap
+          size to at least 2048 MB. You can do this by including the following in your
+          project's <code>gradle.properties</code> file:
+
+<pre>
+org.gradle.jvmargs = -Xmx2048m
+</pre>
+          </p>
+
+          <p>
+          If you have defined a value for <a class="external-link" href=
+          "http://google.github.io/android-gradle-dsl/current/com.android.build.gradle.internal.dsl.DexOptions.html#com.android.build.gradle.internal.dsl.DexOptions:javaMaxHeapSize">
+          <code>javaMaxHeapSize</code></a> in your module-level <code>build.gradle</code>
+          file, you need to set <code>org.gradle.jvmargs</code> to the value of
+          <code>javaMaxHeapSize</code> + 1024 MB. For example, if you have set
+          <code>javaMaxHeapSize</code> to "2048m", you need to add the following to your
+          project's <code>gradle.properties</code> file:
+
+<pre>
+org.gradle.jvmargs = -Xmx3072m
+</pre>
+          </p>
+
+          <p>
+            To disable dexing-in-process, add the following code to your module-level
+            <code>build.gradle</code> file:
+
+<pre>
+android {
+  ...
+  dexOptions {
+      dexInProcess false
+  }
+}
+</pre>
+          </p>
+        </li>
+      </ul>
+    </dd>
+  </div>
+</div>
+
+<div class="toggle-content closed">
+  <p><a href="#" onclick="return toggleContent(this)">
+    <img src="{@docRoot}assets/images/styles/disclosure_down.png" class="toggle-content-img"
       alt=""/>Android Plugin for Gradle, Revision 2.0.0</a> <em>(April 2016)</em>
   </p>
 
diff --git a/docs/html/tools/revisions/studio.jd b/docs/html/tools/revisions/studio.jd
index 9579ae2..5747f52 100755
--- a/docs/html/tools/revisions/studio.jd
+++ b/docs/html/tools/revisions/studio.jd
@@ -49,9 +49,52 @@
 <p>The sections below provide notes about successive releases of
 Android Studio, as denoted by revision number. </p>
 
+
 <div class="toggle-content open">
   <p><a href="#" onclick="return toggleContent(this)">
     <img src="{@docRoot}assets/images/styles/disclosure_up.png" class="toggle-content-img"
+      alt=""/>Android Studio v2.1.0</a> <em>(April 2016)</em>
+  </p>
+  <div class="toggle-content-toggleme">
+
+<p>The primary changes in this update provide support for development with the
+<a href="{@docRoot}preview/index.html">Android N Preview</a>.</p>
+
+<p>The Android N platform adds support for <a
+href="{@docRoot}preview/j8-jack.html">Java 8 language features</a>, which
+require a new experimental compiler called Jack. The latest version of Jack is
+currently supported only in Android Studio 2.1. So if you want to use Java 8
+language features, you need to use Android Studio 2.1 to build your app.</p>
+
+<p class="note"><strong>Note:</strong> <a
+href="{@docRoot}tools/building/building-studio.html#instant-run">Instant Run</a>
+is disabled when you enable the Jack compiler because they currently are not
+compatible.</p>
+
+<p>Although Android Studio 2.1 is now stable, the Jack compiler is still
+experimental and you must enable it with <a
+href="{@docRoot}preview/j8-jack.html#configuration">the <code>jackOptions</code>
+property</a> in your <code>build.gradle</code> file.</p>
+
+<p>Other than the changes to support the N Preview, Android Studio 2.1
+includes minor bug fixes and the following enhancements:</p>
+    <ul>
+      <li>The Java-aware C++ debugger is now enabled by default when you're
+using an N device or emulator and select <strong>Native</strong> debugger mode
+(in the <strong>Debugger</strong> tab for your run/debug configuration).</li>
+    </ul>
+    <p>For other build enhancements, including incremental Java compilation
+    and dexing-in-process, update your <a
+href="{@docRoot}tools/revisions/gradle-plugin.html">Android Plugin for
+Gradle</a> to version 2.1.0.</p>
+  </div>
+</div>
+
+
+
+<div class="toggle-content closed">
+  <p><a href="#" onclick="return toggleContent(this)">
+    <img src="{@docRoot}assets/images/styles/disclosure_down.png" class="toggle-content-img"
       alt=""/>Android Studio v2.0.0</a> <em>(April 2016)</em>
   </p>
 
diff --git a/docs/html/tools/tools_toc.cs b/docs/html/tools/tools_toc.cs
index c390523..73d4ff3 100644
--- a/docs/html/tools/tools_toc.cs
+++ b/docs/html/tools/tools_toc.cs
@@ -147,6 +147,9 @@
         <div class="nav-section-header">
           <a href="<?cs var:toroot ?>tools/help/android-monitor.html">Android Monitor</a></div>
         <ul>
+          <li><a href="<?cs var:toroot ?>tools/help/am-basics.html"><span
+            class="en">Android Monitor Basics</span></a>
+          </li>
           <li><a href="<?cs var:toroot ?>tools/help/am-logcat.html"><span
             class="en">logcat Monitor</span></a>
           </li>
@@ -162,6 +165,25 @@
           <li><a href="<?cs var:toroot ?>tools/help/am-network.html"><span
             class="en">Network Monitor</span></a>
           </li>
+            <li><a href="<?cs var:toroot ?>tools/help/am-hprof.html"><span
+            class="en">HPROF Viewer and Analyzer</span></a>
+           </li>
+            <li><a href="<?cs var:toroot ?>tools/help/am-allocation.html"><span
+            class="en">Allocation Tracker</span></a>
+             </li>
+            <li><a href="<?cs var:toroot ?>tools/help/am-methodtrace.html"><span
+            class="en">Method Trace</span></a>
+            </li>
+            <li><a href="<?cs var:toroot ?>tools/help/am-sysinfo.html"><span
+            class="en">System Information</span></a>
+            </li>
+            <li><a href="<?cs var:toroot ?>tools/help/am-screenshot.html"><span
+            class="en">Screen Capture</span></a>
+            </li>
+            <li><a href="<?cs var:toroot ?>tools/help/am-video.html"><span
+            class="en">Video Capture</span></a>
+            </li>
+          </li>
         </ul>
       </li>
 
@@ -217,6 +239,7 @@
       </li>
 
       <li><a href="<?cs var:toroot ?>tools/help/hprof-conv.html">hprof-conv</a></li>
+      <li><a href="<?cs var:toroot ?>tools/help/image-asset-studio.html">Image Asset Studio</a></li>
       <li><a href="<?cs var:toroot ?>tools/help/jobb.html">jobb</a></li>
       <li><a href="<?cs var:toroot ?>tools/help/lint.html">lint</span></a></li>
       <li class="nav-section">
diff --git a/docs/html/training/_book.yaml b/docs/html/training/_book.yaml
index cd4df43..8f8fab2 100644
--- a/docs/html/training/_book.yaml
+++ b/docs/html/training/_book.yaml
@@ -4,8 +4,9 @@
   section:
   - title: Building Your First App
     path: /training/basics/firstapp/index.html
-    custom_link_attributes:
-    - description="After you've installed the Android SDK, start with this class to learn the basics about Android app development."
+    path_attributes:
+    - name: description
+      value: After you've installed the Android SDK, start with this class to learn the basics about Android app development.
     section:
     - title: Creating an Android Project
       path: /training/basics/firstapp/creating-project.html
@@ -17,8 +18,9 @@
       path: /training/basics/firstapp/starting-activity.html
   - title: Supporting Different Devices
     path: /training/basics/supporting-devices/index.html
-    custom_link_attributes:
-    - description="How to build your app with alternative resources that provide an optimized user experience on multiple device form factors using a single APK."
+    path_attributes:
+    - name: description
+      value: How to build your app with alternative resources that provide an optimized user experience on multiple device form factors using a single APK.
     section:
     - title: Supporting Different Languages
       path: /training/basics/supporting-devices/languages.html
@@ -28,137 +30,215 @@
       path: /training/basics/supporting-devices/platforms.html
   - title: Managing the Activity Lifecycle
     path: /training/basics/activity-lifecycle/index.html
-    custom_link_attributes:
-    - ja-lang="アクティビティのライフサイクル 管理"
-    - ko-lang="액티비티 수명 주기 관리하기"
-    - pt-br-lang="Como gerenciar o ciclo de vida da atividade"
-    - ru-lang="Управление жизненным циклом операций"
-    - zh-cn-lang="管理活动生命周期"
-    - zh-tw-lang="管理應用行為顯示生命週期"
-    - description="How Android activities live and die and how to create a seamless user experience by implementing lifecycle callback methods."
+    path_attributes:
+    - name: ja-lang
+      value: アクティビティのライフサイクル 管理
+    - name: ko-lang
+      value: 액티비티 수명 주기 관리하기
+    - name: pt-br-lang
+      value: Como gerenciar o ciclo de vida da atividade
+    - name: ru-lang
+      value: Управление жизненным циклом операций
+    - name: zh-cn-lang
+      value: 管理活动生命周期
+    - name: zh-tw-lang
+      value: 管理應用行為顯示生命週期
+    - name: description
+      value: How Android activities live and die and how to create a seamless user experience by implementing lifecycle callback methods.
     section:
     - title: Starting an Activity
       path: /training/basics/activity-lifecycle/starting.html
-      custom_link_attributes:
-      - ja-lang="アクティビティを開始する"
-      - ko-lang="액티비티 시작하기"
-      - pt-br-lang="Iniciando uma atividade"
-      - ru-lang="Запуск операции"
-      - zh-cn-lang="开始活动"
-      - zh-tw-lang="啟動應用行為顯示"
+      path_attributes:
+      - name: ja-lang
+        value: アクティビティを開始する
+      - name: ko-lang
+        value: 액티비티 시작하기
+      - name: pt-br-lang
+        value: Iniciando uma atividade
+      - name: ru-lang
+        value: Запуск операции
+      - name: zh-cn-lang
+        value: 开始活动
+      - name: zh-tw-lang
+        value: 啟動應用行為顯示
     - title: Pausing and Resuming an Activity
       path: /training/basics/activity-lifecycle/pausing.html
     - title: Stopping and Restarting an Activity
       path: /training/basics/activity-lifecycle/stopping.html
-      custom_link_attributes:
-      - ja-lang="アクティビティの一時停止と再開"
-      - ko-lang="액티비티 일시정지 및 재개하기"
-      - pt-br-lang="Pausando e reiniciando uma atividade"
-      - ru-lang="Приостановка и возобновление операции"
-      - zh-cn-lang="暂停和继续活动"
-      - zh-tw-lang="暫停並繼續應用行為顯示"
+      path_attributes:
+      - name: ja-lang
+        value: アクティビティの一時停止と再開
+      - name: ko-lang
+        value: 액티비티 일시정지 및 재개하기
+      - name: pt-br-lang
+        value: Pausando e reiniciando uma atividade
+      - name: ru-lang
+        value: Приостановка и возобновление операции
+      - name: zh-cn-lang
+        value: 暂停和继续活动
+      - name: zh-tw-lang
+        value: 暫停並繼續應用行為顯示
     - title: Recreating an Activity
       path: /training/basics/activity-lifecycle/recreating.html
-      custom_link_attributes:
-      - ja-lang="アクティビティを再作成する"
-      - ko-lang="액티비티 재생성하기"
-      - pt-br-lang="Recriando uma atividade"
-      - ru-lang="Воссоздание операции"
-      - zh-cn-lang="重新创建活动"
-      - zh-tw-lang="重新建立應用行為顯示"
+      path_attributes:
+      - name: ja-lang
+        value: アクティビティを再作成する
+      - name: ko-lang
+        value: 액티비티 재생성하기
+      - name: pt-br-lang
+        value: Recriando uma atividade
+      - name: ru-lang
+        value: Воссоздание операции
+      - name: zh-cn-lang
+        value: 重新创建活动
+      - name: zh-tw-lang
+        value: 重新建立應用行為顯示
   - title: Building a Dynamic UI with Fragments
     path: /training/basics/fragments/index.html
-    custom_link_attributes:
-    - description="How to build a user interface for your app that is flexible enough to present multiple UI components on large screens and a more constrained set of UI components on smaller screens—essential for building a single APK for both phones and tablets."
+    path_attributes:
+    - name: description
+      value: How to build a user interface for your app that is flexible enough to present multiple UI components on large screens and a more constrained set of UI components on smaller screens—essential for building a single APK for both phones and tablets.
     section:
     - title: Creating a Fragment
       path: /training/basics/fragments/creating.html
     - title: Building a Flexible UI
       path: /training/basics/fragments/fragment-ui.html
-      custom_link_attributes:
-      - zh-cn-lang="构建灵活的界面"
+      path_attributes:
+      - name: zh-cn-lang
+        value: 构建灵活的界面
     - title: Communicating with Other Fragments
       path: /training/basics/fragments/communicating.html
   - title: Saving Data
     path: /training/basics/data-storage/index.html
-    custom_link_attributes:
-    - ja-lang="データの保存"
-    - ko-lang="데이터 저장하기"
-    - pt-br-lang="Salvando dados"
-    - ru-lang="Сохранение данных"
-    - zh-cn-lang="保存数据"
-    - zh-tw-lang="儲存資料"
-    - description="How to save data on the device, whether it's temporary files, downloaded app assets, user media, structured data, or something else."
+    path_attributes:
+    - name: ja-lang
+      value: データの保存
+    - name: ko-lang
+      value: 데이터 저장하기
+    - name: pt-br-lang
+      value: Salvando dados
+    - name: ru-lang
+      value: Сохранение данных
+    - name: zh-cn-lang
+      value: 保存数据
+    - name: zh-tw-lang
+      value: 儲存資料
+    - name: description
+      value: How to save data on the device, whether it's temporary files, downloaded app assets, user media, structured data, or something else.
     section:
     - title: Saving Key-Value Sets
       path: /training/basics/data-storage/shared-preferences.html
-      custom_link_attributes:
-      - ja-lang="キー値セットを保存する"
-      - ko-lang="키-값 세트 저장하기"
-      - pt-br-lang="Salvando conjuntos de valor-chave"
-      - ru-lang="Сохранение наборов \"ключ-значение\""
-      - zh-cn-lang="保存键值集"
-      - zh-tw-lang="儲存索引鍵值組"
+      path_attributes:
+      - name: ja-lang
+        value: キー値セットを保存する
+      - name: ko-lang
+        value: 키-값 세트 저장하기
+      - name: pt-br-lang
+        value: Salvando conjuntos de valor-chave
+      - name: ru-lang
+        value: Сохранение наборов "ключ-значение"
+      - name: zh-cn-lang
+        value: 保存键值集
+      - name: zh-tw-lang
+        value: 儲存索引鍵值組
     - title: Saving Files
       path: /training/basics/data-storage/files.html
-      custom_link_attributes:
-      - ja-lang="ファイルを保存する"
-      - ko-lang="파일 저장하기"
-      - pt-br-lang="Salvando arquivos"
-      - ru-lang="Сохранение файлов"
-      - zh-cn-lang="保存文件"
-      - zh-tw-lang="儲存檔案"
+      path_attributes:
+      - name: ja-lang
+        value: ファイルを保存する
+      - name: ko-lang
+        value: 파일 저장하기
+      - name: pt-br-lang
+        value: Salvando arquivos
+      - name: ru-lang
+        value: Сохранение файлов
+      - name: zh-cn-lang
+        value: 保存文件
+      - name: zh-tw-lang
+        value: 儲存檔案
     - title: Saving Data in SQL Databases
       path: /training/basics/data-storage/databases.html
-      custom_link_attributes:
-      - ja-lang="SQL データベースにデータを保存する"
-      - ko-lang="SQL 데이터베이스에 데이터 저장하기"
-      - pt-br-lang="Salvando dados em bancos de dados do SQL"
-      - ru-lang="Сохранение данных в базах данных SQL"
-      - zh-cn-lang="在 SQL 数据库中保存数据"
-      - zh-tw-lang="在 SQL 資料庫中儲存資料"
+      path_attributes:
+      - name: ja-lang
+        value: SQL データベースにデータを保存する
+      - name: ko-lang
+        value: SQL 데이터베이스에 데이터 저장하기
+      - name: pt-br-lang
+        value: Salvando dados em bancos de dados do SQL
+      - name: ru-lang
+        value: Сохранение данных в базах данных SQL
+      - name: zh-cn-lang
+        value: 在 SQL 数据库中保存数据
+      - name: zh-tw-lang
+        value: 在 SQL 資料庫中儲存資料
   - title: Interacting with Other Apps
     path: /training/basics/intents/index.html
-    custom_link_attributes:
-    - ja-lang="他のアプリとの相互操作"
-    - ko-lang="액티비티 수명 주기 관리하기"
-    - pt-br-lang="Interagindo com outros aplicativos"
-    - ru-lang="Взаимодействие с другими приложениями"
-    - zh-cn-lang="与其他应用交互"
-    - zh-tw-lang="與其他應用程式互動"
-    - description="How to build a user experience that leverages other apps available on the device to perform advanced user tasks, such as capture a photo or view an address on a map."
+    path_attributes:
+    - name: ja-lang
+      value: 他のアプリとの相互操作
+    - name: ko-lang
+      value: 액티비티 수명 주기 관리하기
+    - name: pt-br-lang
+      value: Interagindo com outros aplicativos
+    - name: ru-lang
+      value: Взаимодействие с другими приложениями
+    - name: zh-cn-lang
+      value: 与其他应用交互
+    - name: zh-tw-lang
+      value: 與其他應用程式互動
+    - name: description
+      value: How to build a user experience that leverages other apps available on the device to perform advanced user tasks, such as capture a photo or view an address on a map.
     section:
     - title: Sending the User to Another App
       path: /training/basics/intents/sending.html
-      custom_link_attributes:
-      - ja-lang="別のアプリにユーザーを送る"
-      - ko-lang="다른 앱으로 사용자 보내기"
-      - pt-br-lang="Enviando o usuário para outro aplicativo"
-      - ru-lang="Направление пользователя в другое приложение"
-      - zh-cn-lang="向另一个应用发送用户"
-      - zh-tw-lang="將使用者傳送至其他應用程式"
+      path_attributes:
+      - name: ja-lang
+        value: 別のアプリにユーザーを送る
+      - name: ko-lang
+        value: 다른 앱으로 사용자 보내기
+      - name: pt-br-lang
+        value: Enviando o usuário para outro aplicativo
+      - name: ru-lang
+        value: Направление пользователя в другое приложение
+      - name: zh-cn-lang
+        value: 向另一个应用发送用户
+      - name: zh-tw-lang
+        value: 將使用者傳送至其他應用程式
     - title: Getting a Result from the Activity
       path: /training/basics/intents/result.html
-      custom_link_attributes:
-      - ja-lang="アクティビティから結果を取得する"
-      - ko-lang="액티비티로부터 결과 가져오기"
-      - pt-br-lang="Obtendo resultados de uma atividade"
-      - ru-lang="Получение результата операции"
-      - zh-cn-lang="获取活动的结果"
-      - zh-tw-lang="從應用行為顯示取得結果"
+      path_attributes:
+      - name: ja-lang
+        value: アクティビティから結果を取得する
+      - name: ko-lang
+        value: 액티비티로부터 결과 가져오기
+      - name: pt-br-lang
+        value: Obtendo resultados de uma atividade
+      - name: ru-lang
+        value: Получение результата операции
+      - name: zh-cn-lang
+        value: 获取活动的结果
+      - name: zh-tw-lang
+        value: 從應用行為顯示取得結果
     - title: Allowing Other Apps to Start Your Activity
       path: /training/basics/intents/filters.html
-      custom_link_attributes:
-      - ja-lang="他のアプリからのアクティビティの開始を許可する"
-      - ko-lang="다른 앱이 자신의 액티비티를 시작하도록 허용하기"
-      - pt-br-lang="Permitindo que outros aplicativos iniciem sua atividade"
-      - ru-lang="Разрешение другим приложениям на запуск вашей операции"
-      - zh-cn-lang="允许其他应用开始您的活动"
-      - zh-tw-lang="允許其他應用程式啟動您的應用行為顯示"
+      path_attributes:
+      - name: ja-lang
+        value: 他のアプリからのアクティビティの開始を許可する
+      - name: ko-lang
+        value: 다른 앱이 자신의 액티비티를 시작하도록 허용하기
+      - name: pt-br-lang
+        value: Permitindo que outros aplicativos iniciem sua atividade
+      - name: ru-lang
+        value: Разрешение другим приложениям на запуск вашей операции
+      - name: zh-cn-lang
+        value: 允许其他应用开始您的活动
+      - name: zh-tw-lang
+        value: 允許其他應用程式啟動您的應用行為顯示
   - title: Working with System Permissions
     path: /training/permissions/index.html
-    custom_link_attributes:
-    - description="How to declare that your app needs access to features and resources outside of its 'sandbox', and how to request those privileges at runtime."
+    path_attributes:
+    - name: description
+      value: How to declare that your app needs access to features and resources outside of its 'sandbox', and how to request those privileges at runtime.
     section:
     - title: Declaring Permissions
       path: /training/permissions/declaring.html
@@ -172,8 +252,9 @@
   section:
   - title: Sharing Simple Data
     path: /training/sharing/index.html
-    custom_link_attributes:
-    - description="How to take your app interaction to the next level by sharing information with other apps, receive information back, and provide a simple and scalable way to perform Share actions with user content."
+    path_attributes:
+    - name: description
+      value: How to take your app interaction to the next level by sharing information with other apps, receive information back, and provide a simple and scalable way to perform Share actions with user content.
     section:
     - title: Sending Simple Data to Other Apps
       path: /training/sharing/send.html
@@ -183,8 +264,9 @@
       path: /training/sharing/shareaction.html
   - title: Sharing Files
     path: /training/secure-file-sharing/index.html
-    custom_link_attributes:
-    - description="How to provide secure access to a file associated with your app using a content URI and temporary access permissions."
+    path_attributes:
+    - name: description
+      value: How to provide secure access to a file associated with your app using a content URI and temporary access permissions.
     section:
     - title: Setting Up File Sharing
       path: /training/secure-file-sharing/setup-sharing.html
@@ -196,8 +278,9 @@
       path: /training/secure-file-sharing/retrieve-info.html
   - title: Sharing Files with NFC
     path: /training/beam-files/index.html
-    custom_link_attributes:
-    - description="How to transfer files between devices using the NFC Android Beam feature."
+    path_attributes:
+    - name: description
+      value: How to transfer files between devices using the NFC Android Beam feature.
     section:
     - title: Sending Files to Another Device
       path: /training/beam-files/send-files.html
@@ -209,8 +292,9 @@
   section:
   - title: Managing Audio Playback
     path: /training/managing-audio/index.html
-    custom_link_attributes:
-    - description="How to respond to hardware audio key presses, request audio focus when playing audio, and respond appropriately to changes in audio focus."
+    path_attributes:
+    - name: description
+      value: How to respond to hardware audio key presses, request audio focus when playing audio, and respond appropriately to changes in audio focus.
     section:
     - title: Controlling Your App's Volume and Playback
       path: /training/managing-audio/volume-playback.html
@@ -220,8 +304,9 @@
       path: /training/managing-audio/audio-output.html
   - title: Capturing Photos
     path: /training/camera/index.html
-    custom_link_attributes:
-    - description="How to leverage existing camera apps on the user's device to capture photos or control the camera hardware directly and build your own camera app."
+    path_attributes:
+    - name: description
+      value: How to leverage existing camera apps on the user's device to capture photos or control the camera hardware directly and build your own camera app.
     section:
     - title: Taking Photos Simply
       path: /training/camera/photobasics.html
@@ -231,8 +316,9 @@
       path: /training/camera/cameradirect.html
   - title: Printing Content
     path: /training/printing/index.html
-    custom_link_attributes:
-    - description="How to print photos, HTML documents, and custom documents from your app."
+    path_attributes:
+    - name: description
+      value: How to print photos, HTML documents, and custom documents from your app.
     section:
     - title: Photos
       path: /training/printing/photos.html
@@ -246,8 +332,9 @@
   section:
   - title: Displaying Bitmaps Efficiently
     path: /training/displaying-bitmaps/index.html
-    custom_link_attributes:
-    - description="How to load and process bitmaps while keeping your user interface responsive and avoid exceeding memory limits."
+    path_attributes:
+    - name: description
+      value: How to load and process bitmaps while keeping your user interface responsive and avoid exceeding memory limits.
     section:
     - title: Loading Large Bitmaps Efficiently
       path: /training/displaying-bitmaps/load-bitmap.html
@@ -261,8 +348,9 @@
       path: /training/displaying-bitmaps/display-bitmap.html
   - title: Displaying Graphics with OpenGL ES
     path: /training/graphics/opengl/index.html
-    custom_link_attributes:
-    - description="How to create OpenGL graphics within the Android app framework and respond to touch input."
+    path_attributes:
+    - name: description
+      value: How to create OpenGL graphics within the Android app framework and respond to touch input.
     section:
     - title: Building an OpenGL ES Environment
       path: /training/graphics/opengl/environment.html
@@ -278,8 +366,9 @@
       path: /training/graphics/opengl/touch.html
   - title: Animating Views Using Scenes and Transitions
     path: /training/transitions/index.html
-    custom_link_attributes:
-    - description="How to animate state changes in a view hierarchy using transitions."
+    path_attributes:
+    - name: description
+      value: How to animate state changes in a view hierarchy using transitions.
     section:
     - title: The Transitions Framework
       path: /training/transitions/overview.html
@@ -291,8 +380,9 @@
       path: /training/transitions/custom-transitions.html
   - title: Adding Animations
     path: /training/animation/index.html
-    custom_link_attributes:
-    - description="How to add transitional animations to your user interface."
+    path_attributes:
+    - name: description
+      value: How to add transitional animations to your user interface.
     section:
     - title: Crossfading Two Views
       path: /training/animation/crossfade.html
@@ -310,8 +400,9 @@
   section:
   - title: Connecting Devices Wirelessly
     path: /training/connect-devices-wirelessly/index.html
-    custom_link_attributes:
-    - description="How to find and connect to local devices using Network Service Discovery and how to create peer-to-peer connections with Wi-Fi."
+    path_attributes:
+    - name: description
+      value: How to find and connect to local devices using Network Service Discovery and how to create peer-to-peer connections with Wi-Fi.
     section:
     - title: Using Network Service Discovery
       path: /training/connect-devices-wirelessly/nsd.html
@@ -321,8 +412,9 @@
       path: /training/connect-devices-wirelessly/nsd-wifi-direct.html
   - title: Performing Network Operations
     path: /training/basics/network-ops/index.html
-    custom_link_attributes:
-    - description="How to create a network connection, monitor the connection for changes in connectivity, and perform transactions with XML data."
+    path_attributes:
+    - name: description
+      value: How to create a network connection, monitor the connection for changes in connectivity, and perform transactions with XML data.
     section:
     - title: Connecting to the Network
       path: /training/basics/network-ops/connecting.html
@@ -332,8 +424,9 @@
       path: /training/basics/network-ops/xml.html
   - title: Transferring Data Without Draining the Battery
     path: /training/efficient-downloads/index.html
-    custom_link_attributes:
-    - description="How to minimize your app's impact on the battery when performing downloads and other network transactions."
+    path_attributes:
+    - name: description
+      value: How to minimize your app's impact on the battery when performing downloads and other network transactions.
     section:
     - title: Optimizing Downloads for Efficient Network Access
       path: /training/efficient-downloads/efficient-network-access.html
@@ -345,8 +438,9 @@
       path: /training/efficient-downloads/connectivity_patterns.html
   - title: Syncing to the Cloud
     path: /training/backup/index.html
-    custom_link_attributes:
-    - description="How to sync and back up app and user data to remote web services in the cloud and how to restore the data back to multiple devices."
+    path_attributes:
+    - name: description
+      value: How to sync and back up app and user data to remote web services in the cloud and how to restore the data back to multiple devices.
     section:
     - title: Configuring Auto Backup
       path: /training/backup/autosyncapi.html
@@ -354,12 +448,14 @@
       path: /training/backup/backupapi.html
   - title: Resolving Cloud Save Conflicts
     path: /training/cloudsave/conflict-res.html
-    custom_link_attributes:
-    - description="How to design a robust conflict resolution strategy for apps that save data to the cloud."
+    path_attributes:
+    - name: description
+      value: How to design a robust conflict resolution strategy for apps that save data to the cloud.
   - title: Transferring Data Using Sync Adapters
     path: /training/sync-adapters/index.html
-    custom_link_attributes:
-    - description="How to transfer data between the cloud and the device using the Android sync adapter framework"
+    path_attributes:
+    - name: description
+      value: How to transfer data between the cloud and the device using the Android sync adapter framework
     section:
     - title: Creating a Stub Authenticator
       path: /training/sync-adapters/creating-authenticator.html
@@ -371,8 +467,9 @@
       path: /training/sync-adapters/running-sync-adapter.html
   - title: Transmitting Network Data Using Volley
     path: /training/volley/index.html
-    custom_link_attributes:
-    - description="How to perform fast, scalable UI operations over the network using Volley"
+    path_attributes:
+    - name: description
+      value: How to perform fast, scalable UI operations over the network using Volley
     section:
     - title: Sending a Simple Request
       path: /training/volley/simple.html
@@ -388,8 +485,9 @@
   section:
   - title: Making Your App Location-Aware
     path: /training/location/index.html
-    custom_link_attributes:
-    - description="How to add location-aware features to your app by getting the user's current location."
+    path_attributes:
+    - name: description
+      value: How to add location-aware features to your app by getting the user's current location.
     section:
     - title: Getting the Last Known Location
       path: /training/location/retrieve-current.html
@@ -403,16 +501,18 @@
       path: /training/location/geofencing.html
   - title: Adding Maps
     path: /training/maps/index.html
-    custom_link_attributes:
-    - description="How to add maps and mapping information to your app."
+    path_attributes:
+    - name: description
+      value: How to add maps and mapping information to your app.
 
 - title: Building Apps with User Info & Sign-In
   path: /training/building-userinfo.html
   section:
   - title: Accessing Contacts Data
     path: /training/contacts-provider/index.html
-    custom_link_attributes:
-    - description="How to use Android's central address book, the Contacts Provider, to display contacts and their details and modify contact information."
+    path_attributes:
+    - name: description
+      value: How to use Android's central address book, the Contacts Provider, to display contacts and their details and modify contact information.
     section:
     - title: Retrieving a List of Contacts
       path: /training/contacts-provider/retrieve-names.html
@@ -424,16 +524,18 @@
       path: /training/contacts-provider/display-contact-badge.html
   - title: Adding Sign-In
     path: /training/sign-in/index.html
-    custom_link_attributes:
-    - description="How to add user sign-in functionality to your app."
+    path_attributes:
+    - name: description
+      value: How to add user sign-in functionality to your app.
 
 - title: Building Apps for Wearables
   path: /training/building-wearables.html
   section:
   - title: Adding Wearable Features to Notifications
     path: /training/wearables/notifications/index.html
-    custom_link_attributes:
-    - description="How to build handheld notifications that are synced to and look great on wearables."
+    path_attributes:
+    - name: description
+      value: How to build handheld notifications that are synced to and look great on wearables.
     section:
     - title: Creating a Notification
       path: /training/wearables/notifications/creating.html
@@ -445,8 +547,9 @@
       path: /training/wearables/notifications/stacks.html
   - title: Creating Wearable Apps
     path: /training/wearables/apps/index.html
-    custom_link_attributes:
-    - description="How to build apps that run directly on wearables."
+    path_attributes:
+    - name: description
+      value: How to build apps that run directly on wearables.
     section:
     - title: Creating and Running a Wearable App
       path: /training/wearables/apps/creating.html
@@ -462,8 +565,9 @@
       path: /training/wearables/apps/bt-debugging.html
   - title: Creating Custom UIs
     path: /training/wearables/ui/index.html
-    custom_link_attributes:
-    - description="How to create custom user interfaces for wearable apps."
+    path_attributes:
+    - name: description
+      value: How to create custom user interfaces for wearable apps.
     section:
     - title: Defining Layouts
       path: /training/wearables/ui/layouts.html
@@ -479,8 +583,9 @@
       path: /training/wearables/ui/exit.html
   - title: Sending and Syncing Data
     path: /training/wearables/data-layer/index.html
-    custom_link_attributes:
-    - description="How to sync data between handhelds and wearables."
+    path_attributes:
+    - name: description
+      value: How to sync data between handhelds and wearables.
     section:
     - title: Accessing the Wearable Data Layer
       path: /training/wearables/data-layer/accessing.html
@@ -494,8 +599,9 @@
       path: /training/wearables/data-layer/events.html
   - title: Creating Watch Faces
     path: /training/wearables/watch-faces/index.html
-    custom_link_attributes:
-    - description="How to create watch faces for wearables."
+    path_attributes:
+    - name: description
+      value: How to create watch faces for wearables.
     section:
     - title: Designing Watch Faces
       path: /training/wearables/watch-faces/designing.html
@@ -515,70 +621,85 @@
       path: /training/wearables/watch-faces/performance.html
   - title: Detecting Location
     path: /training/articles/wear-location-detection.html
-    custom_link_attributes:
-    - description="How to detect location data on Android Wear devices."
+    path_attributes:
+    - name: description
+      value: How to detect location data on Android Wear devices.
   - title: Requesting Permissions
     path: /training/articles/wear-permissions.html
-    custom_link_attributes:
-    - description="How to request permissions on Android Wear devices."
+    path_attributes:
+    - name: description
+      value: How to request permissions on Android Wear devices.
   - title: Using the Speaker
     path: /training/wearables/wearable-sounds.html
-    custom_link_attributes:
-    - description="How to use the speaker on Android Wear devices."
+    path_attributes:
+    - name: description
+      value: How to use the speaker on Android Wear devices.
 
 - title: Building Apps for TV
   path: /training/tv/index.html
   section:
   - title: Building TV Apps
     path: /training/tv/start/index.html
-    custom_link_attributes:
-    - ja-lang="TV アプリのビルド"
-    - description="How to start building TV apps or extend your existing app to run on TV devices."
+    path_attributes:
+    - name: ja-lang
+      value: TV アプリのビルド
+    - name: description
+      value: How to start building TV apps or extend your existing app to run on TV devices.
     section:
     - title: Getting Started with TV Apps
       path: /training/tv/start/start.html
-      custom_link_attributes:
-      - ja-lang="TV アプリのビルドを開始する"
+      path_attributes:
+      - name: ja-lang
+        value: TV アプリのビルドを開始する
     - title: Handling TV Hardware
       path: /training/tv/start/hardware.html
-      custom_link_attributes:
-      - ja-lang="TV ハードウェアを処理する"
+      path_attributes:
+      - name: ja-lang
+        value: TV ハードウェアを処理する
     - title: Building TV Layouts
       path: /training/tv/start/layouts.html
-      custom_link_attributes:
-      - ja-lang="TV 向けレイアウトをビルドする"
+      path_attributes:
+      - name: ja-lang
+        value: TV 向けレイアウトをビルドする
     - title: Creating TV Navigation
       path: /training/tv/start/navigation.html
-      custom_link_attributes:
-      - ja-lang="TV 用のナビゲーションを作成する"
+      path_attributes:
+      - name: ja-lang
+        value: TV 用のナビゲーションを作成する
   - title: Building TV Playback Apps
     path: /training/tv/playback/index.html
-    custom_link_attributes:
-    - ja-lang="TV 再生アプリのビルド"
-    - description="How to build apps that provide media catalogs and play content."
+    path_attributes:
+    - name: ja-lang
+      value: TV 再生アプリのビルド
+    - name: description
+      value: How to build apps that provide media catalogs and play content.
     section:
     - title: Creating a Catalog Browser
       path: /training/tv/playback/browse.html
-      custom_link_attributes:
-      - ja-lang="カタログ ブラウザを作成する"
+      path_attributes:
+      - name: ja-lang
+        value: カタログ ブラウザを作成する
     - title: Providing a Card View
       path: /training/tv/playback/card.html
     - title: Building a Details View
       path: /training/tv/playback/details.html
-      custom_link_attributes:
-      - ja-lang="詳細ビューをビルドする"
+      path_attributes:
+      - name: ja-lang
+        value: 詳細ビューをビルドする
     - title: Displaying a Now Playing Card
       path: /training/tv/playback/now-playing.html
-      custom_link_attributes:
-      - ja-lang="再生中カードを表示する"
+      path_attributes:
+      - name: ja-lang
+        value: 再生中カードを表示する
     - title: Adding a Guided Step
       path: /training/tv/playback/guided-step.html
     - title: Enabling Background Playback
       path: /training/tv/playback/options.html
   - title: Helping Users Find Content on TV
     path: /training/tv/discovery/index.html
-    custom_link_attributes:
-    - description="How to help users discover content from your app."
+    path_attributes:
+    - name: description
+      value: How to help users discover content from your app.
     section:
     - title: Recommending TV Content
       path: /training/tv/discovery/recommendations.html
@@ -588,12 +709,14 @@
       path: /training/tv/discovery/in-app-search.html
   - title: Building TV Games
     path: /training/tv/games/index.html
-    custom_link_attributes:
-    - description="How to build games for TV."
+    path_attributes:
+    - name: description
+      value: How to build games for TV.
   - title: Building TV Channels
     path: /training/tv/tif/index.html
-    custom_link_attributes:
-    - description="How to build channels for TV."
+    path_attributes:
+    - name: description
+      value: How to build channels for TV.
     section:
     - title: Developing a TV Input Service
       path: /training/tv/tif/tvinput.html
@@ -603,24 +726,28 @@
       path: /training/tv/tif/ui.html
   - title: TV Apps Checklist
     path: /training/tv/publishing/checklist.html
-    custom_link_attributes:
-    - description="An itemized list of requirements for TV apps."
+    path_attributes:
+    - name: description
+      value: An itemized list of requirements for TV apps.
 
 - title: Building Apps for Auto
   path: /training/auto/index.html
   section:
   - title: Getting Started with Auto
     path: /training/auto/start/index.html
-    custom_link_attributes:
-    - description="How to start building or extending apps that work with Auto devices."
+    path_attributes:
+    - name: description
+      value: How to start building or extending apps that work with Auto devices.
   - title: Playing Audio for Auto
     path: /training/auto/audio/index.html
-    custom_link_attributes:
-    - description="How to extend audio apps to play content on Auto devices."
+    path_attributes:
+    - name: description
+      value: How to extend audio apps to play content on Auto devices.
   - title: Messaging for Auto
     path: /training/auto/messaging/index.html
-    custom_link_attributes:
-    - description="How to extend text messaging apps to work with Auto devices."
+    path_attributes:
+    - name: description
+      value: How to extend text messaging apps to work with Auto devices.
 
 - title: Building Apps for Work
   path: /training/enterprise/index.html
@@ -639,8 +766,9 @@
   section:
   - title: Designing Effective Navigation
     path: /training/design-navigation/index.html
-    custom_link_attributes:
-    - description="How to plan your app's screen hierarchy and forms of navigation so users can effectively and intuitively traverse your app content using various navigation patterns."
+    path_attributes:
+    - name: description
+      value: How to plan your app's screen hierarchy and forms of navigation so users can effectively and intuitively traverse your app content using various navigation patterns.
     section:
     - title: Planning Screens and Their Relationships
       path: /training/design-navigation/screen-planning.html
@@ -654,8 +782,9 @@
       path: /training/design-navigation/wireframing.html
   - title: Implementing Effective Navigation
     path: /training/implementing-navigation/index.html
-    custom_link_attributes:
-    - description="How to implement various navigation patterns such as swipe views, a navigation drawer, and up navigation."
+    path_attributes:
+    - name: description
+      value: How to implement various navigation patterns such as swipe views, a navigation drawer, and up navigation.
     section:
     - title: Creating Swipe Views with Tabs
       path: /training/implementing-navigation/lateral.html
@@ -669,8 +798,9 @@
       path: /training/implementing-navigation/descendant.html
   - title: Notifying the User
     path: /training/notify-user/index.html
-    custom_link_attributes:
-    - description="How to display messages called notifications outside of your application's UI."
+    path_attributes:
+    - name: description
+      value: How to display messages called notifications outside of your application's UI.
     section:
     - title: Building a Notification
       path: /training/notify-user/build-notification.html
@@ -684,8 +814,9 @@
       path: /training/notify-user/display-progress.html
   - title: Supporting Swipe-to-Refresh
     path: /training/swipe/index.html
-    custom_link_attributes:
-    - description="How to modify your app's layout to support manual content updates triggered by the swipe-to-refresh gesture."
+    path_attributes:
+    - name: description
+      value: How to modify your app's layout to support manual content updates triggered by the swipe-to-refresh gesture.
     section:
     - title: Adding Swipe-to-Refresh To Your App
       path: /training/swipe/add-swipe-interface.html
@@ -693,8 +824,9 @@
       path: /training/swipe/respond-refresh-request.html
   - title: Adding Search Functionality
     path: /training/search/index.html
-    custom_link_attributes:
-    - description="How to properly add a search interface to your app and create a searchable database."
+    path_attributes:
+    - name: description
+      value: How to properly add a search interface to your app and create a searchable database.
     section:
     - title: Setting up the Search Interface
       path: /training/search/setup.html
@@ -704,8 +836,9 @@
       path: /training/search/backward-compat.html
   - title: Making Your App Content Searchable by Google
     path: /training/app-indexing/index.html
-    custom_link_attributes:
-    - description="How to enable deep linking and indexing of your application content so that users can open this content directly from their mobile search results."
+    path_attributes:
+    - name: description
+      value: How to enable deep linking and indexing of your application content so that users can open this content directly from their mobile search results.
     section:
     - title: Enabling Deep Links for App Content
       path: /training/app-indexing/deep-linking.html
@@ -713,47 +846,64 @@
       path: /training/app-indexing/enabling-app-indexing.html
   - title: Optimizing Content for the Assistant
     path: /training/articles/assistant.html
-    custom_link_attributes:
-    - description="Support contextually relevant actions through the Assist API."
+    path_attributes:
+    - name: description
+      value: Support contextually relevant actions through the Assist API.
   - title: Handling App Links
     path: /training/app-links/index.html
-    custom_link_attributes:
-    - description="How to enable the system to handle web requests by taking the user directly to your app instead of your website."
+    path_attributes:
+    - name: description
+      value: How to enable the system to handle web requests by taking the user directly to your app instead of your website.
 
 - title: Best Practices for User Interface
   path: /training/best-ui.html
   section:
   - title: Designing for Multiple Screens
     path: /training/multiscreen/index.html
-    custom_link_attributes:
-    - es-lang="Cómo diseñar aplicaciones para varias pantallas"
-    - ja-lang="複数画面のデザイン"
-    - zh-cn-lang="针对多种屏幕进行设计"
-    - description="How to build a user interface that's flexible enough to fit perfectly on any screen and how to create different interaction patterns that are optimized for different screen sizes."
+    path_attributes:
+    - name: es-lang
+      value: Cómo diseñar aplicaciones para varias pantallas
+    - name: ja-lang
+      value: 複数画面のデザイン
+    - name: zh-cn-lang
+      value: 针对多种屏幕进行设计
+    - name: description
+      value: How to build a user interface that's flexible enough to fit perfectly on any screen and how to create different interaction patterns that are optimized for different screen sizes.
     section:
     - title: Supporting Different Screen Sizes
       path: /training/multiscreen/screensizes.html
-      custom_link_attributes:
-      - es-lang="Cómo admitir varios tamaños de pantalla"
-      - ja-lang="さまざまな画面サイズのサポート"
-      - ko-lang="다양한 화면 크기 지원"
-      - zh-cn-lang="支持各种屏幕尺寸"
+      path_attributes:
+      - name: es-lang
+        value: Cómo admitir varios tamaños de pantalla
+      - name: ja-lang
+        value: さまざまな画面サイズのサポート
+      - name: ko-lang
+        value: 다양한 화면 크기 지원
+      - name: zh-cn-lang
+        value: 支持各种屏幕尺寸
     - title: Supporting Different Screen Densities
       path: /training/multiscreen/screendensities.html
-      custom_link_attributes:
-      - es-lang="Cómo admitir varias densidades de pantalla"
-      - ja-lang="さまざまな画面密度のサポート"
-      - zh-cn-lang="支持各种屏幕密度"
+      path_attributes:
+      - name: es-lang
+        value: Cómo admitir varias densidades de pantalla
+      - name: ja-lang
+        value: さまざまな画面密度のサポート
+      - name: zh-cn-lang
+        value: 支持各种屏幕密度
     - title: Implementing Adaptive UI Flows
       path: /training/multiscreen/adaptui.html
-      custom_link_attributes:
-      - es-lang="Cómo implementar interfaces de usuario adaptables"
-      - ja-lang="順応性のある UI フローの実装"
-      - zh-cn-lang="实施自适应用户界面流程"
+      path_attributes:
+      - name: es-lang
+        value: Cómo implementar interfaces de usuario adaptables
+      - name: ja-lang
+        value: 順応性のある UI フローの実装
+      - name: zh-cn-lang
+        value: 实施自适应用户界面流程
   - title: Adding the App Bar
     path: /training/appbar/index.html
-    custom_link_attributes:
-    - description="How to use the support library's toolbar widget to implement an app bar that displays properly on a wide range of devices."
+    path_attributes:
+    - name: description
+      value: How to use the support library's toolbar widget to implement an app bar that displays properly on a wide range of devices.
     section:
     - title: Setting Up the App Bar
       path: /training/appbar/setting-up.html
@@ -765,8 +915,9 @@
       path: /training/appbar/action-views.html
   - title: Showing Pop-Up Messages
     path: /training/snackbar/index.html
-    custom_link_attributes:
-    - description="How to use the support library's Snackbar widget to display a brief pop-up message."
+    path_attributes:
+    - name: description
+      value: How to use the support library's Snackbar widget to display a brief pop-up message.
     section:
     - title: Building and Displaying a Pop-Up Message
       path: /training/snackbar/showing.html
@@ -774,8 +925,9 @@
       path: /training/snackbar/action.html
   - title: Creating Custom Views
     path: /training/custom-views/index.html
-    custom_link_attributes:
-    - description="How to build custom UI widgets that are interactive and smooth."
+    path_attributes:
+    - name: description
+      value: How to build custom UI widgets that are interactive and smooth.
     section:
     - title: Creating a Custom View Class
       path: /training/custom-views/create-view.html
@@ -787,8 +939,9 @@
       path: /training/custom-views/optimizing-view.html
   - title: Creating Backward-Compatible UIs
     path: /training/backward-compatible-ui/index.html
-    custom_link_attributes:
-    - description="How to use UI components and other APIs from the more recent versions of Android while remaining compatible with older versions of the platform."
+    path_attributes:
+    - name: description
+      value: How to use UI components and other APIs from the more recent versions of Android while remaining compatible with older versions of the platform.
     section:
     - title: Abstracting the New APIs
       path: /training/backward-compatible-ui/abstracting.html
@@ -800,8 +953,9 @@
       path: /training/backward-compatible-ui/using-component.html
   - title: Implementing Accessibility
     path: /training/accessibility/index.html
-    custom_link_attributes:
-    - description="How to make your app accessible to users with vision impairment or other physical disabilities."
+    path_attributes:
+    - name: description
+      value: How to make your app accessible to users with vision impairment or other physical disabilities.
     section:
     - title: Developing Accessible Applications
       path: /training/accessibility/accessible-app.html
@@ -811,8 +965,9 @@
       path: /training/accessibility/testing.html
   - title: Managing the System UI
     path: /training/system-ui/index.html
-    custom_link_attributes:
-    - description="How to hide and show status and navigation bars across different versions of Android, while managing the display of other screen components."
+    path_attributes:
+    - name: description
+      value: How to hide and show status and navigation bars across different versions of Android, while managing the display of other screen components.
     section:
     - title: Dimming the System Bars
       path: /training/system-ui/dim.html
@@ -826,110 +981,184 @@
       path: /training/system-ui/visibility.html
   - title: Creating Apps with Material Design
     path: /training/material/index.html
-    custom_link_attributes:
-    - es-lang="Crear aplicaciones con Material Design"
-    - in-lang="Desain Bahan untuk Pengembang"
-    - ja-lang="マテリアル デザインでのアプリ作成"
-    - ko-lang="개발자를 위한 머티리얼 디자인"
-    - pt-br-lang="Material Design para desenvolvedores"
-    - ru-lang="Создание приложений с помощью Material Design"
-    - vi-lang="Material Design cho Nhà phát triển"
-    - zh-cn-lang="面向开发者的材料设计"
-    - zh-tw-lang="開發人員材料設計"
-    - description="How to implement material design on Android."
+    path_attributes:
+    - name: es-lang
+      value: Crear aplicaciones con Material Design
+    - name: in-lang
+      value: Desain Bahan untuk Pengembang
+    - name: ja-lang
+      value: マテリアル デザインでのアプリ作成
+    - name: ko-lang
+      value: 개발자를 위한 머티리얼 디자인
+    - name: pt-br-lang
+      value: Material Design para desenvolvedores
+    - name: ru-lang
+      value: Создание приложений с помощью Material Design
+    - name: vi-lang
+      value: Material Design cho Nhà phát triển
+    - name: zh-cn-lang
+      value: 面向开发者的材料设计
+    - name: zh-tw-lang
+      value: 開發人員材料設計
+    - name: description
+      value: How to implement material design on Android.
     section:
     - title: Getting Started
       path: /training/material/get-started.html
-      custom_link_attributes:
-      - es-lang="Comencemos"
-      - in-lang="Memulai"
-      - ja-lang="スタート ガイド"
-      - ko-lang="시작하기"
-      - pt-br-lang="Como iniciar"
-      - ru-lang="Начало работы"
-      - vi-lang="Bắt đầu"
-      - zh-cn-lang="入门指南"
-      - zh-tw-lang="開始使用"
+      path_attributes:
+      - name: es-lang
+        value: Comencemos
+      - name: in-lang
+        value: Memulai
+      - name: ja-lang
+        value: スタート ガイド
+      - name: ko-lang
+        value: 시작하기
+      - name: pt-br-lang
+        value: Como iniciar
+      - name: ru-lang
+        value: Начало работы
+      - name: vi-lang
+        value: Bắt đầu
+      - name: zh-cn-lang
+        value: 入门指南
+      - name: zh-tw-lang
+        value: 開始使用
     - title: Using the Material Theme
       path: /training/material/theme.html
-      custom_link_attributes:
-      - es-lang="Usar el tema Material"
-      - in-lang="Menggunakan Tema Bahan"
-      - ja-lang="マテリアル テーマの使用"
-      - ko-lang="머티어리얼 테마 사용"
-      - pt-br-lang="Como usar o tema do Material"
-      - ru-lang="Использование темы Material Design"
-      - vi-lang="Sử dụng Chủ đề Material"
-      - zh-cn-lang="使用材料主题"
-      - zh-tw-lang="使用材料設計風格"
+      path_attributes:
+      - name: es-lang
+        value: Usar el tema Material
+      - name: in-lang
+        value: Menggunakan Tema Bahan
+      - name: ja-lang
+        value: マテリアル テーマの使用
+      - name: ko-lang
+        value: 머티어리얼 테마 사용
+      - name: pt-br-lang
+        value: Como usar o tema do Material
+      - name: ru-lang
+        value: Использование темы Material Design
+      - name: vi-lang
+        value: Sử dụng Chủ đề Material
+      - name: zh-cn-lang
+        value: 使用材料主题
+      - name: zh-tw-lang
+        value: 使用材料設計風格
     - title: Creating Lists and Cards
       path: /training/material/lists-cards.html
-      custom_link_attributes:
-      - es-lang="Crear listas y tarjetas"
-      - in-lang="Membuat Daftar dan Kartu"
-      - ja-lang="リストとカードの作成"
-      - ko-lang="목록 및 카드 생성"
-      - pt-br-lang="Como criar listas e cartões"
-      - ru-lang="Создание списков и подсказок"
-      - vi-lang="Tạo Danh sách và Thẻ"
-      - zh-cn-lang="创建列表与卡片"
-      - zh-tw-lang="建立清單和卡片"
+      path_attributes:
+      - name: es-lang
+        value: Crear listas y tarjetas
+      - name: in-lang
+        value: Membuat Daftar dan Kartu
+      - name: ja-lang
+        value: リストとカードの作成
+      - name: ko-lang
+        value: 목록 및 카드 생성
+      - name: pt-br-lang
+        value: Como criar listas e cartões
+      - name: ru-lang
+        value: Создание списков и подсказок
+      - name: vi-lang
+        value: Tạo Danh sách và Thẻ
+      - name: zh-cn-lang
+        value: 创建列表与卡片
+      - name: zh-tw-lang
+        value: 建立清單和卡片
     - title: Defining Shadows and Clipping Views
       path: /training/material/shadows-clipping.html
-      custom_link_attributes:
-      - es-lang="Definir vistas de recorte y sombras"
-      - in-lang="Mendefinisikan Bayangan dan Memangkas Tampilan"
-      - ja-lang="シャドウとクリッピング ビューの定義"
-      - ko-lang="그림자 정의 및 뷰 클리핑"
-      - pt-br-lang="Como definir sombras e recortar visualizações"
-      - ru-lang="Определение теней и обрезка представлений"
-      - vi-lang="Định nghĩa Đổ bóng và Dạng xem Cắt hình"
-      - zh-cn-lang="定义阴影与裁剪视图"
-      - zh-tw-lang="定義陰影和裁剪檢視"
+      path_attributes:
+      - name: es-lang
+        value: Definir vistas de recorte y sombras
+      - name: in-lang
+        value: Mendefinisikan Bayangan dan Memangkas Tampilan
+      - name: ja-lang
+        value: シャドウとクリッピング ビューの定義
+      - name: ko-lang
+        value: 그림자 정의 및 뷰 클리핑
+      - name: pt-br-lang
+        value: Como definir sombras e recortar visualizações
+      - name: ru-lang
+        value: Определение теней и обрезка представлений
+      - name: vi-lang
+        value: Định nghĩa Đổ bóng và Dạng xem Cắt hình
+      - name: zh-cn-lang
+        value: 定义阴影与裁剪视图
+      - name: zh-tw-lang
+        value: 定義陰影和裁剪檢視
     - title: Working with Drawables
       path: /training/material/drawables.html
-      custom_link_attributes:
-      - es-lang="Trabajar con interfaces dibujables"
-      - in-lang="Bekerja dengan Drawable"
-      - ja-lang="ドローアブルの使用"
-      - ko-lang="Drawable 사용"
-      - pt-br-lang="Como trabalhar com desenháveis"
-      - ru-lang="Работа с элементами дизайна"
-      - vi-lang="Làm việc với Nội dung vẽ được"
-      - zh-cn-lang="使用 Drawables"
-      - zh-tw-lang="使用可繪項目"
+      path_attributes:
+      - name: es-lang
+        value: Trabajar con interfaces dibujables
+      - name: in-lang
+        value: Bekerja dengan Drawable
+      - name: ja-lang
+        value: ドローアブルの使用
+      - name: ko-lang
+        value: Drawable 사용
+      - name: pt-br-lang
+        value: Como trabalhar com desenháveis
+      - name: ru-lang
+        value: Работа с элементами дизайна
+      - name: vi-lang
+        value: Làm việc với Nội dung vẽ được
+      - name: zh-cn-lang
+        value: 使用 Drawables
+      - name: zh-tw-lang
+        value: 使用可繪項目
     - title: Defining Custom Animations
       path: /training/material/animations.html
-      custom_link_attributes:
-      - es-lang="Definir animaciones personalizadas"
-      - in-lang="Mendefinisikan Animasi Custom"
-      - ja-lang="カスタム アニメーションの定義"
-      - ko-lang="사용자지정 애니메이션 정의"
-      - pt-br-lang="Como definir animações personalizadas"
-      - ru-lang="Определение настраиваемой анимации"
-      - vi-lang="Định nghĩa Hoạt hình Tùy chỉnh"
-      - zh-cn-lang="定义定制动画"
-      - zh-tw-lang="定義自訂動畫"
+      path_attributes:
+      - name: es-lang
+        value: Definir animaciones personalizadas
+      - name: in-lang
+        value: Mendefinisikan Animasi Custom
+      - name: ja-lang
+        value: カスタム アニメーションの定義
+      - name: ko-lang
+        value: 사용자지정 애니메이션 정의
+      - name: pt-br-lang
+        value: Como definir animações personalizadas
+      - name: ru-lang
+        value: Определение настраиваемой анимации
+      - name: vi-lang
+        value: Định nghĩa Hoạt hình Tùy chỉnh
+      - name: zh-cn-lang
+        value: 定义定制动画
+      - name: zh-tw-lang
+        value: 定義自訂動畫
     - title: Maintaining Compatibility
       path: /training/material/compatibility.html
-      custom_link_attributes:
-      - es-lang="Mantener la compatibilidad"
-      - in-lang="Mempertahankan Kompatibilitas"
-      - ja-lang="互換性の維持"
-      - ko-lang="호환성 유지"
-      - pt-br-lang="Como manter a compatibilidade"
-      - ru-lang="Обеспечение совместимости"
-      - vi-lang="Duy trì Tính tương thích"
-      - zh-cn-lang="维护兼容性"
-      - zh-tw-lang="維持相容性"
+      path_attributes:
+      - name: es-lang
+        value: Mantener la compatibilidad
+      - name: in-lang
+        value: Mempertahankan Kompatibilitas
+      - name: ja-lang
+        value: 互換性の維持
+      - name: ko-lang
+        value: 호환성 유지
+      - name: pt-br-lang
+        value: Como manter a compatibilidade
+      - name: ru-lang
+        value: Обеспечение совместимости
+      - name: vi-lang
+        value: Duy trì Tính tương thích
+      - name: zh-cn-lang
+        value: 维护兼容性
+      - name: zh-tw-lang
+        value: 維持相容性
 
 - title: Best Practices for User Input
   path: /training/best-user-input.html
   section:
   - title: Using Touch Gestures
     path: /training/gestures/index.html
-    custom_link_attributes:
-    - description="How to write apps that allow users to interact with the touch screen via touch gestures."
+    path_attributes:
+    - name: description
+      value: How to write apps that allow users to interact with the touch screen via touch gestures.
     section:
     - title: Detecting Common Gestures
       path: /training/gestures/detector.html
@@ -945,8 +1174,9 @@
       path: /training/gestures/viewgroup.html
   - title: Handling Keyboard Input
     path: /training/keyboard-input/index.html
-    custom_link_attributes:
-    - description="How to specify the appearance and behaviors of soft input methods (such as on-screen keyboards) and how to optimize the experience with hardware keyboards."
+    path_attributes:
+    - name: description
+      value: How to specify the appearance and behaviors of soft input methods (such as on-screen keyboards) and how to optimize the experience with hardware keyboards.
     section:
     - title: Specifying the Input Method Type
       path: /training/keyboard-input/style.html
@@ -958,8 +1188,9 @@
       path: /training/keyboard-input/commands.html
   - title: Supporting Game Controllers
     path: /training/game-controllers/index.html
-    custom_link_attributes:
-    - description="How to write apps that support game controllers."
+    path_attributes:
+    - name: description
+      value: How to write apps that support game controllers.
     section:
     - title: Handling Controller Actions
       path: /training/game-controllers/controller-input.html
@@ -973,8 +1204,9 @@
   section:
   - title: Running in a Background Service
     path: /training/run-background-service/index.html
-    custom_link_attributes:
-    - description="How to improve UI performance and responsiveness by sending work to a Service running in the background"
+    path_attributes:
+    - name: description
+      value: How to improve UI performance and responsiveness by sending work to a Service running in the background
     section:
     - title: Creating a Background Service
       path: /training/run-background-service/create-service.html
@@ -984,8 +1216,9 @@
       path: /training/run-background-service/report-status.html
   - title: Loading Data in the Background
     path: /training/load-data-background/index.html
-    custom_link_attributes:
-    - description="How to use CursorLoader to query data without affecting UI responsiveness."
+    path_attributes:
+    - name: description
+      value: How to use CursorLoader to query data without affecting UI responsiveness.
     section:
     - title: Running a Query with a CursorLoader
       path: /training/load-data-background/setup-loader.html
@@ -993,8 +1226,9 @@
       path: /training/load-data-background/handle-results.html
   - title: Managing Device Awake State
     path: /training/scheduling/index.html
-    custom_link_attributes:
-    - description="How to use repeating alarms and wake locks to run background jobs."
+    path_attributes:
+    - name: description
+      value: How to use repeating alarms and wake locks to run background jobs.
     section:
     - title: Keeping the Device Awake
       path: /training/scheduling/wakelock.html
@@ -1006,16 +1240,19 @@
   section:
   - title: Managing Your App's Memory
     path: /training/articles/memory.html
-    custom_link_attributes:
-    - description="How to keep your app's memory footprint small in order to improve performance on a variety of mobile devices."
+    path_attributes:
+    - name: description
+      value: How to keep your app's memory footprint small in order to improve performance on a variety of mobile devices.
   - title: Performance Tips
     path: /training/articles/perf-tips.html
-    custom_link_attributes:
-    - description="How to optimize your app's performance in various ways to improve its responsiveness and battery efficiency."
+    path_attributes:
+    - name: description
+      value: How to optimize your app's performance in various ways to improve its responsiveness and battery efficiency.
   - title: Improving Layout Performance
     path: /training/improving-layouts/index.html
-    custom_link_attributes:
-    - description="How to identify problems in your app's layout performance and improve the UI responsiveness."
+    path_attributes:
+    - name: description
+      value: How to identify problems in your app's layout performance and improve the UI responsiveness.
     section:
     - title: Optimizing Layout Hierarchies
       path: /training/improving-layouts/optimizing-layout.html
@@ -1027,11 +1264,15 @@
       path: /training/improving-layouts/smooth-scrolling.html
   - title: Optimizing Battery Life
     path: /training/monitoring-device-state/index.html
-    custom_link_attributes:
-    - es-lang="Cómo optimizar la duración de la batería"
-    - ja-lang="電池消費量の最適化"
-    - zh-cn-lang="优化电池使用时间"
-    - description="How to minimize the amount of power your app requires by adapting to current power conditions and performing power-hungry tasks at proper intervals."
+    path_attributes:
+    - name: es-lang
+      value: Cómo optimizar la duración de la batería
+    - name: ja-lang
+      value: 電池消費量の最適化
+    - name: zh-cn-lang
+      value: 优化电池使用时间
+    - name: description
+      value: How to minimize the amount of power your app requires by adapting to current power conditions and performing power-hungry tasks at proper intervals.
     section:
     - title: Reducing Network Battery Drain
       path: /training/performance/battery/network/index.html
@@ -1052,32 +1293,45 @@
       path: /training/monitoring-device-state/doze-standby.html
     - title: Monitoring the Battery Level and Charging State
       path: /training/monitoring-device-state/battery-monitoring.html
-      custom_link_attributes:
-      - es-lang="Cómo controlar el nivel de batería y el estado de carga"
-      - ja-lang="電池残量と充電状態の監視"
-      - zh-cn-lang="监控电池电量和充电状态"
+      path_attributes:
+      - name: es-lang
+        value: Cómo controlar el nivel de batería y el estado de carga
+      - name: ja-lang
+        value: 電池残量と充電状態の監視
+      - name: zh-cn-lang
+        value: 监控电池电量和充电状态
     - title: Determining and Monitoring the Docking State and Type
       path: /training/monitoring-device-state/docking-monitoring.html
-      custom_link_attributes:
-      - es-lang="Cómo determinar y controlar el tipo de conector y el estado de la conexión"
-      - ja-lang="ホルダーの装着状態とタイプの特定と監視"
-      - zh-cn-lang="确定和监控基座对接状态和类型"
+      path_attributes:
+      - name: es-lang
+        value: Cómo determinar y controlar el tipo de conector y el estado de la conexión
+      - name: ja-lang
+        value: ホルダーの装着状態とタイプの特定と監視
+      - name: zh-cn-lang
+        value: 确定和监控基座对接状态和类型
     - title: Determining and Monitoring the Connectivity Status
       path: /training/monitoring-device-state/connectivity-monitoring.html
-      custom_link_attributes:
-      - es-lang="Cómo determinar y controlar el estado de la conectividad"
-      - ja-lang="接続状態の特定と監視"
-      - zh-cn-lang="确定和监控网络连接状态"
+      path_attributes:
+      - name: es-lang
+        value: Cómo determinar y controlar el estado de la conectividad
+      - name: ja-lang
+        value: 接続状態の特定と監視
+      - name: zh-cn-lang
+        value: 确定和监控网络连接状态
     - title: Manipulating Broadcast Receivers On Demand
       path: /training/monitoring-device-state/manifest-receivers.html
-      custom_link_attributes:
-      - es-lang="Cómo manipular los receptores de emisión bajo demanda"
-      - ja-lang="オンデマンドでのブロードキャスト レシーバ操作"
-      - zh-cn-lang="根据需要操作广播接收器"
+      path_attributes:
+      - name: es-lang
+        value: Cómo manipular los receptores de emisión bajo demanda
+      - name: ja-lang
+        value: オンデマンドでのブロードキャスト レシーバ操作
+      - name: zh-cn-lang
+        value: 根据需要操作广播接收器
   - title: Sending Operations to Multiple Threads
     path: /training/multiple-threads/index.html
-    custom_link_attributes:
-    - description="How to improve the performance and scalability of long-running operations by dispatching work to multiple threads."
+    path_attributes:
+    - name: description
+      value: How to improve the performance and scalability of long-running operations by dispatching work to multiple threads.
     section:
     - title: Specifying the Code to Run on a Thread
       path: /training/multiple-threads/define-runnable.html
@@ -1089,68 +1343,81 @@
       path: /training/multiple-threads/communicate-ui.html
   - title: Keeping Your App Responsive
     path: /training/articles/perf-anr.html
-    custom_link_attributes:
-    - description="How to keep your app responsive to user interaction so the UI does not lock-up and display an \"Application Not Responding\" dialog."
+    path_attributes:
+    - name: description
+      value: How to keep your app responsive to user interaction so the UI does not lock-up and display an "Application Not Responding" dialog.
   - title: JNI Tips
     path: /training/articles/perf-jni.html
-    custom_link_attributes:
-    - description="How to efficiently use the Java Native Interface with the Android NDK."
+    path_attributes:
+    - name: description
+      value: How to efficiently use the Java Native Interface with the Android NDK.
   - title: SMP Primer for Android
     path: /training/articles/smp.html
-    custom_link_attributes:
-    - description="Tips for coding Android apps on symmetric multiprocessor systems."
+    path_attributes:
+    - name: description
+      value: Tips for coding Android apps on symmetric multiprocessor systems.
 
 - title: Best Practices for Security & Privacy
   path: /training/best-security.html
   section:
   - title: Security Tips
     path: /training/articles/security-tips.html
-    custom_link_attributes:
-    - description="How to perform various tasks and keep your app's data and your user's data secure."
+    path_attributes:
+    - name: description
+      value: How to perform various tasks and keep your app's data and your user's data secure.
   - title: Security with HTTPS and SSL
     path: /training/articles/security-ssl.html
-    custom_link_attributes:
-    - description="How to ensure that your app is secure when performing network transactions."
+    path_attributes:
+    - name: description
+      value: How to ensure that your app is secure when performing network transactions.
   - title: Updating Your Security Provider to Protect Against SSL Exploits
     path: /training/articles/security-gms-provider.html
-    custom_link_attributes:
-    - description="How to use and update Google Play services security provider, to protect against SSL exploits."
+    path_attributes:
+    - name: description
+      value: How to use and update Google Play services security provider, to protect against SSL exploits.
   - title: Checking Device Compatibility with SafetyNet
     path: /training/safetynet/index.html
-    custom_link_attributes:
-    - description="How to use the SafetyNet service to analyze a device where your app is running and get information about its compatibility with your app."
+    path_attributes:
+    - name: description
+      value: How to use the SafetyNet service to analyze a device where your app is running and get information about its compatibility with your app.
   - title: Enhancing Security with Device Management Policies
     path: /training/enterprise/device-management-policy.html
-    custom_link_attributes:
-    - description="How to create an application that enforces security policies on devices."
+    path_attributes:
+    - name: description
+      value: How to create an application that enforces security policies on devices.
 
 - title: Best Practices for Permissions & Identifiers
   path: /training/best-permissions-ids.html
   section:
   - title: Permissions and User Data
     path: /training/articles/user-data-overview.html
-    custom_link_attributes:
-    - description="Overview of app permissions on Android and how they affect your users."
+    path_attributes:
+    - name: description
+      value: Overview of app permissions on Android and how they affect your users.
   - title: Best Practices for App Permissions
     path: /training/articles/user-data-permissions.html
-    custom_link_attributes:
-    - description="How to manage permissions the right way for users."
+    path_attributes:
+    - name: description
+      value: How to manage permissions the right way for users.
   - title: Best Practices for Unique Identifiers
     path: /training/articles/user-data-ids.html
-    custom_link_attributes:
-    - description="Unique identifiers available and how to choose the right one for your use case."
+    path_attributes:
+    - name: description
+      value: Unique identifiers available and how to choose the right one for your use case.
 
 - title: Best Practices for Testing
   path: /training/testing/index.html
   section:
   - title: Getting Started with Testing
     path: /training/testing/start/index.html
-    custom_link_attributes:
-    - description="How to get started with testing your Android applications."
+    path_attributes:
+    - name: description
+      value: How to get started with testing your Android applications.
   - title: Building Effective Unit Tests
     path: /training/testing/unit-testing/index.html
-    custom_link_attributes:
-    - description="How to build effective unit tests for Android apps."
+    path_attributes:
+    - name: description
+      value: How to build effective unit tests for Android apps.
     section:
     - title: Building Local Unit Tests
       path: /training/testing/unit-testing/local-unit-tests.html
@@ -1158,8 +1425,9 @@
       path: /training/testing/unit-testing/instrumented-unit-tests.html
   - title: Automating UI Tests
     path: /training/testing/ui-testing/index.html
-    custom_link_attributes:
-    - description="How to automate your user interface tests for Android apps."
+    path_attributes:
+    - name: description
+      value: How to automate your user interface tests for Android apps.
     section:
     - title: Testing UI for a Single App
       path: /training/testing/ui-testing/espresso-testing.html
@@ -1167,8 +1435,9 @@
       path: /training/testing/ui-testing/uiautomator-testing.html
   - title: Testing App Component Integrations
     path: /training/testing/integration-testing/index.html
-    custom_link_attributes:
-    - description="How to build effective integration tests for Android apps."
+    path_attributes:
+    - name: description
+      value: How to build effective integration tests for Android apps.
     section:
     - title: Testing Your Service
       path: /training/testing/integration-testing/service-testing.html
@@ -1176,16 +1445,18 @@
       path: /training/testing/integration-testing/content-provider-testing.html
   - title: Testing Display Performance
     path: /training/testing/performance.html
-    custom_link_attributes:
-    - description="How to automate UI performance testing."
+    path_attributes:
+    - name: description
+      value: How to automate UI performance testing.
 
 - title: Using Google Play to Distribute & Monetize
   path: /training/distribute.html
   section:
   - title: Selling In-app Products
     path: /training/in-app-billing/index.html
-    custom_link_attributes:
-    - description="How to sell in-app products from your application using In-app Billing."
+    path_attributes:
+    - name: description
+      value: How to sell in-app products from your application using In-app Billing.
     section:
     - title: Preparing Your App
       path: /training/in-app-billing/preparing-iab-app.html
@@ -1197,8 +1468,9 @@
       path: /training/in-app-billing/test-iab-app.html
   - title: Maintaining Multiple APKs
     path: /training/multiple-apks/index.html
-    custom_link_attributes:
-    - description="How to publish your app on Google Play with separate APKs that target different devices, while using a single app listing."
+    path_attributes:
+    - name: description
+      value: How to publish your app on Google Play with separate APKs that target different devices, while using a single app listing.
     section:
     - title: Creating Multiple APKs for Different API Levels
       path: /training/multiple-apks/api.html
diff --git a/docs/image_sources/tools/support-library/appbar-kitkat-orig.png b/docs/image_sources/tools/support-library/appbar-kitkat-orig.png
new file mode 100644
index 0000000..ab680ce
--- /dev/null
+++ b/docs/image_sources/tools/support-library/appbar-kitkat-orig.png
Binary files differ
diff --git a/graphics/java/android/graphics/pdf/PdfRenderer.java b/graphics/java/android/graphics/pdf/PdfRenderer.java
index feb8052..520ebe5 100644
--- a/graphics/java/android/graphics/pdf/PdfRenderer.java
+++ b/graphics/java/android/graphics/pdf/PdfRenderer.java
@@ -129,6 +129,10 @@
      * <strong>Note:</strong> This class takes ownership of the passed in file descriptor
      * and is responsible for closing it when the renderer is closed.
      * </p>
+     * <p>
+     * If the file is from an untrusted source it is recommended to run the renderer in a separate,
+     * isolated process with minimal permissions to limit the impact of security exploits.
+     * </p>
      *
      * @param input Seekable file descriptor to read from.
      *
diff --git a/graphics/java/android/view/PixelCopy.java b/graphics/java/android/view/PixelCopy.java
index 95c930c..29bf963 100644
--- a/graphics/java/android/view/PixelCopy.java
+++ b/graphics/java/android/view/PixelCopy.java
@@ -123,6 +123,9 @@
     public static void request(@NonNull Surface source, @NonNull Bitmap dest,
             @NonNull OnPixelCopyFinishedListener listener, @NonNull Handler listenerThread) {
         validateBitmapDest(dest);
+        if (!source.isValid()) {
+            throw new IllegalArgumentException("Surface isn't valid, source.isValid() == false");
+        }
         // TODO: Make this actually async and fast and cool and stuff
         int result = ThreadedRenderer.copySurfaceInto(source, dest);
         listenerThread.post(new Runnable() {
diff --git a/include/androidfw/ZipUtils.h b/include/androidfw/ZipUtils.h
index 094eaa8..55575d7 100644
--- a/include/androidfw/ZipUtils.h
+++ b/include/androidfw/ZipUtils.h
@@ -21,6 +21,7 @@
 #define __LIBS_ZIPUTILS_H
 
 #include <stdint.h>
+#include <string.h>
 #include <stdio.h>
 #include <time.h>
 
@@ -63,16 +64,21 @@
 
     /*
      * Utility function to convert ZIP's time format to a timespec struct.
+     *
+     * NOTE: this method will clear all existing state from |timespec|.
      */
     static inline void zipTimeToTimespec(uint32_t when, struct tm* timespec) {
         const uint32_t date = when >> 16;
+
+        memset(timespec, 0, sizeof(struct tm));
         timespec->tm_year = ((date >> 9) & 0x7F) + 80; // Zip is years since 1980
-        timespec->tm_mon = (date >> 5) & 0x0F;
+        timespec->tm_mon = ((date >> 5) & 0x0F) - 1;
         timespec->tm_mday = date & 0x1F;
 
         timespec->tm_hour = (when >> 11) & 0x1F;
         timespec->tm_min = (when >> 5) & 0x3F;
         timespec->tm_sec = (when & 0x1F) << 1;
+        timespec->tm_isdst = -1;
     }
 private:
     ZipUtils() {}
diff --git a/libs/androidfw/tests/ZipUtils_test.cpp b/libs/androidfw/tests/ZipUtils_test.cpp
index c6038b5..7293843 100644
--- a/libs/androidfw/tests/ZipUtils_test.cpp
+++ b/libs/androidfw/tests/ZipUtils_test.cpp
@@ -45,7 +45,7 @@
     EXPECT_EQ(2011, t.tm_year + 1900)
             << "Year was improperly converted.";
 
-    EXPECT_EQ(6, t.tm_mon)
+    EXPECT_EQ(5, t.tm_mon)
             << "Month was improperly converted.";
 
     EXPECT_EQ(29, t.tm_mday)
@@ -59,6 +59,11 @@
 
     EXPECT_EQ(40, t.tm_sec)
             << "Second was improperly converted.";
+
+    // We don't have enough information to determine timezone related info.
+    EXPECT_EQ(-1, t.tm_isdst);
+    EXPECT_EQ(0, t.tm_gmtoff);
+    EXPECT_EQ(nullptr, t.tm_zone);
 }
 
 }
diff --git a/libs/hwui/GlopBuilder.cpp b/libs/hwui/GlopBuilder.cpp
index fdbe76a..0a8e3f3 100644
--- a/libs/hwui/GlopBuilder.cpp
+++ b/libs/hwui/GlopBuilder.cpp
@@ -471,18 +471,19 @@
     return *this;
 }
 
-GlopBuilder& GlopBuilder::setFillExternalTexture(Texture& texture) {
+GlopBuilder& GlopBuilder::setFillExternalTexture(Texture& texture, Matrix4& textureTransform) {
     TRIGGER_STAGE(kFillStage);
     REQUIRE_STAGES(kMeshStage | kRoundRectClipStage);
 
     mOutGlop->fill.texture = { &texture,
             GL_TEXTURE_EXTERNAL_OES, GL_LINEAR, GL_CLAMP_TO_EDGE,
-            nullptr };
+            &textureTransform };
 
     setFill(SK_ColorWHITE, 1.0f, SkXfermode::kSrc_Mode, Blend::ModeOrderSwap::NoSwap,
             nullptr, nullptr);
 
     mDescription.modulate = mOutGlop->fill.color.a < 1.0f;
+    mDescription.hasTextureTransform = true;
     return *this;
 }
 
diff --git a/libs/hwui/GlopBuilder.h b/libs/hwui/GlopBuilder.h
index b6c186d..a9dd56f 100644
--- a/libs/hwui/GlopBuilder.h
+++ b/libs/hwui/GlopBuilder.h
@@ -73,7 +73,7 @@
     // TODO: Texture should probably know and own its target.
     // setFillLayer() forces it to GL_TEXTURE which isn't always correct.
     // Similarly setFillLayer normally forces its own wrap & filter mode
-    GlopBuilder& setFillExternalTexture(Texture& texture);
+    GlopBuilder& setFillExternalTexture(Texture& texture, Matrix4& textureTransform);
 
     GlopBuilder& setTransform(const Snapshot& snapshot, const int transformFlags) {
         return setTransform(*snapshot.transform, transformFlags);
diff --git a/libs/hwui/Matrix.h b/libs/hwui/Matrix.h
index 36007cd..9cde5d6 100644
--- a/libs/hwui/Matrix.h
+++ b/libs/hwui/Matrix.h
@@ -236,6 +236,8 @@
 
     static const Matrix4& identity();
 
+    void invalidateType() { mType = kTypeUnknown; }
+
 private:
     mutable uint8_t mType;
 
diff --git a/libs/hwui/Readback.cpp b/libs/hwui/Readback.cpp
index 49596e1..55f823d 100644
--- a/libs/hwui/Readback.cpp
+++ b/libs/hwui/Readback.cpp
@@ -101,7 +101,10 @@
     // Setup the source
     sp<GraphicBuffer> sourceBuffer;
     sp<Fence> sourceFence;
-    status_t err = surface.getLastQueuedBuffer(&sourceBuffer, &sourceFence);
+    Matrix4 texTransform;
+    status_t err = surface.getLastQueuedBuffer(&sourceBuffer, &sourceFence,
+            texTransform.data);
+    texTransform.invalidateType();
     if (err != NO_ERROR) {
         ALOGW("Failed to get last queued buffer, error = %d", err);
         return CopyResult::UnknownError;
@@ -163,8 +166,8 @@
         Glop glop;
         GlopBuilder(renderState, caches, &glop)
                 .setRoundRectClipState(nullptr)
-                .setMeshTexturedUvQuad(nullptr, Rect(0, 1, 1, 0)) // TODO: simplify with VBO
-                .setFillExternalTexture(sourceTexture)
+                .setMeshTexturedUnitQuad(nullptr)
+                .setFillExternalTexture(sourceTexture, texTransform)
                 .setTransform(Matrix4::identity(), TransformFlags::None)
                 .setModelViewMapUnitToRect(destRect)
                 .build();
diff --git a/media/java/android/media/MediaCodecInfo.java b/media/java/android/media/MediaCodecInfo.java
index 05e12a1..6257238 100644
--- a/media/java/android/media/MediaCodecInfo.java
+++ b/media/java/android/media/MediaCodecInfo.java
@@ -1247,7 +1247,8 @@
         private Range<Double> estimateFrameRatesFor(int width, int height) {
             Size size = findClosestSize(width, height);
             Range<Long> range = mMeasuredFrameRates.get(size);
-            Double ratio = (double)(size.getWidth() * size.getHeight()) / (width * height);
+            Double ratio = getBlockCount(size.getWidth(), size.getHeight())
+                    / (double)Math.max(getBlockCount(width, height), 1);
             return Range.create(range.getLower() * ratio, range.getUpper() * ratio);
         }
 
@@ -2688,20 +2689,20 @@
         public static final int VP9Profile3HDR = 0x2000;
 
         // from OMX_VIDEO_VP9LEVELTYPE
-        public static final int VP9Level1  = 0x0;
-        public static final int VP9Level11 = 0x1;
-        public static final int VP9Level2  = 0x2;
-        public static final int VP9Level21 = 0x4;
-        public static final int VP9Level3  = 0x8;
-        public static final int VP9Level31 = 0x10;
-        public static final int VP9Level4  = 0x20;
-        public static final int VP9Level41 = 0x40;
-        public static final int VP9Level5  = 0x80;
-        public static final int VP9Level51 = 0x100;
-        public static final int VP9Level52 = 0x200;
-        public static final int VP9Level6  = 0x400;
-        public static final int VP9Level61 = 0x800;
-        public static final int VP9Level62 = 0x1000;
+        public static final int VP9Level1  = 0x1;
+        public static final int VP9Level11 = 0x2;
+        public static final int VP9Level2  = 0x4;
+        public static final int VP9Level21 = 0x8;
+        public static final int VP9Level3  = 0x10;
+        public static final int VP9Level31 = 0x20;
+        public static final int VP9Level4  = 0x40;
+        public static final int VP9Level41 = 0x80;
+        public static final int VP9Level5  = 0x100;
+        public static final int VP9Level51 = 0x200;
+        public static final int VP9Level52 = 0x400;
+        public static final int VP9Level6  = 0x800;
+        public static final int VP9Level61 = 0x1000;
+        public static final int VP9Level62 = 0x2000;
 
         // from OMX_VIDEO_HEVCPROFILETYPE
         public static final int HEVCProfileMain        = 0x01;
diff --git a/media/java/android/media/MediaFormat.java b/media/java/android/media/MediaFormat.java
index 346f083..93c595f 100644
--- a/media/java/android/media/MediaFormat.java
+++ b/media/java/android/media/MediaFormat.java
@@ -46,7 +46,8 @@
  * <tr><td>{@link #KEY_HEIGHT}</td><td>Integer</td><td></td></tr>
  * <tr><td>{@link #KEY_COLOR_FORMAT}</td><td>Integer</td><td>set by the user
  *         for encoders, readable in the output format of decoders</b></td></tr>
- * <tr><td>{@link #KEY_FRAME_RATE}</td><td>Integer or Float</td><td><b>encoder-only</b></td></tr>
+ * <tr><td>{@link #KEY_FRAME_RATE}</td><td>Integer or Float</td><td>required for <b>encoders</b>,
+ *         optional for <b>decoders</b></td></tr>
  * <tr><td>{@link #KEY_CAPTURE_RATE}</td><td>Integer</td><td></td></tr>
  * <tr><td>{@link #KEY_I_FRAME_INTERVAL}</td><td>Integer</td><td><b>encoder-only</b></td></tr>
  * <tr><td>{@link #KEY_INTRA_REFRESH_PERIOD}</td><td>Integer</td><td><b>encoder-only</b>, optional</td></tr>
@@ -197,7 +198,19 @@
 
     /**
      * A key describing the frame rate of a video format in frames/sec.
-     * The associated value is an integer or a float.
+     * The associated value is normally an integer when the value is used by the platform,
+     * but video codecs also accept float configuration values.
+     * Specifically, {@link MediaExtractor#getTrackFormat MediaExtractor} provides an integer
+     * value corresponding to the frame rate information of the track if specified and non-zero.
+     * Otherwise, this key is not present. {@link MediaCodec#configure MediaCodec} accepts both
+     * float and integer values. This represents the desired operating frame rate if the
+     * {@link #KEY_OPERATING_RATE} is not present and {@link #KEY_PRIORITY} is {@code 0}
+     * (realtime). For video encoders this value corresponds to the intended frame rate,
+     * although encoders are expected
+     * to support variable frame rate based on {@link MediaCodec.BufferInfo#presentationTimeUs
+     * buffer timestamp}. This key is not used in the {@code MediaCodec}
+     * {@link MediaCodec#getInputFormat input}/{@link MediaCodec#getOutputFormat output} formats,
+     * nor by {@link MediaMuxer#addTrack MediaMuxer}.
      */
     public static final String KEY_FRAME_RATE = "frame-rate";
 
diff --git a/media/java/android/media/tv/TvInputManager.java b/media/java/android/media/tv/TvInputManager.java
index 1d894e1..22bb5f1 100644
--- a/media/java/android/media/tv/TvInputManager.java
+++ b/media/java/android/media/tv/TvInputManager.java
@@ -188,6 +188,9 @@
             RECORDING_ERROR_RESOURCE_BUSY})
     public @interface RecordingError {}
 
+    static final int RECORDING_ERROR_START = 0;
+    static final int RECORDING_ERROR_END = 2;
+
     /**
      * Error for {@link TvInputService.RecordingSession#notifyError(int)} and
      * {@link TvRecordingClient.RecordingCallback#onError(int)}: The requested operation cannot be
@@ -195,7 +198,7 @@
      * for the problem is defined on the higher version than application's
      * <code>android:targetSdkVersion</code>.
      */
-    public static final int RECORDING_ERROR_UNKNOWN = 0;
+    public static final int RECORDING_ERROR_UNKNOWN = RECORDING_ERROR_START;
 
     /**
      * Error for {@link TvInputService.RecordingSession#notifyError(int)} and
@@ -209,7 +212,7 @@
      * {@link TvRecordingClient.RecordingCallback#onError(int)}: Recording cannot proceed because
      * a required recording resource was not able to be allocated.
      */
-    public static final int RECORDING_ERROR_RESOURCE_BUSY = 2;
+    public static final int RECORDING_ERROR_RESOURCE_BUSY = RECORDING_ERROR_END;
 
     /** @hide */
     @Retention(RetentionPolicy.SOURCE)
diff --git a/media/java/android/media/tv/TvInputService.java b/media/java/android/media/tv/TvInputService.java
index 488b284..168fcdc 100644
--- a/media/java/android/media/tv/TvInputService.java
+++ b/media/java/android/media/tv/TvInputService.java
@@ -1613,7 +1613,14 @@
          * <li>{@link TvInputManager#RECORDING_ERROR_RESOURCE_BUSY}
          * </ul>
          */
-        public void notifyError(@TvInputManager.RecordingError final int error) {
+        public void notifyError(@TvInputManager.RecordingError int error) {
+            if (error < TvInputManager.RECORDING_ERROR_START
+                    || error > TvInputManager.RECORDING_ERROR_END) {
+                Log.w(TAG, "notifyError - invalid error code (" + error
+                        + ") is changed to RECORDING_ERROR_UNKNOWN.");
+                error = TvInputManager.RECORDING_ERROR_UNKNOWN;
+            }
+            final int validError = error;
             executeOrPostRunnableOnMainThread(new Runnable() {
                 @MainThread
                 @Override
@@ -1621,7 +1628,7 @@
                     try {
                         if (DEBUG) Log.d(TAG, "notifyError");
                         if (mSessionCallback != null) {
-                            mSessionCallback.onError(error);
+                            mSessionCallback.onError(validError);
                         }
                     } catch (RemoteException e) {
                         Log.w(TAG, "error in notifyError", e);
diff --git a/packages/SettingsLib/res/values/strings.xml b/packages/SettingsLib/res/values/strings.xml
index 74c98e4..efa34ff 100644
--- a/packages/SettingsLib/res/values/strings.xml
+++ b/packages/SettingsLib/res/values/strings.xml
@@ -421,8 +421,6 @@
     <string name="wifi_aggressive_handover">Aggressive Wi\u2011Fi to Cellular handover</string>
     <!-- Setting Checkbox title whether to enable WiFi Scanning in the presence of traffic. [CHAR LIMIT=80] -->
     <string name="wifi_allow_scan_with_traffic">Always allow Wi\u2011Fi Roam Scans</string>
-    <!-- Setting Checkbox title whether to enable WiFi Scanning in the presence of traffic. [CHAR LIMIT=80] -->
-    <string name="legacy_dhcp_client">Use legacy DHCP client</string>
     <!-- Setting Checkbox title whether to always keep cellular data active. [CHAR LIMIT=80] -->
     <string name="mobile_data_always_on">Cellular data always active</string>
     <!-- Setting Checkbox title for disabling Bluetooth absolute volume -->
diff --git a/packages/SettingsLib/src/com/android/settingslib/drawer/SettingsDrawerActivity.java b/packages/SettingsLib/src/com/android/settingslib/drawer/SettingsDrawerActivity.java
index bcbc6ac..bf75046 100644
--- a/packages/SettingsLib/src/com/android/settingslib/drawer/SettingsDrawerActivity.java
+++ b/packages/SettingsLib/src/com/android/settingslib/drawer/SettingsDrawerActivity.java
@@ -52,7 +52,7 @@
     protected static final boolean DEBUG_TIMING = false;
     private static final String TAG = "SettingsDrawerActivity";
 
-    static final String EXTRA_SHOW_MENU = "show_drawer_menu";
+    public static final String EXTRA_SHOW_MENU = "show_drawer_menu";
 
     private static List<DashboardCategory> sDashboardCategories;
     private static HashMap<Pair<String, String>, Tile> sTileCache;
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
index db720bb..5ff9c0c 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
@@ -846,7 +846,7 @@
 
                 // Special case for location (sigh).
                 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
-                    return null;
+                    continue;
                 }
 
                 Setting setting = mSettingsRegistry.getSettingLocked(
@@ -871,7 +871,8 @@
 
         // Special case for location (sigh).
         if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
-            return null;
+            return mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
+                    owningUserId).getNullSetting();
         }
 
         // Get the value.
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsState.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsState.java
index 6dfd0e6..2de0618c 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsState.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsState.java
@@ -16,7 +16,6 @@
 
 package com.android.providers.settings;
 
-import android.os.Bundle;
 import android.os.Handler;
 import android.os.Message;
 import android.os.SystemClock;
@@ -159,6 +158,10 @@
         return mVersion;
     }
 
+    public Setting getNullSetting() {
+        return mNullSetting;
+    }
+
     // The settings provider must hold its lock when calling here.
     public void setVersionLocked(int version) {
         if (version == mVersion) {
diff --git a/packages/SystemUI/res/color/remote_input_text.xml b/packages/SystemUI/res/color/remote_input_text.xml
index 11ce0b7..8e18e16 100644
--- a/packages/SystemUI/res/color/remote_input_text.xml
+++ b/packages/SystemUI/res/color/remote_input_text.xml
@@ -16,6 +16,6 @@
   -->
 
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
-    <item android:state_enabled="true" android:color="@android:color/white" />
+    <item android:state_enabled="true" android:color="@color/remote_input_text_enabled" /> <!-- white -->
     <item android:color="#99ffffff" /> <!-- 60% white -->
 </selector>
\ No newline at end of file
diff --git a/packages/SystemUI/res/layout/volume_dialog_row.xml b/packages/SystemUI/res/layout/volume_dialog_row.xml
index f0ae1c9..be05a3a 100644
--- a/packages/SystemUI/res/layout/volume_dialog_row.xml
+++ b/packages/SystemUI/res/layout/volume_dialog_row.xml
@@ -18,6 +18,7 @@
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:clipChildren="false"
+    android:clipToPadding="false"
     android:id="@+id/volume_dialog_row"
     android:paddingEnd="@dimen/volume_button_size" >
 
diff --git a/packages/SystemUI/res/values/colors.xml b/packages/SystemUI/res/values/colors.xml
index c75741c..cb51649 100644
--- a/packages/SystemUI/res/values/colors.xml
+++ b/packages/SystemUI/res/values/colors.xml
@@ -157,6 +157,7 @@
     <color name="minimize_dock_shadow_end">#00000000</color>
 
     <color name="default_remote_input_background">@*android:color/notification_default_color</color>
+    <color name="remote_input_text_enabled">#ffffffff</color>
     <color name="remote_input_hint">#99ffffff</color>
 
     <color name="remote_input_accent">#eeeeee</color>
diff --git a/packages/SystemUI/src/com/android/systemui/ImageWallpaper.java b/packages/SystemUI/src/com/android/systemui/ImageWallpaper.java
index c72f5d2..0962d84 100644
--- a/packages/SystemUI/src/com/android/systemui/ImageWallpaper.java
+++ b/packages/SystemUI/src/com/android/systemui/ImageWallpaper.java
@@ -158,6 +158,7 @@
         private int mLastRequestedHeight = -1;
         private AsyncTask<Void, Void, Bitmap> mLoader;
         private boolean mNeedsDrawAfterLoadingWallpaper;
+        private boolean mSurfaceValid;
 
         public DrawableEngine() {
             super();
@@ -249,11 +250,6 @@
         }
 
         @Override
-        public void onTouchEvent(MotionEvent event) {
-            super.onTouchEvent(event);
-        }
-
-        @Override
         public void onOffsetsChanged(float xOffset, float yOffset,
                 float xOffsetStep, float yOffsetStep,
                 int xPixels, int yPixels) {
@@ -288,13 +284,23 @@
         @Override
         public void onSurfaceDestroyed(SurfaceHolder holder) {
             super.onSurfaceDestroyed(holder);
+            if (DEBUG) {
+                Log.i(TAG, "onSurfaceDestroyed");
+            }
+
             mLastSurfaceWidth = mLastSurfaceHeight = -1;
+            mSurfaceValid = false;
         }
 
         @Override
         public void onSurfaceCreated(SurfaceHolder holder) {
             super.onSurfaceCreated(holder);
+            if (DEBUG) {
+                Log.i(TAG, "onSurfaceCreated");
+            }
+
             mLastSurfaceWidth = mLastSurfaceHeight = -1;
+            mSurfaceValid = true;
         }
 
         @Override
@@ -314,6 +320,9 @@
         }
 
         void drawFrame() {
+            if (!mSurfaceValid) {
+                return;
+            }
             try {
                 DisplayInfo displayInfo = getDefaultDisplayInfo();
                 int newRotation = displayInfo.rotation;
diff --git a/packages/SystemUI/src/com/android/systemui/Prefs.java b/packages/SystemUI/src/com/android/systemui/Prefs.java
index 28ed84f..907616c 100644
--- a/packages/SystemUI/src/com/android/systemui/Prefs.java
+++ b/packages/SystemUI/src/com/android/systemui/Prefs.java
@@ -44,6 +44,7 @@
         Key.TV_PICTURE_IN_PICTURE_ONBOARDING_SHOWN,
         Key.QS_HOTSPOT_ADDED,
         Key.QS_DATA_SAVER_ADDED,
+        Key.QS_DATA_SAVER_DIALOG_SHOWN,
         Key.QS_INVERT_COLORS_ADDED,
         Key.QS_WORK_ADDED,
         Key.QS_NIGHT_ADDED,
@@ -63,6 +64,7 @@
         String TV_PICTURE_IN_PICTURE_ONBOARDING_SHOWN = "TvPictureInPictureOnboardingShown";
         String QS_HOTSPOT_ADDED = "QsHotspotAdded";
         String QS_DATA_SAVER_ADDED = "QsDataSaverAdded";
+        String QS_DATA_SAVER_DIALOG_SHOWN = "QsDataSaverDialogShown";
         String QS_INVERT_COLORS_ADDED = "QsInvertColorsAdded";
         String QS_WORK_ADDED = "QsWorkAdded";
         String QS_NIGHT_ADDED = "QsNightAdded";
diff --git a/packages/SystemUI/src/com/android/systemui/qs/customize/QSCustomizer.java b/packages/SystemUI/src/com/android/systemui/qs/customize/QSCustomizer.java
index 716185f..b2aa966 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/customize/QSCustomizer.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/customize/QSCustomizer.java
@@ -106,6 +106,7 @@
     public void setHost(QSTileHost host) {
         mHost = host;
         mPhoneStatusBar = host.getPhoneStatusBar();
+        mTileAdapter.setHost(host);
     }
 
     public void setContainer(NotificationsQuickSettingsContainer notificationsQsContainer) {
diff --git a/packages/SystemUI/src/com/android/systemui/qs/customize/TileAdapter.java b/packages/SystemUI/src/com/android/systemui/qs/customize/TileAdapter.java
index 41b49d8..ec0eefb 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/customize/TileAdapter.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/customize/TileAdapter.java
@@ -81,6 +81,7 @@
     private Holder mCurrentDrag;
     private boolean mAccessibilityMoving;
     private int mAccessibilityFromIndex;
+    private QSTileHost mHost;
 
     public TileAdapter(Context context) {
         mContext = context;
@@ -88,6 +89,10 @@
         mItemTouchHelper = new ItemTouchHelper(mCallbacks);
     }
 
+    public void setHost(QSTileHost host) {
+        mHost = host;
+    }
+
     @Override
     public long getItemId(int position) {
         return mTiles.get(position) != null ? mAllTiles.indexOf(mTiles.get(position))
@@ -108,7 +113,7 @@
             newSpecs.add(mTiles.get(i).spec);
         }
         host.changeTiles(mCurrentSpecs, newSpecs);
-        setTileSpecs(newSpecs);
+        mCurrentSpecs = newSpecs;
     }
 
     public void setTileSpecs(List<String> currentSpecs) {
@@ -285,6 +290,7 @@
         move(mAccessibilityFromIndex, position, v);
         notifyItemChanged(mAccessibilityFromIndex);
         notifyItemMoved(mAccessibilityFromIndex, position);
+        saveSpecs(mHost);
     }
 
     private void showAccessibilityDialog(final int position, final View v) {
@@ -373,6 +379,7 @@
                     fromLabel, (to + 1));
         }
         v.announceForAccessibility(announcement);
+        saveSpecs(mHost);
         return true;
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/DataSaverTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/DataSaverTile.java
index dded595..0ce805e 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/DataSaverTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/DataSaverTile.java
@@ -14,12 +14,15 @@
 
 package com.android.systemui.qs.tiles;
 
+import android.content.DialogInterface;
 import android.content.Intent;
 
 import com.android.internal.logging.MetricsLogger;
 import com.android.internal.logging.MetricsProto.MetricsEvent;
+import com.android.systemui.Prefs;
 import com.android.systemui.R;
 import com.android.systemui.qs.QSTile;
+import com.android.systemui.statusbar.phone.SystemUIDialog;
 import com.android.systemui.statusbar.policy.DataSaverController;
 
 public class DataSaverTile extends QSTile<QSTile.BooleanState> implements
@@ -53,6 +56,29 @@
 
     @Override
     protected void handleClick() {
+        if (Prefs.getBoolean(mContext, Prefs.Key.QS_DATA_SAVER_DIALOG_SHOWN, false)) {
+            // Do it right away.
+            toggleDataSaver();
+            return;
+        }
+        // Shows dialog first
+        SystemUIDialog dialog = new SystemUIDialog(mContext);
+        dialog.setTitle(com.android.internal.R.string.data_saver_enable_title);
+        dialog.setMessage(com.android.internal.R.string.data_saver_description);
+        dialog.setPositiveButton(com.android.internal.R.string.data_saver_enable_button,
+                new DialogInterface.OnClickListener() {
+                    @Override
+                    public void onClick(DialogInterface dialog, int which) {
+                        toggleDataSaver();
+                    }
+                });
+        dialog.setNegativeButton(com.android.internal.R.string.cancel, null);
+        dialog.setShowForAllUsers(true);
+        dialog.show();
+        Prefs.putBoolean(mContext, Prefs.Key.QS_DATA_SAVER_DIALOG_SHOWN, true);
+    }
+
+    private void toggleDataSaver() {
         mState.value = !mDataSaverController.isDataSaverEnabled();
         MetricsLogger.action(mContext, getMetricsCategory(), mState.value);
         mDataSaverController.setDataSaverEnabled(mState.value);
diff --git a/packages/SystemUI/src/com/android/systemui/stackdivider/ForcedResizableInfoActivityController.java b/packages/SystemUI/src/com/android/systemui/stackdivider/ForcedResizableInfoActivityController.java
index 9294ecd..34a37ba 100644
--- a/packages/SystemUI/src/com/android/systemui/stackdivider/ForcedResizableInfoActivityController.java
+++ b/packages/SystemUI/src/com/android/systemui/stackdivider/ForcedResizableInfoActivityController.java
@@ -111,6 +111,7 @@
             Intent intent = new Intent(mContext, ForcedResizableInfoActivity.class);
             ActivityOptions options = ActivityOptions.makeBasic();
             options.setLaunchTaskId(mPendingTaskIds.valueAt(i));
+            options.setAvoidMoveToFront(true);
             mContext.startActivity(intent, options.toBundle());
         }
         mPendingTaskIds.clear();
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/ExpandableNotificationRow.java b/packages/SystemUI/src/com/android/systemui/statusbar/ExpandableNotificationRow.java
index 8239425..5b16fce 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/ExpandableNotificationRow.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/ExpandableNotificationRow.java
@@ -277,6 +277,10 @@
         int intrinsicBefore = getIntrinsicHeight();
         mIsHeadsUp = isHeadsUp;
         mPrivateLayout.setHeadsUp(isHeadsUp);
+        if (mIsSummaryWithChildren) {
+            // The overflow might change since we allow more lines as HUN.
+            mChildrenContainer.updateGroupOverflow();
+        }
         if (intrinsicBefore != getIntrinsicHeight()) {
             notifyHeightChanged(false  /* needsAnimation */);
         }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationContentView.java b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationContentView.java
index 7be50c4..5e9a8bc 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationContentView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationContentView.java
@@ -17,6 +17,7 @@
 package com.android.systemui.statusbar;
 
 import android.app.Notification;
+import android.app.PendingIntent;
 import android.app.RemoteInput;
 import android.content.Context;
 import android.graphics.Rect;
@@ -55,15 +56,6 @@
     private final Rect mClipBounds = new Rect();
     private final int mMinContractedHeight;
     private final int mNotificationContentMarginEnd;
-    private final OnLayoutChangeListener mLayoutUpdater = new OnLayoutChangeListener() {
-        @Override
-        public void onLayoutChange(View v, int left, int top, int right, int bottom,
-                int oldLeft,
-                int oldTop, int oldRight, int oldBottom) {
-            selectLayout(false /* animate */, false /* force */);
-        }
-    };
-
 
     private View mContractedChild;
     private View mExpandedChild;
@@ -118,6 +110,9 @@
     private int mTransformationStartVisibleType;
     private boolean mUserExpanding;
     private int mSingleLineWidthIndention;
+    private boolean mForceSelectNextLayout = true;
+    private PendingIntent mPreviousExpandedRemoteInputIntent;
+    private PendingIntent mPreviousHeadsUpRemoteInputIntent;
 
     public NotificationContentView(Context context, AttributeSet attrs) {
         super(context, attrs);
@@ -267,6 +262,8 @@
         super.onLayout(changed, left, top, right, bottom);
         updateClipping();
         invalidateOutline();
+        selectLayout(false /* animate */, mForceSelectNextLayout /* force */);
+        mForceSelectNextLayout = false;
     }
 
     @Override
@@ -280,13 +277,19 @@
             mContractedChild.animate().cancel();
             removeView(mContractedChild);
         }
+        mPreviousExpandedRemoteInputIntent =
+                mExpandedRemoteInput != null ? mExpandedRemoteInput.getPendingIntent() : null;
         if (mExpandedChild != null) {
             mExpandedChild.animate().cancel();
             removeView(mExpandedChild);
+            mExpandedRemoteInput = null;
         }
+        mPreviousHeadsUpRemoteInputIntent =
+                mHeadsUpRemoteInput != null ? mHeadsUpRemoteInput.getPendingIntent() : null;
         if (mHeadsUpChild != null) {
             mHeadsUpChild.animate().cancel();
             removeView(mHeadsUpChild);
+            mHeadsUpRemoteInput = null;
         }
         mContractedChild = null;
         mExpandedChild = null;
@@ -308,44 +311,35 @@
     public void setContractedChild(View child) {
         if (mContractedChild != null) {
             mContractedChild.animate().cancel();
-            mContractedChild.removeOnLayoutChangeListener(mLayoutUpdater);
             removeView(mContractedChild);
         }
         addView(child);
         mContractedChild = child;
-        mContractedChild.addOnLayoutChangeListener(mLayoutUpdater);
         mContractedWrapper = NotificationViewWrapper.wrap(getContext(), child,
                 mContainingNotification);
-        selectLayout(false /* animate */, true /* force */);
         mContractedWrapper.setDark(mDark, false /* animate */, 0 /* delay */);
     }
 
     public void setExpandedChild(View child) {
         if (mExpandedChild != null) {
             mExpandedChild.animate().cancel();
-            mExpandedChild.removeOnLayoutChangeListener(mLayoutUpdater);
             removeView(mExpandedChild);
         }
         addView(child);
         mExpandedChild = child;
-        mExpandedChild.addOnLayoutChangeListener(mLayoutUpdater);
         mExpandedWrapper = NotificationViewWrapper.wrap(getContext(), child,
                 mContainingNotification);
-        selectLayout(false /* animate */, true /* force */);
     }
 
     public void setHeadsUpChild(View child) {
         if (mHeadsUpChild != null) {
             mHeadsUpChild.animate().cancel();
-            mHeadsUpChild.removeOnLayoutChangeListener(mLayoutUpdater);
             removeView(mHeadsUpChild);
         }
         addView(child);
         mHeadsUpChild = child;
-        mHeadsUpChild.addOnLayoutChangeListener(mLayoutUpdater);
         mHeadsUpWrapper = NotificationViewWrapper.wrap(getContext(), child,
                 mContainingNotification);
-        selectLayout(false /* animate */, true /* force */);
     }
 
     @Override
@@ -399,7 +393,8 @@
             updateBackgroundColor(true /* animate */);
         }
         if (mTransformationStartVisibleType != UNDEFINED
-                && mVisibleType != mTransformationStartVisibleType) {
+                && mVisibleType != mTransformationStartVisibleType
+                && getViewForVisibleType(mTransformationStartVisibleType) != null) {
             final TransformableView shownView = getTransformableViewForVisibleType(mVisibleType);
             final TransformableView hiddenView = getTransformableViewForVisibleType(
                     mTransformationStartVisibleType);
@@ -492,20 +487,66 @@
         }
         if (mUserExpanding) {
             updateContentTransformation();
-            return;
-        }
-        int visibleType = calculateVisibleType();
-        if (visibleType != mVisibleType || force) {
-            if (animate && ((visibleType == VISIBLE_TYPE_EXPANDED && mExpandedChild != null)
-                    || (visibleType == VISIBLE_TYPE_HEADSUP && mHeadsUpChild != null)
-                    || (visibleType == VISIBLE_TYPE_SINGLELINE && mSingleLineView != null)
-                    || visibleType == VISIBLE_TYPE_CONTRACTED)) {
-                animateToVisibleType(visibleType);
-            } else {
-                updateViewVisibilities(visibleType);
+        } else {
+            int visibleType = calculateVisibleType();
+            if (visibleType != mVisibleType || force) {
+            View visibleView = getViewForVisibleType(visibleType);
+            if (visibleView != null) {
+                visibleView.setVisibility(VISIBLE);
+                transferRemoteInputFocus(visibleType);
             }
-            mVisibleType = visibleType;
-            updateBackgroundColor(animate);
+
+                if (animate && ((visibleType == VISIBLE_TYPE_EXPANDED && mExpandedChild != null)
+                        || (visibleType == VISIBLE_TYPE_HEADSUP && mHeadsUpChild != null)
+                        || (visibleType == VISIBLE_TYPE_SINGLELINE && mSingleLineView != null)
+                        || visibleType == VISIBLE_TYPE_CONTRACTED)) {
+                    animateToVisibleType(visibleType);
+                } else {
+                    updateViewVisibilities(visibleType);
+                }
+                mVisibleType = visibleType;
+                updateBackgroundColor(animate);
+            }
+        }
+        if (mForceSelectNextLayout) {
+            forceUpdateVisibilities();
+        }
+    }
+
+    private void forceUpdateVisibilities() {
+        boolean contractedVisible = mVisibleType == VISIBLE_TYPE_CONTRACTED
+                || mTransformationStartVisibleType == VISIBLE_TYPE_CONTRACTED;
+        boolean expandedVisible = mVisibleType == VISIBLE_TYPE_EXPANDED
+                || mTransformationStartVisibleType == VISIBLE_TYPE_EXPANDED;
+        boolean headsUpVisible = mVisibleType == VISIBLE_TYPE_HEADSUP
+                || mTransformationStartVisibleType == VISIBLE_TYPE_HEADSUP;
+        boolean singleLineVisible = mVisibleType == VISIBLE_TYPE_SINGLELINE
+                || mTransformationStartVisibleType == VISIBLE_TYPE_SINGLELINE;
+        if (!contractedVisible) {
+            mContractedChild.setVisibility(View.INVISIBLE);
+        } else {
+            mContractedWrapper.setVisible(true);
+        }
+        if (mExpandedChild != null) {
+            if (!expandedVisible) {
+                mExpandedChild.setVisibility(View.INVISIBLE);
+            } else {
+                mExpandedWrapper.setVisible(true);
+            }
+        }
+        if (mHeadsUpChild != null) {
+            if (!headsUpVisible) {
+                mHeadsUpChild.setVisibility(View.INVISIBLE);
+            } else {
+                mHeadsUpWrapper.setVisible(true);
+            }
+        }
+        if (mSingleLineView != null) {
+            if (!singleLineVisible) {
+                mSingleLineView.setVisibility(View.INVISIBLE);
+            } else {
+                mSingleLineView.setVisible(true);
+            }
         }
     }
 
@@ -543,7 +584,7 @@
     private void animateToVisibleType(int visibleType) {
         final TransformableView shownView = getTransformableViewForVisibleType(visibleType);
         final TransformableView hiddenView = getTransformableViewForVisibleType(mVisibleType);
-        if (shownView == hiddenView) {
+        if (shownView == hiddenView || hiddenView == null) {
             shownView.setVisible(true);
             return;
         }
@@ -559,6 +600,19 @@
         });
     }
 
+    private void transferRemoteInputFocus(int visibleType) {
+        if (visibleType == VISIBLE_TYPE_HEADSUP
+                && mHeadsUpRemoteInput != null
+                && (mExpandedRemoteInput != null && mExpandedRemoteInput.isActive())) {
+            mHeadsUpRemoteInput.stealFocusFrom(mExpandedRemoteInput);
+        }
+        if (visibleType == VISIBLE_TYPE_EXPANDED
+                && mExpandedRemoteInput != null
+                && (mHeadsUpRemoteInput != null && mHeadsUpRemoteInput.isActive())) {
+            mExpandedRemoteInput.stealFocusFrom(mHeadsUpRemoteInput);
+        }
+    }
+
     /**
      * @param visibleType one of the static enum types in this view
      * @return the corresponding transformable view according to the given visible type
@@ -619,8 +673,9 @@
                 height = mContentHeight;
             }
             int expandedVisualType = getVisualTypeForHeight(height);
-            int collapsedVisualType = getVisualTypeForHeight(
-                    mContainingNotification.getCollapsedHeight());
+            int collapsedVisualType = mIsChildInGroup && !isGroupExpanded()
+                    ? VISIBLE_TYPE_SINGLELINE
+                    : getVisualTypeForHeight(mContainingNotification.getCollapsedHeight());
             return mTransformationStartVisibleType == collapsedVisualType
                     ? expandedVisualType
                     : collapsedVisualType;
@@ -734,8 +789,10 @@
             mHeadsUpWrapper.notifyContentUpdated(entry.notification);
         }
         updateShowingLegacyBackground();
-        selectLayout(false /* animate */, true /* force */);
+        mForceSelectNextLayout = true;
         setDark(mDark, false /* animate */, 0 /* delay */);
+        mPreviousExpandedRemoteInputIntent = null;
+        mPreviousHeadsUpRemoteInputIntent = null;
     }
 
     private void updateSingleLineView() {
@@ -771,19 +828,23 @@
 
         View bigContentView = mExpandedChild;
         if (bigContentView != null) {
-            mExpandedRemoteInput = applyRemoteInput(bigContentView, entry, hasRemoteInput);
+            mExpandedRemoteInput = applyRemoteInput(bigContentView, entry, hasRemoteInput,
+                    mPreviousExpandedRemoteInputIntent);
         } else {
             mExpandedRemoteInput = null;
         }
+
         View headsUpContentView = mHeadsUpChild;
         if (headsUpContentView != null) {
-            mHeadsUpRemoteInput = applyRemoteInput(headsUpContentView, entry, hasRemoteInput);
+            mHeadsUpRemoteInput = applyRemoteInput(headsUpContentView, entry, hasRemoteInput,
+                    mPreviousHeadsUpRemoteInputIntent);
         } else {
             mHeadsUpRemoteInput = null;
         }
     }
 
-    private RemoteInputView applyRemoteInput(View view, NotificationData.Entry entry, boolean hasRemoteInput) {
+    private RemoteInputView applyRemoteInput(View view, NotificationData.Entry entry,
+            boolean hasRemoteInput, PendingIntent existingPendingIntent) {
         View actionContainerCandidate = view.findViewById(
                 com.android.internal.R.id.actions_container);
         if (actionContainerCandidate instanceof FrameLayout) {
@@ -812,8 +873,26 @@
                     color = mContext.getColor(R.color.default_remote_input_background);
                 }
                 existing.setBackgroundColor(NotificationColorUtil.ensureTextBackgroundColor(color,
-                        mContext.getColor(R.color.remote_input_text),
+                        mContext.getColor(R.color.remote_input_text_enabled),
                         mContext.getColor(R.color.remote_input_hint)));
+
+                if (existingPendingIntent != null || existing.isActive()) {
+                    // The current action could be gone, or the pending intent no longer valid.
+                    // If we find a matching action in the new notification, focus, otherwise close.
+                    Notification.Action[] actions = entry.notification.getNotification().actions;
+                    if (existingPendingIntent != null) {
+                        existing.setPendingIntent(existingPendingIntent);
+                    }
+                    if (existing.updatePendingIntentFromActions(actions)) {
+                        if (!existing.isActive()) {
+                            existing.focus();
+                        }
+                    } else {
+                        if (existing.isActive()) {
+                            existing.close();
+                        }
+                    }
+                }
             }
             return existing;
         }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarIconView.java b/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarIconView.java
index 6d76763e..ce0163e 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarIconView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarIconView.java
@@ -327,7 +327,14 @@
     public static String contentDescForNotification(Context c, Notification n) {
         Notification.Builder builder = Notification.Builder.recoverBuilder(c, n);
         String appName = builder.loadHeaderAppName();
+
+        CharSequence title = n.extras.getString(Notification.EXTRA_TITLE);
         CharSequence ticker = n.tickerText;
-        return c.getString(R.string.accessibility_desc_notification_icon, appName, ticker);
+
+        CharSequence desc = !TextUtils.isEmpty(ticker) ? ticker
+                : !TextUtils.isEmpty(title) ? title : "";
+
+        return c.getString(R.string.accessibility_desc_notification_icon, appName, desc);
     }
+
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationMediaTemplateViewWrapper.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationMediaTemplateViewWrapper.java
index 3c95a78..4ce330c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationMediaTemplateViewWrapper.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationMediaTemplateViewWrapper.java
@@ -52,7 +52,7 @@
         // This also clears the existing types
         super.updateTransformedTypes();
         if (mActions != null) {
-            mTransformationHelper.addTransformedView(TransformableView.TRANSFORMING_VIEW_TEXT,
+            mTransformationHelper.addTransformedView(TransformableView.TRANSFORMING_VIEW_ACTIONS,
                     mActions);
         }
     }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/TransformState.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/TransformState.java
index f04fe5e..8207215 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/TransformState.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/TransformState.java
@@ -100,8 +100,17 @@
         boolean transformY = (transformationFlags & TRANSOFORM_Y) != 0;
         boolean transformScale = transformScale();
         // lets animate the positions correctly
-        if (transformationAmount == 0.0f) {
-            int[] otherPosition = otherState.getLocationOnScreen();
+        if (transformationAmount == 0.0f
+                || transformX && getTransformationStartX() == UNDEFINED
+                || transformY && getTransformationStartY() == UNDEFINED
+                || transformScale && getTransformationStartScaleX() == UNDEFINED
+                || transformScale && getTransformationStartScaleY() == UNDEFINED) {
+            int[] otherPosition;
+            if (transformationAmount != 0.0f) {
+                otherPosition = otherState.getLaidOutLocationOnScreen();
+            } else {
+                otherPosition = otherState.getLocationOnScreen();
+            }
             int[] ownStablePosition = getLaidOutLocationOnScreen();
             if (customTransformation == null
                     || !customTransformation.initTransformation(this, otherState)) {
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 23e3561..6fc32de 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
@@ -409,6 +409,9 @@
                 if (mKeyguardBottomArea != null) {
                     mKeyguardBottomArea.setUserSetupComplete(mUserSetup);
                 }
+                if (mNetworkController != null) {
+                    mNetworkController.setUserSetupComplete(mUserSetup);
+                }
             }
             if (mIconPolicy != null) {
                 mIconPolicy.setCurrentUserSetup(mUserSetup);
@@ -838,6 +841,7 @@
             }
         });
         mNetworkController = new NetworkControllerImpl(mContext, mHandlerThread.getLooper());
+        mNetworkController.setUserSetupComplete(mUserSetup);
         mHotspotController = new HotspotControllerImpl(mContext);
         mBluetoothController = new BluetoothControllerImpl(mContext, mHandlerThread.getLooper());
         mSecurityController = new SecurityControllerImpl(mContext);
@@ -1437,7 +1441,11 @@
     public void removeNotification(String key, RankingMap ranking) {
         boolean deferRemoval = false;
         if (mHeadsUpManager.isHeadsUp(key)) {
-            deferRemoval = !mHeadsUpManager.removeNotification(key);
+            // A cancel() in repsonse to a remote input shouldn't be delayed, as it makes the
+            // sending look longer than it takes.
+            boolean ignoreEarliestRemovalTime = mRemoteInputController.isSpinning(key)
+                    && !FORCE_REMOTE_INPUT_HISTORY;
+            deferRemoval = !mHeadsUpManager.removeNotification(key,  ignoreEarliestRemovalTime);
         }
         if (key.equals(mMediaNotificationKey)) {
             clearCurrentMediaNotification();
@@ -1985,19 +1993,29 @@
                 artworkDrawable = new BitmapDrawable(mBackdropBack.getResources(), artworkBitmap);
             }
         }
+        boolean allowWhenShade = false;
         if (ENABLE_LOCKSCREEN_WALLPAPER && artworkDrawable == null) {
             Bitmap lockWallpaper = mLockscreenWallpaper.getBitmap();
             if (lockWallpaper != null) {
                 artworkDrawable = new LockscreenWallpaper.WallpaperDrawable(
                         mBackdropBack.getResources(), lockWallpaper);
+                // We're in the SHADE mode on the SIM screen - yet we still need to show
+                // the lockscreen wallpaper in that mode.
+                allowWhenShade = mStatusBarKeyguardViewManager != null
+                        && mStatusBarKeyguardViewManager.isShowing();
             }
         }
 
+        boolean hideBecauseOccluded = mStatusBarKeyguardViewManager != null
+                && mStatusBarKeyguardViewManager.isOccluded();
+
         final boolean hasArtwork = artworkDrawable != null;
 
-        if ((hasArtwork || DEBUG_MEDIA_FAKE_ARTWORK) && mState != StatusBarState.SHADE
+        if ((hasArtwork || DEBUG_MEDIA_FAKE_ARTWORK)
+                && (mState != StatusBarState.SHADE || allowWhenShade)
                 && mFingerprintUnlockController.getMode()
-                        != FingerprintUnlockController.MODE_WAKE_AND_UNLOCK_PULSING) {
+                        != FingerprintUnlockController.MODE_WAKE_AND_UNLOCK_PULSING
+                && !hideBecauseOccluded) {
             // time to show some art!
             if (mBackdrop.getVisibility() != View.VISIBLE) {
                 mBackdrop.setVisibility(View.VISIBLE);
@@ -2065,7 +2083,8 @@
                     Log.v(TAG, "DEBUG_MEDIA: Fading out album artwork");
                 }
                 if (mFingerprintUnlockController.getMode()
-                        == FingerprintUnlockController.MODE_WAKE_AND_UNLOCK_PULSING) {
+                        == FingerprintUnlockController.MODE_WAKE_AND_UNLOCK_PULSING
+                        || hideBecauseOccluded) {
 
                     // We are unlocking directly - no animation!
                     mBackdrop.setVisibility(View.GONE);
@@ -2353,7 +2372,7 @@
         if (wasHeadsUp) {
             if (!shouldPeek) {
                 // We don't want this to be interrupting anymore, lets remove it
-                mHeadsUpManager.removeNotification(key);
+                mHeadsUpManager.removeNotification(key, false /* ignoreEarliestRemovalTime */);
             } else {
                 mHeadsUpManager.updateNotification(entry, alertAgain);
             }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java
index 117e2b3..dcad75a 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java
@@ -247,6 +247,7 @@
             }
         }
         mOccluded = occluded;
+        mPhoneStatusBar.updateMediaMetaData(false, false);
         mStatusBarWindowManager.setKeyguardOccluded(occluded);
         reset();
     }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/BrightnessMirrorController.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/BrightnessMirrorController.java
index 7a6d080..ddded49 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/BrightnessMirrorController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/BrightnessMirrorController.java
@@ -25,12 +25,14 @@
 import com.android.systemui.R;
 import com.android.systemui.statusbar.ScrimView;
 import com.android.systemui.statusbar.phone.StatusBarWindowView;
+import com.android.systemui.statusbar.stack.NotificationStackScrollLayout;
 
 /**
  * Controls showing and hiding of the brightness mirror.
  */
 public class BrightnessMirrorController {
 
+    private final NotificationStackScrollLayout mStackScroller;
     public long TRANSITION_DURATION_OUT = 150;
     public long TRANSITION_DURATION_IN = 200;
 
@@ -45,10 +47,13 @@
         mScrimBehind = (ScrimView) statusBarWindow.findViewById(R.id.scrim_behind);
         mBrightnessMirror = statusBarWindow.findViewById(R.id.brightness_mirror);
         mNotificationPanel = statusBarWindow.findViewById(R.id.notification_panel);
+        mStackScroller = (NotificationStackScrollLayout) statusBarWindow.findViewById(
+                R.id.notification_stack_scroller);
     }
 
     public void showMirror() {
         mBrightnessMirror.setVisibility(View.VISIBLE);
+        mStackScroller.setFadedOut(true);
         mScrimBehind.animateViewAlpha(0.0f, TRANSITION_DURATION_OUT, Interpolators.ALPHA_OUT);
         outAnimation(mNotificationPanel.animate())
                 .withLayer();
@@ -62,6 +67,7 @@
                     @Override
                     public void run() {
                         mBrightnessMirror.setVisibility(View.INVISIBLE);
+                        mStackScroller.setFadedOut(false);
                     }
                 });
     }
@@ -69,7 +75,8 @@
     private ViewPropertyAnimator outAnimation(ViewPropertyAnimator a) {
         return a.alpha(0.0f)
                 .setDuration(TRANSITION_DURATION_OUT)
-                .setInterpolator(Interpolators.ALPHA_OUT);
+                .setInterpolator(Interpolators.ALPHA_OUT)
+                .withEndAction(null);
     }
     private ViewPropertyAnimator inAnimation(ViewPropertyAnimator a) {
         return a.alpha(1.0f)
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/HeadsUpManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/HeadsUpManager.java
index 52fb470..d3ae549 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/HeadsUpManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/HeadsUpManager.java
@@ -264,9 +264,9 @@
      * @return true if the notification was removed and false if it still needs to be kept around
      * for a bit since it wasn't shown long enough
      */
-    public boolean removeNotification(String key) {
+    public boolean removeNotification(String key, boolean ignoreEarliestRemovalTime) {
         if (DEBUG) Log.v(TAG, "remove");
-        if (wasShownLongEnough(key)) {
+        if (wasShownLongEnough(key) || ignoreEarliestRemovalTime) {
             releaseImmediately(key);
             return true;
         } else {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/MobileSignalController.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/MobileSignalController.java
index 80dcfb6..83e25eb 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/MobileSignalController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/MobileSignalController.java
@@ -114,6 +114,11 @@
         notifyListenersIfNecessary();
     }
 
+    public void setUserSetupComplete(boolean userSetup) {
+        mCurrentState.userSetup = userSetup;
+        notifyListenersIfNecessary();
+    }
+
     @Override
     public void updateConnectivity(BitSet connectedTransports, BitSet validatedTransports) {
         boolean isValidated = validatedTransports.get(mTransportType);
@@ -204,11 +209,13 @@
 
         String contentDescription = getStringIfExists(getContentDescription());
         String dataContentDescription = getStringIfExists(icons.mDataContentDescription);
+        final boolean dataDisabled = mCurrentState.iconGroup == TelephonyIcons.DATA_DISABLED
+                && mCurrentState.userSetup;
 
-        // Show icon in QS when we are connected or need to show roaming.
+        // Show icon in QS when we are connected or need to show roaming or data is disabled.
         boolean showDataIcon = mCurrentState.dataConnected
                 || mCurrentState.iconGroup == TelephonyIcons.ROAMING
-                || mCurrentState.iconGroup == TelephonyIcons.DATA_DISABLED;
+                || dataDisabled;
         IconState statusIcon = new IconState(mCurrentState.enabled && !mCurrentState.airplaneMode,
                 getCurrentIconId(), contentDescription);
 
@@ -230,7 +237,7 @@
                         && mCurrentState.activityOut;
         showDataIcon &= mCurrentState.isDefault
                 || mCurrentState.iconGroup == TelephonyIcons.ROAMING
-                || mCurrentState.iconGroup == TelephonyIcons.DATA_DISABLED;
+                || dataDisabled;
         int typeIcon = showDataIcon ? icons.mDataType : 0;
         callback.setMobileDataIndicators(statusIcon, qsIcon, typeIcon, qsTypeIcon,
                 activityIn, activityOut, dataContentDescription, description, icons.mIsWide,
@@ -511,6 +518,7 @@
         boolean airplaneMode;
         boolean carrierNetworkChangeMode;
         boolean isDefault;
+        boolean userSetup;
 
         @Override
         public void copyFrom(State s) {
@@ -524,6 +532,7 @@
             isEmergency = state.isEmergency;
             airplaneMode = state.airplaneMode;
             carrierNetworkChangeMode = state.carrierNetworkChangeMode;
+            userSetup = state.userSetup;
         }
 
         @Override
@@ -537,7 +546,9 @@
             builder.append("isDefault=").append(isDefault).append(',');
             builder.append("isEmergency=").append(isEmergency).append(',');
             builder.append("airplaneMode=").append(airplaneMode).append(',');
-            builder.append("carrierNetworkChangeMode=").append(carrierNetworkChangeMode);
+            builder.append("carrierNetworkChangeMode=").append(carrierNetworkChangeMode)
+                    .append(',');
+            builder.append("userSetup=").append(userSetup);
         }
 
         @Override
@@ -550,6 +561,7 @@
                     && ((MobileState) o).isEmergency == isEmergency
                     && ((MobileState) o).airplaneMode == airplaneMode
                     && ((MobileState) o).carrierNetworkChangeMode == carrierNetworkChangeMode
+                    && ((MobileState) o).userSetup == userSetup
                     && ((MobileState) o).isDefault == isDefault;
         }
     }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkControllerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkControllerImpl.java
index 40dacd3..a633241 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkControllerImpl.java
@@ -130,6 +130,7 @@
 
     @VisibleForTesting
     ServiceState mLastServiceState;
+    private boolean mUserSetup;
 
     /**
      * Construct this controller object and register for updates.
@@ -490,6 +491,7 @@
                 MobileSignalController controller = new MobileSignalController(mContext, mConfig,
                         mHasMobileDataFeature, mPhone, mCallbackHandler,
                         this, subscriptions.get(i), mSubDefaults, mReceiverHandler.getLooper());
+                controller.setUserSetupComplete(mUserSetup);
                 mMobileSignalControllers.put(subId, controller);
                 if (subscriptions.get(i).getSimSlotIndex() == 0) {
                     mDefaultSignalController = controller;
@@ -516,6 +518,23 @@
         updateAirplaneMode(true /* force */);
     }
 
+    public void setUserSetupComplete(final boolean userSetup) {
+        mReceiverHandler.post(new Runnable() {
+            @Override
+            public void run() {
+                handleSetUserSetupComplete(userSetup);
+            }
+        });
+    }
+
+    @VisibleForTesting
+    void handleSetUserSetupComplete(boolean userSetup) {
+        mUserSetup = userSetup;
+        for (MobileSignalController controller : mMobileSignalControllers.values()) {
+            controller.setUserSetupComplete(mUserSetup);
+        }
+    }
+
     @VisibleForTesting
     boolean hasCorrectMobileControllers(List<SubscriptionInfo> allSubscriptions) {
         if (allSubscriptions.size() != mMobileSignalControllers.size()) {
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 ecd1772..a855aed 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/RemoteInputView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/RemoteInputView.java
@@ -16,6 +16,7 @@
 
 package com.android.systemui.statusbar.policy;
 
+import android.app.Notification;
 import android.app.PendingIntent;
 import android.app.RemoteInput;
 import android.content.Context;
@@ -43,6 +44,8 @@
 import android.widget.ProgressBar;
 import android.widget.TextView;
 
+import com.android.internal.logging.MetricsLogger;
+import com.android.internal.logging.MetricsProto;
 import com.android.systemui.R;
 import com.android.systemui.statusbar.NotificationData;
 import com.android.systemui.statusbar.RemoteInputController;
@@ -88,8 +91,6 @@
         mEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
             @Override
             public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
-
-                // Check if this was the result of hitting the enter key
                 final boolean isSoftImeEvent = event == null
                         && (actionId == EditorInfo.IME_ACTION_DONE
                         || actionId == EditorInfo.IME_ACTION_NEXT
@@ -99,7 +100,10 @@
                         && event.getAction() == KeyEvent.ACTION_DOWN;
 
                 if (isSoftImeEvent || isKeyboardEnterKey) {
-                    sendRemoteInput();
+                    if (mEditText.length() > 0) {
+                        sendRemoteInput();
+                    }
+                    // Consume action to prevent IME from closing.
                     return true;
                 }
                 return false;
@@ -126,10 +130,14 @@
         mEditText.mShowImeOnInputConnection = false;
         mController.remoteInputSent(mEntry);
 
+        MetricsLogger.action(mContext, MetricsProto.MetricsEvent.ACTION_REMOTE_INPUT_SEND,
+                mEntry.notification.getPackageName());
         try {
             mPendingIntent.send(mContext, 0, fillInIntent);
         } catch (PendingIntent.CanceledException e) {
             Log.i(TAG, "Unable to send remote input result", e);
+            MetricsLogger.action(mContext, MetricsProto.MetricsEvent.ACTION_REMOTE_INPUT_FAIL,
+                    mEntry.notification.getPackageName());
         }
     }
 
@@ -164,6 +172,8 @@
         mController.removeRemoteInput(mEntry);
         mEntry.remoteInputText = mEditText.getText();
         setVisibility(INVISIBLE);
+        MetricsLogger.action(mContext, MetricsProto.MetricsEvent.ACTION_REMOTE_INPUT_CLOSE,
+                mEntry.notification.getPackageName());
     }
 
     @Override
@@ -197,6 +207,10 @@
     }
 
     public void focus() {
+        MetricsLogger.action(mContext, MetricsProto.MetricsEvent.ACTION_REMOTE_INPUT_OPEN,
+                mEntry.notification.getPackageName());
+
+        setVisibility(VISIBLE);
         mController.addRemoteInput(mEntry);
         mEditText.setInnerFocusable(true);
         mEditText.mShowImeOnInputConnection = true;
@@ -250,6 +264,7 @@
             findScrollContainer();
             if (mScrollContainer != null) {
                 mScrollContainer.requestDisallowLongPress();
+                mScrollContainer.requestDisallowDismiss();
             }
         }
         return super.onInterceptTouchEvent(ev);
@@ -275,6 +290,63 @@
         }
     }
 
+    public boolean isActive() {
+        return mEditText.isFocused();
+    }
+
+    public void stealFocusFrom(RemoteInputView other) {
+        other.close();
+        setPendingIntent(other.mPendingIntent);
+        setRemoteInput(other.mRemoteInputs, other.mRemoteInput);
+        focus();
+    }
+
+    /**
+     * Tries to find an action in {@param actions} that matches the current pending intent
+     * of this view and updates its state to that of the found action
+     *
+     * @return true if a matching action was found, false otherwise
+     */
+    public boolean updatePendingIntentFromActions(Notification.Action[] actions) {
+        boolean found = false;
+        if (mPendingIntent == null || actions == null) {
+            return false;
+        }
+        Intent current = mPendingIntent.getIntent();
+        if (current == null) {
+            return false;
+        }
+
+        for (Notification.Action a : actions) {
+            RemoteInput[] inputs = a.getRemoteInputs();
+            if (a.actionIntent == null || inputs == null) {
+                continue;
+            }
+            Intent candidate = a.actionIntent.getIntent();
+            if (!current.filterEquals(candidate)) {
+                continue;
+            }
+
+            RemoteInput input = null;
+            for (RemoteInput i : inputs) {
+                if (i.getAllowFreeFormInput()) {
+                    input = i;
+                }
+            }
+            if (input == null) {
+                continue;
+            }
+            setPendingIntent(a.actionIntent);
+            setRemoteInput(inputs, input);
+            return true;
+        }
+        return false;
+    }
+
+    public PendingIntent getPendingIntent() {
+        return mPendingIntent;
+    }
+
     /**
      * An EditText that changes appearance based on whether it's focusable and becomes
      * un-focusable whenever the user navigates away from it or it becomes invisible.
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserSwitcherController.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserSwitcherController.java
index c82ba3b..6800772 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserSwitcherController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserSwitcherController.java
@@ -119,7 +119,7 @@
         filter.addAction(Intent.ACTION_USER_REMOVED);
         filter.addAction(Intent.ACTION_USER_INFO_CHANGED);
         filter.addAction(Intent.ACTION_USER_SWITCHED);
-        filter.addAction(Intent.ACTION_USER_STOPPING);
+        filter.addAction(Intent.ACTION_USER_STOPPED);
         filter.addAction(Intent.ACTION_USER_UNLOCKED);
         mContext.registerReceiverAsUser(mReceiver, UserHandle.SYSTEM, filter,
                 null /* permission */, null /* scheduler */);
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 be98d7a..a1e89b7 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/stack/NotificationChildrenContainer.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/stack/NotificationChildrenContainer.java
@@ -139,7 +139,9 @@
         for (int i = 0; i < childCount; i++) {
             ExpandableNotificationRow child = mChildren.get(i);
             boolean isOverflow = i == overflowIndex;
-            child.setSingleLineWidthIndention(isOverflow ? mOverflowNumber.getMeasuredWidth() : 0);
+            child.setSingleLineWidthIndention(isOverflow && mOverflowNumber != null
+                    ? mOverflowNumber.getMeasuredWidth()
+                    : 0);
             child.measure(widthMeasureSpec, newHeightSpec);
             height += child.getMeasuredHeight();
 
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 3e0f930..0a4dce8 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/stack/NotificationStackScrollLayout.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/stack/NotificationStackScrollLayout.java
@@ -23,6 +23,7 @@
 import android.animation.TimeAnimator;
 import android.animation.ValueAnimator;
 import android.animation.ValueAnimator.AnimatorUpdateListener;
+import android.annotation.FloatRange;
 import android.annotation.Nullable;
 import android.content.Context;
 import android.content.res.Configuration;
@@ -231,6 +232,7 @@
      * animating.
      */
     private boolean mOnlyScrollingInThisMotion;
+    private boolean mDisallowDismissInThisMotion;
     private boolean mInterceptDelegateEnabled;
     private boolean mDelegateToScrollView;
     private boolean mDisallowScrollingInThisMotion;
@@ -327,6 +329,8 @@
     };
     private PorterDuffXfermode mSrcMode = new PorterDuffXfermode(PorterDuff.Mode.SRC);
     private boolean mPulsing;
+    private boolean mDrawBackgroundAsSrc;
+    private boolean mFadedOut;
 
     public NotificationStackScrollLayout(Context context) {
         this(context, null);
@@ -439,7 +443,12 @@
     }
 
     public void setDrawBackgroundAsSrc(boolean asSrc) {
-        mBackgroundPaint.setXfermode(asSrc ? mSrcMode : null);
+        mDrawBackgroundAsSrc = asSrc;
+        updateSrcDrawing();
+    }
+
+    private void updateSrcDrawing() {
+        mBackgroundPaint.setXfermode(mDrawBackgroundAsSrc && !mFadedOut ? mSrcMode : null);
         invalidate();
     }
 
@@ -1023,7 +1032,8 @@
         if (!mIsBeingDragged
                 && !mExpandingNotification
                 && !mExpandedInThisMotion
-                && !mOnlyScrollingInThisMotion) {
+                && !mOnlyScrollingInThisMotion
+                && !mDisallowDismissInThisMotion) {
             horizontalSwipeWantsIt = mSwipeHelper.onTouchEvent(ev);
         }
         return horizontalSwipeWantsIt || scrollerWantsIt || expandWantsIt || super.onTouchEvent(ev);
@@ -1743,7 +1753,9 @@
     }
 
     private void applyCurrentBackgroundBounds() {
-        mScrimController.setExcludedBackgroundArea(mCurrentBounds);
+        if (!mFadedOut) {
+            mScrimController.setExcludedBackgroundArea(mCurrentBounds);
+        }
         invalidate();
     }
 
@@ -2003,7 +2015,8 @@
         if (!mIsBeingDragged
                 && !mExpandingNotification
                 && !mExpandedInThisMotion
-                && !mOnlyScrollingInThisMotion) {
+                && !mOnlyScrollingInThisMotion
+                && !mDisallowDismissInThisMotion) {
             swipeWantsIt = mSwipeHelper.onInterceptTouchEvent(ev);
         }
         return swipeWantsIt || scrollWantsIt || expandWantsIt || super.onInterceptTouchEvent(ev);
@@ -2031,6 +2044,7 @@
             mExpandedInThisMotion = false;
             mOnlyScrollingInThisMotion = !mScroller.isFinished();
             mDisallowScrollingInThisMotion = false;
+            mDisallowDismissInThisMotion = false;
             mTouchIsClick = true;
             mInitialTouchX = ev.getX();
             mInitialTouchY = ev.getY();
@@ -2695,6 +2709,11 @@
         removeLongPressCallback();
     }
 
+    @Override
+    public void requestDisallowDismiss() {
+        mDisallowDismissInThisMotion = true;
+    }
+
     public void removeLongPressCallback() {
         mSwipeHelper.removeLongPressCallback();
     }
@@ -3421,6 +3440,24 @@
         updateNotificationAnimationStates();
     }
 
+    public void setFadedOut(boolean fadingOut) {
+        if (fadingOut != mFadedOut) {
+            mFadedOut = fadingOut;
+            if (fadingOut) {
+                mScrimController.setExcludedBackgroundArea(null);
+            } else {
+                applyCurrentBackgroundBounds();
+            }
+            updateSrcDrawing();
+        }
+    }
+
+    @Override
+    public void setAlpha(@FloatRange(from = 0.0, to = 1.0) float alpha) {
+        super.setAlpha(alpha);
+        setFadedOut(alpha != 1.0f);
+    }
+
     /**
      * A listener that is notified when some child locations might have changed.
      */
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/stack/ScrollContainer.java b/packages/SystemUI/src/com/android/systemui/statusbar/stack/ScrollContainer.java
index a35465e..64efa69 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/stack/ScrollContainer.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/stack/ScrollContainer.java
@@ -33,4 +33,9 @@
      * Request that the view is made visible by scrolling to it.
      */
     void scrollTo(View v);
+
+    /**
+     * Request that the view does not dismiss for the current touch.
+     */
+    void requestDisallowDismiss();
 }
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 dd12360..fe5d8bc 100644
--- a/packages/SystemUI/src/com/android/systemui/tv/pip/PipRecentsOverlayManager.java
+++ b/packages/SystemUI/src/com/android/systemui/tv/pip/PipRecentsOverlayManager.java
@@ -134,7 +134,8 @@
      */
     public void requestFocus(boolean allowRecentsFocusable) {
         mRecentsView.setVisibility(allowRecentsFocusable ? View.VISIBLE : View.GONE);
-        if (!mIsPipRecentsOverlayShown || !mIsRecentsShown || mIsPipFocusedInRecent) {
+        if (!mIsPipRecentsOverlayShown || !mIsRecentsShown || mIsPipFocusedInRecent
+                || !mPipManager.isPipShown()) {
             return;
         }
         mIsPipFocusedInRecent = true;
@@ -153,7 +154,8 @@
      * This should be called only by {@link com.android.systemui.recents.tv.RecentsTvActivity}.
      */
     public void clearFocus() {
-        if (!mIsPipRecentsOverlayShown || !mIsRecentsShown || !mIsPipFocusedInRecent) {
+        if (!mIsPipRecentsOverlayShown || !mIsRecentsShown || !mIsPipFocusedInRecent
+                || !mPipManager.isPipShown()) {
             return;
         }
         if (!mRecentsView.hasFocus()) {
diff --git a/packages/SystemUI/src/com/android/systemui/usb/StorageNotification.java b/packages/SystemUI/src/com/android/systemui/usb/StorageNotification.java
index 2c53e29..36dd727 100644
--- a/packages/SystemUI/src/com/android/systemui/usb/StorageNotification.java
+++ b/packages/SystemUI/src/com/android/systemui/usb/StorageNotification.java
@@ -654,8 +654,9 @@
         intent.putExtra(PackageManager.EXTRA_MOVE_ID, move.moveId);
 
         final VolumeInfo vol = mStorageManager.findVolumeByQualifiedUuid(move.volumeUuid);
-        intent.putExtra(VolumeInfo.EXTRA_VOLUME_ID, vol.getId());
-
+        if (vol != null) {
+            intent.putExtra(VolumeInfo.EXTRA_VOLUME_ID, vol.getId());
+        }
         return PendingIntent.getActivityAsUser(mContext, move.moveId, intent,
                 PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
     }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerBaseTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerBaseTest.java
index 60d33fa..38cac1e 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerBaseTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerBaseTest.java
@@ -111,6 +111,7 @@
         when(mMockTm.getDataEnabled(mSubId)).thenReturn(true);
         setDefaultSubId(mSubId);
         setSubscriptions(mSubId);
+        mNetworkController.handleSetUserSetupComplete(true);
         mMobileSignalController = mNetworkController.mMobileSignalControllers.get(mSubId);
         mPhoneStateListener = mMobileSignalController.mPhoneStateListener;
     }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerDataTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerDataTest.java
index d5eca95..542c390 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerDataTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerDataTest.java
@@ -1,9 +1,9 @@
 package com.android.systemui.statusbar.policy;
 
+import android.net.NetworkCapabilities;
 import android.os.Looper;
 import android.telephony.TelephonyManager;
 import android.test.suitebuilder.annotation.SmallTest;
-
 import com.android.settingslib.net.DataUsageController;
 import org.mockito.Mockito;
 
@@ -99,6 +99,29 @@
                 TelephonyIcons.QS_DATA_4G);
     }
 
+    public void testDataDisabledIcon() {
+        setupNetworkController();
+        Mockito.when(mMockTm.getDataEnabled(mSubId)).thenReturn(false);
+        setupDefaultSignal();
+        updateDataConnectionState(TelephonyManager.DATA_DISCONNECTED, 0);
+        setConnectivity(NetworkCapabilities.TRANSPORT_CELLULAR, false, false);
+
+        verifyDataIndicators(TelephonyIcons.ICON_DATA_DISABLED,
+                TelephonyIcons.QS_ICON_DATA_DISABLED);
+    }
+
+    public void testDataDisabledIcon_UserNotSetup() {
+        setupNetworkController();
+        Mockito.when(mMockTm.getDataEnabled(mSubId)).thenReturn(false);
+        setupDefaultSignal();
+        updateDataConnectionState(TelephonyManager.DATA_DISCONNECTED, 0);
+        setConnectivity(NetworkCapabilities.TRANSPORT_CELLULAR, false, false);
+        mNetworkController.handleSetUserSetupComplete(false);
+
+        // Don't show the X until the device is setup.
+        verifyDataIndicators(0, 0);
+    }
+
     public void test4gDataIconConfigChange() {
         setupDefaultSignal();
         updateDataConnectionState(TelephonyManager.DATA_CONNECTED,
@@ -145,7 +168,6 @@
         verifyLastMobileDataIndicators(true, DEFAULT_SIGNAL_STRENGTH, DEFAULT_ICON);
         verifyLastQsMobileDataIndicators(true, DEFAULT_QS_SIGNAL_STRENGTH,
                 DEFAULT_QS_ICON, in, out);
-
     }
 
     private void verifyDataIndicators(int dataIcon, int qsDataIcon) {
diff --git a/packages/WallpaperBackup/src/com/android/wallpaperbackup/WallpaperBackupAgent.java b/packages/WallpaperBackup/src/com/android/wallpaperbackup/WallpaperBackupAgent.java
index 2f79079..a3ea592 100644
--- a/packages/WallpaperBackup/src/com/android/wallpaperbackup/WallpaperBackupAgent.java
+++ b/packages/WallpaperBackup/src/com/android/wallpaperbackup/WallpaperBackupAgent.java
@@ -22,22 +22,28 @@
 import android.app.backup.BackupDataOutput;
 import android.app.backup.FullBackupDataOutput;
 import android.content.Context;
+import android.graphics.Rect;
 import android.os.Environment;
 import android.os.ParcelFileDescriptor;
 import android.os.UserHandle;
 import android.system.Os;
 import android.util.Slog;
+import android.util.Xml;
+
+import org.xmlpull.v1.XmlPullParser;
 
 import java.io.File;
+import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
+import java.nio.charset.StandardCharsets;
 
 public class WallpaperBackupAgent extends BackupAgent {
     private static final String TAG = "WallpaperBackup";
     private static final boolean DEBUG = false;
 
     // NB: must be kept in sync with WallpaperManagerService but has no
-    // compile-time visiblity.
+    // compile-time visibility.
 
     // Target filenames within the system's wallpaper directory
     static final String WALLPAPER = "wallpaper_orig";
@@ -107,11 +113,7 @@
     }
 
     // We use the default onRestoreFile() implementation that will recreate our stage files,
-    // then postprocess in onRestoreFinished() to move them on top of the live data.
-    //
-    // NOTE: this relies on our local files dir being on the same filesystem as the live
-    // system wallpaper data.  If this is not the case then an actual copy operation will
-    // be needed.
+    // then post-process in onRestoreFinished() to apply the new wallpaper.
     @Override
     public void onRestoreFinished() {
         if (DEBUG) {
@@ -125,19 +127,25 @@
             // to back up the original image on the source device.
             if (imageStage.exists()) {
                 if (DEBUG) {
-                    Slog.v(TAG, "Got restored wallpaper; renaming into place");
+                    Slog.v(TAG, "Got restored wallpaper; applying");
                 }
-                // Rename the image file into place last because that is the trigger for
-                // the wallpaper observer to generate a new crop/scale
-                Os.rename(infoStage.getCanonicalPath(), mWallpaperInfo.getCanonicalPath());
-                Os.rename(imageStage.getCanonicalPath(), mWallpaperFile.getCanonicalPath());
+
+                // Parse the restored info file to find the crop hint.  Note that this currently
+                // relies on a priori knowledge of the wallpaper info file schema.
+                Rect cropHint = parseCropHint(infoStage);
+                if (cropHint != null) {
+                    if (DEBUG) {
+                        Slog.v(TAG, "Restored crop hint " + cropHint + "; now writing data");
+                    }
+                    WallpaperManager wm = getSystemService(WallpaperManager.class);
+                    try (FileInputStream in = new FileInputStream(imageStage)) {
+                        wm.setStream(in, cropHint, true, WallpaperManager.FLAG_SYSTEM);
+                    } finally {} // auto-closes 'in'
+                }
             }
         } catch (Exception e) {
             Slog.e(TAG, "Unable to restore wallpaper: " + e.getMessage());
-            mWm.clearWallpaper(WallpaperManager.FLAG_SYSTEM, UserHandle.USER_SYSTEM);
         } finally {
-            // These "should" not exist because of the renames, but make sure
-            // in case of errors/exceptions/etc.
             if (DEBUG) {
                 Slog.v(TAG, "Removing restore stage files");
             }
@@ -146,8 +154,41 @@
         }
     }
 
+    private Rect parseCropHint(File wallpaperInfo) {
+        Rect cropHint = new Rect();
+        try (FileInputStream stream = new FileInputStream(wallpaperInfo)) {
+            XmlPullParser parser = Xml.newPullParser();
+            parser.setInput(stream, StandardCharsets.UTF_8.name());
+
+            int type;
+            do {
+                type = parser.next();
+                if (type == XmlPullParser.START_TAG) {
+                    String tag = parser.getName();
+                    if ("wp".equals(tag)) {
+                        cropHint.left = getAttributeInt(parser, "cropLeft", 0);
+                        cropHint.top = getAttributeInt(parser, "cropTop", 0);
+                        cropHint.right = getAttributeInt(parser, "cropRight", 0);
+                        cropHint.bottom = getAttributeInt(parser, "cropBottom", 0);
+                    }
+                }
+            } while (type != XmlPullParser.END_DOCUMENT);
+        } catch (Exception e) {
+            // Whoops; can't process the info file at all.  Report failure.
+            Slog.w(TAG, "Failed to parse restored metadata: " + e.getMessage());
+            return null;
+        }
+
+        return cropHint;
+    }
+
+    private int getAttributeInt(XmlPullParser parser, String name, int defValue) {
+        final String value = parser.getAttributeValue(null, name);
+        return (value == null) ? defValue : Integer.parseInt(value);
+    }
+
     //
-    // Key/value API: abstract, so required, but not used
+    // Key/value API: abstract, therefore required; but not used
     //
 
     @Override
diff --git a/proto/src/metrics_constants.proto b/proto/src/metrics_constants.proto
index 7b3fd66..c417fe8 100644
--- a/proto/src/metrics_constants.proto
+++ b/proto/src/metrics_constants.proto
@@ -2169,6 +2169,28 @@
     // User blacklisted an app for Data Saver mode; action pass package name of app.
     ACTION_DATA_SAVER_BLACKLIST = 396;
 
+    // User opened a remote input view associated with a notification. Passes package name of app
+    // that posted the notification. Note that this can also happen transiently during notification
+    // reinflation.
+    ACTION_REMOTE_INPUT_OPEN = 397;
+
+    // User attempt to send data through a remote input view associated with a notification.
+    // Passes package name of app that posted the notification. May succeed or fail.
+    ACTION_REMOTE_INPUT_SEND = 398;
+
+    // Failed attempt to send data through a remote input view associated with a
+    // notification. Passes package name of app that posted the notification.
+    ACTION_REMOTE_INPUT_FAIL = 399;
+
+    // User closed a remote input view associated with a notification. Passes package name of app
+    // that posted the notification. Note that this can also happen transiently during notification
+    // reinflation.
+    ACTION_REMOTE_INPUT_CLOSE = 400;
+
+    // OPEN: Settings > Accounts > Work profile settings
+    // CATEGORY: SETTINGS
+    ACCOUNTS_WORK_PROFILE_SETTINGS = 401;
+
     // Add new aosp constants above this line.
     // END OF AOSP CONSTANTS
   }
diff --git a/services/accessibility/java/com/android/server/accessibility/AccessibilityManagerService.java b/services/accessibility/java/com/android/server/accessibility/AccessibilityManagerService.java
index 1b85016..ae31438 100644
--- a/services/accessibility/java/com/android/server/accessibility/AccessibilityManagerService.java
+++ b/services/accessibility/java/com/android/server/accessibility/AccessibilityManagerService.java
@@ -151,7 +151,10 @@
 
     private static final int WINDOW_ID_UNKNOWN = -1;
 
-    private static int sIdCounter = 0;
+    // Each service has an ID. Also provide one for magnification gesture handling
+    public static final int MAGNIFICATION_GESTURE_HANDLER_ID = 0;
+
+    private static int sIdCounter = MAGNIFICATION_GESTURE_HANDLER_ID + 1;
 
     private static int sNextWindowId;
 
@@ -183,8 +186,6 @@
 
     private MagnificationController mMagnificationController;
 
-    private boolean mUnregisterMagnificationOnReset;
-
     private InteractionBridge mInteractionBridge;
 
     private AlertDialog mEnableTouchExplorationDialog;
@@ -784,11 +785,6 @@
             float scale, float centerX, float centerY) {
         synchronized (mLock) {
             notifyMagnificationChangedLocked(region, scale, centerX, centerY);
-
-            if (mUnregisterMagnificationOnReset && scale == 1.0f) {
-                mUnregisterMagnificationOnReset = false;
-                mMagnificationController.unregister();
-            }
         }
     }
 
@@ -1249,8 +1245,8 @@
     private void updateServicesLocked(UserState userState) {
         Map<ComponentName, Service> componentNameToServiceMap =
                 userState.mComponentNameToServiceMap;
-        boolean isUnlocked = mContext.getSystemService(UserManager.class)
-                .isUserUnlocked(userState.mUserId);
+        boolean isUnlockingOrUnlocked = mContext.getSystemService(UserManager.class)
+                .isUserUnlockingOrUnlocked(userState.mUserId);
 
         for (int i = 0, count = userState.mInstalledServices.size(); i < count; i++) {
             AccessibilityServiceInfo installedService = userState.mInstalledServices.get(i);
@@ -1260,7 +1256,7 @@
             Service service = componentNameToServiceMap.get(componentName);
 
             // Ignore non-encryption-aware services until user is unlocked
-            if (!isUnlocked && !installedService.isDirectBootAware()) {
+            if (!isUnlockingOrUnlocked && !installedService.isDirectBootAware()) {
                 Slog.d(LOG_TAG, "Ignoring non-encryption-aware service " + componentName);
                 continue;
             }
@@ -1736,25 +1732,17 @@
     }
 
     private void updateMagnificationLocked(UserState userState) {
-        final int userId = userState.mUserId;
-        if (userId == mCurrentUserId && mMagnificationController != null) {
-            if (userState.mIsDisplayMagnificationEnabled ||
-                    userHasMagnificationServicesLocked(userState)) {
-                mMagnificationController.setUserId(userState.mUserId);
-            } else {
-                // If the user no longer has any magnification-controlling
-                // services and is not using magnification gestures, then
-                // reset the state to normal.
-                if (mMagnificationController.resetIfNeeded(true)) {
-                    // Animations are still running, so wait until we receive a
-                    // callback verifying that we've reset magnification.
-                    mUnregisterMagnificationOnReset = true;
-                } else {
-                    mUnregisterMagnificationOnReset = false;
-                    mMagnificationController.unregister();
-                    mMagnificationController = null;
-                }
-            }
+        if (userState.mUserId != mCurrentUserId) {
+            return;
+        }
+
+        if (userState.mIsDisplayMagnificationEnabled ||
+                userHasMagnificationServicesLocked(userState)) {
+            // Initialize the magnification controller if necessary
+            getMagnificationController();
+            mMagnificationController.register();
+        } else if (mMagnificationController != null) {
+            mMagnificationController.unregister();
         }
     }
 
@@ -2152,7 +2140,6 @@
         synchronized (mLock) {
             if (mMagnificationController == null) {
                 mMagnificationController = new MagnificationController(mContext, this, mLock);
-                mMagnificationController.register();
                 mMagnificationController.setUserId(mCurrentUserId);
             }
             return mMagnificationController;
@@ -2886,7 +2873,7 @@
             final long identity = Binder.clearCallingIdentity();
             try {
                 final Region region = Region.obtain();
-                getMagnificationController().getMagnifiedRegion(region);
+                getMagnificationController().getMagnificationRegion(region);
                 return region;
             } finally {
                 Binder.restoreCallingIdentity(identity);
@@ -2957,7 +2944,7 @@
             final long identity = Binder.clearCallingIdentity();
             try {
                 return getMagnificationController().setScaleAndCenter(
-                        scale, centerX, centerY, animate);
+                        scale, centerX, centerY, animate, mId);
             } finally {
                 Binder.restoreCallingIdentity(identity);
             }
@@ -3090,10 +3077,11 @@
                     userState.mInstalledServices.remove(mAccessibilityServiceInfo);
                     userState.mEnabledServices.remove(mComponentName);
                     userState.destroyUiAutomationService();
-                    if (readConfigurationForUserStateLocked(userState)) {
-                        onUserStateChangedLocked(userState);
-                    }
                 }
+                if (mId == getMagnificationController().getIdOfLastServiceToMagnify()) {
+                    getMagnificationController().resetIfNeeded(true);
+                }
+                onUserStateChangedLocked(userState);
             }
         }
 
diff --git a/services/accessibility/java/com/android/server/accessibility/MagnificationController.java b/services/accessibility/java/com/android/server/accessibility/MagnificationController.java
index f1b3722..027b6e2 100644
--- a/services/accessibility/java/com/android/server/accessibility/MagnificationController.java
+++ b/services/accessibility/java/com/android/server/accessibility/MagnificationController.java
@@ -17,6 +17,7 @@
 package com.android.server.accessibility;
 
 import com.android.internal.R;
+import com.android.internal.annotations.GuardedBy;
 import com.android.internal.os.SomeArgs;
 import com.android.server.LocalServices;
 
@@ -60,6 +61,8 @@
 
     private static final int DEFAULT_SCREEN_MAGNIFICATION_AUTO_UPDATE = 1;
 
+    private static final int INVALID_ID = -1;
+
     private static final float DEFAULT_MAGNIFICATION_SCALE = 2.0f;
 
     private static final float MIN_SCALE = 1.0f;
@@ -80,9 +83,8 @@
      */
     private final MagnificationSpec mCurrentMagnificationSpec = MagnificationSpec.obtain();
 
-    private final Region mMagnifiedRegion = Region.obtain();
-    private final Region mAvailableRegion = Region.obtain();
-    private final Rect mMagnifiedBounds = new Rect();
+    private final Region mMagnificationRegion = Region.obtain();
+    private final Rect mMagnificationBounds = new Rect();
 
     private final Rect mTempRect = new Rect();
     private final Rect mTempRect1 = new Rect();
@@ -97,35 +99,67 @@
 
     private int mUserId;
 
+    private int mIdOfLastServiceToMagnify = INVALID_ID;
+
+    // Flag indicating that we are registered with window manager.
+    private boolean mRegistered;
+
+    private boolean mUnregisterPending;
+
     public MagnificationController(Context context, AccessibilityManagerService ams, Object lock) {
         mAms = ams;
         mContentResolver = context.getContentResolver();
         mScreenStateObserver = new ScreenStateObserver(context, this);
         mWindowStateObserver = new WindowStateObserver(context, this);
-        mSpecAnimationBridge = new SpecAnimationBridge(context);
         mLock = lock;
+        mSpecAnimationBridge = new SpecAnimationBridge(context, mLock);
     }
 
     /**
-     * Registers magnification-related observers.
+     * Start tracking the magnification region for services that control magnification and the
+     * magnification gesture handler.
+     *
+     * This tracking imposes a cost on the system, so we avoid tracking this data
+     * unless it's required.
      */
     public void register() {
-        mScreenStateObserver.register();
-        mWindowStateObserver.register();
-
-        // Obtain initial state.
-        mWindowStateObserver.getRegions(mMagnifiedRegion, mAvailableRegion);
-        mMagnifiedRegion.getBounds(mMagnifiedBounds);
+        synchronized (mLock) {
+            if (!mRegistered) {
+                mScreenStateObserver.register();
+                mWindowStateObserver.register();
+                mSpecAnimationBridge.setEnabled(true);
+                // Obtain initial state.
+                mWindowStateObserver.getMagnificationRegion(mMagnificationRegion);
+                mMagnificationRegion.getBounds(mMagnificationBounds);
+                mRegistered = true;
+            }
+        }
     }
 
     /**
-     * Unregisters magnification-related observers.
+     * Stop requiring tracking the magnification region. We may remain registered while we
+     * reset magnification.
      */
     public void unregister() {
-        mSpecAnimationBridge.cancel();
+        synchronized (mLock) {
+            if (!isMagnifying()) {
+                unregisterInternalLocked();
+            } else {
+                mUnregisterPending = true;
+                resetLocked(true);
+            }
+        }
+    }
 
-        mScreenStateObserver.unregister();
-        mWindowStateObserver.unregister();
+    private void unregisterInternalLocked() {
+        if (mRegistered) {
+            mSpecAnimationBridge.setEnabled(false);
+            mScreenStateObserver.unregister();
+            mWindowStateObserver.unregister();
+            mMagnificationRegion.setEmpty();
+            mRegistered = false;
+        }
+        mUnregisterPending = false;
     }
 
     /**
@@ -137,24 +171,22 @@
     }
 
     /**
-     * Sets the magnified and available regions.
+     * Update our copy of the current magnification region
      *
      * @param magnified the magnified region
-     * @param available the region available for magnification
      * @param updateSpec {@code true} to update the scale and center based on
      *                   the region bounds, {@code false} to leave them as-is
      */
-    private void setMagnifiedRegion(Region magnified, Region available, boolean updateSpec) {
+    private void onMagnificationRegionChanged(Region magnified, boolean updateSpec) {
         synchronized (mLock) {
             boolean magnificationChanged = false;
             boolean boundsChanged = false;
 
-            if (!mMagnifiedRegion.equals(magnified)) {
-                mMagnifiedRegion.set(magnified);
-                mMagnifiedRegion.getBounds(mMagnifiedBounds);
+            if (!mMagnificationRegion.equals(magnified)) {
+                mMagnificationRegion.set(magnified);
+                mMagnificationRegion.getBounds(mMagnificationBounds);
                 boundsChanged = true;
             }
-            mAvailableRegion.set(available);
             if (updateSpec) {
                 final MagnificationSpec sentSpec = mSpecAnimationBridge.mSentMagnificationSpec;
                 final float scale = sentSpec.scale;
@@ -162,12 +194,12 @@
                 final float offsetY = sentSpec.offsetY;
 
                 // Compute the new center and update spec as needed.
-                final float centerX = (mMagnifiedBounds.width() / 2.0f
-                        + mMagnifiedBounds.left - offsetX) / scale;
-                final float centerY = (mMagnifiedBounds.height() / 2.0f
-                        + mMagnifiedBounds.top - offsetY) / scale;
+                final float centerX = (mMagnificationBounds.width() / 2.0f
+                        + mMagnificationBounds.left - offsetX) / scale;
+                final float centerY = (mMagnificationBounds.height() / 2.0f
+                        + mMagnificationBounds.top - offsetY) / scale;
                 magnificationChanged = setScaleAndCenterLocked(
-                        scale, centerX, centerY, false);
+                        scale, centerX, centerY, false, INVALID_ID);
             }
 
             // If magnification changed we already notified for the change.
@@ -178,7 +210,7 @@
     }
 
     /**
-     * Returns whether the magnified region contains the specified
+     * Returns whether the magnification region contains the specified
      * screen-relative coordinates.
      *
      * @param x the screen-relative X coordinate to check
@@ -186,51 +218,36 @@
      * @return {@code true} if the coordinate is contained within the
      *         magnified region, or {@code false} otherwise
      */
-    public boolean magnifiedRegionContains(float x, float y) {
+    public boolean magnificationRegionContains(float x, float y) {
         synchronized (mLock) {
-            return mMagnifiedRegion.contains((int) x, (int) y);
-        }
-    }
-
-    /**
-     * Returns whether the region available for magnification contains the
-     * specified screen-relative coordinates.
-     *
-     * @param x the screen-relative X coordinate to check
-     * @param y the screen-relative Y coordinate to check
-     * @return {@code true} if the coordinate is contained within the
-     *         region available for magnification, or {@code false} otherwise
-     */
-    private boolean availableRegionContains(float x, float y) {
-        synchronized (mLock) {
-            return mAvailableRegion.contains((int) x, (int) y);
+            return mMagnificationRegion.contains((int) x, (int) y);
         }
     }
 
     /**
      * Populates the specified rect with the screen-relative bounds of the
-     * magnified region. If magnification is not enabled, the returned
+     * magnification region. If magnification is not enabled, the returned
      * bounds will be empty.
      *
      * @param outBounds rect to populate with the bounds of the magnified
      *                  region
      */
-    public void getMagnifiedBounds(@NonNull Rect outBounds) {
+    public void getMagnificationBounds(@NonNull Rect outBounds) {
         synchronized (mLock) {
-            outBounds.set(mMagnifiedBounds);
+            outBounds.set(mMagnificationBounds);
         }
     }
 
     /**
-     * Populates the specified region with the screen-relative magnified
+     * Populates the specified region with the screen-relative magnification
      * region. If magnification is not enabled, then the returned region
      * will be empty.
      *
      * @param outRegion the region to populate
      */
-    public void getMagnifiedRegion(@NonNull Region outRegion) {
+    public void getMagnificationRegion(@NonNull Region outRegion) {
         synchronized (mLock) {
-            outRegion.set(mMagnifiedRegion);
+            outRegion.set(mMagnificationRegion);
         }
     }
 
@@ -263,8 +280,8 @@
      */
     public float getCenterX() {
         synchronized (mLock) {
-            return  (mMagnifiedBounds.width() / 2.0f
-                    + mMagnifiedBounds.left - getOffsetX()) / getScale();
+            return (mMagnificationBounds.width() / 2.0f
+                    + mMagnificationBounds.left - getOffsetX()) / getScale();
         }
     }
 
@@ -286,8 +303,8 @@
      */
     public float getCenterY() {
         synchronized (mLock) {
-            return (mMagnifiedBounds.height() / 2.0f
-                    + mMagnifiedBounds.top - getOffsetY()) / getScale();
+            return (mMagnificationBounds.height() / 2.0f
+                    + mMagnificationBounds.top - getOffsetY()) / getScale();
         }
     }
 
@@ -335,17 +352,25 @@
      */
     public boolean reset(boolean animate) {
         synchronized (mLock) {
-            final MagnificationSpec spec = mCurrentMagnificationSpec;
-            final boolean changed = !spec.isNop();
-            if (changed) {
-                spec.clear();
-                onMagnificationChangedLocked();
-            }
-            mSpecAnimationBridge.updateSentSpec(spec, animate);
-            return changed;
+            return resetLocked(animate);
         }
     }
 
+    private boolean resetLocked(boolean animate) {
+        if (!mRegistered) {
+            return false;
+        }
+        final MagnificationSpec spec = mCurrentMagnificationSpec;
+        final boolean changed = !spec.isNop();
+        if (changed) {
+            spec.clear();
+            onMagnificationChangedLocked();
+        }
+        mIdOfLastServiceToMagnify = INVALID_ID;
+        mSpecAnimationBridge.updateSentSpec(spec, animate);
+        return changed;
+    }
+
     /**
      * Scales the magnified region around the specified pivot point,
      * optionally animating the transition. If animation is disabled, the
@@ -356,16 +381,20 @@
      * @param pivotY the screen-relative Y coordinate around which to scale
      * @param animate {@code true} to animate the transition, {@code false}
      *                to transition immediately
+     * @param id the ID of the service requesting the change
      * @return {@code true} if the magnification spec changed, {@code false} if
      *         the spec did not change
      */
-    public boolean setScale(float scale, float pivotX, float pivotY, boolean animate) {
+    public boolean setScale(float scale, float pivotX, float pivotY, boolean animate, int id) {
         synchronized (mLock) {
+            if (!mRegistered) {
+                return false;
+            }
             // Constrain scale immediately for use in the pivot calculations.
             scale = MathUtils.constrain(scale, MIN_SCALE, MAX_SCALE);
 
             final Rect viewport = mTempRect;
-            mMagnifiedRegion.getBounds(viewport);
+            mMagnificationRegion.getBounds(viewport);
             final MagnificationSpec spec = mCurrentMagnificationSpec;
             final float oldScale = spec.scale;
             final float oldCenterX = (viewport.width() / 2.0f - spec.offsetX) / oldScale;
@@ -376,7 +405,8 @@
             final float offsetY = (oldCenterY - normPivotY) * (oldScale / scale);
             final float centerX = normPivotX + offsetX;
             final float centerY = normPivotY + offsetY;
-            return setScaleAndCenterLocked(scale, centerX, centerY, animate);
+            mIdOfLastServiceToMagnify = id;
+            return setScaleAndCenterLocked(scale, centerX, centerY, animate, id);
         }
     }
 
@@ -390,12 +420,16 @@
      *                center
      * @param animate {@code true} to animate the transition, {@code false}
      *                to transition immediately
+     * @param id the ID of the service requesting the change
      * @return {@code true} if the magnification spec changed, {@code false} if
      *         the spec did not change
      */
-    public boolean setCenter(float centerX, float centerY, boolean animate) {
+    public boolean setCenter(float centerX, float centerY, boolean animate, int id) {
         synchronized (mLock) {
-            return setScaleAndCenterLocked(Float.NaN, centerX, centerY, animate);
+            if (!mRegistered) {
+                return false;
+            }
+            return setScaleAndCenterLocked(Float.NaN, centerX, centerY, animate, id);
         }
     }
 
@@ -411,19 +445,27 @@
      *                center and scale, or {@link Float#NaN} to leave unchanged
      * @param animate {@code true} to animate the transition, {@code false}
      *                to transition immediately
+     * @param id the ID of the service requesting the change
      * @return {@code true} if the magnification spec changed, {@code false} if
      *         the spec did not change
      */
-    public boolean setScaleAndCenter(float scale, float centerX, float centerY, boolean animate) {
+    public boolean setScaleAndCenter(
+            float scale, float centerX, float centerY, boolean animate, int id) {
         synchronized (mLock) {
-            return setScaleAndCenterLocked(scale, centerX, centerY, animate);
+            if (!mRegistered) {
+                return false;
+            }
+            return setScaleAndCenterLocked(scale, centerX, centerY, animate, id);
         }
     }
 
     private boolean setScaleAndCenterLocked(float scale, float centerX, float centerY,
-            boolean animate) {
+            boolean animate, int id) {
         final boolean changed = updateMagnificationSpecLocked(scale, centerX, centerY);
         mSpecAnimationBridge.updateSentSpec(mCurrentMagnificationSpec, animate);
+        if (isMagnifying() && (id != INVALID_ID)) {
+            mIdOfLastServiceToMagnify = id;
+        }
         return changed;
     }
 
@@ -432,22 +474,42 @@
      *
      * @param offsetX the amount in pixels to offset the X center
      * @param offsetY the amount in pixels to offset the Y center
+     * @param id the ID of the service requesting the change
      */
-    public void offsetMagnifiedRegionCenter(float offsetX, float offsetY) {
+    public void offsetMagnifiedRegionCenter(float offsetX, float offsetY, int id) {
         synchronized (mLock) {
+            if (!mRegistered) {
+                return;
+            }
+
             final MagnificationSpec currSpec = mCurrentMagnificationSpec;
             final float nonNormOffsetX = currSpec.offsetX - offsetX;
             currSpec.offsetX = MathUtils.constrain(nonNormOffsetX, getMinOffsetXLocked(), 0);
             final float nonNormOffsetY = currSpec.offsetY - offsetY;
             currSpec.offsetY = MathUtils.constrain(nonNormOffsetY, getMinOffsetYLocked(), 0);
+            if (id != INVALID_ID) {
+                mIdOfLastServiceToMagnify = id;
+            }
             mSpecAnimationBridge.updateSentSpec(currSpec, false);
         }
     }
 
+    /**
+     * Get the ID of the last service that changed the magnification spec.
+     *
+     * @return The id
+     */
+    public int getIdOfLastServiceToMagnify() {
+        return mIdOfLastServiceToMagnify;
+    }
+
     private void onMagnificationChangedLocked() {
         mAms.onMagnificationStateChanged();
-        mAms.notifyMagnificationChanged(mMagnifiedRegion,
+        mAms.notifyMagnificationChanged(mMagnificationRegion,
                 getScale(), getCenterX(), getCenterY());
+        if (mUnregisterPending && !isMagnifying()) {
+            unregisterInternalLocked();
+        }
     }
 
     /**
@@ -503,8 +565,8 @@
             scale = getScale();
         }
 
-        // Ensure requested center is within the available region.
-        if (!availableRegionContains(centerX, centerY)) {
+        // Ensure requested center is within the magnification region.
+        if (!magnificationRegionContains(centerX, centerY)) {
             return false;
         }
 
@@ -518,16 +580,16 @@
             changed = true;
         }
 
-        final float nonNormOffsetX = mMagnifiedBounds.width() / 2.0f
-                + mMagnifiedBounds.left - centerX * scale;
+        final float nonNormOffsetX = mMagnificationBounds.width() / 2.0f
+                + mMagnificationBounds.left - centerX * scale;
         final float offsetX = MathUtils.constrain(nonNormOffsetX, getMinOffsetXLocked(), 0);
         if (Float.compare(currSpec.offsetX, offsetX) != 0) {
             currSpec.offsetX = offsetX;
             changed = true;
         }
 
-        final float nonNormOffsetY = mMagnifiedBounds.height() / 2.0f
-                + mMagnifiedBounds.top - centerY * scale;
+        final float nonNormOffsetY = mMagnificationBounds.height() / 2.0f
+                + mMagnificationBounds.top - centerY * scale;
         final float offsetY = MathUtils.constrain(nonNormOffsetY, getMinOffsetYLocked(), 0);
         if (Float.compare(currSpec.offsetY, offsetY) != 0) {
             currSpec.offsetY = offsetY;
@@ -542,12 +604,12 @@
     }
 
     private float getMinOffsetXLocked() {
-        final float viewportWidth = mMagnifiedBounds.width();
+        final float viewportWidth = mMagnificationBounds.width();
         return viewportWidth - viewportWidth * mCurrentMagnificationSpec.scale;
     }
 
     private float getMinOffsetYLocked() {
-        final float viewportHeight = mMagnifiedBounds.height();
+        final float viewportHeight = mMagnificationBounds.height();
         return viewportHeight - viewportHeight * mCurrentMagnificationSpec.scale;
     }
 
@@ -595,7 +657,7 @@
         final float scale = getSentScale();
         final float offsetX = getSentOffsetX();
         final float offsetY = getSentOffsetY();
-        getMagnifiedBounds(outFrame);
+        getMagnificationBounds(outFrame);
         outFrame.offset((int) -offsetX, (int) -offsetY);
         outFrame.scale(1.0f / scale);
     }
@@ -603,7 +665,7 @@
     private void requestRectangleOnScreen(int left, int top, int right, int bottom) {
         synchronized (mLock) {
             final Rect magnifiedFrame = mTempRect;
-            getMagnifiedBounds(magnifiedFrame);
+            getMagnificationBounds(magnifiedFrame);
             if (!magnifiedFrame.intersects(left, top, right, bottom)) {
                 return;
             }
@@ -640,7 +702,7 @@
             }
 
             final float scale = getScale();
-            offsetMagnifiedRegionCenter(scrollX * scale, scrollY * scale);
+            offsetMagnifiedRegionCenter(scrollX * scale, scrollY * scale, INVALID_ID);
         }
     }
 
@@ -656,7 +718,7 @@
 
         /**
          * The magnification spec that was sent to the window manager. This should
-         * only be accessed and modified on the main (e.g. animation) thread.
+         * only be accessed with the lock held.
          */
         private final MagnificationSpec mSentMagnificationSpec = MagnificationSpec.obtain();
 
@@ -667,8 +729,13 @@
         private final ValueAnimator mTransformationAnimator;
 
         private final long mMainThreadId;
+        private final Object mLock;
 
-        private SpecAnimationBridge(Context context) {
+        @GuardedBy("mLock")
+        private boolean mEnabled = false;
+
+        private SpecAnimationBridge(Context context, Object lock) {
+            mLock = lock;
             final Looper mainLooper = context.getMainLooper();
             mMainThreadId = mainLooper.getThread().getId();
 
@@ -685,9 +752,19 @@
             mTransformationAnimator.setInterpolator(new DecelerateInterpolator(2.5f));
         }
 
-        public void cancel() {
-            if (mTransformationAnimator != null && mTransformationAnimator.isRunning()) {
-                mTransformationAnimator.cancel();
+        /**
+         * Enabled means the bridge will accept input. When not enabled, the output of the animator
+         * will be ignored
+         */
+        public void setEnabled(boolean enabled) {
+            synchronized (mLock) {
+                if (enabled != mEnabled) {
+                    mEnabled = enabled;
+                    if (!mEnabled) {
+                        mSentMagnificationSpec.clear();
+                        mWindowManager.setMagnificationSpec(mSentMagnificationSpec);
+                    }
+                }
             }
         }
 
@@ -710,28 +787,32 @@
             }
 
             // If the current and sent specs don't match, update the sent spec.
-            final boolean changed = !mSentMagnificationSpec.equals(spec);
-            if (changed) {
-                if (animate) {
-                    animateMagnificationSpec(spec);
-                } else {
-                    setMagnificationSpec(spec);
+            synchronized (mLock) {
+                final boolean changed = !mSentMagnificationSpec.equals(spec);
+                if (changed) {
+                    if (animate) {
+                        animateMagnificationSpecLocked(spec);
+                    } else {
+                        setMagnificationSpecLocked(spec);
+                    }
                 }
             }
         }
 
-        private void animateMagnificationSpec(MagnificationSpec toSpec) {
+        private void animateMagnificationSpecLocked(MagnificationSpec toSpec) {
             mTransformationAnimator.setObjectValues(mSentMagnificationSpec, toSpec);
             mTransformationAnimator.start();
         }
 
-        private void setMagnificationSpec(MagnificationSpec spec) {
-            if (DEBUG_SET_MAGNIFICATION_SPEC) {
-                Slog.i(LOG_TAG, "Sending: " + spec);
-            }
+        private void setMagnificationSpecLocked(MagnificationSpec spec) {
+            if (mEnabled) {
+                if (DEBUG_SET_MAGNIFICATION_SPEC) {
+                    Slog.i(LOG_TAG, "Sending: " + spec);
+                }
 
-            mSentMagnificationSpec.setTo(spec);
-            mWindowManager.setMagnificationSpec(spec);
+                mSentMagnificationSpec.setTo(spec);
+                mWindowManager.setMagnificationSpec(spec);
+            }
         }
 
         private class UpdateHandler extends Handler {
@@ -759,12 +840,16 @@
 
             @Override
             public MagnificationSpec get(SpecAnimationBridge object) {
-                return object.mSentMagnificationSpec;
+                synchronized (object.mLock) {
+                    return object.mSentMagnificationSpec;
+                }
             }
 
             @Override
             public void set(SpecAnimationBridge object, MagnificationSpec value) {
-                object.setMagnificationSpec(value);
+                synchronized (object.mLock) {
+                    object.setMagnificationSpecLocked(value);
+                }
             }
         }
 
@@ -862,15 +947,14 @@
         }
 
         @Override
-        public void onMagnifiedBoundsChanged(Region magnified, Region available) {
+        public void onMagnificationRegionChanged(Region magnificationRegion) {
             final SomeArgs args = SomeArgs.obtain();
-            args.arg1 = Region.obtain(magnified);
-            args.arg2 = Region.obtain(available);
+            args.arg1 = Region.obtain(magnificationRegion);
             mHandler.obtainMessage(MESSAGE_ON_MAGNIFIED_BOUNDS_CHANGED, args).sendToTarget();
         }
 
-        private void handleOnMagnifiedBoundsChanged(Region magnified, Region available) {
-            mController.setMagnifiedRegion(magnified, available, mSpecIsDirty);
+        private void handleOnMagnifiedBoundsChanged(Region magnificationRegion) {
+            mController.onMagnificationRegionChanged(magnificationRegion, mSpecIsDirty);
             mSpecIsDirty = false;
         }
 
@@ -911,8 +995,15 @@
             mController.resetIfNeeded(true);
         }
 
-        public void getRegions(@NonNull Region outMagnified, @NonNull Region outAvailable) {
-            mWindowManager.getMagnificationRegions(outMagnified, outAvailable);
+        /**
+         * This method is used to get the magnification region in the tiny time slice between
+         * registering the callbacks and handling the message.
+         * TODO: Elimiante this extra path, perhaps by processing the message immediately
+         *
+         * @param outMagnificationRegion
+         */
+        public void getMagnificationRegion(@NonNull Region outMagnificationRegion) {
+            mWindowManager.getMagnificationRegion(outMagnificationRegion);
         }
 
         private class CallbackHandler extends Handler {
@@ -926,10 +1017,8 @@
                     case MESSAGE_ON_MAGNIFIED_BOUNDS_CHANGED: {
                         final SomeArgs args = (SomeArgs) message.obj;
                         final Region magnifiedBounds = (Region) args.arg1;
-                        final Region availableBounds = (Region) args.arg2;
-                        handleOnMagnifiedBoundsChanged(magnifiedBounds, availableBounds);
+                        handleOnMagnifiedBoundsChanged(magnifiedBounds);
                         magnifiedBounds.recycle();
-                        availableBounds.recycle();
                     } break;
                     case MESSAGE_ON_RECTANGLE_ON_SCREEN_REQUESTED: {
                         final SomeArgs args = (SomeArgs) message.obj;
diff --git a/services/accessibility/java/com/android/server/accessibility/MagnificationGestureHandler.java b/services/accessibility/java/com/android/server/accessibility/MagnificationGestureHandler.java
index 818ac81..39bc809 100644
--- a/services/accessibility/java/com/android/server/accessibility/MagnificationGestureHandler.java
+++ b/services/accessibility/java/com/android/server/accessibility/MagnificationGestureHandler.java
@@ -237,7 +237,7 @@
         final float eventX = event.getX();
         final float eventY = event.getY();
         if (mMagnificationController.isMagnifying()
-                && mMagnificationController.magnifiedRegionContains(eventX, eventY)) {
+                && mMagnificationController.magnificationRegionContains(eventX, eventY)) {
             final float scale = mMagnificationController.getScale();
             final float scaledOffsetX = mMagnificationController.getOffsetX();
             final float scaledOffsetY = mMagnificationController.getOffsetY();
@@ -381,7 +381,8 @@
                 Slog.i(LOG_TAG, "Panned content by scrollX: " + distanceX
                         + " scrollY: " + distanceY);
             }
-            mMagnificationController.offsetMagnifiedRegionCenter(distanceX, distanceY);
+            mMagnificationController.offsetMagnifiedRegionCenter(distanceX, distanceY,
+                    AccessibilityManagerService.MAGNIFICATION_GESTURE_HANDLER_ID);
             return true;
         }
 
@@ -421,7 +422,8 @@
 
             final float pivotX = detector.getFocusX();
             final float pivotY = detector.getFocusY();
-            mMagnificationController.setScale(scale, pivotX, pivotY, false);
+            mMagnificationController.setScale(scale, pivotX, pivotY, false,
+                    AccessibilityManagerService.MAGNIFICATION_GESTURE_HANDLER_ID);
             return true;
         }
 
@@ -469,14 +471,14 @@
                     }
                     final float eventX = event.getX();
                     final float eventY = event.getY();
-                    if (mMagnificationController.magnifiedRegionContains(eventX, eventY)) {
+                    if (mMagnificationController.magnificationRegionContains(eventX, eventY)) {
                         if (mLastMoveOutsideMagnifiedRegion) {
                             mLastMoveOutsideMagnifiedRegion = false;
-                            mMagnificationController.setCenter(eventX,
-                                    eventY, true);
+                            mMagnificationController.setCenter(eventX, eventY, true,
+                                    AccessibilityManagerService.MAGNIFICATION_GESTURE_HANDLER_ID);
                         } else {
-                            mMagnificationController.setCenter(eventX,
-                                    eventY, false);
+                            mMagnificationController.setCenter(eventX, eventY, false,
+                                    AccessibilityManagerService.MAGNIFICATION_GESTURE_HANDLER_ID);
                         }
                     } else {
                         mLastMoveOutsideMagnifiedRegion = true;
@@ -571,7 +573,7 @@
             switch (action) {
                 case MotionEvent.ACTION_DOWN: {
                     mHandler.removeMessages(MESSAGE_TRANSITION_TO_DELEGATING_STATE);
-                    if (!mMagnificationController.magnifiedRegionContains(
+                    if (!mMagnificationController.magnificationRegionContains(
                             event.getX(), event.getY())) {
                         transitionToDelegatingStateAndClear();
                         return;
@@ -616,7 +618,7 @@
                         return;
                     }
                     mHandler.removeMessages(MESSAGE_ON_ACTION_TAP_AND_HOLD);
-                    if (!mMagnificationController.magnifiedRegionContains(
+                    if (!mMagnificationController.magnificationRegionContains(
                             event.getX(), event.getY())) {
                         transitionToDelegatingStateAndClear();
                         return;
@@ -726,7 +728,8 @@
             if (!mMagnificationController.isMagnifying()) {
                 final float targetScale = mMagnificationController.getPersistedScale();
                 final float scale = MathUtils.constrain(targetScale, MIN_SCALE, MAX_SCALE);
-                mMagnificationController.setScaleAndCenter(scale, up.getX(), up.getY(), true);
+                mMagnificationController.setScaleAndCenter(scale, up.getX(), up.getY(), true,
+                        AccessibilityManagerService.MAGNIFICATION_GESTURE_HANDLER_ID);
             } else {
                 mMagnificationController.reset(true);
             }
@@ -742,7 +745,8 @@
 
             final float targetScale = mMagnificationController.getPersistedScale();
             final float scale = MathUtils.constrain(targetScale, MIN_SCALE, MAX_SCALE);
-            mMagnificationController.setScaleAndCenter(scale, down.getX(), down.getY(), true);
+            mMagnificationController.setScaleAndCenter(scale, down.getX(), down.getY(), true,
+                    AccessibilityManagerService.MAGNIFICATION_GESTURE_HANDLER_ID);
 
             transitionToState(STATE_VIEWPORT_DRAGGING);
         }
diff --git a/services/appwidget/java/com/android/server/appwidget/AppWidgetServiceImpl.java b/services/appwidget/java/com/android/server/appwidget/AppWidgetServiceImpl.java
index 0428ecf..7b9d4456 100644
--- a/services/appwidget/java/com/android/server/appwidget/AppWidgetServiceImpl.java
+++ b/services/appwidget/java/com/android/server/appwidget/AppWidgetServiceImpl.java
@@ -335,7 +335,7 @@
                     Provider provider = installedProviders.get(i);
 
                     final int userId = provider.getUserId();
-                    if (!mUserManager.isUserUnlocked(userId) ||
+                    if (!mUserManager.isUserUnlockingOrUnlocked(userId) ||
                             isProfileWithLockedParent(userId)) {
                         continue;
                     }
@@ -369,7 +369,7 @@
     }
 
     private void onPackageBroadcastReceived(Intent intent, int userId) {
-        if (!mUserManager.isUserUnlocked(userId) ||
+        if (!mUserManager.isUserUnlockingOrUnlocked(userId) ||
                 isProfileWithLockedParent(userId)) {
             return;
         }
@@ -455,7 +455,7 @@
      * userId must be the group parent.
      */
     private void reloadWidgetsMaskedStateForGroup(int userId) {
-        if (!mUserManager.isUserUnlocked(userId)) {
+        if (!mUserManager.isUserUnlockingOrUnlocked(userId)) {
             return;
         }
         synchronized (mLock) {
@@ -472,7 +472,7 @@
         try {
             UserInfo user  = mUserManager.getUserInfo(userId);
 
-            boolean lockedProfile = !mUserManager.isUserUnlocked(userId);
+            boolean lockedProfile = !mUserManager.isUserUnlockingOrUnlocked(userId);
             boolean quietProfile = user.isQuietModeEnabled();
             final int N = mProviders.size();
             for (int i = 0; i < N; i++) {
@@ -656,7 +656,7 @@
     }
 
     private void ensureGroupStateLoadedLocked(int userId) {
-        if (!mUserManager.isUserUnlocked(userId)) {
+        if (!mUserManager.isUserUnlockingOrUnlocked(userId)) {
             throw new IllegalStateException(
                     "User " + userId + " must be unlocked for widgets to be available");
         }
@@ -3363,7 +3363,7 @@
             if (userInfo != null && userInfo.isManagedProfile()) {
                 UserInfo parentInfo = mUserManager.getProfileParent(userId);
                 if (parentInfo != null
-                        && !mUserManager.isUserUnlocked(parentInfo.getUserHandle())) {
+                        && !mUserManager.isUserUnlockingOrUnlocked(parentInfo.getUserHandle())) {
                     return true;
                 }
             }
@@ -3378,7 +3378,7 @@
         if (userInfo != null && userInfo.isManagedProfile()) {
             UserInfo parentInfo = mUserManager.getProfileParent(userId);
             if (parentInfo != null
-                    && mUserManager.isUserUnlocked(parentInfo.getUserHandle())) {
+                    && mUserManager.isUserUnlockingOrUnlocked(parentInfo.getUserHandle())) {
                 return true;
             }
         }
diff --git a/services/backup/java/com/android/server/backup/BackupManagerService.java b/services/backup/java/com/android/server/backup/BackupManagerService.java
index 6288b56..1b63cd4 100644
--- a/services/backup/java/com/android/server/backup/BackupManagerService.java
+++ b/services/backup/java/com/android/server/backup/BackupManagerService.java
@@ -3706,7 +3706,7 @@
                         result = BackupTransport.TRANSPORT_OK;
                     }
                 } catch (IOException e) {
-                    Slog.e(TAG, "Error backing up " + mPkg.packageName, e);
+                    Slog.e(TAG, "Error backing up " + mPkg.packageName + ": " + e.getMessage());
                     result = BackupTransport.AGENT_ERROR;
                 } finally {
                     try {
@@ -4466,7 +4466,6 @@
                             }
                         }
 
-
                         // If we've lost our running criteria, tell the transport to cancel
                         // and roll back this (partial) backup payload; otherwise tell it
                         // that we've reached the clean finish state.
@@ -4484,14 +4483,16 @@
                             }
                         }
 
-                        // TRANSPORT_ERROR here means that we've hit an error that the runner
-                        // doesn't know about, so it's still moving data but we're pulling the
+                        // A transport-originated error here means that we've hit an error that the
+                        // runner doesn't know about, so it's still moving data but we're pulling the
                         // rug out from under it.  Don't ask for its result:  we already know better
                         // and we'll hang if we block waiting for it, since it relies on us to
                         // read back the data it's writing into the engine.  Just proceed with
                         // a graceful failure.  The runner/engine mechanism will tear itself
-                        // down cleanly when we close the pipes from this end.
-                        if (backupPackageStatus != BackupTransport.TRANSPORT_ERROR) {
+                        // down cleanly when we close the pipes from this end.  Transport-level
+                        // errors take precedence over agent/app-specific errors for purposes of
+                        // determining our course of action.
+                        if (backupPackageStatus == BackupTransport.TRANSPORT_OK) {
                             // We still could fail in backup runner thread, getting result from there.
                             int backupRunnerResult = backupRunner.getBackupResultBlocking();
                             if (backupRunnerResult != BackupTransport.TRANSPORT_OK) {
@@ -4499,10 +4500,14 @@
                                 // not TRANSPORT_ERROR here, overwrite it.
                                 backupPackageStatus = backupRunnerResult;
                             }
+                        } else {
+                            if (MORE_DEBUG) {
+                                Slog.i(TAG, "Transport-level failure; cancelling agent work");
+                            }
                         }
 
                         if (MORE_DEBUG) {
-                            Slog.i(TAG, "Done trying to send backup data: result="
+                            Slog.i(TAG, "Done delivering backup data: result="
                                     + backupPackageStatus);
                         }
 
@@ -7706,6 +7711,11 @@
         // when we're finished.
         private int mPmToken;
 
+        // When this is restore-during-install, we need to tell the package manager
+        // whether we actually launched the app, because this affects notifications
+        // around externally-visible state transitions.
+        private boolean mDidLaunch;
+
         // Is this a whole-system restore, i.e. are we establishing a new ancestral
         // dataset to base future restore-at-install operations from?
         private boolean mIsSystemRestore;
@@ -7769,6 +7779,7 @@
             mTargetPackage = targetPackage;
             mIsSystemRestore = isFullSystemRestore;
             mFinished = false;
+            mDidLaunch = false;
 
             if (targetPackage != null) {
                 // Single package restore
@@ -8149,6 +8160,9 @@
                 return;
             }
 
+            // Whatever happens next, we've launched the target app now; remember that.
+            mDidLaunch = true;
+
             // And then finally start the restore on this agent
             try {
                 initiateOneRestore(mCurrentPackage, metaInfo.versionCode);
@@ -8430,6 +8444,10 @@
                     // Now we're really done with this one too
                     IoUtils.closeQuietly(mEnginePipes[0]);
 
+                    // In all cases we want to remember whether we launched
+                    // the target app as part of our work so far.
+                    mDidLaunch = (mEngine.getAgent() != null);
+
                     // If we hit a transport-level error, we are done with everything;
                     // if we hit an agent error we just go back to running the queue.
                     if (status == BackupTransport.TRANSPORT_OK) {
@@ -8522,7 +8540,7 @@
             if (mPmToken > 0) {
                 if (MORE_DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
                 try {
-                    mPackageManagerBinder.finishPackageInstall(mPmToken);
+                    mPackageManagerBinder.finishPackageInstall(mPmToken, mDidLaunch);
                 } catch (RemoteException e) { /* can't happen */ }
             } else {
                 // We were invoked via an active restore session, not by the Package
@@ -9682,7 +9700,7 @@
             // Manager to proceed with the post-install handling for this package.
             if (DEBUG) Slog.v(TAG, "Finishing install immediately");
             try {
-                mPackageManagerBinder.finishPackageInstall(token);
+                mPackageManagerBinder.finishPackageInstall(token, false);
             } catch (RemoteException e) { /* can't happen */ }
         }
     }
diff --git a/services/core/java/com/android/server/BatteryService.java b/services/core/java/com/android/server/BatteryService.java
index 8753992..6b51721 100644
--- a/services/core/java/com/android/server/BatteryService.java
+++ b/services/core/java/com/android/server/BatteryService.java
@@ -358,7 +358,7 @@
         try {
             mBatteryStats.setBatteryState(mBatteryProps.batteryStatus, mBatteryProps.batteryHealth,
                     mPlugType, mBatteryProps.batteryLevel, mBatteryProps.batteryTemperature,
-                    mBatteryProps.batteryVoltage);
+                    mBatteryProps.batteryVoltage, mBatteryProps.batteryChargeCounter);
         } catch (RemoteException e) {
             // Should never happen.
         }
diff --git a/services/core/java/com/android/server/ConnectivityService.java b/services/core/java/com/android/server/ConnectivityService.java
index f06583b..00dcdea 100644
--- a/services/core/java/com/android/server/ConnectivityService.java
+++ b/services/core/java/com/android/server/ConnectivityService.java
@@ -29,8 +29,11 @@
 import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
 import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
 import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
+import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
 import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
 import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
+import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
+import static android.net.NetworkPolicyManager.RULE_UNKNOWN;
 
 import android.annotation.Nullable;
 import android.app.BroadcastOptions;
@@ -97,8 +100,10 @@
 import android.security.KeyStore;
 import android.telephony.TelephonyManager;
 import android.text.TextUtils;
+import android.util.ArraySet;
 import android.util.LocalLog;
 import android.util.LocalLog.ReadOnlyLocalLog;
+import android.util.Log;
 import android.util.Pair;
 import android.util.Slog;
 import android.util.SparseArray;
@@ -122,9 +127,9 @@
 import com.android.server.am.BatteryStatsService;
 import com.android.server.connectivity.DataConnectionStats;
 import com.android.server.connectivity.KeepaliveTracker;
-import com.android.server.connectivity.NetworkDiagnostics;
 import com.android.server.connectivity.Nat464Xlat;
 import com.android.server.connectivity.NetworkAgentInfo;
+import com.android.server.connectivity.NetworkDiagnostics;
 import com.android.server.connectivity.NetworkMonitor;
 import com.android.server.connectivity.PacManager;
 import com.android.server.connectivity.PermissionMonitor;
@@ -132,8 +137,8 @@
 import com.android.server.connectivity.Vpn;
 import com.android.server.net.BaseNetworkObserver;
 import com.android.server.net.LockdownVpnTracker;
+
 import com.google.android.collect.Lists;
-import com.google.android.collect.Sets;
 
 import org.xmlpull.v1.XmlPullParser;
 import org.xmlpull.v1.XmlPullParserException;
@@ -153,11 +158,11 @@
 import java.util.Collection;
 import java.util.HashMap;
 import java.util.HashSet;
-import java.util.SortedSet;
-import java.util.TreeSet;
 import java.util.List;
 import java.util.Map;
 import java.util.Objects;
+import java.util.SortedSet;
+import java.util.TreeSet;
 
 /**
  * @hide
@@ -203,9 +208,14 @@
     /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
     private Object mRulesLock = new Object();
     /** Currently active network rules by UID. */
+    @GuardedBy("mRulesLock")
     private SparseIntArray mUidRules = new SparseIntArray();
     /** Set of ifaces that are costly. */
-    private HashSet<String> mMeteredIfaces = Sets.newHashSet();
+    @GuardedBy("mRulesLock")
+    private ArraySet<String> mMeteredIfaces = new ArraySet<>();
+    /** Flag indicating if background data is restricted. */
+    @GuardedBy("mRulesLock")
+    private boolean mRestrictBackground;
 
     final private Context mContext;
     private int mNetworkPreference;
@@ -652,7 +662,8 @@
         mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
 
         try {
-            mPolicyManager.registerListener(mPolicyListener);
+            mPolicyManager.setConnectivityListener(mPolicyListener);
+            mRestrictBackground = mPolicyManager.getRestrictBackground();
         } catch (RemoteException e) {
             // ouch, no rules updates means some processes may never get network
             loge("unable to register INetworkPolicyListener" + e.toString());
@@ -731,7 +742,7 @@
         //set up the listener for user state for creating user VPNs
         IntentFilter intentFilter = new IntentFilter();
         intentFilter.addAction(Intent.ACTION_USER_STARTING);
-        intentFilter.addAction(Intent.ACTION_USER_STOPPING);
+        intentFilter.addAction(Intent.ACTION_USER_STOPPED);
         intentFilter.addAction(Intent.ACTION_USER_ADDED);
         intentFilter.addAction(Intent.ACTION_USER_REMOVED);
         intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
@@ -820,7 +831,7 @@
         throw new IllegalStateException("No free netIds");
     }
 
-    private NetworkState getFilteredNetworkState(int networkType, int uid) {
+    private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
         if (mLegacyTypeTracker.isTypeSupported(networkType)) {
             final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
             final NetworkState state;
@@ -835,7 +846,7 @@
                 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
                         null, null, null);
             }
-            filterNetworkStateForUid(state, uid);
+            filterNetworkStateForUid(state, uid, ignoreBlocked);
             return state;
         } else {
             return NetworkState.EMPTY;
@@ -891,22 +902,36 @@
     /**
      * Check if UID should be blocked from using the network with the given LinkProperties.
      */
-    private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
-        final boolean networkCostly;
+    private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
+            boolean ignoreBlocked) {
+        // Networks aren't blocked when ignoring blocked status
+        if (ignoreBlocked) return false;
+        // Networks are never blocked for system services
+        if (uid < Process.FIRST_APPLICATION_UID) return false;
+
+        final boolean networkMetered;
         final int uidRules;
 
         final String iface = (lp == null ? "" : lp.getInterfaceName());
         synchronized (mRulesLock) {
-            networkCostly = mMeteredIfaces.contains(iface);
-            uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
+            networkMetered = mMeteredIfaces.contains(iface);
+            uidRules = mUidRules.get(uid, RULE_UNKNOWN);
         }
 
-        if (uidRules == RULE_REJECT_ALL) {
-            return true;
-        } else if ((uidRules == RULE_REJECT_METERED) && networkCostly) {
-            return true;
-        } else {
-            return false;
+        switch (uidRules) {
+            case RULE_ALLOW_ALL:
+            case RULE_ALLOW_METERED:
+            case RULE_TEMPORARY_ALLOW_METERED:
+                return false;
+            case RULE_REJECT_METERED:
+                return networkMetered;
+            case RULE_REJECT_ALL:
+                return true;
+            case RULE_UNKNOWN:
+            default:
+                // When background data is restricted device-wide, the default
+                // behavior for apps should be like RULE_REJECT_METERED
+                return mRestrictBackground ? networkMetered : false;
         }
     }
 
@@ -931,10 +956,10 @@
      * on {@link #isNetworkWithLinkPropertiesBlocked}, or
      * {@link NetworkInfo#isMetered()} based on network policies.
      */
-    private void filterNetworkStateForUid(NetworkState state, int uid) {
+    private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
         if (state == null || state.networkInfo == null || state.linkProperties == null) return;
 
-        if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
+        if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
             state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
         }
         if (mLockdownTracker != null) {
@@ -963,7 +988,7 @@
         enforceAccessPermission();
         final int uid = Binder.getCallingUid();
         final NetworkState state = getUnfilteredActiveNetworkState(uid);
-        filterNetworkStateForUid(state, uid);
+        filterNetworkStateForUid(state, uid, false);
         maybeLogBlockedNetworkInfo(state.networkInfo, uid);
         return state.networkInfo;
     }
@@ -971,16 +996,16 @@
     @Override
     public Network getActiveNetwork() {
         enforceAccessPermission();
-        return getActiveNetworkForUidInternal(Binder.getCallingUid());
+        return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
     }
 
     @Override
-    public Network getActiveNetworkForUid(int uid) {
+    public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
         enforceConnectivityInternalPermission();
-        return getActiveNetworkForUidInternal(uid);
+        return getActiveNetworkForUidInternal(uid, ignoreBlocked);
     }
 
-    private Network getActiveNetworkForUidInternal(final int uid) {
+    private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
         final int user = UserHandle.getUserId(uid);
         int vpnNetId = NETID_UNSET;
         synchronized (mVpns) {
@@ -995,7 +1020,10 @@
             if (nai != null) return nai.network;
         }
         nai = getDefaultNetwork();
-        if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
+        if (nai != null
+                && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
+            nai = null;
+        }
         return nai != null ? nai.network : null;
     }
 
@@ -1007,10 +1035,10 @@
     }
 
     @Override
-    public NetworkInfo getActiveNetworkInfoForUid(int uid) {
+    public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
         enforceConnectivityInternalPermission();
         final NetworkState state = getUnfilteredActiveNetworkState(uid);
-        filterNetworkStateForUid(state, uid);
+        filterNetworkStateForUid(state, uid, ignoreBlocked);
         return state.networkInfo;
     }
 
@@ -1024,22 +1052,21 @@
             // getUnfilteredActiveNetworkState.
             final NetworkState state = getUnfilteredActiveNetworkState(uid);
             if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
-                filterNetworkStateForUid(state, uid);
+                filterNetworkStateForUid(state, uid, false);
                 return state.networkInfo;
             }
         }
-        final NetworkState state = getFilteredNetworkState(networkType, uid);
+        final NetworkState state = getFilteredNetworkState(networkType, uid, false);
         return state.networkInfo;
     }
 
     @Override
-    public NetworkInfo getNetworkInfoForNetwork(Network network) {
+    public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
         enforceAccessPermission();
-        final int uid = Binder.getCallingUid();
         final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
         if (nai != null) {
             final NetworkState state = nai.getNetworkState();
-            filterNetworkStateForUid(state, uid);
+            filterNetworkStateForUid(state, uid, ignoreBlocked);
             return state.networkInfo;
         } else {
             return null;
@@ -1064,8 +1091,8 @@
     public Network getNetworkForType(int networkType) {
         enforceAccessPermission();
         final int uid = Binder.getCallingUid();
-        NetworkState state = getFilteredNetworkState(networkType, uid);
-        if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
+        NetworkState state = getFilteredNetworkState(networkType, uid, false);
+        if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
             return state.network;
         }
         return null;
@@ -1382,6 +1409,15 @@
             if (LOGD_RULES) {
                 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
             }
+
+            synchronized (mRulesLock) {
+                mRestrictBackground = restrictBackground;
+            }
+
+            if (restrictBackground) {
+                log("onRestrictBackgroundChanged(true): disabling tethering");
+                mTethering.untetherAll();
+            }
         }
 
         @Override
@@ -1813,6 +1849,18 @@
         pw.decreaseIndent();
         pw.println();
 
+        pw.println("Metered Interfaces:");
+        pw.increaseIndent();
+        for (String value : mMeteredIfaces) {
+            pw.println(value);
+        }
+        pw.decreaseIndent();
+        pw.println();
+
+        pw.print("Restrict background: ");
+        pw.println(mRestrictBackground);
+        pw.println();
+
         pw.println("Network Requests:");
         pw.increaseIndent();
         for (NetworkRequestInfo nri : mNetworkRequests.values()) {
@@ -2568,7 +2616,14 @@
     public int tether(String iface) {
         ConnectivityManager.enforceTetherChangePermission(mContext);
         if (isTetheringSupported()) {
-            return mTethering.tether(iface);
+            final int status = mTethering.tether(iface);
+            if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
+                try {
+                    mPolicyManager.onTetheringChanged(iface, true);
+                } catch (RemoteException e) {
+                }
+            }
+            return status;
         } else {
             return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
         }
@@ -2579,7 +2634,14 @@
         ConnectivityManager.enforceTetherChangePermission(mContext);
 
         if (isTetheringSupported()) {
-            return mTethering.untether(iface);
+            final int status = mTethering.untether(iface);
+            if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
+                try {
+                    mPolicyManager.onTetheringChanged(iface, false);
+                } catch (RemoteException e) {
+                }
+            }
+            return status;
         } else {
             return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
         }
@@ -2740,7 +2802,7 @@
             // which isn't meant to work on uncreated networks.
             if (!nai.created) return;
 
-            if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
+            if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return;
 
             nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
         }
@@ -3594,7 +3656,7 @@
         synchronized(mVpns) {
             Vpn userVpn = mVpns.get(userId);
             if (userVpn == null) {
-                loge("Stopping user has no VPN");
+                loge("Stopped user has no VPN");
                 return;
             }
             mVpns.delete(userId);
@@ -3639,7 +3701,7 @@
 
             if (Intent.ACTION_USER_STARTING.equals(action)) {
                 onUserStart(userId);
-            } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
+            } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
                 onUserStop(userId);
             } else if (Intent.ACTION_USER_ADDED.equals(action)) {
                 onUserAdded(userId);
@@ -4255,10 +4317,10 @@
         Collection<InetAddress> dnses = newLp.getDnsServers();
         if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
         try {
-            mNetd.setDnsServersForNetwork(
+            mNetd.setDnsConfigurationForNetwork(
                     netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
         } catch (Exception e) {
-            loge("Exception in setDnsServersForNetwork: " + e);
+            loge("Exception in setDnsConfigurationForNetwork: " + e);
         }
         final NetworkAgentInfo defaultNai = getDefaultNetwork();
         if (defaultNai != null && defaultNai.network.netId == netId) {
diff --git a/services/core/java/com/android/server/InputMethodManagerService.java b/services/core/java/com/android/server/InputMethodManagerService.java
index 79d16da..a584f70 100644
--- a/services/core/java/com/android/server/InputMethodManagerService.java
+++ b/services/core/java/com/android/server/InputMethodManagerService.java
@@ -1020,7 +1020,7 @@
         // If the system is not ready or the device is not yed unlocked by the user, then we use
         // copy-on-write settings.
         final boolean useCopyOnWriteSettings =
-                !mSystemReady || !mUserManager.isUserUnlocked(newUserId);
+                !mSystemReady || !mUserManager.isUserUnlockingOrUnlocked(newUserId);
         mSettings.switchCurrentUser(newUserId, useCopyOnWriteSettings);
         updateCurrentProfileIds();
         // InputMethodFileManager should be reset when the user is changed
@@ -1077,7 +1077,7 @@
                 mSystemReady = true;
                 final int currentUserId = mSettings.getCurrentUserId();
                 mSettings.switchCurrentUser(currentUserId,
-                        !mUserManager.isUserUnlocked(currentUserId));
+                        !mUserManager.isUserUnlockingOrUnlocked(currentUserId));
                 mKeyguardManager = mContext.getSystemService(KeyguardManager.class);
                 mNotificationManager = mContext.getSystemService(NotificationManager.class);
                 mStatusBar = statusBar;
diff --git a/services/core/java/com/android/server/LockSettingsService.java b/services/core/java/com/android/server/LockSettingsService.java
index a3ef6b6..cbf7e80 100644
--- a/services/core/java/com/android/server/LockSettingsService.java
+++ b/services/core/java/com/android/server/LockSettingsService.java
@@ -256,13 +256,13 @@
         for (int i = 0; i < users.size(); i++) {
             UserInfo user = users.get(i);
             UserHandle userHandle = user.getUserHandle();
-            if (!mUserManager.isUserUnlocked(userHandle)) {
+            if (!mUserManager.isUserUnlockingOrUnlocked(userHandle)) {
                 if (!user.isManagedProfile()) {
                     showEncryptionNotification(userHandle);
                 } else {
                     UserInfo parent = mUserManager.getProfileParent(user.id);
                     if (parent != null &&
-                            mUserManager.isUserUnlocked(parent.getUserHandle()) &&
+                            mUserManager.isUserUnlockingOrUnlocked(parent.getUserHandle()) &&
                             !mUserManager.isQuietModeEnabled(userHandle)) {
                         // Only show notifications for managed profiles once their parent
                         // user is unlocked.
@@ -350,7 +350,7 @@
             UserInfo profile = profiles.get(i);
             if (profile.isManagedProfile()) {
                 UserHandle userHandle = profile.getUserHandle();
-                if (!mUserManager.isUserUnlocked(userHandle) &&
+                if (!mUserManager.isUserUnlockingOrUnlocked(userHandle) &&
                         !mUserManager.isQuietModeEnabled(userHandle)) {
                     showEncryptionNotificationForProfile(userHandle);
                 }
@@ -1281,8 +1281,14 @@
         // service can't connect to vold, it restarts, and then the new instance
         // does successfully connect.
         final IMountService service = getMountService();
-        String password = service.getPassword();
-        service.clearPassword();
+        String password;
+        long identity = Binder.clearCallingIdentity();
+        try {
+            password = service.getPassword();
+            service.clearPassword();
+        } finally {
+            Binder.restoreCallingIdentity(identity);
+        }
         if (password == null) {
             return false;
         }
diff --git a/services/core/java/com/android/server/MountService.java b/services/core/java/com/android/server/MountService.java
index ec05dae..7253870 100644
--- a/services/core/java/com/android/server/MountService.java
+++ b/services/core/java/com/android/server/MountService.java
@@ -2648,6 +2648,8 @@
      */
     @Override
     public int getPasswordType() {
+        mContext.enforceCallingOrSelfPermission(Manifest.permission.STORAGE_INTERNAL,
+            "no permission to access the crypt keeper");
 
         waitForReady();
 
@@ -2672,6 +2674,8 @@
      */
     @Override
     public void setField(String field, String contents) throws RemoteException {
+        mContext.enforceCallingOrSelfPermission(Manifest.permission.STORAGE_INTERNAL,
+            "no permission to access the crypt keeper");
 
         waitForReady();
 
@@ -2690,6 +2694,8 @@
      */
     @Override
     public String getField(String field) throws RemoteException {
+        mContext.enforceCallingOrSelfPermission(Manifest.permission.STORAGE_INTERNAL,
+            "no permission to access the crypt keeper");
 
         waitForReady();
 
@@ -2714,6 +2720,8 @@
      */
     @Override
     public boolean isConvertibleToFBE() throws RemoteException {
+        mContext.enforceCallingOrSelfPermission(Manifest.permission.STORAGE_INTERNAL,
+            "no permission to access the crypt keeper");
 
         waitForReady();
 
@@ -2728,8 +2736,9 @@
 
     @Override
     public String getPassword() throws RemoteException {
-        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_KEYGUARD_SECURE_STORAGE,
+        mContext.enforceCallingOrSelfPermission(Manifest.permission.STORAGE_INTERNAL,
                 "only keyguard can retrieve password");
+
         if (!isReady()) {
             return new String();
         }
@@ -2752,6 +2761,9 @@
 
     @Override
     public void clearPassword() throws RemoteException {
+        mContext.enforceCallingOrSelfPermission(Manifest.permission.STORAGE_INTERNAL,
+                "only keyguard can clear password");
+
         if (!isReady()) {
             return;
         }
@@ -2816,17 +2828,19 @@
         enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
         waitForReady();
 
-        // When a user has secure lock screen, require a challenge token to
-        // actually unlock. This check is mostly in place for emulation mode.
-        if (mLockPatternUtils.isSecure(userId) && ArrayUtils.isEmpty(token)) {
-            throw new IllegalStateException("Token required to unlock secure user " + userId);
-        }
+        if (StorageManager.isFileEncryptedNativeOrEmulated()) {
+            // When a user has secure lock screen, require a challenge token to
+            // actually unlock. This check is mostly in place for emulation mode.
+            if (mLockPatternUtils.isSecure(userId) && ArrayUtils.isEmpty(token)) {
+                throw new IllegalStateException("Token required to unlock secure user " + userId);
+            }
 
-        try {
-            mCryptConnector.execute("cryptfs", "unlock_user_key", userId, serialNumber,
-                    encodeBytes(token), encodeBytes(secret));
-        } catch (NativeDaemonConnectorException e) {
-            throw e.rethrowAsParcelableException();
+            try {
+                mCryptConnector.execute("cryptfs", "unlock_user_key", userId, serialNumber,
+                        encodeBytes(token), encodeBytes(secret));
+            } catch (NativeDaemonConnectorException e) {
+                throw e.rethrowAsParcelableException();
+            }
         }
 
         synchronized (mLock) {
@@ -2852,12 +2866,8 @@
 
     @Override
     public boolean isUserKeyUnlocked(int userId) {
-        if (StorageManager.isFileEncryptedNativeOrEmulated()) {
-            synchronized (mLock) {
-                return ArrayUtils.contains(mLocalUnlockedUsers, userId);
-            }
-        } else {
-            return true;
+        synchronized (mLock) {
+            return ArrayUtils.contains(mLocalUnlockedUsers, userId);
         }
     }
 
diff --git a/services/core/java/com/android/server/NetworkManagementService.java b/services/core/java/com/android/server/NetworkManagementService.java
index 9fc17a2..2418160 100644
--- a/services/core/java/com/android/server/NetworkManagementService.java
+++ b/services/core/java/com/android/server/NetworkManagementService.java
@@ -47,6 +47,7 @@
 import static com.android.server.NetworkManagementSocketTagger.PROP_QTAGUID_ENABLED;
 import android.annotation.NonNull;
 import android.app.ActivityManagerNative;
+import android.content.ContentResolver;
 import android.content.Context;
 import android.net.ConnectivityManager;
 import android.net.INetd;
@@ -76,6 +77,7 @@
 import android.os.StrictMode;
 import android.os.SystemClock;
 import android.os.SystemProperties;
+import android.provider.Settings;
 import android.telephony.DataConnectionRealTimeInfo;
 import android.telephony.PhoneStateListener;
 import android.telephony.SubscriptionManager;
@@ -175,6 +177,12 @@
         public static final int StrictCleartext           = 617;
     }
 
+    /* Defaults for resolver parameters. */
+    public static final int DNS_RESOLVER_DEFAULT_SAMPLE_VALIDITY_SECONDS = 1800;
+    public static final int DNS_RESOLVER_DEFAULT_SUCCESS_THRESHOLD_PERCENT = 25;
+    public static final int DNS_RESOLVER_DEFAULT_MIN_SAMPLES = 8;
+    public static final int DNS_RESOLVER_DEFAULT_MAX_SAMPLES = 64;
+
     /**
      * String indicating a softap command.
      */
@@ -1927,6 +1935,51 @@
     }
 
     @Override
+    public void setDnsConfigurationForNetwork(int netId, String[] servers, String domains) {
+        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
+
+        ContentResolver resolver = mContext.getContentResolver();
+
+        int sampleValidity = Settings.Global.getInt(resolver,
+                Settings.Global.DNS_RESOLVER_SAMPLE_VALIDITY_SECONDS,
+                DNS_RESOLVER_DEFAULT_SAMPLE_VALIDITY_SECONDS);
+        if (sampleValidity < 0 || sampleValidity > 65535) {
+            Slog.w(TAG, "Invalid sampleValidity=" + sampleValidity + ", using default=" +
+                    DNS_RESOLVER_DEFAULT_SAMPLE_VALIDITY_SECONDS);
+            sampleValidity = DNS_RESOLVER_DEFAULT_SAMPLE_VALIDITY_SECONDS;
+        }
+
+        int successThreshold = Settings.Global.getInt(resolver,
+                Settings.Global.DNS_RESOLVER_SUCCESS_THRESHOLD_PERCENT,
+                DNS_RESOLVER_DEFAULT_SUCCESS_THRESHOLD_PERCENT);
+        if (successThreshold < 0 || successThreshold > 100) {
+            Slog.w(TAG, "Invalid successThreshold=" + successThreshold + ", using default=" +
+                    DNS_RESOLVER_DEFAULT_SUCCESS_THRESHOLD_PERCENT);
+            successThreshold = DNS_RESOLVER_DEFAULT_SUCCESS_THRESHOLD_PERCENT;
+        }
+
+        int minSamples = Settings.Global.getInt(resolver,
+                Settings.Global.DNS_RESOLVER_MIN_SAMPLES, DNS_RESOLVER_DEFAULT_MIN_SAMPLES);
+        int maxSamples = Settings.Global.getInt(resolver,
+                Settings.Global.DNS_RESOLVER_MAX_SAMPLES, DNS_RESOLVER_DEFAULT_MAX_SAMPLES);
+        if (minSamples < 0 || minSamples > maxSamples || maxSamples > 64) {
+            Slog.w(TAG, "Invalid sample count (min, max)=(" + minSamples + ", " + maxSamples +
+                    "), using default=(" + DNS_RESOLVER_DEFAULT_MIN_SAMPLES + ", " +
+                    DNS_RESOLVER_DEFAULT_MAX_SAMPLES + ")");
+            minSamples = DNS_RESOLVER_DEFAULT_MIN_SAMPLES;
+            maxSamples = DNS_RESOLVER_DEFAULT_MAX_SAMPLES;
+        }
+
+        final String[] domainStrs = domains == null ? new String[0] : domains.split(" ");
+        final int[] params = { sampleValidity, successThreshold, minSamples, maxSamples };
+        try {
+            mNetdService.setResolverConfiguration(netId, servers, domainStrs, params);
+        } catch (RemoteException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    @Override
     public void setDnsServersForNetwork(int netId, String[] servers, String domains) {
         mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
 
@@ -2048,13 +2101,13 @@
         }
     }
 
-    private void closeSocketsForFirewallChain(int chain, String chainName) {
+    private void closeSocketsForFirewallChainLocked(int chain, String chainName) {
         // UID ranges to close sockets on.
         UidRange[] ranges;
         // UID ranges whose sockets we won't touch.
         int[] exemptUids;
 
-        SparseIntArray rules = getUidFirewallRules(chain);
+        final SparseIntArray rules = getUidFirewallRules(chain);
         int numUids = 0;
 
         if (getFirewallType(chain) == FIREWALL_TYPE_WHITELIST) {
@@ -2119,7 +2172,7 @@
             mFirewallChainStates.put(chain, enable);
 
             final String operation = enable ? "enable_chain" : "disable_chain";
-            String chainName;
+            final String chainName;
             switch(chain) {
                 case FIREWALL_CHAIN_STANDBY:
                     chainName = FIREWALL_CHAIN_NAME_STANDBY;
@@ -2146,7 +2199,7 @@
             // whitelist and blacklist chains allow RSTs through.
             if (enable) {
                 if (DBG) Slog.d(TAG, "Closing sockets after enabling chain " + chainName);
-                closeSocketsForFirewallChain(chain, chainName);
+                closeSocketsForFirewallChainLocked(chain, chainName);
             }
         }
     }
diff --git a/services/core/java/com/android/server/TextServicesManagerService.java b/services/core/java/com/android/server/TextServicesManagerService.java
index a628747..4b0d4be 100644
--- a/services/core/java/com/android/server/TextServicesManagerService.java
+++ b/services/core/java/com/android/server/TextServicesManagerService.java
@@ -166,7 +166,7 @@
         mMonitor = new TextServicesMonitor();
         mMonitor.register(context, null, true);
         final boolean useCopyOnWriteSettings =
-                !mSystemReady || !mUserManager.isUserUnlocked(userId);
+                !mSystemReady || !mUserManager.isUserUnlockingOrUnlocked(userId);
         mSettings = new TextServicesSettings(context.getContentResolver(), userId,
                 useCopyOnWriteSettings);
 
@@ -176,7 +176,7 @@
 
     private void resetInternalState(@UserIdInt int userId) {
         final boolean useCopyOnWriteSettings =
-                !mSystemReady || !mUserManager.isUserUnlocked(userId);
+                !mSystemReady || !mUserManager.isUserUnlockingOrUnlocked(userId);
         mSettings.switchCurrentUser(userId, useCopyOnWriteSettings);
         updateCurrentProfileIds();
         unbindServiceLocked();
diff --git a/services/core/java/com/android/server/accounts/AccountManagerService.java b/services/core/java/com/android/server/accounts/AccountManagerService.java
index 480da72..98b3b08 100644
--- a/services/core/java/com/android/server/accounts/AccountManagerService.java
+++ b/services/core/java/com/android/server/accounts/AccountManagerService.java
@@ -304,7 +304,7 @@
     }
 
     private final SparseArray<UserAccounts> mUsers = new SparseArray<>();
-    private final SparseBooleanArray mUnlockedUsers = new SparseBooleanArray();
+    private final SparseBooleanArray mLocalUnlockedUsers = new SparseBooleanArray();
 
     private static AtomicReference<AccountManagerService> sThis = new AtomicReference<>();
     private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
@@ -409,7 +409,6 @@
      */
     public void validateAccounts(int userId) {
         final UserAccounts accounts = getUserAccounts(userId);
-
         // Invalidate user-specific cache to make sure we catch any
         // removed authenticators.
         validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
@@ -424,17 +423,15 @@
         if (Log.isLoggable(TAG, Log.DEBUG)) {
             Log.d(TAG, "validateAccountsInternal " + accounts.userId
                     + " isCeDatabaseAttached=" + accounts.openHelper.isCeDatabaseAttached()
-                    + " userLocked=" + mUnlockedUsers.get(accounts.userId));
+                    + " userLocked=" + mLocalUnlockedUsers.get(accounts.userId));
         }
+
         if (invalidateAuthenticatorCache) {
             mAuthenticatorCache.invalidateCache(accounts.userId);
         }
 
-        final HashMap<String, Integer> knownAuth = new HashMap<>();
-        for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service :
-                mAuthenticatorCache.getAllServices(accounts.userId)) {
-            knownAuth.put(service.type.type, service.uid);
-        }
+        final HashMap<String, Integer> knownAuth = getAuthenticatorTypeAndUIDForUser(
+                mAuthenticatorCache, accounts.userId);
 
         synchronized (accounts.cacheLock) {
             final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
@@ -452,6 +449,7 @@
             // Create a list of authenticator type whose previous uid no longer exists
             HashSet<String> obsoleteAuthType = Sets.newHashSet();
             try {
+                SparseBooleanArray knownUids = null;
                 while (metaCursor.moveToNext()) {
                     String type = TextUtils.split(metaCursor.getString(0), META_KEY_DELIMITER)[1];
                     String uid = metaCursor.getString(1);
@@ -466,23 +464,48 @@
                         // Remove it from the knownAuth list if it's unchanged.
                         knownAuth.remove(type);
                     } else {
-                        // Only add it to the list if it no longer exists or uid different
-                        obsoleteAuthType.add(type);
-                        // And delete it from the TABLE_META
-                        db.delete(
-                                TABLE_META,
-                                META_KEY + "=? AND " + META_VALUE + "=?",
-                                new String[] {
-                                        META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + type,
-                                        uid}
-                                );
+                        /*
+                         * The authenticator is presently not cached and should only be triggered
+                         * when we think an authenticator has been removed (or is being updated).
+                         * But we still want to check if any data with the associated uid is
+                         * around. This is an (imperfect) signal that the package may be updating.
+                         *
+                         * A side effect of this is that an authenticator sharing a uid with
+                         * multiple apps won't get its credentials wiped as long as some app with
+                         * that uid is still on the device. But I suspect that this is a rare case.
+                         * And it isn't clear to me how an attacker could really exploit that
+                         * feature.
+                         *
+                         * The upshot is that we don't have to worry about accounts getting
+                         * uninstalled while the authenticator's package is being updated.
+                         *
+                         */
+                        if (knownUids == null) {
+                            knownUids = getUidsOfInstalledOrUpdatedPackagesAsUser(accounts.userId); 
+                        }
+                        if (!knownUids.get(Integer.parseInt(uid))) {
+                            // The authenticator is not presently available to the cache. And the
+                            // package no longer has a data directory (so we surmise it isn't updating).
+                            // So purge its data from the account databases.
+                            obsoleteAuthType.add(type);
+                            // And delete it from the TABLE_META
+                            db.delete(
+                                    TABLE_META,
+                                    META_KEY + "=? AND " + META_VALUE + "=?",
+                                    new String[] {
+                                            META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + type,
+                                            uid}
+                                    );
+                        }
                     }
                 }
             } finally {
                 metaCursor.close();
             }
 
-            // Add the newly registered authenticator to TABLE_META
+            // Add the newly registered authenticator to TABLE_META. If old authenticators have
+            // been renabled (after being updated for example), then we just overwrite the old
+            // values.
             Iterator<Entry<String, Integer>> iterator = knownAuth.entrySet().iterator();
             while (iterator.hasNext()) {
                 Entry<String, Integer> entry = iterator.next();
@@ -490,7 +513,7 @@
                 values.put(META_KEY,
                         META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + entry.getKey());
                 values.put(META_VALUE, entry.getValue());
-                db.insert(TABLE_META, null, values);
+                db.insertWithOnConflict(TABLE_META, null, values, SQLiteDatabase.CONFLICT_REPLACE);
             }
 
             Cursor cursor = db.query(TABLE_ACCOUNTS,
@@ -544,10 +567,32 @@
         }
     }
 
+    private SparseBooleanArray getUidsOfInstalledOrUpdatedPackagesAsUser(int userId) {
+        // Get the UIDs of all apps that might have data on the device. We want
+        // to preserve user data if the app might otherwise be storing data.
+        List<PackageInfo> pkgsWithData =
+                mPackageManager.getInstalledPackagesAsUser(
+                        PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
+        SparseBooleanArray knownUids = new SparseBooleanArray(pkgsWithData.size());
+        for (PackageInfo pkgInfo : pkgsWithData) {
+            if (pkgInfo.applicationInfo != null
+                    && (pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0) {
+                knownUids.put(pkgInfo.applicationInfo.uid, true);
+            }
+        }
+        return knownUids;
+    }
+
     private static HashMap<String, Integer> getAuthenticatorTypeAndUIDForUser(
             Context context,
             int userId) {
         AccountAuthenticatorCache authCache = new AccountAuthenticatorCache(context);
+        return getAuthenticatorTypeAndUIDForUser(authCache, userId);
+    }
+
+    private static HashMap<String, Integer> getAuthenticatorTypeAndUIDForUser(
+            IAccountAuthenticatorCache authCache,
+            int userId) {
         HashMap<String, Integer> knownAuth = new HashMap<>();
         for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service : authCache
                 .getAllServices(userId)) {
@@ -575,7 +620,7 @@
                 validateAccounts = true;
             }
             // open CE database if necessary
-            if (!accounts.openHelper.isCeDatabaseAttached() && mUnlockedUsers.get(userId)) {
+            if (!accounts.openHelper.isCeDatabaseAttached() && mLocalUnlockedUsers.get(userId)) {
                 Log.i(TAG, "User " + userId + " is unlocked - opening CE database");
                 synchronized (accounts.cacheLock) {
                     File preNDatabaseFile = new File(getPreNDatabaseName(userId));
@@ -648,8 +693,8 @@
         synchronized (mUsers) {
             accounts = mUsers.get(userId);
             mUsers.remove(userId);
-            userUnlocked = mUnlockedUsers.get(userId);
-            mUnlockedUsers.delete(userId);
+            userUnlocked = mLocalUnlockedUsers.get(userId);
+            mLocalUnlockedUsers.delete(userId);
         }
         if (accounts != null) {
             synchronized (accounts.cacheLock) {
@@ -686,7 +731,7 @@
             Log.v(TAG, "onUserUnlocked " + userId);
         }
         synchronized (mUsers) {
-            mUnlockedUsers.put(userId, true);
+            mLocalUnlockedUsers.put(userId, true);
         }
         if (userId < 1) return;
         syncSharedAccounts(userId);
@@ -746,7 +791,7 @@
         if (account == null) {
             return null;
         }
-        if (!isUserUnlocked(accounts.userId)) {
+        if (!isLocalUnlockedUser(accounts.userId)) {
             Log.w(TAG, "Password is not available - user " + accounts.userId + " data is locked");
             return null;
         }
@@ -828,7 +873,7 @@
                     account.type);
             throw new SecurityException(msg);
         }
-        if (!isUserUnlocked(userId)) {
+        if (!isLocalUnlockedUser(userId)) {
             Log.w(TAG, "User " + userId + " data is locked. callingUid " + callingUid);
             return null;
         }
@@ -1109,7 +1154,7 @@
         if (account == null) {
             return false;
         }
-        if (!isUserUnlocked(accounts.userId)) {
+        if (!isLocalUnlockedUser(accounts.userId)) {
             Log.w(TAG, "Account " + account + " cannot be added - user " + accounts.userId
                     + " is locked. callingUid=" + callingUid);
             return false;
@@ -1176,9 +1221,9 @@
         return true;
     }
 
-    private boolean isUserUnlocked(int userId) {
+    private boolean isLocalUnlockedUser(int userId) {
         synchronized (mUsers) {
-            return mUnlockedUsers.get(userId);
+            return mLocalUnlockedUsers.get(userId);
         }
     }
 
@@ -1193,7 +1238,7 @@
         for (UserInfo user : users) {
             if (user.isRestricted() && (parentUserId == user.restrictedProfileParentId)) {
                 addSharedAccountAsUser(account, user.id);
-                if (getUserManager().isUserUnlocked(user.id)) {
+                if (isLocalUnlockedUser(user.id)) {
                     mMessageHandler.sendMessage(mMessageHandler.obtainMessage(
                             MESSAGE_COPY_SHARED_ACCOUNT, parentUserId, user.id, account));
                 }
@@ -1597,7 +1642,7 @@
 
     private boolean removeAccountInternal(UserAccounts accounts, Account account, int callingUid) {
         int deleted;
-        boolean userUnlocked = isUserUnlocked(accounts.userId);
+        boolean userUnlocked = isLocalUnlockedUser(accounts.userId);
         if (!userUnlocked) {
             Slog.i(TAG, "Removing account " + account + " while user "+ accounts.userId
                     + " is still locked. CE data will be removed later");
@@ -1792,7 +1837,7 @@
                     account.type);
             throw new SecurityException(msg);
         }
-        if (!isUserUnlocked(userId)) {
+        if (!isLocalUnlockedUser(userId)) {
             Log.w(TAG, "Authtoken not available - user " + userId + " data is locked. callingUid "
                     + callingUid);
             return null;
@@ -4037,8 +4082,7 @@
                 return false;
             }
 
-            final ActivityManager am = mContext.getSystemService(ActivityManager.class);
-            if (am.isUserRunningAndLocked(mAccounts.userId)
+            if (!isLocalUnlockedUser(mAccounts.userId)
                     && !authenticatorInfo.componentInfo.directBootAware) {
                 Slog.w(TAG, "Blocking binding to authenticator " + authenticatorInfo.componentName
                         + " which isn't encryption aware");
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index 9d7ddc7..ddb9b8a 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -1946,9 +1946,7 @@
                     startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
                 }
                 installEncryptionUnawareProviders(userId);
-                if (msg.obj instanceof ProgressReporter) {
-                    ((ProgressReporter) msg.obj).finish();
-                }
+                mUserController.finishUserUnlocked((UserState) msg.obj);
                 break;
             }
             case SYSTEM_USER_CURRENT_MSG: {
@@ -5949,6 +5947,15 @@
 
     }
 
+    final boolean clearBroadcastQueueForUserLocked(int userId) {
+        boolean didSomething = false;
+        for (int i = mBroadcastQueues.length - 1; i >= 0; i--) {
+            didSomething |= mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked(
+                    null, null, userId, true);
+        }
+        return didSomething;
+    }
+
     final boolean forceStopPackageLocked(String packageName, int appId,
             boolean callerWillRestart, boolean purgeCache, boolean doit,
             boolean evenPersistent, boolean uninstalling, int userId, String reason) {
@@ -6304,7 +6311,11 @@
         app.debugging = false;
         app.cached = false;
         app.killedByAm = false;
-        app.unlocked = mContext.getSystemService(UserManager.class).isUserUnlocked(app.userId);
+
+        // We carefully use the same state that PackageManager uses for
+        // filtering, since we use this flag to decide if we need to install
+        // providers when user is unlocked later
+        app.unlocked = StorageManager.isUserKeyUnlocked(app.userId);
 
         mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
 
@@ -11024,14 +11035,6 @@
      * belonging to any running apps.
      */
     private void installEncryptionUnawareProviders(int userId) {
-        if (!StorageManager.isFileEncryptedNativeOrEmulated()) {
-            // TODO: eventually pivot this back to look at current user state,
-            // similar to the comment in UserManager.isUserUnlocked(), but for
-            // now, if we started apps when "unlocked" then unaware providers
-            // have already been spun up.
-            return;
-        }
-
         // We're only interested in providers that are encryption unaware, and
         // we don't care about uninstalled apps, since there's no way they're
         // running at this point.
@@ -17178,6 +17181,7 @@
             if (isProtectedBroadcast
                     || Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)
                     || Intent.ACTION_DISMISS_KEYBOARD_SHORTCUTS.equals(action)
+                    || Intent.ACTION_MEDIA_BUTTON.equals(action)
                     || Intent.ACTION_MEDIA_SCANNER_SCAN_FILE.equals(action)
                     || Intent.ACTION_SHOW_KEYBOARD_SHORTCUTS.equals(action)
                     || AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(action)
diff --git a/services/core/java/com/android/server/am/ActivityRecord.java b/services/core/java/com/android/server/am/ActivityRecord.java
index a41a8ef..2386a36 100755
--- a/services/core/java/com/android/server/am/ActivityRecord.java
+++ b/services/core/java/com/android/server/am/ActivityRecord.java
@@ -21,6 +21,7 @@
 import static android.app.ActivityManager.StackId.PINNED_STACK_ID;
 import static android.content.pm.ActivityInfo.RESIZE_MODE_CROP_WINDOWS;
 import static android.content.pm.ActivityInfo.FLAG_ALWAYS_FOCUSABLE;
+import static android.content.pm.ActivityInfo.RESIZE_MODE_RESIZEABLE;
 import static android.content.pm.ActivityInfo.RESIZE_MODE_RESIZEABLE_AND_PIPABLE;
 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_CONFIGURATION;
 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SWITCH;
@@ -822,6 +823,11 @@
         return !isHomeActivity() && (isResizeable() || service.mForceResizableActivities);
     }
 
+    boolean isNonResizableOrForced() {
+        return !isHomeActivity() && info.resizeMode != RESIZE_MODE_RESIZEABLE
+                && info.resizeMode != RESIZE_MODE_RESIZEABLE_AND_PIPABLE;
+    }
+
     boolean supportsPictureInPicture() {
         return !isHomeActivity() && info.resizeMode == RESIZE_MODE_RESIZEABLE_AND_PIPABLE;
     }
diff --git a/services/core/java/com/android/server/am/ActivityStack.java b/services/core/java/com/android/server/am/ActivityStack.java
index 37bd401..21fc4d8 100644
--- a/services/core/java/com/android/server/am/ActivityStack.java
+++ b/services/core/java/com/android/server/am/ActivityStack.java
@@ -3438,7 +3438,9 @@
                 mWindowManager.prepareAppTransition(transit, false);
                 mWindowManager.setAppVisibility(r.appToken, false);
                 mWindowManager.executeAppTransition();
-                mStackSupervisor.mWaitingVisibleActivities.add(r);
+                if (!mStackSupervisor.mWaitingVisibleActivities.contains(r)) {
+                    mStackSupervisor.mWaitingVisibleActivities.add(r);
+                }
             }
             return finishCurrentActivityLocked(r, (r.visible || r.nowVisible) ?
                     FINISH_AFTER_VISIBLE : FINISH_AFTER_PAUSE, oomAdj) == null;
@@ -3457,8 +3459,11 @@
         // First things first: if this activity is currently visible,
         // and the resumed activity is not yet visible, then hold off on
         // finishing until the resumed one becomes visible.
+
+        final ActivityRecord next = mStackSupervisor.topRunningActivityLocked();
+
         if (mode == FINISH_AFTER_VISIBLE && (r.visible || r.nowVisible)
-                && !mStackSupervisor.allResumedActivitiesVisible()) {
+                && next != null && !next.nowVisible) {
             if (!mStackSupervisor.mStoppingActivities.contains(r)) {
                 addToStopping(r, false /* immediate */);
             }
diff --git a/services/core/java/com/android/server/am/ActivityStackSupervisor.java b/services/core/java/com/android/server/am/ActivityStackSupervisor.java
index f192a9d..20ef0e8 100644
--- a/services/core/java/com/android/server/am/ActivityStackSupervisor.java
+++ b/services/core/java/com/android/server/am/ActivityStackSupervisor.java
@@ -3508,6 +3508,7 @@
             return;
         }
 
+        final ActivityRecord topActivity = task.getTopActivity();
         if (!task.canGoInDockedStack() || forceNonResizable) {
             // Display a warning toast that we tried to put a non-dockable task in the docked stack.
             mService.mHandler.sendEmptyMessage(NOTIFY_ACTIVITY_DISMISSING_DOCKED_STACK_MSG);
@@ -3515,9 +3516,9 @@
             // Dismiss docked stack. If task appeared to be in docked stack but is not resizable -
             // we need to move it to top of fullscreen stack, otherwise it will be covered.
             moveTasksToFullscreenStackLocked(DOCKED_STACK_ID, actualStackId == DOCKED_STACK_ID);
-        } else if (task.mResizeMode == RESIZE_MODE_FORCE_RESIZEABLE) {
-            String packageName = task.getTopActivity() != null
-                    ? task.getTopActivity().appInfo.packageName : null;
+        } else if (topActivity != null && topActivity.isNonResizableOrForced()
+                && !topActivity.noDisplay) {
+            String packageName = topActivity.appInfo.packageName;
             mService.mHandler.obtainMessage(NOTIFY_FORCED_RESIZABLE_MSG, task.taskId, 0,
                     packageName).sendToTarget();
         }
diff --git a/services/core/java/com/android/server/am/ActivityStarter.java b/services/core/java/com/android/server/am/ActivityStarter.java
index 6622b34..33b87b6 100644
--- a/services/core/java/com/android/server/am/ActivityStarter.java
+++ b/services/core/java/com/android/server/am/ActivityStarter.java
@@ -171,6 +171,7 @@
     private boolean mMovedToFront;
     private boolean mNoAnimation;
     private boolean mKeepCurTransition;
+    private boolean mAvoidMoveToFront;
 
     private IVoiceInteractionSession mVoiceSession;
     private IVoiceInteractor mVoiceInteractor;
@@ -207,6 +208,7 @@
         mMovedToFront = false;
         mNoAnimation = false;
         mKeepCurTransition = false;
+        mAvoidMoveToFront = false;
 
         mVoiceSession = null;
         mVoiceInteractor = null;
@@ -683,8 +685,8 @@
                     Binder.restoreCallingIdentity(token);
                 }
                 if (parent != null
-                        && userManager.isUserUnlocked(parent.getUserHandle())
-                        && !userManager.isUserUnlocked(userInfo.getUserHandle())) {
+                        && userManager.isUserUnlockingOrUnlocked(parent.getUserHandle())
+                        && !userManager.isUserUnlockingOrUnlocked(userInfo.getUserHandle())) {
                     rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId,
                             PackageManager.MATCH_DIRECT_BOOT_AWARE
                                     | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
@@ -1223,6 +1225,18 @@
             mDoResume = false;
         }
 
+        if (mOptions != null && mOptions.getLaunchTaskId() != -1 && mOptions.getAvoidMoveToFront()) {
+            final TaskRecord task = mSupervisor.anyTaskForIdLocked(mOptions.getLaunchTaskId());
+            final ActivityRecord top = task != null ? task.getTopActivity() : null;
+            if (top != null && !top.visible) {
+
+                // The caller specifies that we'd like to be avoided to be moved to the front, so be
+                // it!
+                mDoResume = false;
+                mAvoidMoveToFront = true;
+            }
+        }
+
         mNotTop = (mLaunchFlags & FLAG_ACTIVITY_PREVIOUS_IS_TOP) != 0 ? r : null;
 
         mInTask = inTask;
@@ -1419,8 +1433,9 @@
         ActivityRecord curTop = (focusStack == null)
                 ? null : focusStack.topRunningNonDelayedActivityLocked(mNotTop);
 
-        if (curTop != null && (curTop.task != intentActivity.task ||
-                curTop.task != focusStack.topTask())) {
+        if (curTop != null
+                && (curTop.task != intentActivity.task || curTop.task != focusStack.topTask())
+                && !mAvoidMoveToFront) {
             mStartActivity.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
             if (mSourceRecord == null || (mSourceStack.topActivity() != null &&
                     mSourceStack.topActivity().task == mSourceRecord.task)) {
@@ -1631,7 +1646,7 @@
             mTargetStack.moveToFront("sourceStackToFront");
         }
         final TaskRecord topTask = mTargetStack.topTask();
-        if (topTask != sourceTask) {
+        if (topTask != sourceTask && !mAvoidMoveToFront) {
             mTargetStack.moveTaskToFrontLocked(sourceTask, mNoAnimation, mOptions,
                     mStartActivity.appTimeTracker, "sourceTaskToFront");
         }
diff --git a/services/core/java/com/android/server/am/AppErrors.java b/services/core/java/com/android/server/am/AppErrors.java
index e9ed34b..3ed9969 100644
--- a/services/core/java/com/android/server/am/AppErrors.java
+++ b/services/core/java/com/android/server/am/AppErrors.java
@@ -304,6 +304,15 @@
      * @param crashInfo describing the failure
      */
     void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
+        final long origId = Binder.clearCallingIdentity();
+        try {
+            crashApplicationInner(r, crashInfo);
+        } finally {
+            Binder.restoreCallingIdentity(origId);
+        }
+    }
+
+    void crashApplicationInner(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
         long timeMillis = System.currentTimeMillis();
         String shortMsg = crashInfo.exceptionClassName;
         String longMsg = crashInfo.exceptionMessage;
@@ -317,49 +326,20 @@
         AppErrorResult result = new AppErrorResult();
         TaskRecord task;
         synchronized (mService) {
-            if (mService.mController != null) {
-                try {
-                    String name = r != null ? r.processName : null;
-                    int pid = r != null ? r.pid : Binder.getCallingPid();
-                    int uid = r != null ? r.info.uid : Binder.getCallingUid();
-                    if (!mService.mController.appCrashed(name, pid,
-                            shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
-                        if ("1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"))
-                                && "Native crash".equals(crashInfo.exceptionClassName)) {
-                            Slog.w(TAG, "Skip killing native crashed app " + name
-                                    + "(" + pid + ") during testing");
-                        } else {
-                            Slog.w(TAG, "Force-killing crashed app " + name
-                                    + " at watcher's request");
-                            if (r != null) {
-                                r.kill("crash", true);
-                            } else {
-                                // Huh.
-                                Process.killProcess(pid);
-                                ActivityManagerService.killProcessGroup(uid, pid);
-                            }
-                        }
-                        return;
-                    }
-                } catch (RemoteException e) {
-                    mService.mController = null;
-                    Watchdog.getInstance().setActivityController(null);
-                }
+            /**
+             * If crash is handled by instance of {@link android.app.IActivityController},
+             * finish now and don't show the app error dialog.
+             */
+            if (handleAppCrashInActivityController(r, crashInfo, shortMsg, longMsg, stackTrace,
+                    timeMillis)) {
+                return;
             }
 
-            final long origId = Binder.clearCallingIdentity();
-
-            // If this process is running instrumentation, finish it.
+            /**
+             * If this process was running instrumentation, finish now - it will be handled in
+             * {@link ActivityManagerService#handleAppDiedLocked}.
+             */
             if (r != null && r.instrumentationClass != null) {
-                Slog.w(TAG, "Error in app " + r.processName
-                        + " running instrumentation " + r.instrumentationClass + ":");
-                if (shortMsg != null) Slog.w(TAG, "  " + shortMsg);
-                if (longMsg != null) Slog.w(TAG, "  " + longMsg);
-                Bundle info = new Bundle();
-                info.putString("shortMsg", shortMsg);
-                info.putString("longMsg", longMsg);
-                mService.finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
-                Binder.restoreCallingIdentity(origId);
                 return;
             }
 
@@ -375,7 +355,6 @@
             // If we can't identify the process or it's already exceeded its crash quota,
             // quit right away without showing a crash dialog.
             if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace, data)) {
-                Binder.restoreCallingIdentity(origId);
                 return;
             }
 
@@ -385,97 +364,90 @@
             task = data.task;
             msg.obj = data;
             mService.mUiHandler.sendMessage(msg);
-
-            Binder.restoreCallingIdentity(origId);
         }
 
         int res = result.get();
 
         Intent appErrorIntent = null;
-        final long ident = Binder.clearCallingIdentity();
-        try {
-            MetricsLogger.action(mContext, MetricsProto.MetricsEvent.ACTION_APP_CRASH, res);
-            if (res == AppErrorDialog.TIMEOUT) {
-                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();
-                                        }
-                                    });
+        MetricsLogger.action(mContext, MetricsProto.MetricsEvent.ACTION_APP_CRASH, res);
+        if (res == AppErrorDialog.TIMEOUT) {
+            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);
-                }
-                if (res == AppErrorDialog.RESTART) {
-                    mService.removeProcessLocked(r, false, true, "crash");
-                    if (task != null) {
+                        // Wait until cache has been cleared before we restart.
                         try {
-                            mService.startActivityFromRecents(task.taskId,
-                                    ActivityOptions.makeBasic().toBundle());
-                        } catch (IllegalArgumentException e) {
-                            // Hmm, that didn't work, app might have crashed before creating a
-                            // recents entry. Let's see if we have a safe-to-restart intent.
-                            if (task.intent.getCategories().contains(
-                                    Intent.CATEGORY_LAUNCHER)) {
-                                mService.startActivityInPackage(task.mCallingUid,
-                                        task.mCallingPackage, task.intent,
-                                        null, null, null, 0, 0,
-                                        ActivityOptions.makeBasic().toBundle(),
-                                        task.userId, null, null);
-                            }
+                            s.acquire();
+                        } catch (InterruptedException e) {
                         }
                     }
                 }
-                if (res == AppErrorDialog.FORCE_QUIT) {
-                    long orig = Binder.clearCallingIdentity();
-                    try {
-                        // Kill it with fire!
-                        mService.mStackSupervisor.handleAppCrashLocked(r);
-                        if (!r.persistent) {
-                            mService.removeProcessLocked(r, false, false, "crash");
-                            mService.mStackSupervisor.resumeFocusedStackTopActivityLocked();
-                        }
-                    } finally {
-                        Binder.restoreCallingIdentity(orig);
-                    }
-                }
-                if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
-                    appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
-                }
-                if (r != null && !r.isolated && res != AppErrorDialog.RESTART) {
-                    // XXX Can't keep track of crash time for isolated processes,
-                    // since they don't have a persistent identity.
-                    mProcessCrashTimes.put(r.info.processName, r.uid,
-                            SystemClock.uptimeMillis());
-                }
             }
-        } finally {
-            Binder.restoreCallingIdentity(ident);
+            // If there was nothing to reset, just restart;
+            res = AppErrorDialog.RESTART;
+        }
+        synchronized (mService) {
+            if (res == AppErrorDialog.MUTE) {
+                stopReportingCrashesLocked(r);
+            }
+            if (res == AppErrorDialog.RESTART) {
+                mService.removeProcessLocked(r, false, true, "crash");
+                if (task != null) {
+                    try {
+                        mService.startActivityFromRecents(task.taskId,
+                                ActivityOptions.makeBasic().toBundle());
+                    } catch (IllegalArgumentException e) {
+                        // Hmm, that didn't work, app might have crashed before creating a
+                        // recents entry. Let's see if we have a safe-to-restart intent.
+                        if (task.intent.getCategories().contains(
+                                Intent.CATEGORY_LAUNCHER)) {
+                            mService.startActivityInPackage(task.mCallingUid,
+                                    task.mCallingPackage, task.intent,
+                                    null, null, null, 0, 0,
+                                    ActivityOptions.makeBasic().toBundle(),
+                                    task.userId, null, null);
+                        }
+                    }
+                }
+            }
+            if (res == AppErrorDialog.FORCE_QUIT) {
+                long orig = Binder.clearCallingIdentity();
+                try {
+                    // Kill it with fire!
+                    mService.mStackSupervisor.handleAppCrashLocked(r);
+                    if (!r.persistent) {
+                        mService.removeProcessLocked(r, false, false, "crash");
+                        mService.mStackSupervisor.resumeFocusedStackTopActivityLocked();
+                    }
+                } finally {
+                    Binder.restoreCallingIdentity(orig);
+                }
+            }
+            if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
+                appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
+            }
+            if (r != null && !r.isolated && res != AppErrorDialog.RESTART) {
+                // XXX Can't keep track of crash time for isolated processes,
+                // since they don't have a persistent identity.
+                mProcessCrashTimes.put(r.info.processName, r.uid,
+                        SystemClock.uptimeMillis());
+            }
         }
 
         if (appErrorIntent != null) {
@@ -487,6 +459,47 @@
         }
     }
 
+    private boolean handleAppCrashInActivityController(ProcessRecord r,
+                                                       ApplicationErrorReport.CrashInfo crashInfo,
+                                                       String shortMsg, String longMsg,
+                                                       String stackTrace, long timeMillis) {
+        if (mService.mController == null) {
+            return false;
+        }
+
+        try {
+            String name = r != null ? r.processName : null;
+            int pid = r != null ? r.pid : Binder.getCallingPid();
+            int uid = r != null ? r.info.uid : Binder.getCallingUid();
+            if (!mService.mController.appCrashed(name, pid,
+                    shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
+                if ("1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"))
+                        && "Native crash".equals(crashInfo.exceptionClassName)) {
+                    Slog.w(TAG, "Skip killing native crashed app " + name
+                            + "(" + pid + ") during testing");
+                } else {
+                    Slog.w(TAG, "Force-killing crashed app " + name
+                            + " at watcher's request");
+                    if (r != null) {
+                        if (!makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace, null))
+                        {
+                            r.kill("crash", true);
+                        }
+                    } else {
+                        // Huh.
+                        Process.killProcess(pid);
+                        ActivityManagerService.killProcessGroup(uid, pid);
+                    }
+                }
+                return true;
+            }
+        } catch (RemoteException e) {
+            mService.mController = null;
+            Watchdog.getInstance().setActivityController(null);
+        }
+        return false;
+    }
+
     private boolean makeAppCrashingLocked(ProcessRecord app,
             String shortMsg, String longMsg, String stackTrace, AppErrorDialog.Data data) {
         app.crashing = true;
diff --git a/services/core/java/com/android/server/am/BatteryStatsService.java b/services/core/java/com/android/server/am/BatteryStatsService.java
index 2516f5d..d34ec86 100644
--- a/services/core/java/com/android/server/am/BatteryStatsService.java
+++ b/services/core/java/com/android/server/am/BatteryStatsService.java
@@ -79,7 +79,8 @@
  * battery life.
  */
 public final class BatteryStatsService extends IBatteryStats.Stub
-        implements PowerManagerInternal.LowPowerModeListener {
+        implements PowerManagerInternal.LowPowerModeListener,
+        BatteryStatsImpl.PlatformIdleStateCallback {
     static final String TAG = "BatteryStatsService";
 
     /**
@@ -173,6 +174,33 @@
         }
     }
 
+    private native int getPlatformLowPowerStats(ByteBuffer outBuffer);
+    private CharsetDecoder mDecoderStat = StandardCharsets.UTF_8
+                    .newDecoder()
+                    .onMalformedInput(CodingErrorAction.REPLACE)
+                    .onUnmappableCharacter(CodingErrorAction.REPLACE)
+                    .replaceWith("?");
+    private ByteBuffer mUtf8BufferStat = ByteBuffer.allocateDirect(MAX_LOW_POWER_STATS_SIZE);
+    private CharBuffer mUtf16BufferStat = CharBuffer.allocate(MAX_LOW_POWER_STATS_SIZE);
+    private static final int MAX_LOW_POWER_STATS_SIZE = 512;
+
+    @Override
+    public String getPlatformLowPowerStats() {
+        mUtf8BufferStat.clear();
+        mUtf16BufferStat.clear();
+        mDecoderStat.reset();
+        int bytesWritten = getPlatformLowPowerStats(mUtf8BufferStat);
+        if (bytesWritten < 0) {
+            return null;
+        } else if (bytesWritten == 0) {
+            return "Empty";
+        }
+        mUtf8BufferStat.limit(bytesWritten);
+        mDecoderStat.decode(mUtf8BufferStat, mUtf16BufferStat, true);
+        mUtf16BufferStat.flip();
+        return mUtf16BufferStat.toString();
+    }
+
     BatteryStatsService(File systemDir, Handler handler) {
         // Our handler here will be accessing the disk, use a different thread than
         // what the ActivityManagerService gave us (no I/O on that one!).
@@ -182,9 +210,9 @@
         mHandler = new BatteryStatsHandler(thread.getLooper());
 
         // BatteryStatsImpl expects the ActivityManagerService handler, so pass that one through.
-        mStats = new BatteryStatsImpl(systemDir, handler, mHandler);
+        mStats = new BatteryStatsImpl(systemDir, handler, mHandler, this);
     }
-    
+
     public void publish(Context context) {
         mContext = context;
         mStats.setRadioScanningTimeout(mContext.getResources().getInteger(
@@ -946,7 +974,7 @@
 
     @Override
     public void setBatteryState(final int status, final int health, final int plugType,
-                                final int level, final int temp, final int volt) {
+            final int level, final int temp, final int volt, final int chargeCount) {
         enforceCallingPermission();
 
         // BatteryService calls us here and we may update external state. It would be wrong
@@ -959,7 +987,8 @@
                     if (mStats.isOnBattery() == onBattery) {
                         // The battery state has not changed, so we don't need to sync external
                         // stats immediately.
-                        mStats.setBatteryStateLocked(status, health, plugType, level, temp, volt);
+                        mStats.setBatteryStateLocked(status, health, plugType, level, temp, volt,
+                                chargeCount);
                         return;
                     }
                 }
@@ -968,7 +997,8 @@
                 // immediately here, we may not collect the relevant data later.
                 updateExternalStatsSync("battery-state", BatteryStatsImpl.ExternalStatsSync.UPDATE_ALL);
                 synchronized (mStats) {
-                    mStats.setBatteryStateLocked(status, health, plugType, level, temp, volt);
+                    mStats.setBatteryStateLocked(status, health, plugType, level, temp, volt,
+                            chargeCount);
                 }
             }
         });
diff --git a/services/core/java/com/android/server/am/UserController.java b/services/core/java/com/android/server/am/UserController.java
index 75d49c3..bfa5b42 100644
--- a/services/core/java/com/android/server/am/UserController.java
+++ b/services/core/java/com/android/server/am/UserController.java
@@ -220,6 +220,7 @@
 
     private void finishUserBoot(UserState uss, IIntentReceiver resultTo) {
         final int userId = uss.mHandle.getIdentifier();
+        Slog.d(TAG, "Finishing user boot " + userId);
         synchronized (mService) {
             // Bail if we ended up with a stale user
             if (mStartedUsers.get(userId) != uss) return;
@@ -248,7 +249,8 @@
                             + "): attempting unlock because parent is unlocked");
                     maybeUnlockUser(userId);
                 } else {
-                    Slog.d(TAG, "User " + userId + " (parent " + parent.id
+                    String parentId = (parent == null) ? "<null>" : String.valueOf(parent.id);
+                    Slog.d(TAG, "User " + userId + " (parent " + parentId
                             + "): delaying unlock because parent is locked");
                 }
             } else {
@@ -268,7 +270,7 @@
             if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
 
             // Only keep marching forward if user is actually unlocked
-            if (!isUserKeyUnlocked(userId)) return;
+            if (!StorageManager.isUserKeyUnlocked(userId)) return;
 
             if (uss.setState(STATE_RUNNING_LOCKED, STATE_RUNNING_UNLOCKING)) {
                 uss.mUnlockProgress.start();
@@ -279,9 +281,29 @@
                 mUserManager.onBeforeUnlockUser(userId);
                 uss.mUnlockProgress.setProgress(20);
 
-                // Dispatch unlocked to system services
-                mHandler.obtainMessage(SYSTEM_USER_UNLOCK_MSG, userId, 0, uss.mUnlockProgress)
+                // Dispatch unlocked to system services; when fully dispatched,
+                // that calls through to the next "unlocked" phase
+                mHandler.obtainMessage(SYSTEM_USER_UNLOCK_MSG, userId, 0, uss)
                         .sendToTarget();
+            }
+        }
+    }
+
+    /**
+     * Step from {@link UserState#STATE_RUNNING_UNLOCKING} to
+     * {@link UserState#STATE_RUNNING_UNLOCKED}.
+     */
+    void finishUserUnlocked(final UserState uss) {
+        final int userId = uss.mHandle.getIdentifier();
+        synchronized (mService) {
+            // Bail if we ended up with a stale user
+            if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
+
+            // Only keep marching forward if user is actually unlocked
+            if (!StorageManager.isUserKeyUnlocked(userId)) return;
+
+            if (uss.setState(STATE_RUNNING_UNLOCKING, STATE_RUNNING_UNLOCKED)) {
+                uss.mUnlockProgress.finish();
 
                 // Dispatch unlocked to external apps
                 final Intent unlockedIntent = new Intent(Intent.ACTION_USER_UNLOCKED);
@@ -308,47 +330,67 @@
                     }
                 }
 
-                // Send PRE_BOOT broadcasts if fingerprint changed
+                // Send PRE_BOOT broadcasts if user fingerprint changed; we
+                // purposefully block sending BOOT_COMPLETED until after all
+                // PRE_BOOT receivers are finished to avoid ANR'ing apps
                 final UserInfo info = getUserInfo(userId);
                 if (!Objects.equals(info.lastLoggedInFingerprint, Build.FINGERPRINT)) {
                     new PreBootBroadcaster(mService, userId, null) {
                         @Override
                         public void onFinished() {
-                            finishUserUnlocked(uss);
+                            finishUserUnlockedCompleted(uss);
                         }
                     }.sendNext();
                 } else {
-                    finishUserUnlocked(uss);
+                    finishUserUnlockedCompleted(uss);
                 }
             }
         }
     }
 
-    /**
-     * Step from {@link UserState#STATE_RUNNING_UNLOCKING} to
-     * {@link UserState#STATE_RUNNING_UNLOCKED}.
-     */
-    private void finishUserUnlocked(UserState uss) {
+    private void finishUserUnlockedCompleted(UserState uss) {
         final int userId = uss.mHandle.getIdentifier();
         synchronized (mService) {
             // Bail if we ended up with a stale user
             if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
+            final UserInfo userInfo = getUserInfo(userId);
+            if (userInfo == null) {
+                return;
+            }
 
             // Only keep marching forward if user is actually unlocked
-            if (!isUserKeyUnlocked(userId)) return;
+            if (!StorageManager.isUserKeyUnlocked(userId)) return;
 
-            if (uss.setState(STATE_RUNNING_UNLOCKING, STATE_RUNNING_UNLOCKED)) {
-                // Remember that we logged in
-                mUserManager.onUserLoggedIn(userId);
+            // Remember that we logged in
+            mUserManager.onUserLoggedIn(userId);
 
-                final Intent bootIntent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
-                bootIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
-                bootIntent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
-                        | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
-                mService.broadcastIntentLocked(null, null, bootIntent, null, null, 0, null, null,
-                        new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
-                        AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
+            if (!userInfo.isInitialized()) {
+                if (userId != UserHandle.USER_SYSTEM) {
+                    Slog.d(TAG, "Initializing user #" + userId);
+                    Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
+                    intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
+                    mService.broadcastIntentLocked(null, null, intent, null,
+                            new IIntentReceiver.Stub() {
+                                @Override
+                                public void performReceive(Intent intent, int resultCode,
+                                        String data, Bundle extras, boolean ordered,
+                                        boolean sticky, int sendingUser) {
+                                    // Note: performReceive is called with mService lock held
+                                    getUserManager().makeInitialized(userInfo.id);
+                                }
+                            }, 0, null, null, null, AppOpsManager.OP_NONE,
+                            null, true, false, MY_PID, SYSTEM_UID, userId);
+                }
             }
+
+            Slog.d(TAG, "Sending BOOT_COMPLETE user #" + userId);
+            final Intent bootIntent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
+            bootIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
+            bootIntent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
+                    | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
+            mService.broadcastIntentLocked(null, null, bootIntent, null, null, 0, null, null,
+                    new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
+                    AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
         }
     }
 
@@ -458,6 +500,8 @@
                         });
                     }
                 };
+                // Clear broadcast queue for the user to avoid delivering stale broadcasts
+                mService.clearBroadcastQueueForUserLocked(userId);
                 // Kick things off.
                 mService.broadcastIntentLocked(null, null, stoppingIntent,
                         null, stoppingReceiver, 0, null, null,
@@ -655,20 +699,35 @@
         return IMountService.Stub.asInterface(ServiceManager.getService("mount"));
     }
 
-    private boolean isUserKeyUnlocked(int userId) {
-        final IMountService mountService = getMountService();
-        if (mountService != null) {
-            try {
-                return mountService.isUserKeyUnlocked(userId);
-            } catch (RemoteException e) {
-                throw e.rethrowAsRuntimeException();
-            }
-        } else {
-            Slog.w(TAG, "Mount service not published; guessing locked state based on property");
-            return !StorageManager.isFileEncryptedNativeOrEmulated();
-        }
-    }
-
+    /**
+     * Start user, if its not already running.
+     * <p>The user will be brought to the foreground, if {@code foreground} parameter is set.
+     * When starting the user, multiple intents will be broadcast in the following order:</p>
+     * <ul>
+     *     <li>{@link Intent#ACTION_USER_STARTED} - sent to registered receivers of the new user
+     *     <li>{@link Intent#ACTION_USER_BACKGROUND} - sent to registered receivers of the outgoing
+     *     user and all profiles of this user. Sent only if {@code foreground} parameter is true
+     *     <li>{@link Intent#ACTION_USER_FOREGROUND} - sent to registered receivers of the new
+     *     user and all profiles of this user. Sent only if {@code foreground} parameter is true
+     *     <li>{@link Intent#ACTION_USER_SWITCHED} - sent to registered receivers of the new user.
+     *     Sent only if {@code foreground} parameter is true
+     *     <li>{@link Intent#ACTION_USER_STARTING} - ordered broadcast sent to registered receivers
+     *     of the new fg user
+     *     <li>{@link Intent#ACTION_LOCKED_BOOT_COMPLETED} - ordered broadcast sent to receivers of
+     *     the new user
+     *     <li>{@link Intent#ACTION_USER_UNLOCKED} - sent to registered receivers of the new user
+     *     <li>{@link Intent#ACTION_PRE_BOOT_COMPLETED} - ordered broadcast sent to receivers of the
+     *     new user. Sent only when the user is booting after a system update.
+     *     <li>{@link Intent#ACTION_USER_INITIALIZE} - ordered broadcast sent to receivers of the
+     *     new user. Sent only the first time a user is starting.
+     *     <li>{@link Intent#ACTION_BOOT_COMPLETED} - ordered broadcast sent to receivers of the new
+     *     user. Indicates that the user has finished booting.
+     * </ul>
+     *
+     * @param userId ID of the user to start
+     * @param foreground true if user should be brought to the foreground
+     * @return true if the user has been successfully started
+     */
     boolean startUser(final int userId, final boolean foreground) {
         if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
                 != PackageManager.PERMISSION_GRANTED) {
@@ -680,7 +739,7 @@
             throw new SecurityException(msg);
         }
 
-        if (DEBUG_MU) Slog.i(TAG, "starting userid:" + userId + " fore:" + foreground);
+        Slog.i(TAG, "Starting userid:" + userId + " fg:" + foreground);
 
         final long ident = Binder.clearCallingIdentity();
         try {
@@ -790,36 +849,8 @@
                             null, false, false, MY_PID, SYSTEM_UID, userId);
                 }
 
-                if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) {
-                    if (userId != UserHandle.USER_SYSTEM) {
-                        Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
-                        intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
-                        mService.broadcastIntentLocked(null, null, intent, null,
-                                new IIntentReceiver.Stub() {
-                                    @Override
-                                    public void performReceive(Intent intent, int resultCode,
-                                            String data, Bundle extras, boolean ordered,
-                                            boolean sticky, int sendingUser) {
-                                        mHandler.post(new Runnable() {
-                                            @Override
-                                            public void run() {
-                                                onUserInitialized(uss, foreground,
-                                                        oldUserId, userId);
-                                            }
-                                        });
-                                    }
-                                }, 0, null, null, null, AppOpsManager.OP_NONE,
-                                null, true, false, MY_PID, SYSTEM_UID, userId);
-                        uss.initializing = true;
-                    } else {
-                        getUserManager().makeInitialized(userInfo.id);
-                    }
-                }
-
                 if (foreground) {
-                    if (!uss.initializing) {
-                        moveUserToForegroundLocked(uss, oldUserId, userId);
-                    }
+                    moveUserToForegroundLocked(uss, oldUserId, userId);
                 } else {
                     mService.mUserController.finishUserBoot(uss);
                 }
@@ -909,7 +940,7 @@
             }
         }
 
-        if (!isUserKeyUnlocked(userId)) {
+        if (!StorageManager.isUserKeyUnlocked(userId)) {
             final UserInfo userInfo = getUserInfo(userId);
             final IMountService mountService = getMountService();
             try {
@@ -996,8 +1027,8 @@
         }
     }
 
-    void dispatchUserSwitch(final UserState uss, final int oldUserId,
-            final int newUserId) {
+    void dispatchUserSwitch(final UserState uss, final int oldUserId, final int newUserId) {
+        Slog.d(TAG, "Dispatch onUserSwitching oldUser #" + oldUserId + " newUser #" + newUserId);
         final int observerCount = mUserSwitchObservers.beginBroadcast();
         if (observerCount > 0) {
             final IRemoteCallback callback = new IRemoteCallback.Stub() {
@@ -1041,39 +1072,14 @@
     }
 
     void continueUserSwitch(UserState uss, int oldUserId, int newUserId) {
-        completeSwitchAndInitialize(uss, oldUserId, newUserId, false, true);
-    }
-
-    void onUserInitialized(UserState uss, boolean foreground, int oldUserId, int newUserId) {
+        Slog.d(TAG, "Continue user switch oldUser #" + oldUserId + ", newUser #" + newUserId);
         synchronized (mService) {
-            if (foreground) {
-                moveUserToForegroundLocked(uss, oldUserId, newUserId);
-            }
+            mService.mWindowManager.stopFreezingScreen();
         }
-        completeSwitchAndInitialize(uss, oldUserId, newUserId, true, false);
-    }
-
-    void completeSwitchAndInitialize(UserState uss, int oldUserId, int newUserId,
-            boolean clearInitializing, boolean clearSwitching) {
-        boolean unfrozen = false;
-        synchronized (mService) {
-            if (clearInitializing) {
-                uss.initializing = false;
-                getUserManager().makeInitialized(uss.mHandle.getIdentifier());
-            }
-            if (clearSwitching) {
-                uss.switching = false;
-            }
-            if (!uss.switching && !uss.initializing) {
-                mService.mWindowManager.stopFreezingScreen();
-                unfrozen = true;
-            }
-        }
-        if (unfrozen) {
-            mHandler.removeMessages(REPORT_USER_SWITCH_COMPLETE_MSG);
-            mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_COMPLETE_MSG,
-                    newUserId, 0));
-        }
+        uss.switching = false;
+        mHandler.removeMessages(REPORT_USER_SWITCH_COMPLETE_MSG);
+        mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_COMPLETE_MSG,
+                newUserId, 0));
         stopGuestOrEphemeralUserIfBackground();
         stopBackgroundUsersIfEnforced(oldUserId);
     }
@@ -1320,30 +1326,31 @@
         if ((flags & ActivityManager.FLAG_OR_STOPPED) != 0) {
             return true;
         }
-
-        final boolean unlocked;
-        switch (state.state) {
-            case UserState.STATE_STOPPING:
-            case UserState.STATE_SHUTDOWN:
-            default:
-                return false;
-
-            case UserState.STATE_BOOTING:
-            case UserState.STATE_RUNNING_LOCKED:
-                unlocked = false;
-                break;
-
-            case UserState.STATE_RUNNING_UNLOCKING:
-            case UserState.STATE_RUNNING_UNLOCKED:
-                unlocked = true;
-                break;
-        }
-
         if ((flags & ActivityManager.FLAG_AND_LOCKED) != 0) {
-            return !unlocked;
+            switch (state.state) {
+                case UserState.STATE_BOOTING:
+                case UserState.STATE_RUNNING_LOCKED:
+                    return true;
+                default:
+                    return false;
+            }
+        }
+        if ((flags & ActivityManager.FLAG_AND_UNLOCKING_OR_UNLOCKED) != 0) {
+            switch (state.state) {
+                case UserState.STATE_RUNNING_UNLOCKING:
+                case UserState.STATE_RUNNING_UNLOCKED:
+                    return true;
+                default:
+                    return false;
+            }
         }
         if ((flags & ActivityManager.FLAG_AND_UNLOCKED) != 0) {
-            return unlocked;
+            switch (state.state) {
+                case UserState.STATE_RUNNING_UNLOCKED:
+                    return true;
+                default:
+                    return false;
+            }
         }
 
         // One way or another, we're running!
diff --git a/services/core/java/com/android/server/am/UserState.java b/services/core/java/com/android/server/am/UserState.java
index 56abd95..952283e 100644
--- a/services/core/java/com/android/server/am/UserState.java
+++ b/services/core/java/com/android/server/am/UserState.java
@@ -54,7 +54,6 @@
     public int state = STATE_BOOTING;
     public int lastState = STATE_BOOTING;
     public boolean switching;
-    public boolean initializing;
 
     /**
      * The last time that a provider was reported to usage stats as being brought to important
@@ -103,7 +102,6 @@
         pw.print(prefix);
         pw.print("state="); pw.print(stateToString(state));
         if (switching) pw.print(" SWITCHING");
-        if (initializing) pw.print(" INITIALIZING");
         pw.println();
     }
 }
diff --git a/services/core/java/com/android/server/connectivity/MetricsLoggerService.java b/services/core/java/com/android/server/connectivity/MetricsLoggerService.java
index ac5c4ae..5096b35 100644
--- a/services/core/java/com/android/server/connectivity/MetricsLoggerService.java
+++ b/services/core/java/com/android/server/connectivity/MetricsLoggerService.java
@@ -192,11 +192,13 @@
                 }
             }
 
-            if (!mPendingIntents.isEmpty()) {
-                pw.println();
-                pw.println("Pending intents:");
-                for (PendingIntent pi : mPendingIntents) {
-                    pw.println(pi.toString());
+            synchronized (mPendingIntents) {
+                if (!mPendingIntents.isEmpty()) {
+                    pw.println();
+                    pw.println("Pending intents:");
+                    for (PendingIntent pi : mPendingIntents) {
+                        pw.println(pi.toString());
+                    }
                 }
             }
 
@@ -327,9 +329,9 @@
                         result[i++] = e;
                     }
                 }
-            }
 
-            reference.setValue(mLastEventReference);
+                reference.setValue(mLastEventReference);
+            }
 
             return result;
         }
diff --git a/services/core/java/com/android/server/connectivity/NetworkMonitor.java b/services/core/java/com/android/server/connectivity/NetworkMonitor.java
index f7784ac..f4e1424 100644
--- a/services/core/java/com/android/server/connectivity/NetworkMonitor.java
+++ b/services/core/java/com/android/server/connectivity/NetworkMonitor.java
@@ -71,7 +71,11 @@
 import java.io.IOException;
 import java.net.HttpURLConnection;
 import java.net.InetAddress;
+import java.net.MalformedURLException;
+import java.net.UnknownHostException;
 import java.net.URL;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.atomic.AtomicReference;
 import java.util.List;
 import java.util.Random;
 
@@ -228,7 +232,8 @@
     private final AlarmManager mAlarmManager;
     private final NetworkRequest mDefaultRequest;
 
-    private boolean mIsCaptivePortalCheckEnabled = false;
+    private boolean mIsCaptivePortalCheckEnabled;
+    private boolean mUseHttps;
 
     // Set if the user explicitly selected "Do not use this network" in captive portal sign-in app.
     private boolean mUserDoesNotWant = false;
@@ -276,6 +281,8 @@
 
         mIsCaptivePortalCheckEnabled = Settings.Global.getInt(mContext.getContentResolver(),
                 Settings.Global.CAPTIVE_PORTAL_DETECTION_ENABLED, 1) == 1;
+        mUseHttps = Settings.Global.getInt(mContext.getContentResolver(),
+                Settings.Global.CAPTIVE_PORTAL_USE_HTTPS, 1) == 1;
 
         start();
     }
@@ -324,6 +331,21 @@
                     return HANDLED;
                 case CMD_CAPTIVE_PORTAL_APP_FINISHED:
                     log("CaptivePortal App responded with " + message.arg1);
+
+                    // If the user has seen and acted on a captive portal notification, and the
+                    // captive portal app is now closed, disable HTTPS probes. This avoids the
+                    // following pathological situation:
+                    //
+                    // 1. HTTP probe returns a captive portal, HTTPS probe fails or times out.
+                    // 2. User opens the app and logs into the captive portal.
+                    // 3. HTTP starts working, but HTTPS still doesn't work for some other reason -
+                    //    perhaps due to the network blocking HTTPS?
+                    //
+                    // In this case, we'll fail to validate the network even after the app is
+                    // dismissed. There is now no way to use this network, because the app is now
+                    // gone, so the user cannot select "Use this network as is".
+                    mUseHttps = false;
+
                     switch (message.arg1) {
                         case APP_RETURN_DISMISSED:
                             sendMessage(CMD_FORCE_REEVALUATION, 0 /* no UID */, 0);
@@ -424,6 +446,8 @@
      */
     @VisibleForTesting
     public static final class CaptivePortalProbeResult {
+        static final CaptivePortalProbeResult FAILED = new CaptivePortalProbeResult(599, null);
+
         final int mHttpResponseCode; // HTTP response code returned from Internet probe.
         final String mRedirectUrl;   // Redirect destination returned from Internet probe.
 
@@ -431,6 +455,11 @@
             mHttpResponseCode = httpResponseCode;
             mRedirectUrl = redirectUrl;
         }
+
+        boolean isSuccessful() { return mHttpResponseCode == 204; }
+        boolean isPortal() {
+            return !isSuccessful() && mHttpResponseCode >= 200 && mHttpResponseCode <= 399;
+        }
     }
 
     // Being in the EvaluatingState State indicates the Network is being evaluated for internet
@@ -481,6 +510,7 @@
                     //    expensive metered network, or unwanted leaking of the User Agent string.
                     if (!mDefaultRequest.networkCapabilities.satisfiedByNetworkCapabilities(
                             mNetworkAgentInfo.networkCapabilities)) {
+                        validationLog("Network would not satisfy default request, not validating");
                         transitionTo(mValidatedState);
                         return HANDLED;
                     }
@@ -492,10 +522,9 @@
                     // will be unresponsive. isCaptivePortal() could be executed on another Thread
                     // if this is found to cause problems.
                     CaptivePortalProbeResult probeResult = isCaptivePortal();
-                    if (probeResult.mHttpResponseCode == 204) {
+                    if (probeResult.isSuccessful()) {
                         transitionTo(mValidatedState);
-                    } else if (probeResult.mHttpResponseCode >= 200 &&
-                            probeResult.mHttpResponseCode <= 399) {
+                    } else if (probeResult.isPortal()) {
                         mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
                                 NETWORK_TEST_RESULT_INVALID, mNetId, probeResult.mRedirectUrl));
                         transitionTo(mCaptivePortalState);
@@ -659,11 +688,112 @@
         }
     }
 
-    public static String getCaptivePortalServerUrl(Context context) {
+    private static String getCaptivePortalServerUrl(Context context, boolean isHttps) {
         String server = Settings.Global.getString(context.getContentResolver(),
                 Settings.Global.CAPTIVE_PORTAL_SERVER);
         if (server == null) server = DEFAULT_SERVER;
-        return "http://" + server + "/generate_204";
+        return (isHttps ? "https" : "http") + "://" + server + "/generate_204";
+    }
+
+    public static String getCaptivePortalServerUrl(Context context) {
+        return getCaptivePortalServerUrl(context, false);
+    }
+
+    @VisibleForTesting
+    protected CaptivePortalProbeResult isCaptivePortal() {
+        if (!mIsCaptivePortalCheckEnabled) return new CaptivePortalProbeResult(204, null);
+
+        URL pacUrl = null, httpUrl = null, httpsUrl = null;
+
+        // On networks with a PAC instead of fetching a URL that should result in a 204
+        // response, we instead simply fetch the PAC script.  This is done for a few reasons:
+        // 1. At present our PAC code does not yet handle multiple PACs on multiple networks
+        //    until something like https://android-review.googlesource.com/#/c/115180/ lands.
+        //    Network.openConnection() will ignore network-specific PACs and instead fetch
+        //    using NO_PROXY.  If a PAC is in place, the only fetch we know will succeed with
+        //    NO_PROXY is the fetch of the PAC itself.
+        // 2. To proxy the generate_204 fetch through a PAC would require a number of things
+        //    happen before the fetch can commence, namely:
+        //        a) the PAC script be fetched
+        //        b) a PAC script resolver service be fired up and resolve the captive portal
+        //           server.
+        //    Network validation could be delayed until these prerequisities are satisifed or
+        //    could simply be left to race them.  Neither is an optimal solution.
+        // 3. PAC scripts are sometimes used to block or restrict Internet access and may in
+        //    fact block fetching of the generate_204 URL which would lead to false negative
+        //    results for network validation.
+        final ProxyInfo proxyInfo = mNetworkAgentInfo.linkProperties.getHttpProxy();
+        if (proxyInfo != null && !Uri.EMPTY.equals(proxyInfo.getPacFileUrl())) {
+            try {
+                pacUrl = new URL(proxyInfo.getPacFileUrl().toString());
+            } catch (MalformedURLException e) {
+                validationLog("Invalid PAC URL: " + proxyInfo.getPacFileUrl().toString());
+                return CaptivePortalProbeResult.FAILED;
+            }
+        }
+
+        if (pacUrl == null) {
+            try {
+                httpUrl = new URL(getCaptivePortalServerUrl(mContext, false));
+                httpsUrl = new URL(getCaptivePortalServerUrl(mContext, true));
+            } catch (MalformedURLException e) {
+                validationLog("Bad validation URL: " + getCaptivePortalServerUrl(mContext, false));
+                return CaptivePortalProbeResult.FAILED;
+            }
+        }
+
+        long startTime = SystemClock.elapsedRealtime();
+
+        // Pre-resolve the captive portal server host so we can log it.
+        // Only do this if HttpURLConnection is about to, to avoid any potentially
+        // unnecessary resolution.
+        String hostToResolve = null;
+        if (pacUrl != null) {
+            hostToResolve = pacUrl.getHost();
+        } else if (proxyInfo != null) {
+            hostToResolve = proxyInfo.getHost();
+        } else {
+            hostToResolve = httpUrl.getHost();
+        }
+
+        if (!TextUtils.isEmpty(hostToResolve)) {
+            String probeName = ValidationProbeEvent.getProbeName(ValidationProbeEvent.PROBE_DNS);
+            final Stopwatch dnsTimer = new Stopwatch().start();
+            try {
+                InetAddress[] addresses = mNetworkAgentInfo.network.getAllByName(hostToResolve);
+                long dnsLatency = dnsTimer.stop();
+                ValidationProbeEvent.logEvent(mNetId, dnsLatency,
+                        ValidationProbeEvent.PROBE_DNS, ValidationProbeEvent.DNS_SUCCESS);
+                final StringBuffer connectInfo = new StringBuffer(", " + hostToResolve + "=");
+                for (InetAddress address : addresses) {
+                    connectInfo.append(address.getHostAddress());
+                    if (address != addresses[addresses.length-1]) connectInfo.append(",");
+                }
+                validationLog(probeName + " OK " + dnsLatency + "ms" + connectInfo);
+            } catch (UnknownHostException e) {
+                long dnsLatency = dnsTimer.stop();
+                ValidationProbeEvent.logEvent(mNetId, dnsLatency,
+                        ValidationProbeEvent.PROBE_DNS, ValidationProbeEvent.DNS_FAILURE);
+                validationLog(probeName + " FAIL " + dnsLatency + "ms, " + hostToResolve);
+            }
+        }
+
+        CaptivePortalProbeResult result;
+        if (pacUrl != null) {
+            result = sendHttpProbe(pacUrl, ValidationProbeEvent.PROBE_PAC);
+        } else if (mUseHttps) {
+            result = sendParallelHttpProbes(httpsUrl, httpUrl);
+        } else {
+            result = sendHttpProbe(httpUrl, ValidationProbeEvent.PROBE_HTTP);
+        }
+
+        long endTime = SystemClock.elapsedRealtime();
+
+        sendNetworkConditionsBroadcast(true /* response received */,
+                result.isPortal() /* isCaptivePortal */,
+                startTime, endTime);
+
+        return result;
     }
 
     /**
@@ -671,60 +801,14 @@
      * Returns HTTP response code.
      */
     @VisibleForTesting
-    protected CaptivePortalProbeResult isCaptivePortal() {
-        if (!mIsCaptivePortalCheckEnabled) return new CaptivePortalProbeResult(204, null);
-
+    protected CaptivePortalProbeResult sendHttpProbe(URL url, int probeType) {
         HttpURLConnection urlConnection = null;
         int httpResponseCode = 599;
         String redirectUrl = null;
         final Stopwatch probeTimer = new Stopwatch().start();
         try {
-            URL url = new URL(getCaptivePortalServerUrl(mContext));
-            // On networks with a PAC instead of fetching a URL that should result in a 204
-            // response, we instead simply fetch the PAC script.  This is done for a few reasons:
-            // 1. At present our PAC code does not yet handle multiple PACs on multiple networks
-            //    until something like https://android-review.googlesource.com/#/c/115180/ lands.
-            //    Network.openConnection() will ignore network-specific PACs and instead fetch
-            //    using NO_PROXY.  If a PAC is in place, the only fetch we know will succeed with
-            //    NO_PROXY is the fetch of the PAC itself.
-            // 2. To proxy the generate_204 fetch through a PAC would require a number of things
-            //    happen before the fetch can commence, namely:
-            //        a) the PAC script be fetched
-            //        b) a PAC script resolver service be fired up and resolve the captive portal
-            //           server.
-            //    Network validation could be delayed until these prerequisities are satisifed or
-            //    could simply be left to race them.  Neither is an optimal solution.
-            // 3. PAC scripts are sometimes used to block or restrict Internet access and may in
-            //    fact block fetching of the generate_204 URL which would lead to false negative
-            //    results for network validation.
-            boolean fetchPac = false;
-            final ProxyInfo proxyInfo = mNetworkAgentInfo.linkProperties.getHttpProxy();
-            if (proxyInfo != null && !Uri.EMPTY.equals(proxyInfo.getPacFileUrl())) {
-                url = new URL(proxyInfo.getPacFileUrl().toString());
-                fetchPac = true;
-            }
-            final StringBuffer connectInfo = new StringBuffer();
-            String hostToResolve = null;
-            // Only resolve a host if HttpURLConnection is about to, to avoid any potentially
-            // unnecessary resolution.
-            if (proxyInfo == null || fetchPac) {
-                hostToResolve = url.getHost();
-            } else if (proxyInfo != null) {
-                hostToResolve = proxyInfo.getHost();
-            }
-            if (!TextUtils.isEmpty(hostToResolve)) {
-                connectInfo.append(", " + hostToResolve + "=");
-                final InetAddress[] addresses =
-                        mNetworkAgentInfo.network.getAllByName(hostToResolve);
-                for (InetAddress address : addresses) {
-                    connectInfo.append(address.getHostAddress());
-                    if (address != addresses[addresses.length-1]) connectInfo.append(",");
-                }
-            }
-            validationLog("Checking " + url.toString() + " on " +
-                    mNetworkAgentInfo.networkInfo.getExtraInfo() + connectInfo);
             urlConnection = (HttpURLConnection) mNetworkAgentInfo.network.openConnection(url);
-            urlConnection.setInstanceFollowRedirects(fetchPac);
+            urlConnection.setInstanceFollowRedirects(probeType == ValidationProbeEvent.PROBE_PAC);
             urlConnection.setConnectTimeout(SOCKET_TIMEOUT_MS);
             urlConnection.setReadTimeout(SOCKET_TIMEOUT_MS);
             urlConnection.setUseCaches(false);
@@ -738,7 +822,9 @@
             // Time how long it takes to get a response to our request
             long responseTimestamp = SystemClock.elapsedRealtime();
 
-            validationLog("isCaptivePortal: ret=" + httpResponseCode +
+            validationLog(ValidationProbeEvent.getProbeName(probeType) + " " + url +
+                    " time=" + (responseTimestamp - requestTimestamp) + "ms" +
+                    " ret=" + httpResponseCode +
                     " headers=" + urlConnection.getHeaderFields());
             // NOTE: We may want to consider an "HTTP/1.0 204" response to be a captive
             // portal.  The only example of this seen so far was a captive portal.  For
@@ -756,14 +842,10 @@
                 httpResponseCode = 204;
             }
 
-            if (httpResponseCode == 200 && fetchPac) {
+            if (httpResponseCode == 200 && probeType == ValidationProbeEvent.PROBE_PAC) {
                 validationLog("PAC fetch 200 response interpreted as 204 response.");
                 httpResponseCode = 204;
             }
-
-            sendNetworkConditionsBroadcast(true /* response received */,
-                    httpResponseCode != 204 /* isCaptivePortal */,
-                    requestTimestamp, responseTimestamp);
         } catch (IOException e) {
             validationLog("Probably not a portal: exception " + e);
             if (httpResponseCode == 599) {
@@ -774,11 +856,68 @@
                 urlConnection.disconnect();
             }
         }
-        final int probeType = ValidationProbeEvent.PROBE_HTTP;
         ValidationProbeEvent.logEvent(mNetId, probeTimer.stop(), probeType, httpResponseCode);
         return new CaptivePortalProbeResult(httpResponseCode, redirectUrl);
     }
 
+    private CaptivePortalProbeResult sendParallelHttpProbes(URL httpsUrl, URL httpUrl) {
+        // Number of probes to wait for. We might wait for all of them, but we might also return if
+        // only one of them has replied. For example, we immediately return if the HTTP probe finds
+        // a captive portal, even if the HTTPS probe is timing out.
+        final CountDownLatch latch = new CountDownLatch(2);
+
+        // Which probe result we're going to use. This doesn't need to be atomic, but it does need
+        // to be final because otherwise we can't set it from the ProbeThreads.
+        final AtomicReference<CaptivePortalProbeResult> finalResult = new AtomicReference<>();
+
+        final class ProbeThread extends Thread {
+            private final boolean mIsHttps;
+            private volatile CaptivePortalProbeResult mResult;
+
+            public ProbeThread(boolean isHttps) {
+                mIsHttps = isHttps;
+            }
+
+            public CaptivePortalProbeResult getResult() {
+                return mResult;
+            }
+
+            @Override
+            public void run() {
+                if (mIsHttps) {
+                    mResult = sendHttpProbe(httpsUrl, ValidationProbeEvent.PROBE_HTTPS);
+                } else {
+                    mResult = sendHttpProbe(httpUrl, ValidationProbeEvent.PROBE_HTTP);
+                }
+                if ((mIsHttps && mResult.isSuccessful()) || (!mIsHttps && mResult.isPortal())) {
+                    // HTTPS succeeded, or HTTP found a portal. Don't wait for the other probe.
+                    finalResult.compareAndSet(null, mResult);
+                    latch.countDown();
+                }
+                // Signal that one probe has completed. If we've already made a decision, or if this
+                // is the second probe, the latch will be at zero and we'll return a result.
+                latch.countDown();
+            }
+        }
+
+        ProbeThread httpsProbe = new ProbeThread(true);
+        ProbeThread httpProbe = new ProbeThread(false);
+        httpsProbe.start();
+        httpProbe.start();
+
+        try {
+            latch.await();
+        } catch (InterruptedException e) {
+            validationLog("Error: probe wait interrupted!");
+            return CaptivePortalProbeResult.FAILED;
+        }
+
+        // If there was no deciding probe, that means that both probes completed. Return HTTPS.
+        finalResult.compareAndSet(null, httpsProbe.getResult());
+
+        return finalResult.get();
+    }
+
     /**
      * @param responseReceived - whether or not we received a valid HTTP response to our request.
      * If false, isCaptivePortal and responseTimestampMs are ignored
diff --git a/services/core/java/com/android/server/connectivity/Tethering.java b/services/core/java/com/android/server/connectivity/Tethering.java
index c2022d5..1012f9a 100644
--- a/services/core/java/com/android/server/connectivity/Tethering.java
+++ b/services/core/java/com/android/server/connectivity/Tethering.java
@@ -610,6 +610,13 @@
         return ConnectivityManager.TETHER_ERROR_NO_ERROR;
     }
 
+    public void untetherAll() {
+        if (DBG) Log.d(TAG, "Untethering " + mIfaces);
+        for (String iface : mIfaces.keySet()) {
+            untether(iface);
+        }
+    }
+
     public int getLastTetherError(String iface) {
         TetherInterfaceSM sm = null;
         synchronized (mPublicSync) {
diff --git a/services/core/java/com/android/server/content/ContentService.java b/services/core/java/com/android/server/content/ContentService.java
index 03eb019..2103cce 100644
--- a/services/core/java/com/android/server/content/ContentService.java
+++ b/services/core/java/com/android/server/content/ContentService.java
@@ -352,6 +352,10 @@
         if (DEBUG) Slog.d(TAG, "Notifying update of " + uri + " for user " + userHandle
                 + " from observer " + observer + ", flags " + Integer.toHexString(flags));
 
+        if (uri == null) {
+            throw new NullPointerException("Uri must not be null");
+        }
+
         final int uid = Binder.getCallingUid();
         final int pid = Binder.getCallingPid();
         final int callingUserHandle = UserHandle.getCallingUserId();
diff --git a/services/core/java/com/android/server/content/SyncManager.java b/services/core/java/com/android/server/content/SyncManager.java
index fcf2162..493fc4a 100644
--- a/services/core/java/com/android/server/content/SyncManager.java
+++ b/services/core/java/com/android/server/content/SyncManager.java
@@ -396,8 +396,8 @@
                 onUserRemoved(userId);
             } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
                 onUserUnlocked(userId);
-            } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
-                onUserStopping(userId);
+            } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
+                onUserStopped(userId);
             }
         }
     };
@@ -550,7 +550,7 @@
         intentFilter = new IntentFilter();
         intentFilter.addAction(Intent.ACTION_USER_REMOVED);
         intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
-        intentFilter.addAction(Intent.ACTION_USER_STOPPING);
+        intentFilter.addAction(Intent.ACTION_USER_STOPPED);
         mContext.registerReceiverAsUser(
                 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
 
@@ -1422,7 +1422,7 @@
         }
     }
 
-    private void onUserStopping(int userId) {
+    private void onUserStopped(int userId) {
         updateRunningAccounts(null /* Don't sync any target */);
 
         cancelActiveSync(
diff --git a/services/core/java/com/android/server/fingerprint/EnrollClient.java b/services/core/java/com/android/server/fingerprint/EnrollClient.java
index b636ce5..6a533c9 100644
--- a/services/core/java/com/android/server/fingerprint/EnrollClient.java
+++ b/services/core/java/com/android/server/fingerprint/EnrollClient.java
@@ -51,7 +51,8 @@
                     " getGroupId():" + getGroupId());
         }
         if (remaining == 0) {
-            FingerprintUtils.getInstance().addFingerprintForUser(getContext(), fingerId, groupId);
+            FingerprintUtils.getInstance().addFingerprintForUser(getContext(), fingerId,
+                    getTargetUserId());
         }
         return sendEnrollResult(fingerId, groupId, remaining);
     }
diff --git a/services/core/java/com/android/server/fingerprint/FingerprintService.java b/services/core/java/com/android/server/fingerprint/FingerprintService.java
index 9a2db8e..ae01635 100644
--- a/services/core/java/com/android/server/fingerprint/FingerprintService.java
+++ b/services/core/java/com/android/server/fingerprint/FingerprintService.java
@@ -540,13 +540,15 @@
         startClient(client, true /* initiatedByClient */);
     }
 
-    private void startEnrollment(IBinder token, byte [] cryptoToken, int callingUserId, int groupId,
+    private void startEnrollment(IBinder token, byte [] cryptoToken, int userId,
             IFingerprintServiceReceiver receiver, int flags, boolean restricted,
             String opPackageName) {
-        updateActiveGroup(groupId, opPackageName);
+        updateActiveGroup(userId, opPackageName);
+
+        final int groupId = userId; // default group for fingerprint enrollment
 
         EnrollClient client = new EnrollClient(getContext(), mHalDeviceId, token, receiver,
-                callingUserId, groupId, cryptoToken, restricted, opPackageName) {
+                userId, groupId, cryptoToken, restricted, opPackageName) {
 
             @Override
             public IFingerprintDaemon getFingerprintDaemon() {
@@ -680,15 +682,14 @@
         }
 
         @Override // Binder call
-        public void enroll(final IBinder token, final byte[] cryptoToken, final int groupId,
+        public void enroll(final IBinder token, final byte[] cryptoToken, final int userId,
                 final IFingerprintServiceReceiver receiver, final int flags,
                 final String opPackageName) {
             checkPermission(MANAGE_FINGERPRINT);
             final int limit =  mContext.getResources().getInteger(
                     com.android.internal.R.integer.config_fingerprintMaxTemplatesPerUser);
-            final int callingUserId = UserHandle.getCallingUserId();
-            final int enrolled = FingerprintService.this.
-                    getEnrolledFingerprints(callingUserId).size();
+
+            final int enrolled = FingerprintService.this.getEnrolledFingerprints(userId).size();
             if (enrolled >= limit) {
                 Slog.w(TAG, "Too many fingerprints registered");
                 return;
@@ -696,7 +697,7 @@
 
             // Group ID is arbitrarily set to parent profile user ID. It just represents
             // the default fingerprints for the user.
-            if (!isCurrentUserOrProfile(groupId)) {
+            if (!isCurrentUserOrProfile(userId)) {
                 return;
             }
 
@@ -704,7 +705,7 @@
             mHandler.post(new Runnable() {
                 @Override
                 public void run() {
-                    startEnrollment(token, cryptoToken, callingUserId, groupId, receiver, flags,
+                    startEnrollment(token, cryptoToken, userId, receiver, flags,
                             restricted, opPackageName);
                 }
             });
diff --git a/services/core/java/com/android/server/job/JobStore.java b/services/core/java/com/android/server/job/JobStore.java
index 5ad988a..1f7d312 100644
--- a/services/core/java/com/android/server/job/JobStore.java
+++ b/services/core/java/com/android/server/job/JobStore.java
@@ -333,6 +333,7 @@
             out.attribute(null, "sourceUserId", String.valueOf(jobStatus.getSourceUserId()));
             out.attribute(null, "uid", Integer.toString(jobStatus.getUid()));
             out.attribute(null, "priority", String.valueOf(jobStatus.getPriority()));
+            out.attribute(null, "flags", String.valueOf(jobStatus.getFlags()));
         }
 
         private void writeBundleToXml(PersistableBundle extras, XmlSerializer out)
@@ -543,6 +544,10 @@
                 if (val != null) {
                     jobBuilder.setPriority(Integer.parseInt(val));
                 }
+                val = parser.getAttributeValue(null, "flags");
+                if (val != null) {
+                    jobBuilder.setFlags(Integer.parseInt(val));
+                }
                 val = parser.getAttributeValue(null, "sourceUserId");
                 sourceUserId = val == null ? -1 : Integer.parseInt(val);
             } catch (NumberFormatException e) {
diff --git a/services/core/java/com/android/server/job/controllers/ConnectivityController.java b/services/core/java/com/android/server/job/controllers/ConnectivityController.java
index 88cf322..f5aac08 100644
--- a/services/core/java/com/android/server/job/controllers/ConnectivityController.java
+++ b/services/core/java/com/android/server/job/controllers/ConnectivityController.java
@@ -16,6 +16,7 @@
 
 package com.android.server.job.controllers;
 
+import android.app.job.JobInfo;
 import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.Intent;
@@ -97,7 +98,9 @@
     }
 
     private boolean updateConstraintsSatisfied(JobStatus jobStatus) {
-        final NetworkInfo info = mConnManager.getActiveNetworkInfoForUid(jobStatus.getSourceUid());
+        final boolean ignoreBlocked = (jobStatus.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0;
+        final NetworkInfo info = mConnManager.getActiveNetworkInfoForUid(jobStatus.getSourceUid(),
+                ignoreBlocked);
         final boolean connected = (info != null) && info.isConnected();
         final boolean unmetered = connected && !info.isMetered();
         final boolean notRoaming = connected && !info.isRoaming();
diff --git a/services/core/java/com/android/server/job/controllers/JobStatus.java b/services/core/java/com/android/server/job/controllers/JobStatus.java
index 590d075..19bede9 100644
--- a/services/core/java/com/android/server/job/controllers/JobStatus.java
+++ b/services/core/java/com/android/server/job/controllers/JobStatus.java
@@ -297,6 +297,10 @@
         return job.getPriority();
     }
 
+    public int getFlags() {
+        return job.getFlags();
+    }
+
     public boolean hasConnectivityConstraint() {
         return (requiredConstraints&CONSTRAINT_CONNECTIVITY) != 0;
     }
@@ -416,12 +420,12 @@
         // satisfied).
         // AppNotIdle implicit constraint must be satisfied
         // DeviceNotDozing implicit constraint must be satisfied
-        return (isConstraintsSatisfied()
-                || (!job.isPeriodic()
-                && hasDeadlineConstraint() && (satisfiedConstraints&CONSTRAINT_DEADLINE) != 0)
-                )
-                && (satisfiedConstraints & CONSTRAINT_APP_NOT_IDLE) != 0
-                && (satisfiedConstraints & CONSTRAINT_DEVICE_NOT_DOZING) != 0;
+        final boolean deadlineSatisfied = (!job.isPeriodic() && hasDeadlineConstraint()
+                && (satisfiedConstraints & CONSTRAINT_DEADLINE) != 0);
+        final boolean notIdle = (satisfiedConstraints & CONSTRAINT_APP_NOT_IDLE) != 0;
+        final boolean notDozing = (satisfiedConstraints & CONSTRAINT_DEVICE_NOT_DOZING) != 0
+                || (job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0;
+        return (isConstraintsSatisfied() || deadlineSatisfied) && notIdle && notDozing;
     }
 
     static final int CONSTRAINTS_OF_INTEREST =
@@ -561,6 +565,10 @@
             if (job.getPriority() != 0) {
                 pw.print(prefix); pw.print("  Priority: "); pw.println(job.getPriority());
             }
+            if (job.getFlags() != 0) {
+                pw.print(prefix); pw.print("  Flags: ");
+                pw.println(Integer.toHexString(job.getFlags()));
+            }
             pw.print(prefix); pw.print("  Requires: charging=");
             pw.print(job.isRequireCharging()); pw.print(" deviceIdle=");
             pw.println(job.isRequireDeviceIdle());
@@ -613,6 +621,9 @@
             pw.print(prefix); pw.print("Satisfied constraints:");
             dumpConstraints(pw, satisfiedConstraints);
             pw.println();
+            pw.print(prefix); pw.print("Unsatisfied constraints:");
+            dumpConstraints(pw, (requiredConstraints & ~satisfiedConstraints));
+            pw.println();
         }
         if (changedAuthorities != null) {
             pw.print(prefix); pw.println("Changed authorities:");
diff --git a/services/core/java/com/android/server/net/NetworkPolicyManagerService.java b/services/core/java/com/android/server/net/NetworkPolicyManagerService.java
index 43f47fa..50d9368 100644
--- a/services/core/java/com/android/server/net/NetworkPolicyManagerService.java
+++ b/services/core/java/com/android/server/net/NetworkPolicyManagerService.java
@@ -48,7 +48,6 @@
 import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
 import static android.net.NetworkPolicyManager.POLICY_NONE;
 import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
-import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
 import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
 import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
 import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
@@ -349,6 +348,9 @@
     /** Foreground at UID granularity. */
     final SparseIntArray mUidState = new SparseIntArray();
 
+    /** Higher priority listener before general event dispatch */
+    private INetworkPolicyListener mConnectivityListener;
+
     private final RemoteCallbackList<INetworkPolicyListener>
             mListeners = new RemoteCallbackList<>();
 
@@ -465,7 +467,7 @@
                 continue;
             }
             for (int j = 0; j < numberUsers; j++) {
-                final UserInfo user = users.get(i);
+                final UserInfo user = users.get(j);
                 final int uid = UserHandle.getUid(user.id, app.uid);
                 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
                 if (LOGD) Slog.d(TAG, "revoked whistelist status for uid " + uid + ": "
@@ -1391,6 +1393,7 @@
                 final String tag = in.getName();
                 if (type == START_TAG) {
                     if (TAG_POLICY_LIST.equals(tag)) {
+                        final boolean oldValue = mRestrictBackground;
                         version = readIntAttribute(in, ATTR_VERSION);
                         if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
                             mRestrictBackground = readBooleanAttribute(
@@ -1398,6 +1401,12 @@
                         } else {
                             mRestrictBackground = false;
                         }
+                        if (mRestrictBackground != oldValue) {
+                            // Some early services may have read the default value,
+                            // so notify them that it's changed
+                            mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
+                                    mRestrictBackground ? 1 : 0, 0).sendToTarget();
+                        }
 
                     } else if (TAG_NETWORK_POLICY.equals(tag)) {
                         final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
@@ -1766,20 +1775,25 @@
     }
 
     @Override
+    public void setConnectivityListener(INetworkPolicyListener listener) {
+        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
+        if (mConnectivityListener != null) {
+            throw new IllegalStateException("Connectivity listener already registered");
+        }
+        mConnectivityListener = listener;
+    }
+
+    @Override
     public void registerListener(INetworkPolicyListener listener) {
         // TODO: create permission for observing network policy
         mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
-
         mListeners.register(listener);
-
-        // TODO: consider dispatching existing rules to new listeners
     }
 
     @Override
     public void unregisterListener(INetworkPolicyListener listener) {
         // TODO: create permission for observing network policy
         mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
-
         mListeners.unregister(listener);
     }
 
@@ -1899,6 +1913,18 @@
     }
 
     @Override
+    public void onTetheringChanged(String iface, boolean tethering) {
+        // No need to enforce permission because setRestrictBackground() will do it.
+        if (LOGD) Log.d(TAG, "onTetherStateChanged(" + iface + ", " + tethering + ")");
+        synchronized (mRulesLock) {
+            if (mRestrictBackground && tethering) {
+                Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
+                setRestrictBackground(false);
+            }
+        }
+    }
+
+    @Override
     public void setRestrictBackground(boolean restrictBackground) {
         mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
         final long token = Binder.clearCallingIdentity();
@@ -2742,8 +2768,8 @@
         final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
         final boolean isWhitelisted = mRestrictBackgroundWhitelistUids.get(uid);
 
-        int newRule = RULE_ALLOW_ALL;
-        final int oldRule = mUidRules.get(uid);
+        int newRule = RULE_UNKNOWN;
+        final int oldRule = mUidRules.get(uid, RULE_UNKNOWN);
 
         // First step: define the new rule based on user restrictions and foreground state.
         if (isForeground) {
@@ -2765,8 +2791,7 @@
                     + ", oldRule: " + ruleToString(oldRule));
         }
 
-
-        if (newRule == RULE_ALLOW_ALL) {
+        if (newRule == RULE_UNKNOWN) {
             mUidRules.delete(uid);
         } else {
             mUidRules.put(uid, newRule);
@@ -2846,6 +2871,45 @@
         }
     }
 
+    private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
+        if (listener != null) {
+            try {
+                listener.onUidRulesChanged(uid, uidRules);
+            } catch (RemoteException ignored) {
+            }
+        }
+    }
+
+    private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
+            String[] meteredIfaces) {
+        if (listener != null) {
+            try {
+                listener.onMeteredIfacesChanged(meteredIfaces);
+            } catch (RemoteException ignored) {
+            }
+        }
+    }
+
+    private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
+            boolean restrictBackground) {
+        if (listener != null) {
+            try {
+                listener.onRestrictBackgroundChanged(restrictBackground);
+            } catch (RemoteException ignored) {
+            }
+        }
+    }
+
+    private void dispatchRestrictBackgroundWhitelistChanged(INetworkPolicyListener listener,
+            int uid, boolean whitelisted) {
+        if (listener != null) {
+            try {
+                listener.onRestrictBackgroundWhitelistChanged(uid, whitelisted);
+            } catch (RemoteException ignored) {
+            }
+        }
+    }
+
     private Handler.Callback mHandlerCallback = new Handler.Callback() {
         @Override
         public boolean handleMessage(Message msg) {
@@ -2853,30 +2917,22 @@
                 case MSG_RULES_CHANGED: {
                     final int uid = msg.arg1;
                     final int uidRules = msg.arg2;
+                    dispatchUidRulesChanged(mConnectivityListener, uid, uidRules);
                     final int length = mListeners.beginBroadcast();
                     for (int i = 0; i < length; i++) {
                         final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
-                        if (listener != null) {
-                            try {
-                                listener.onUidRulesChanged(uid, uidRules);
-                            } catch (RemoteException e) {
-                            }
-                        }
+                        dispatchUidRulesChanged(listener, uid, uidRules);
                     }
                     mListeners.finishBroadcast();
                     return true;
                 }
                 case MSG_METERED_IFACES_CHANGED: {
                     final String[] meteredIfaces = (String[]) msg.obj;
+                    dispatchMeteredIfacesChanged(mConnectivityListener, meteredIfaces);
                     final int length = mListeners.beginBroadcast();
                     for (int i = 0; i < length; i++) {
                         final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
-                        if (listener != null) {
-                            try {
-                                listener.onMeteredIfacesChanged(meteredIfaces);
-                            } catch (RemoteException e) {
-                            }
-                        }
+                        dispatchMeteredIfacesChanged(listener, meteredIfaces);
                     }
                     mListeners.finishBroadcast();
                     return true;
@@ -2903,15 +2959,11 @@
                 }
                 case MSG_RESTRICT_BACKGROUND_CHANGED: {
                     final boolean restrictBackground = msg.arg1 != 0;
+                    dispatchRestrictBackgroundChanged(mConnectivityListener, restrictBackground);
                     final int length = mListeners.beginBroadcast();
                     for (int i = 0; i < length; i++) {
                         final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
-                        if (listener != null) {
-                            try {
-                                listener.onRestrictBackgroundChanged(restrictBackground);
-                            } catch (RemoteException e) {
-                            }
-                        }
+                        dispatchRestrictBackgroundChanged(listener, restrictBackground);
                     }
                     mListeners.finishBroadcast();
                     final Intent intent =
@@ -2935,18 +2987,16 @@
                     final boolean changed = msg.arg2 == 1;
                     final Boolean whitelisted = (Boolean) msg.obj;
 
+                    // First notify internal listeners...
                     if (whitelisted != null) {
+                        final boolean whitelistedBool = whitelisted.booleanValue();
+                        dispatchRestrictBackgroundWhitelistChanged(mConnectivityListener, uid,
+                                whitelistedBool);
                         final int length = mListeners.beginBroadcast();
                         for (int i = 0; i < length; i++) {
-                            // First notify internal listeners...
                             final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
-                            if (listener != null) {
-                                try {
-                                    listener.onRestrictBackgroundWhitelistChanged(uid,
-                                            whitelisted.booleanValue());
-                                } catch (RemoteException e) {
-                                }
-                            }
+                            dispatchRestrictBackgroundWhitelistChanged(listener, uid,
+                                    whitelistedBool);
                         }
                         mListeners.finishBroadcast();
                     }
diff --git a/services/core/java/com/android/server/pm/OtaDexoptService.java b/services/core/java/com/android/server/pm/OtaDexoptService.java
index 50b8670..649a27c 100644
--- a/services/core/java/com/android/server/pm/OtaDexoptService.java
+++ b/services/core/java/com/android/server/pm/OtaDexoptService.java
@@ -22,9 +22,7 @@
 import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
 
 import android.content.Context;
-import android.content.pm.ApplicationInfo;
 import android.content.pm.IOtaDexopt;
-import android.content.pm.PackageManager;
 import android.content.pm.PackageParser;
 import android.os.Environment;
 import android.os.RemoteException;
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index 397e1ce..61e36d9 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -439,6 +439,8 @@
      */
     private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
 
+    static final String PLATFORM_PACKAGE_NAME = "android";
+
     static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
 
     static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
@@ -500,8 +502,8 @@
 
     public static final int REASON_LAST = REASON_FORCED_DEXOPT;
 
-    // Special String to skip shared libraries check during compilation.
-    private static final String SPECIAL_SHARED_LIBRARY = "&";
+    /** Special library name that skips shared libraries check during compilation. */
+    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
 
     final ServiceThread mHandlerThread;
 
@@ -1572,6 +1574,7 @@
                     if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
 
                     PostInstallData data = mRunningInstalls.get(msg.arg1);
+                    final boolean didRestore = (msg.arg2 != 0);
                     mRunningInstalls.delete(msg.arg1);
 
                     if (data != null) {
@@ -1586,7 +1589,8 @@
 
                         // Handle the parent package
                         handlePackagePostInstall(parentRes, grantPermissions, killApp,
-                                grantedPermissions, args.observer);
+                                grantedPermissions, didRestore, args.installerPackageName,
+                                args.observer);
 
                         // Handle the child packages
                         final int childCount = (parentRes.addedChildPackages != null)
@@ -1594,7 +1598,8 @@
                         for (int i = 0; i < childCount; i++) {
                             PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
                             handlePackagePostInstall(childRes, grantPermissions, killApp,
-                                    grantedPermissions, args.observer);
+                                    grantedPermissions, false, args.installerPackageName,
+                                    args.observer);
                         }
 
                         // Log tracing if needed
@@ -1790,6 +1795,7 @@
 
     private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
             boolean killApp, String[] grantedPermissions,
+            boolean launchedForRestore, String installerPackage,
             IPackageInstallObserver2 installObserver) {
         if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
             // Send the removed broadcasts
@@ -1874,6 +1880,14 @@
                             null /*package*/, null /*extras*/, 0 /*flags*/,
                             packageName /*targetPackage*/,
                             null /*finishedReceiver*/, updateUsers);
+                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
+                    // First-install and we did a restore, so we're responsible for the
+                    // first-launch broadcast.
+                    if (DEBUG_BACKUP) {
+                        Slog.i(TAG, "Post-restore of " + packageName
+                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
+                    }
+                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
                 }
 
                 // Send broadcast package appeared if forward locked/external for all users
@@ -2338,7 +2352,7 @@
                                         dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
                                         getCompilerFilterForReason(REASON_SHARED_APK),
                                         StorageManager.UUID_PRIVATE_INTERNAL,
-                                        SPECIAL_SHARED_LIBRARY);
+                                        SKIP_SHARED_LIBRARY_CHECK);
                             }
                         } catch (FileNotFoundException e) {
                             Slog.w(TAG, "Library not found: " + lib);
@@ -2664,14 +2678,8 @@
             // Prepare storage for system user really early during boot,
             // since core system apps like SettingsProvider and SystemUI
             // can't wait for user to start
-            final int storageFlags;
-            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
-                storageFlags = StorageManager.FLAG_STORAGE_DE;
-            } else {
-                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
-            }
             reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
-                    storageFlags);
+                    StorageManager.FLAG_STORAGE_DE);
 
             // If this is first boot after an OTA, and a normal boot, then
             // we need to clear code cache directories.
@@ -3102,7 +3110,7 @@
 
     @Override
     public void checkPackageStartable(String packageName, int userId) {
-        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
+        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
 
         synchronized (mPackages) {
             final PackageSetting ps = mSettings.mPackages.get(packageName);
@@ -3453,30 +3461,6 @@
     }
 
     /**
-     * Return if the user key is currently unlocked.
-     */
-    private boolean isUserKeyUnlocked(int userId) {
-        if (StorageManager.isFileEncryptedNativeOrEmulated()) {
-            final IMountService mount = IMountService.Stub
-                    .asInterface(ServiceManager.getService("mount"));
-            if (mount == null) {
-                Slog.w(TAG, "Early during boot, assuming locked");
-                return false;
-            }
-            final long token = Binder.clearCallingIdentity();
-            try {
-                return mount.isUserKeyUnlocked(userId);
-            } catch (RemoteException e) {
-                throw e.rethrowAsRuntimeException();
-            } finally {
-                Binder.restoreCallingIdentity(token);
-            }
-        } else {
-            return true;
-        }
-    }
-
-    /**
      * Update given flags based on encryption status of current user.
      */
     private int updateFlags(int flags, int userId) {
@@ -3487,7 +3471,7 @@
             // give them what they want
         } else {
             // Caller expressed no opinion, so match based on user state
-            if (isUserKeyUnlocked(userId)) {
+            if (StorageManager.isUserKeyUnlocked(userId)) {
                 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
             } else {
                 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
@@ -9745,7 +9729,9 @@
                 switch (grant) {
                     case GRANT_INSTALL: {
                         // Revoke this as runtime permission to handle the case of
-                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
+                        // a runtime permission being downgraded to an install one.
+                        // Also in permission review mode we keep dangerous permissions
+                        // for legacy apps
                         for (int userId : UserManagerService.getInstance().getUserIds()) {
                             if (origPermissions.getRuntimePermissionState(
                                     bp.name, userId) != null) {
@@ -9793,10 +9779,21 @@
                                     && !appSupportsRuntimePermissions) {
                                 // For legacy apps that need a permission review, every new
                                 // runtime permission is granted but it is pending a review.
-                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
-                                    permissionsState.grantRuntimePermission(bp, userId);
-                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
-                                    // We changed the permission and flags, hence have to write.
+                                // We also need to review only platform defined runtime
+                                // permissions as these are the only ones the platform knows
+                                // how to disable the API to simulate revocation as legacy
+                                // apps don't expect to run with revoked permissions.
+                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
+                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
+                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
+                                        // We changed the flags, hence have to write.
+                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
+                                                changedRuntimePermissionUserIds, userId);
+                                    }
+                                }
+                                if (permissionsState.grantRuntimePermission(bp, userId)
+                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
+                                    // We changed the permission, hence have to write.
                                     changedRuntimePermissionUserIds = ArrayUtils.appendInt(
                                             changedRuntimePermissionUserIds, userId);
                                 }
@@ -11725,7 +11722,7 @@
     }
 
     @Override
-    public void finishPackageInstall(int token) {
+    public void finishPackageInstall(int token, boolean didLaunch) {
         enforceSystemOrRoot("Only the system is allowed to finish installs");
 
         if (DEBUG_INSTALL) {
@@ -11733,7 +11730,7 @@
         }
         Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
 
-        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
+        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
         mHandler.sendMessage(msg);
     }
 
@@ -12062,6 +12059,54 @@
         });
     }
 
+    /**
+     * Callback from PackageSettings whenever an app is first transitioned out of the
+     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
+     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
+     * here whether the app is the target of an ongoing install, and only send the
+     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
+     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
+     * handling.
+     */
+    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
+        // Serialize this with the rest of the install-process message chain.  In the
+        // restore-at-install case, this Runnable will necessarily run before the
+        // POST_INSTALL message is processed, so the contents of mRunningInstalls
+        // are coherent.  In the non-restore case, the app has already completed install
+        // and been launched through some other means, so it is not in a problematic
+        // state for observers to see the FIRST_LAUNCH signal.
+        mHandler.post(new Runnable() {
+            @Override
+            public void run() {
+                for (int i = 0; i < mRunningInstalls.size(); i++) {
+                    final PostInstallData data = mRunningInstalls.valueAt(i);
+                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
+                        // right package; but is it for the right user?
+                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
+                            if (userId == data.res.newUsers[uIndex]) {
+                                if (DEBUG_BACKUP) {
+                                    Slog.i(TAG, "Package " + pkgName
+                                            + " being restored so deferring FIRST_LAUNCH");
+                                }
+                                return;
+                            }
+                        }
+                    }
+                }
+                // didn't find it, so not being restored
+                if (DEBUG_BACKUP) {
+                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
+                }
+                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
+            }
+        });
+    }
+
+    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
+        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
+                installerPkg, null, userIds);
+    }
+
     private abstract class HandlerParams {
         private static final int MAX_RETRIES = 4;
 
@@ -16081,7 +16126,7 @@
 
         final UserManager um = mContext.getSystemService(UserManager.class);
         final int flags;
-        if (um.isUserUnlocked(userId)) {
+        if (um.isUserUnlockingOrUnlocked(userId)) {
             flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
         } else if (um.isUserRunning(userId)) {
             flags = StorageManager.FLAG_STORAGE_DE;
@@ -18765,7 +18810,7 @@
         final UserManager um = mContext.getSystemService(UserManager.class);
         for (UserInfo user : um.getUsers()) {
             final int flags;
-            if (um.isUserUnlocked(user.id)) {
+            if (um.isUserUnlockingOrUnlocked(user.id)) {
                 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
             } else if (um.isUserRunning(user.id)) {
                 flags = StorageManager.FLAG_STORAGE_DE;
@@ -19079,7 +19124,7 @@
         // First look for stale data that doesn't belong, and check if things
         // have changed since we did our last restorecon
         if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
-            if (!isUserKeyUnlocked(userId)) {
+            if (!StorageManager.isUserKeyUnlocked(userId)) {
                 throw new RuntimeException(
                         "Yikes, someone asked us to reconcile CE storage while " + userId
                                 + " was still locked; this would have caused massive data loss!");
@@ -19187,7 +19232,7 @@
         final UserManager um = mContext.getSystemService(UserManager.class);
         for (UserInfo user : um.getUsers()) {
             final int flags;
-            if (um.isUserUnlocked(user.id)) {
+            if (um.isUserUnlockingOrUnlocked(user.id)) {
                 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
             } else if (um.isUserRunning(user.id)) {
                 flags = StorageManager.FLAG_STORAGE_DE;
diff --git a/services/core/java/com/android/server/pm/Settings.java b/services/core/java/com/android/server/pm/Settings.java
index f20a36e..1040f85 100644
--- a/services/core/java/com/android/server/pm/Settings.java
+++ b/services/core/java/com/android/server/pm/Settings.java
@@ -4133,7 +4133,7 @@
         return pkg.getCurrentEnabledStateLPr(classNameStr, userId);
     }
 
-    boolean setPackageStoppedStateLPw(PackageManagerService yucky, String packageName,
+    boolean setPackageStoppedStateLPw(PackageManagerService pm, String packageName,
             boolean stopped, boolean allowedByPermission, int uid, int userId) {
         int appId = UserHandle.getAppId(uid);
         final PackageSetting pkgSetting = mPackages.get(packageName);
@@ -4158,9 +4158,7 @@
             // pkgSetting.pkg.mSetStopped = stopped;
             if (pkgSetting.getNotLaunched(userId)) {
                 if (pkgSetting.installerPackageName != null) {
-                    yucky.sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH,
-                            pkgSetting.name, null, 0,
-                            pkgSetting.installerPackageName, null, new int[] {userId});
+                    pm.notifyFirstLaunch(pkgSetting.name, pkgSetting.installerPackageName, userId);
                 }
                 pkgSetting.setNotLaunched(false, userId);
             }
diff --git a/services/core/java/com/android/server/pm/ShortcutService.java b/services/core/java/com/android/server/pm/ShortcutService.java
index 5764161..c0874ef 100644
--- a/services/core/java/com/android/server/pm/ShortcutService.java
+++ b/services/core/java/com/android/server/pm/ShortcutService.java
@@ -1561,48 +1561,46 @@
 
     // === House keeping ===
 
-    @VisibleForTesting
-    void cleanUpPackageLocked(String packageName, int owningUserId, int packageUserId) {
-        cleanUpPackageLocked(packageName, owningUserId, packageUserId,
-                /* forceForCommandLine= */ false);
+    private void cleanUpPackageForAllLoadedUsers(String packageName, @UserIdInt int packageUserId) {
+        synchronized (mLock) {
+            forEachLoadedUserLocked(user ->
+                    cleanUpPackageLocked(packageName, user.getUserId(), packageUserId));
+        }
     }
 
     /**
      * Remove all the information associated with a package.  This will really remove all the
      * information, including the restore information (i.e. it'll remove packages even if they're
      * shadow).
+     *
+     * This is called when an app is uninstalled, or an app gets "clear data"ed.
      */
-    private void cleanUpPackageLocked(String packageName, int owningUserId, int packageUserId,
-            boolean forceForCommandLine) {
-        if (!forceForCommandLine && isPackageInstalled(packageName, packageUserId)) {
-            wtf("Package " + packageName + " is still installed for user " + packageUserId);
-            return;
-        }
-
+    @VisibleForTesting
+    void cleanUpPackageLocked(String packageName, int owningUserId, int packageUserId) {
         final boolean wasUserLoaded = isUserLoadedLocked(owningUserId);
 
-        final ShortcutUser mUser = getUserShortcutsLocked(owningUserId);
+        final ShortcutUser user = getUserShortcutsLocked(owningUserId);
         boolean doNotify = false;
 
         // First, remove the package from the package list (if the package is a publisher).
         if (packageUserId == owningUserId) {
-            if (mUser.removePackage(this, packageName) != null) {
+            if (user.removePackage(this, packageName) != null) {
                 doNotify = true;
             }
         }
 
         // Also remove from the launcher list (if the package is a launcher).
-        mUser.removeLauncher(packageUserId, packageName);
+        user.removeLauncher(packageUserId, packageName);
 
         // Then remove pinned shortcuts from all launchers.
-        final ArrayMap<PackageWithUser, ShortcutLauncher> launchers = mUser.getAllLaunchers();
+        final ArrayMap<PackageWithUser, ShortcutLauncher> launchers = user.getAllLaunchers();
         for (int i = launchers.size() - 1; i >= 0; i--) {
             launchers.valueAt(i).cleanUpPackage(packageName, packageUserId);
         }
         // Now there may be orphan shortcuts because we removed pinned shortucts at the previous
         // step.  Remove them too.
-        for (int i = mUser.getAllPackages().size() - 1; i >= 0; i--) {
-            mUser.getAllPackages().valueAt(i).refreshPinnedFlags(this);
+        for (int i = user.getAllPackages().size() - 1; i >= 0; i--) {
+            user.getAllPackages().valueAt(i).refreshPinnedFlags(this);
         }
 
         scheduleSaveUser(owningUserId);
@@ -1842,6 +1840,11 @@
         public void onPackageRemoved(String packageName, int uid) {
             handlePackageRemoved(packageName, getChangingUserId());
         }
+
+        @Override
+        public void onPackageDataCleared(String packageName, int uid) {
+            handlePackageDataCleared(packageName, getChangingUserId());
+        }
     };
 
     /**
@@ -1915,16 +1918,15 @@
             Slog.d(TAG, String.format("handlePackageRemoved: %s user=%d", packageName,
                     packageUserId));
         }
-        handlePackageRemovedInner(packageName, packageUserId, /* forceForCommandLine =*/ false);
+        cleanUpPackageForAllLoadedUsers(packageName, packageUserId);
     }
 
-    private void handlePackageRemovedInner(String packageName, @UserIdInt int packageUserId,
-            boolean forceForCommandLine) {
-        synchronized (mLock) {
-            forEachLoadedUserLocked(user ->
-                cleanUpPackageLocked(packageName, user.getUserId(), packageUserId,
-                        forceForCommandLine));
+    private void handlePackageDataCleared(String packageName, int packageUserId) {
+        if (DEBUG) {
+            Slog.d(TAG, String.format("handlePackageDataCleared: %s user=%d", packageName,
+                    packageUserId));
         }
+        cleanUpPackageForAllLoadedUsers(packageName, packageUserId);
     }
 
     // === PackageManager interaction ===
@@ -2390,8 +2392,7 @@
 
             Slog.i(TAG, "cmd: handleClearShortcuts: " + mUserId + ", " + packageName);
 
-            ShortcutService.this.handlePackageRemovedInner(packageName, mUserId,
-                    /* forceForCommandLine= */ true);
+            ShortcutService.this.cleanUpPackageForAllLoadedUsers(packageName, mUserId);
         }
     }
 
diff --git a/services/core/java/com/android/server/pm/UserManagerService.java b/services/core/java/com/android/server/pm/UserManagerService.java
index a085370..a2d859b 100644
--- a/services/core/java/com/android/server/pm/UserManagerService.java
+++ b/services/core/java/com/android/server/pm/UserManagerService.java
@@ -692,7 +692,7 @@
     @Override
     public boolean trySetQuietModeDisabled(int userHandle, IntentSender target) {
         final int credentialOwnerUserId = getCredentialOwnerProfile(userHandle);
-        if (mContext.getSystemService(StorageManager.class).isUserKeyUnlocked(userHandle)
+        if (StorageManager.isUserKeyUnlocked(userHandle)
                 || !mLockPatternUtils.isSecure(credentialOwnerUserId)) {
             // if the user is already unlocked, no need to show a profile challenge
             setQuietModeEnabled(userHandle, false);
diff --git a/services/core/java/com/android/server/policy/PhoneWindowManager.java b/services/core/java/com/android/server/policy/PhoneWindowManager.java
index df74ed1..2636d09 100644
--- a/services/core/java/com/android/server/policy/PhoneWindowManager.java
+++ b/services/core/java/com/android/server/policy/PhoneWindowManager.java
@@ -4317,11 +4317,25 @@
             pf.top = df.top = of.top = mUnrestrictedScreenTop;
             pf.right = df.right = of.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
             pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
-            cf.bottom = vf.bottom = mStableBottom;
-            // Note: In Phone landscape mode, the button bar should also be excluded.
-            cf.right = vf.right = mStableRight;
-            cf.left = vf.left = mStableLeft;
-            cf.top = vf.top = mStableTop;
+            if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
+                cf.left = mDockLeft;
+                cf.top = mDockTop;
+                cf.right = mDockRight;
+                cf.bottom = mDockBottom;
+            } else {
+                cf.left = mContentLeft;
+                cf.top = mContentTop;
+                cf.right = mContentRight;
+                cf.bottom = mContentBottom;
+            }
+            if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
+                vf.left = mCurLeft;
+                vf.top = mCurTop;
+                vf.right = mCurRight;
+                vf.bottom = mCurBottom;
+            } else {
+                vf.set(cf);
+            }
         } else if (win == mStatusBar) {
             pf.left = df.left = of.left = mUnrestrictedScreenLeft;
             pf.top = df.top = of.top = mUnrestrictedScreenTop;
@@ -5145,7 +5159,6 @@
             mKeyguardOccluded = false;
             mKeyguardDelegate.setOccluded(false);
             mStatusBar.getAttrs().privateFlags |= PRIVATE_FLAG_KEYGUARD;
-            mStatusBar.getAttrs().flags |= FLAG_SHOW_WALLPAPER;
             return true;
         } else if (!wasOccluded && isOccluded && showing) {
             mKeyguardOccluded = true;
diff --git a/services/core/java/com/android/server/search/SearchManagerService.java b/services/core/java/com/android/server/search/SearchManagerService.java
index e3e1097..4d91814 100644
--- a/services/core/java/com/android/server/search/SearchManagerService.java
+++ b/services/core/java/com/android/server/search/SearchManagerService.java
@@ -112,7 +112,7 @@
             if (um.getUserInfo(userId) == null) {
                 throw new IllegalStateException("User " + userId + " doesn't exist");
             }
-            if (!um.isUserUnlocked(userId)) {
+            if (!um.isUserUnlockingOrUnlocked(userId)) {
                 throw new IllegalStateException("User " + userId + " isn't unlocked");
             }
         } finally {
diff --git a/services/core/java/com/android/server/wallpaper/WallpaperManagerService.java b/services/core/java/com/android/server/wallpaper/WallpaperManagerService.java
index d6ace91..af7e66d 100644
--- a/services/core/java/com/android/server/wallpaper/WallpaperManagerService.java
+++ b/services/core/java/com/android/server/wallpaper/WallpaperManagerService.java
@@ -862,7 +862,6 @@
 
         IntentFilter userFilter = new IntentFilter();
         userFilter.addAction(Intent.ACTION_USER_REMOVED);
-        userFilter.addAction(Intent.ACTION_USER_STOPPING);
         mContext.registerReceiver(new BroadcastReceiver() {
             @Override
             public void onReceive(Context context, Intent intent) {
@@ -871,12 +870,6 @@
                     onRemoveUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
                             UserHandle.USER_NULL));
                 }
-                // TODO: Race condition causing problems when cleaning up on stopping a user.
-                // Comment this out for now.
-                // else if (Intent.ACTION_USER_STOPPING.equals(action)) {
-                //     onStoppingUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
-                //             UserHandle.USER_NULL));
-                // }
             }
         }, userFilter);
 
diff --git a/services/core/java/com/android/server/wm/AccessibilityController.java b/services/core/java/com/android/server/wm/AccessibilityController.java
index 3ef077b..101f56f 100644
--- a/services/core/java/com/android/server/wm/AccessibilityController.java
+++ b/services/core/java/com/android/server/wm/AccessibilityController.java
@@ -124,9 +124,9 @@
         }
     }
 
-    public void getMagnificationRegionsLocked(Region outMagnified, Region outAvailable) {
+    public void getMagnificationRegionLocked(Region outMagnificationRegion) {
         if (mDisplayMagnifier != null) {
-            mDisplayMagnifier.getMagnificationRegionsLocked(outMagnified, outAvailable);
+            mDisplayMagnifier.getMagnificationRegionLocked(outMagnificationRegion);
         }
     }
 
@@ -400,8 +400,8 @@
             return spec;
         }
 
-        public void getMagnificationRegionsLocked(Region outMagnified, Region outAvailable) {
-            mMagnifedViewport.getBoundsLocked(outMagnified, outAvailable);
+        public void getMagnificationRegionLocked(Region outMagnificationRegion) {
+            mMagnifedViewport.getMagnificationRegionLocked(outMagnificationRegion);
         }
 
         public void destroyLocked() {
@@ -424,10 +424,8 @@
 
             private final Matrix mTempMatrix = new Matrix();
 
-            private final Region mMagnifiedBounds = new Region();
-            private final Region mAvailableBounds = new Region();
-            private final Region mOldMagnifiedBounds = new Region();
-            private final Region mOldAvailableBounds = new Region();
+            private final Region mMagnificationRegion = new Region();
+            private final Region mOldMagnificationRegion = new Region();
 
             private final Path mCircularPath;
 
@@ -463,10 +461,8 @@
                 recomputeBoundsLocked();
             }
 
-            public void getBoundsLocked(@NonNull Region outMagnified,
-                    @NonNull Region outAvailable) {
-                outMagnified.set(mMagnifiedBounds);
-                outAvailable.set(mAvailableBounds);
+            public void getMagnificationRegionLocked(@NonNull Region outMagnificationRegion) {
+                outMagnificationRegion.set(mMagnificationRegion);
             }
 
             public void updateMagnificationSpecLocked(MagnificationSpec spec) {
@@ -488,11 +484,12 @@
                 final int screenWidth = mTempPoint.x;
                 final int screenHeight = mTempPoint.y;
 
-                mMagnifiedBounds.set(0, 0, 0, 0);
-                mAvailableBounds.set(0, 0, screenWidth, screenHeight);
+                mMagnificationRegion.set(0, 0, 0, 0);
+                final Region availableBounds = mTempRegion1;
+                availableBounds.set(0, 0, screenWidth, screenHeight);
 
                 if (mCircularPath != null) {
-                    mAvailableBounds.setPath(mCircularPath, mAvailableBounds);
+                    availableBounds.setPath(mCircularPath, availableBounds);
                 }
 
                 Region nonMagnifiedBounds = mTempRegion4;
@@ -526,21 +523,21 @@
                             (int) windowFrame.right, (int) windowFrame.bottom);
                     // Only update new regions
                     Region portionOfWindowAlreadyAccountedFor = mTempRegion3;
-                    portionOfWindowAlreadyAccountedFor.set(mMagnifiedBounds);
+                    portionOfWindowAlreadyAccountedFor.set(mMagnificationRegion);
                     portionOfWindowAlreadyAccountedFor.op(nonMagnifiedBounds, Region.Op.UNION);
                     windowBounds.op(portionOfWindowAlreadyAccountedFor, Region.Op.DIFFERENCE);
 
                     if (mWindowManagerService.mPolicy.canMagnifyWindow(windowState.mAttrs.type)) {
-                        mMagnifiedBounds.op(windowBounds, Region.Op.UNION);
-                        mMagnifiedBounds.op(mAvailableBounds, Region.Op.INTERSECT);
+                        mMagnificationRegion.op(windowBounds, Region.Op.UNION);
+                        mMagnificationRegion.op(availableBounds, Region.Op.INTERSECT);
                     } else {
                         nonMagnifiedBounds.op(windowBounds, Region.Op.UNION);
-                        mAvailableBounds.op(windowBounds, Region.Op.DIFFERENCE);
+                        availableBounds.op(windowBounds, Region.Op.DIFFERENCE);
                     }
 
                     // Update accounted bounds
                     Region accountedBounds = mTempRegion2;
-                    accountedBounds.set(mMagnifiedBounds);
+                    accountedBounds.set(mMagnificationRegion);
                     accountedBounds.op(nonMagnifiedBounds, Region.Op.UNION);
                     accountedBounds.op(0, 0, screenWidth, screenHeight, Region.Op.INTERSECT);
 
@@ -556,43 +553,36 @@
 
                 visibleWindows.clear();
 
-                mMagnifiedBounds.op(mDrawBorderInset, mDrawBorderInset,
+                mMagnificationRegion.op(mDrawBorderInset, mDrawBorderInset,
                         screenWidth - mDrawBorderInset, screenHeight - mDrawBorderInset,
                         Region.Op.INTERSECT);
 
-                final boolean magnifiedChanged = !mOldMagnifiedBounds.equals(mMagnifiedBounds);
-                final boolean availableChanged = !mOldAvailableBounds.equals(mAvailableBounds);
-                if (magnifiedChanged || availableChanged) {
-                    if (magnifiedChanged) {
-                        mWindow.setBounds(mMagnifiedBounds);
-                        Rect dirtyRect = mTempRect1;
-                        if (mFullRedrawNeeded) {
-                            mFullRedrawNeeded = false;
-                            dirtyRect.set(mDrawBorderInset, mDrawBorderInset,
-                                    screenWidth - mDrawBorderInset,
-                                    screenHeight - mDrawBorderInset);
-                            mWindow.invalidate(dirtyRect);
-                        } else {
-                            Region dirtyRegion = mTempRegion3;
-                            dirtyRegion.set(mMagnifiedBounds);
-                            dirtyRegion.op(mOldMagnifiedBounds, Region.Op.UNION);
-                            dirtyRegion.op(nonMagnifiedBounds, Region.Op.INTERSECT);
-                            dirtyRegion.getBounds(dirtyRect);
-                            mWindow.invalidate(dirtyRect);
-                        }
-
-                        mOldMagnifiedBounds.set(mMagnifiedBounds);
+                final boolean magnifiedChanged =
+                        !mOldMagnificationRegion.equals(mMagnificationRegion);
+                if (magnifiedChanged) {
+                    mWindow.setBounds(mMagnificationRegion);
+                    final Rect dirtyRect = mTempRect1;
+                    if (mFullRedrawNeeded) {
+                        mFullRedrawNeeded = false;
+                        dirtyRect.set(mDrawBorderInset, mDrawBorderInset,
+                                screenWidth - mDrawBorderInset,
+                                screenHeight - mDrawBorderInset);
+                        mWindow.invalidate(dirtyRect);
+                    } else {
+                        final Region dirtyRegion = mTempRegion3;
+                        dirtyRegion.set(mMagnificationRegion);
+                        dirtyRegion.op(mOldMagnificationRegion, Region.Op.UNION);
+                        dirtyRegion.op(nonMagnifiedBounds, Region.Op.INTERSECT);
+                        dirtyRegion.getBounds(dirtyRect);
+                        mWindow.invalidate(dirtyRect);
                     }
 
-                    if (availableChanged) {
-                        mOldAvailableBounds.set(mAvailableBounds);
-                    }
-
+                    mOldMagnificationRegion.set(mMagnificationRegion);
                     final SomeArgs args = SomeArgs.obtain();
-                    args.arg1 = Region.obtain(mMagnifiedBounds);
-                    args.arg2 = Region.obtain(mAvailableBounds);
+                    args.arg1 = Region.obtain(mMagnificationRegion);
                     mHandler.obtainMessage(
-                            MyHandler.MESSAGE_NOTIFY_MAGNIFIED_BOUNDS_CHANGED, args).sendToTarget();
+                            MyHandler.MESSAGE_NOTIFY_MAGNIFICATION_REGION_CHANGED, args)
+                            .sendToTarget();
                 }
             }
 
@@ -616,14 +606,14 @@
             public void setMagnifiedRegionBorderShownLocked(boolean shown, boolean animate) {
                 if (shown) {
                     mFullRedrawNeeded = true;
-                    mOldMagnifiedBounds.set(0, 0, 0, 0);
+                    mOldMagnificationRegion.set(0, 0, 0, 0);
                 }
                 mWindow.setShown(shown, animate);
             }
 
             public void getMagnifiedFrameInContentCoordsLocked(Rect rect) {
                 MagnificationSpec spec = mMagnificationSpec;
-                mMagnifiedBounds.getBounds(rect);
+                mMagnificationRegion.getBounds(rect);
                 rect.offset((int) -spec.offsetX, (int) -spec.offsetY);
                 rect.scale(1.0f / spec.scale);
             }
@@ -886,7 +876,7 @@
         }
 
         private class MyHandler extends Handler {
-            public static final int MESSAGE_NOTIFY_MAGNIFIED_BOUNDS_CHANGED = 1;
+            public static final int MESSAGE_NOTIFY_MAGNIFICATION_REGION_CHANGED = 1;
             public static final int MESSAGE_NOTIFY_RECTANGLE_ON_SCREEN_REQUESTED = 2;
             public static final int MESSAGE_NOTIFY_USER_CONTEXT_CHANGED = 3;
             public static final int MESSAGE_NOTIFY_ROTATION_CHANGED = 4;
@@ -899,13 +889,11 @@
             @Override
             public void handleMessage(Message message) {
                 switch (message.what) {
-                    case MESSAGE_NOTIFY_MAGNIFIED_BOUNDS_CHANGED: {
+                    case MESSAGE_NOTIFY_MAGNIFICATION_REGION_CHANGED: {
                         final SomeArgs args = (SomeArgs) message.obj;
                         final Region magnifiedBounds = (Region) args.arg1;
-                        final Region availableBounds = (Region) args.arg2;
-                        mCallbacks.onMagnifiedBoundsChanged(magnifiedBounds, availableBounds);
+                        mCallbacks.onMagnificationRegionChanged(magnifiedBounds);
                         magnifiedBounds.recycle();
-                        availableBounds.recycle();
                     } break;
 
                     case MESSAGE_NOTIFY_RECTANGLE_ON_SCREEN_REQUESTED: {
diff --git a/services/core/java/com/android/server/wm/AppTransition.java b/services/core/java/com/android/server/wm/AppTransition.java
index 9199d10..094b217 100644
--- a/services/core/java/com/android/server/wm/AppTransition.java
+++ b/services/core/java/com/android/server/wm/AppTransition.java
@@ -39,6 +39,7 @@
 import static com.android.internal.R.styleable.WindowAnimation_wallpaperIntraOpenExitAnimation;
 import static com.android.internal.R.styleable.WindowAnimation_wallpaperOpenEnterAnimation;
 import static com.android.internal.R.styleable.WindowAnimation_wallpaperOpenExitAnimation;
+import static com.android.server.wm.AppWindowAnimator.PROLONG_ANIMATION_AT_START;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ANIM;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_APP_TRANSITIONS;
 import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
@@ -228,6 +229,7 @@
 
     private int mLastClipRevealMaxTranslation;
     private boolean mLastHadClipReveal;
+    private boolean mProlongedAnimationsEnded;
 
     AppTransition(Context context, WindowManagerService service) {
         mContext = context;
@@ -371,6 +373,22 @@
                 topClosingAppAnimator != null ? topClosingAppAnimator.animation : null);
         mService.getDefaultDisplayContentLocked().getDockedDividerController()
                 .notifyAppTransitionStarting(openingApps, closingApps);
+
+        // Prolong the start for the transition when docking a task from recents, unless recents
+        // ended it already then we don't need to wait.
+        if (mNextAppTransition == TRANSIT_DOCK_TASK_FROM_RECENTS && !mProlongedAnimationsEnded) {
+            for (int i = openingApps.size() - 1; i >= 0; i--) {
+                final AppWindowAnimator appAnimator = openingApps.valueAt(i).mAppAnimator;
+                appAnimator.startProlongAnimation(PROLONG_ANIMATION_AT_START);
+            }
+        }
+    }
+
+    /**
+     * Let the transitions manager know that the somebody wanted to end the prolonged animations.
+     */
+    void notifyProlongedAnimationsEnded() {
+        mProlongedAnimationsEnded = true;
     }
 
     void clear() {
@@ -380,6 +398,7 @@
         mNextAppTransitionAnimationsSpecsFuture = null;
         mDefaultNextAppTransitionAnimationSpec = null;
         mAnimationFinishedCallback = null;
+        mProlongedAnimationsEnded = false;
     }
 
     void freeze() {
@@ -1914,14 +1933,6 @@
                 setAppTransition(transit);
             }
         }
-        if (transit != TRANSIT_DOCK_TASK_FROM_RECENTS
-                && mNextAppTransition == TRANSIT_DOCK_TASK_FROM_RECENTS) {
-
-            // Somebody is trying to start another transition while we are waiting for the docking
-            // window to be drawn. Because TRANSIT_DOCK_TASK_FROM_RECENTS starts prolonged
-            // animations, we need to override it or our prolonged animations will never be ended.
-            setAppTransition(transit);
-        }
         boolean prepared = prepare();
         if (isTransitionSet()) {
             mService.mH.removeMessages(H.APP_TRANSITION_TIMEOUT);
diff --git a/services/core/java/com/android/server/wm/AppWindowToken.java b/services/core/java/com/android/server/wm/AppWindowToken.java
index 3b1f34a..b4ead44 100644
--- a/services/core/java/com/android/server/wm/AppWindowToken.java
+++ b/services/core/java/com/android/server/wm/AppWindowToken.java
@@ -390,8 +390,8 @@
     }
 
     boolean hasSavedSurface() {
-        for (int i = windows.size() -1; i >= 0; i--) {
-            final WindowState ws = windows.get(i);
+        for (int i = allAppWindows.size() -1; i >= 0; i--) {
+            final WindowState ws = allAppWindows.get(i);
             if (ws.hasSavedSurface()) {
                 return true;
             }
@@ -408,8 +408,8 @@
         // Check if we have enough drawn windows to mark allDrawn= true.
         int numInteresting = 0;
         int numDrawn = 0;
-        for (int i = windows.size() - 1; i >= 0; i--) {
-            WindowState w = windows.get(i);
+        for (int i = allAppWindows.size() - 1; i >= 0; i--) {
+            WindowState w = allAppWindows.get(i);
             if (w.hasSavedSurface()) {
                 w.restoreSavedSurface();
             }
@@ -429,8 +429,8 @@
     }
 
     void destroySavedSurfaces() {
-        for (int i = windows.size() - 1; i >= 0; i--) {
-            WindowState win = windows.get(i);
+        for (int i = allAppWindows.size() - 1; i >= 0; i--) {
+            WindowState win = allAppWindows.get(i);
             win.destroySavedSurface();
         }
         mAnimatingWithSavedSurface = false;
diff --git a/services/core/java/com/android/server/wm/BoundsAnimationController.java b/services/core/java/com/android/server/wm/BoundsAnimationController.java
index debb382..220a6de 100644
--- a/services/core/java/com/android/server/wm/BoundsAnimationController.java
+++ b/services/core/java/com/android/server/wm/BoundsAnimationController.java
@@ -24,10 +24,12 @@
 import android.animation.Animator;
 import android.animation.ValueAnimator;
 import android.graphics.Rect;
+import android.os.IBinder;
 import android.os.Debug;
 import android.util.ArrayMap;
 import android.util.Slog;
 import android.view.animation.LinearInterpolator;
+import android.view.WindowManagerInternal;
 
 /**
  * Enables animating bounds of objects.
@@ -49,6 +51,32 @@
     // Only accessed on UI thread.
     private ArrayMap<AnimateBoundsUser, BoundsAnimator> mRunningAnimations = new ArrayMap<>();
 
+    private final WindowManagerInternal.AppTransitionListener mAppTransitionNotifier
+        = new WindowManagerInternal.AppTransitionListener() {
+                public void onAppTransitionCancelledLocked() {
+                    animationFinished();
+                }
+                public void onAppTransitionFinishedLocked(IBinder token) {
+                    animationFinished();
+                }
+                private void animationFinished() {
+                    if (mFinishAnimationAfterTransition) {
+                        for (int i = 0; i < mRunningAnimations.size(); i++) {
+                            BoundsAnimator b = mRunningAnimations.valueAt(i);
+                            b.onAnimationEnd(null);
+                        }
+                    }
+                }
+            };
+
+    private final AppTransition mAppTransition;
+    private boolean mFinishAnimationAfterTransition = false;
+
+    BoundsAnimationController(AppTransition transition) {
+        mAppTransition = transition;
+        mAppTransition.registerListenerLocked(mAppTransitionNotifier);
+    }
+
     private final class BoundsAnimator extends ValueAnimator
             implements ValueAnimator.AnimatorUpdateListener, ValueAnimator.AnimatorListener {
         private final AnimateBoundsUser mTarget;
@@ -129,6 +157,7 @@
         public void onAnimationStart(Animator animation) {
             if (DEBUG) Slog.d(TAG, "onAnimationStart: mTarget=" + mTarget
                     + " mReplacement=" + mReplacement);
+            mFinishAnimationAfterTransition = false;
             // Ensure that we have prepared the target for animation before
             // we trigger any size changes, so it can swap surfaces
             // in to appropriate modes, or do as it wishes otherwise.
@@ -150,10 +179,21 @@
             if (DEBUG) Slog.d(TAG, "onAnimationEnd: mTarget=" + mTarget
                     + " mMoveToFullScreen=" + mMoveToFullScreen + " mWillReplace=" + mWillReplace);
 
-            finishAnimation();
+            // There could be another animation running. For example in the
+            // move to fullscreen case, recents will also be closing while the
+            // previous task will be taking its place in the fullscreen stack.
+            // we have to ensure this is completed before we finish the animation
+            // and take our place in the fullscreen stack.
+            if (mAppTransition.isRunning() && !mFinishAnimationAfterTransition) {
+                mFinishAnimationAfterTransition = true;
+                return;
+            }
+
             if (mMoveToFullScreen && !mWillReplace) {
                 mTarget.moveToFullscreen();
             }
+
+            finishAnimation();
         }
 
         @Override
diff --git a/services/core/java/com/android/server/wm/DockedStackDividerController.java b/services/core/java/com/android/server/wm/DockedStackDividerController.java
index 8174c13..c640b2a 100644
--- a/services/core/java/com/android/server/wm/DockedStackDividerController.java
+++ b/services/core/java/com/android/server/wm/DockedStackDividerController.java
@@ -377,7 +377,7 @@
 
         // If the app that having visibility change is not the top visible one in the task,
         // it does not affect whether the docked stack is minimized, ignore it.
-        if (task.getTopVisibleAppToken() == null || task.getTopVisibleAppToken() != wtoken) {
+        if (task.getTopAppToken() == null || task.getTopAppToken() != wtoken) {
             return;
         }
 
@@ -598,7 +598,7 @@
     }
 
     private boolean animateForMinimizedDockedStack(long now) {
-        final TaskStack stack = mDisplayContent.getDockedStackVisibleForUserLocked();
+        final TaskStack stack = mService.mStackIdToStack.get(DOCKED_STACK_ID);
         if (!mAnimationStarted) {
             mAnimationStarted = true;
             mAnimationStartTime = now;
diff --git a/services/core/java/com/android/server/wm/Task.java b/services/core/java/com/android/server/wm/Task.java
index 6925fa5..8d41dab 100644
--- a/services/core/java/com/android/server/wm/Task.java
+++ b/services/core/java/com/android/server/wm/Task.java
@@ -719,6 +719,10 @@
         return null;
     }
 
+    AppWindowToken getTopAppToken() {
+        return mAppTokens.size() > 0 ? mAppTokens.get(mAppTokens.size() - 1) : null;
+    }
+
     @Override
     public boolean isFullscreen() {
         if (useCurrentBounds()) {
diff --git a/services/core/java/com/android/server/wm/TaskStack.java b/services/core/java/com/android/server/wm/TaskStack.java
index 6f8207e..4224c57 100644
--- a/services/core/java/com/android/server/wm/TaskStack.java
+++ b/services/core/java/com/android/server/wm/TaskStack.java
@@ -110,11 +110,6 @@
     /** Detach this stack from its display when animation completes. */
     boolean mDeferDetach;
 
-    // Display rotation as of the last time the display information was updated for this stack.
-    private int mLastUpdateDisplayInfoRotation = -1;
-    // Display rotation as of the last time the configuration was updated for this stack.
-    private int mLastConfigChangedRotation = -1;
-
     // Whether the stack and all its tasks is currently being drag-resized
     private boolean mDragResizing;
 
@@ -371,36 +366,27 @@
         final int newDensity = mDisplayContent.getDisplayInfo().logicalDensityDpi;
         if (mRotation == newRotation && mDensity == newDensity) {
             setBounds(mTmpRect2);
-        } else {
-            mLastUpdateDisplayInfoRotation = newRotation;
-            updateBoundsAfterConfigChange(true);
         }
+
+        // If the rotation or density didn't match, we'll update it in onConfigurationChanged.
     }
 
     boolean onConfigurationChanged() {
-        mLastConfigChangedRotation = getDisplayInfo().rotation;
-        return updateBoundsAfterConfigChange(false);
+        return updateBoundsAfterConfigChange();
     }
 
-    boolean updateBoundsAfterConfigChange(boolean scheduleResize) {
+    private boolean updateBoundsAfterConfigChange() {
         if (mFullscreen) {
             // Bounds will already be set correctly when display info is updated in the case of
             // fullscreen.
             return false;
         }
 
-        if (mLastConfigChangedRotation != mLastUpdateDisplayInfoRotation) {
-            // We wait for the rotation values after configuration change and display info. update
-            // to be equal before updating the bounds due to rotation change otherwise things might
-            // get out of alignment...
-            return false;
-        }
-
         final int newRotation = getDisplayInfo().rotation;
         final int newDensity = getDisplayInfo().logicalDensityDpi;
 
         if (mRotation == newRotation && mDensity == newDensity) {
-            // Nothing to do here if the rotation didn't change
+            // Nothing to do here as we already update the state in updateDisplayInfo.
             return false;
         }
 
@@ -416,16 +402,7 @@
             }
         }
 
-        if (scheduleResize) {
-            // Post message to inform activity manager of the bounds change simulating
-            // a one-way call. We do this to prevent a deadlock between window manager
-            // lock and activity manager lock been held.
-            mService.mH.obtainMessage(RESIZE_STACK, mStackId,
-                    0 /*allowResizeInDockedMode*/, mTmpRect2).sendToTarget();
-        } else {
-            mBoundsAfterRotation.set(mTmpRect2);
-        }
-
+        mBoundsAfterRotation.set(mTmpRect2);
         return true;
     }
 
@@ -1121,6 +1098,14 @@
         pw.println(prefix + "mDeferDetach=" + mDeferDetach);
         pw.println(prefix + "mFullscreen=" + mFullscreen);
         pw.println(prefix + "mBounds=" + mBounds.toShortString());
+        if (mMinimizeAmount != 0f) {
+            pw.println(prefix + "mMinimizeAmout=" + mMinimizeAmount);
+        }
+        if (mAdjustedForIme) {
+            pw.println(prefix + "mAdjustedForIme=true");
+            pw.println(prefix + "mAdjustImeAmount=" + mAdjustImeAmount);
+            pw.println(prefix + "mAdjustDividerAmount=" + mAdjustDividerAmount);
+        }
         if (!mAdjustedBounds.isEmpty()) {
             pw.println(prefix + "mAdjustedBounds=" + mAdjustedBounds.toShortString());
         }
diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java
index cf415ff..57f551c 100644
--- a/services/core/java/com/android/server/wm/WindowManagerService.java
+++ b/services/core/java/com/android/server/wm/WindowManagerService.java
@@ -715,8 +715,7 @@
 
     final WindowAnimator mAnimator;
 
-    private final BoundsAnimationController mBoundsAnimationController =
-            new BoundsAnimationController();
+    private final BoundsAnimationController mBoundsAnimationController;
 
     SparseArray<Task> mTaskIdToTask = new SparseArray<>();
 
@@ -974,6 +973,8 @@
         mAppTransition = new AppTransition(context, this);
         mAppTransition.registerListenerLocked(mActivityManagerAppTransitionNotifier);
 
+        mBoundsAnimationController = new BoundsAnimationController(mAppTransition);
+
         mActivityManager = ActivityManagerNative.getDefault();
         mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
         mAppOps = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE);
@@ -3625,8 +3626,7 @@
             // disregarding font scale, which should remain set to
             // the value of the previous configuration.
             mTempConfiguration.setToDefaults();
-            mTempConfiguration.fontScale = currentConfig.fontScale;
-            mTempConfiguration.uiMode = currentConfig.uiMode;
+            mTempConfiguration.updateFrom(currentConfig);
             computeScreenConfigurationLocked(mTempConfiguration);
             if (currentConfig.diff(mTempConfiguration) != 0) {
                 mWaitingForConfig = true;
@@ -3689,11 +3689,15 @@
         }
 
         synchronized(mWindowMap) {
-            mCurConfiguration = new Configuration(config);
             if (mWaitingForConfig) {
                 mWaitingForConfig = false;
                 mLastFinishedFreezeSource = "new-config";
             }
+            boolean configChanged = mCurConfiguration.diff(config) != 0;
+            if (!configChanged) {
+                return null;
+            }
+            mCurConfiguration = new Configuration(config);
             return onConfigurationChanged();
         }
     }
@@ -3941,6 +3945,7 @@
                     appToken.mAppAnimator.endProlongedAnimation();
                 }
             }
+            mAppTransition.notifyProlongedAnimationsEnded();
         }
     }
 
@@ -4330,15 +4335,21 @@
             }
         }
 
-        if (visibilityChanged && !delayed) {
-            if (visible) {
+        if (visibilityChanged) {
+            if (visible && !delayed) {
                 // The token was made immediately visible, there will be no entrance animation.
                 // We need to inform the client the enter animation was finished.
                 wtoken.mEnteringAnimation = true;
                 mActivityManagerAppTransitionNotifier.onAppTransitionFinishedLocked(wtoken.token);
             }
-            getDefaultDisplayContentLocked().getDockedDividerController()
-                    .notifyAppVisibilityChanged(wtoken, visible);
+
+            if (!mClosingApps.contains(wtoken) && !mOpeningApps.contains(wtoken)) {
+                // The token is not closing nor opening, so even if there is an animation set, that
+                // doesn't mean that it goes through the normal app transition cycle so we have
+                // to inform the docked controller about visibility change.
+                getDefaultDisplayContentLocked().getDockedDividerController()
+                        .notifyAppVisibilityChanged(wtoken, visible);
+            }
         }
 
         return delayed;
@@ -6287,9 +6298,11 @@
                         + maxLayer + " appToken=" + appToken);
                 for (int i = 0; i < windows.size(); i++) {
                     WindowState win = windows.get(i);
+                    WindowSurfaceController controller = win.mWinAnimator.mSurfaceController;
                     Slog.i(TAG_WM, win + ": " + win.mLayer
                             + " animLayer=" + win.mWinAnimator.mAnimLayer
-                            + " surfaceLayer=" + win.mWinAnimator.mSurfaceController.getLayer());
+                            + " surfaceLayer=" + ((controller == null)
+                                ? "null" : controller.getLayer()));
                 }
             }
 
@@ -8877,8 +8890,7 @@
 
         boolean configChanged = updateOrientationFromAppTokensLocked(false);
         mTempConfiguration.setToDefaults();
-        mTempConfiguration.fontScale = mCurConfiguration.fontScale;
-        mTempConfiguration.uiMode = mCurConfiguration.uiMode;
+        mTempConfiguration.updateFrom(mCurConfiguration);
         computeScreenConfigurationLocked(mTempConfiguration);
         configChanged |= mCurConfiguration.diff(mTempConfiguration) != 0;
 
@@ -10975,12 +10987,10 @@
         }
 
         @Override
-        public void getMagnificationRegions(@NonNull Region outMagnified,
-                @NonNull Region outAvailable) {
+        public void getMagnificationRegion(@NonNull Region magnificationRegion) {
             synchronized (mWindowMap) {
                 if (mAccessibilityController != null) {
-                    mAccessibilityController.getMagnificationRegionsLocked(
-                            outMagnified, outAvailable);
+                    mAccessibilityController.getMagnificationRegionLocked(magnificationRegion);
                 } else {
                     throw new IllegalStateException("Magnification callbacks not set!");
                 }
diff --git a/services/core/java/com/android/server/wm/WindowStateAnimator.java b/services/core/java/com/android/server/wm/WindowStateAnimator.java
index 1493bc7..e319407 100644
--- a/services/core/java/com/android/server/wm/WindowStateAnimator.java
+++ b/services/core/java/com/android/server/wm/WindowStateAnimator.java
@@ -1441,6 +1441,18 @@
             return;
         }
 
+        // Do not change surface properties of opening apps if we are waiting for the
+        // transition to be ready. transitionGoodToGo could be not ready even after all
+        // opening apps are drawn. It's only waiting on isFetchingAppTransitionsSpecs()
+        // to get the animation spec. (For example, go into Recents and immediately open
+        // the same app again before the app's surface is destroyed or saved, the surface
+        // is always ready in the whole process.) If we go ahead here, the opening app
+        // will be shown with the full size before the correct animation spec arrives.
+        if (mService.mAppTransition.isReady() && isDummyAnimation() &&
+                mService.mOpeningApps.contains(w.mAppToken)) {
+            return;
+        }
+
         boolean displayed = false;
 
         computeShownFrameLocked();
diff --git a/services/core/java/com/android/server/wm/WindowSurfacePlacer.java b/services/core/java/com/android/server/wm/WindowSurfacePlacer.java
index 8937f09..a45ae60 100644
--- a/services/core/java/com/android/server/wm/WindowSurfacePlacer.java
+++ b/services/core/java/com/android/server/wm/WindowSurfacePlacer.java
@@ -1251,10 +1251,6 @@
             if (mService.mAppTransition.isNextAppTransitionThumbnailUp()) {
                 createThumbnailAppAnimator(transit, wtoken, topOpeningLayer, topClosingLayer);
             }
-            if (mService.mAppTransition.getAppTransition()
-                    == AppTransition.TRANSIT_DOCK_TASK_FROM_RECENTS) {
-                appAnimator.startProlongAnimation(PROLONG_ANIMATION_AT_START);
-            }
         }
         return topOpeningApp;
     }
diff --git a/services/core/jni/com_android_server_am_BatteryStatsService.cpp b/services/core/jni/com_android_server_am_BatteryStatsService.cpp
index 5c43659..183a370 100644
--- a/services/core/jni/com_android_server_am_BatteryStatsService.cpp
+++ b/services/core/jni/com_android_server_am_BatteryStatsService.cpp
@@ -27,8 +27,10 @@
 #include <utils/misc.h>
 #include <utils/Log.h>
 #include <hardware/hardware.h>
+#include <hardware/power.h>
 #include <suspend/autosuspend.h>
 
+#include <inttypes.h>
 #include <stdio.h>
 #include <errno.h>
 #include <fcntl.h>
@@ -47,6 +49,7 @@
 
 static bool wakeup_init = false;
 static sem_t wakeup_sem;
+extern struct power_module* gPowerModule;
 
 static void wakeup_callback(bool success)
 {
@@ -170,8 +173,122 @@
     return mergedreasonpos - mergedreason;
 }
 
+static jint getPlatformLowPowerStats(JNIEnv* env, jobject /* clazz */, jobject outBuf) {
+    int num_modes = -1;
+    char *output = (char*)env->GetDirectBufferAddress(outBuf), *offset = output;
+    int remaining = (int)env->GetDirectBufferCapacity(outBuf);
+    power_state_platform_sleep_state_t *list;
+    size_t *voter_list;
+    int total_added = -1;
+
+    if (outBuf == NULL) {
+        jniThrowException(env, "java/lang/NullPointerException", "null argument");
+        goto error;
+    }
+
+    if (!gPowerModule) {
+        ALOGE("%s: gPowerModule not loaded", POWER_HARDWARE_MODULE_ID);
+        goto error;
+    }
+
+    if (! (gPowerModule->get_platform_low_power_stats && gPowerModule->get_number_of_platform_modes
+       && gPowerModule->get_voter_list)) {
+        ALOGE("%s: Missing API", POWER_HARDWARE_MODULE_ID);
+        goto error;
+    }
+
+    if (gPowerModule->get_number_of_platform_modes) {
+        num_modes = gPowerModule->get_number_of_platform_modes(gPowerModule);
+    }
+
+    if (num_modes < 1) {
+        ALOGE("%s: Platform does not even have one low power mode", POWER_HARDWARE_MODULE_ID);
+        goto error;
+    }
+
+    list = (power_state_platform_sleep_state_t *)calloc(num_modes,
+        sizeof(power_state_platform_sleep_state_t));
+    if (!list) {
+        ALOGE("%s: power_state_platform_sleep_state_t allocation failed", POWER_HARDWARE_MODULE_ID);
+        goto error;
+    }
+
+    voter_list = (size_t *)calloc(num_modes, sizeof(*voter_list));
+    if (!voter_list) {
+        ALOGE("%s: voter_list allocation failed", POWER_HARDWARE_MODULE_ID);
+        goto err_free;
+    }
+
+    gPowerModule->get_voter_list(gPowerModule, voter_list);
+
+    for (int i = 0; i < num_modes; i++) {
+        list[i].voters = (power_state_voter_t *)calloc(voter_list[i],
+                         sizeof(power_state_voter_t));
+        if (!list[i].voters) {
+            ALOGE("%s: voter_t allocation failed", POWER_HARDWARE_MODULE_ID);
+            goto err_free;
+        }
+    }
+
+    if (!gPowerModule->get_platform_low_power_stats(gPowerModule, list)) {
+        for (int i = 0; i < num_modes; i++) {
+            int added;
+
+            added = snprintf(offset, remaining, "%s_time=%" PRIu64 " %s_count=%" PRIu64 " ",
+                    list[i].name, list[i].residency_in_msec_since_boot, list[i].name,
+                    list[i].total_transitions);
+            if (added < 0) {
+                break;
+            }
+            if (added > remaining) {
+                added = remaining;
+            }
+            offset += added;
+            remaining -= added;
+            total_added += added;
+
+            for (unsigned int j = 0; j < list[i].number_of_voters; j++) {
+                added = snprintf(offset, remaining, "%s_time=%" PRIu64 " %s_count=%" PRIu64 " ",
+                        list[i].voters[j].name,
+                        list[i].voters[j].total_time_in_msec_voted_for_since_boot,
+                        list[i].voters[j].name,
+                        list[i].voters[j].total_number_of_times_voted_since_boot);
+                if (added < 0) {
+                    break;
+                }
+                if (added > remaining) {
+                    added = remaining;
+                }
+                offset += added;
+                remaining -= added;
+                total_added += added;
+            }
+
+            if (remaining <= 0) {
+                /* rewrite NULL character*/
+                offset--;
+                total_added--;
+                ALOGE("%s module: buffer not enough", POWER_HARDWARE_MODULE_ID);
+                break;
+            }
+        }
+    }
+    *offset = 0;
+    total_added += 1;
+
+err_free:
+    for (int i = 0; i < num_modes; i++) {
+        free(list[i].voters);
+    }
+    free(list);
+    free(voter_list);
+error:
+    return total_added;
+}
+
 static const JNINativeMethod method_table[] = {
     { "nativeWaitWakeup", "(Ljava/nio/ByteBuffer;)I", (void*)nativeWaitWakeup },
+    { "getPlatformLowPowerStats", "(Ljava/nio/ByteBuffer;)I", (void*)getPlatformLowPowerStats },
 };
 
 int register_android_server_BatteryStatsService(JNIEnv *env)
diff --git a/services/core/jni/com_android_server_power_PowerManagerService.cpp b/services/core/jni/com_android_server_power_PowerManagerService.cpp
index 2fdb8e2..cbbfda6a 100644
--- a/services/core/jni/com_android_server_power_PowerManagerService.cpp
+++ b/services/core/jni/com_android_server_power_PowerManagerService.cpp
@@ -48,7 +48,7 @@
 // ----------------------------------------------------------------------------
 
 static jobject gPowerManagerServiceObj;
-static struct power_module* gPowerModule;
+struct power_module* gPowerModule;
 
 static nsecs_t gLastEventTime[USER_ACTIVITY_EVENT_LAST + 1];
 
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
index 56e2001..93fbe5c 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
@@ -6224,6 +6224,8 @@
     }
 
     private void enforceUserUnlocked(int userId) {
+        // Since we're doing this operation on behalf of an app, we only
+        // want to use the actual "unlocked" state.
         Preconditions.checkState(mUserManager.isUserUnlocked(userId),
                 "User must be running and unlocked");
     }
diff --git a/services/net/java/android/net/dhcp/DhcpClient.java b/services/net/java/android/net/dhcp/DhcpClient.java
index 77cd9b6..db521e2 100644
--- a/services/net/java/android/net/dhcp/DhcpClient.java
+++ b/services/net/java/android/net/dhcp/DhcpClient.java
@@ -724,6 +724,7 @@
                     mOffer = null;
                     Log.d(TAG, "Confirmed lease: " + mDhcpLease);
                     setDhcpLeaseExpiry(packet);
+                    notifySuccess();
                     transitionTo(mConfiguringInterfaceState);
                 }
             } else if (packet instanceof DhcpNakPacket) {
@@ -794,7 +795,6 @@
         @Override
         public void enter() {
             super.enter();
-            notifySuccess();
             // TODO: DhcpStateMachine only supported renewing at 50% of the lease time,
             // and did not support rebinding. Now that the legacy DHCP client is gone, fix this.
             scheduleRenew();
@@ -850,6 +850,7 @@
             if (!isValidPacket(packet)) return;
             if ((packet instanceof DhcpAckPacket)) {
                 setDhcpLeaseExpiry(packet);
+                notifySuccess();
                 transitionTo(mDhcpBoundState);
             } else if (packet instanceof DhcpNakPacket) {
                 transitionTo(mDhcpInitState);
diff --git a/services/net/java/android/net/ip/IpManager.java b/services/net/java/android/net/ip/IpManager.java
index 0444686..34152cf 100644
--- a/services/net/java/android/net/ip/IpManager.java
+++ b/services/net/java/android/net/ip/IpManager.java
@@ -282,7 +282,12 @@
             }
 
             public Builder withPreDhcpAction() {
-                mConfig.mRequestedPreDhcpAction = true;
+                mConfig.mRequestedPreDhcpActionMs = DEFAULT_TIMEOUT_MS;
+                return this;
+            }
+
+            public Builder withPreDhcpAction(int dhcpActionTimeoutMs) {
+                mConfig.mRequestedPreDhcpActionMs = dhcpActionTimeoutMs;
                 return this;
             }
 
@@ -307,7 +312,7 @@
         }
 
         /* package */ boolean mUsingIpReachabilityMonitor = true;
-        /* package */ boolean mRequestedPreDhcpAction;
+        /* package */ int mRequestedPreDhcpActionMs;
         /* package */ StaticIpConfiguration mStaticIpConfig;
         /* package */ ApfCapabilities mApfCapabilities;
         /* package */ int mProvisioningTimeoutMs = DEFAULT_TIMEOUT_MS;
@@ -316,7 +321,7 @@
 
         public ProvisioningConfiguration(ProvisioningConfiguration other) {
             mUsingIpReachabilityMonitor = other.mUsingIpReachabilityMonitor;
-            mRequestedPreDhcpAction = other.mRequestedPreDhcpAction;
+            mRequestedPreDhcpActionMs = other.mRequestedPreDhcpActionMs;
             mStaticIpConfig = other.mStaticIpConfig;
             mApfCapabilities = other.mApfCapabilities;
             mProvisioningTimeoutMs = other.mProvisioningTimeoutMs;
@@ -326,7 +331,7 @@
         public String toString() {
             return new StringJoiner(", ", getClass().getSimpleName() + "{", "}")
                     .add("mUsingIpReachabilityMonitor: " + mUsingIpReachabilityMonitor)
-                    .add("mRequestedPreDhcpAction: " + mRequestedPreDhcpAction)
+                    .add("mRequestedPreDhcpActionMs: " + mRequestedPreDhcpActionMs)
                     .add("mStaticIpConfig: " + mStaticIpConfig)
                     .add("mApfCapabilities: " + mApfCapabilities)
                     .add("mProvisioningTimeoutMs: " + mProvisioningTimeoutMs)
@@ -346,6 +351,7 @@
     private static final int CMD_UPDATE_HTTP_PROXY = 7;
     private static final int CMD_SET_MULTICAST_FILTER = 8;
     private static final int EVENT_PROVISIONING_TIMEOUT = 9;
+    private static final int EVENT_DHCPACTION_TIMEOUT = 10;
 
     private static final int MAX_LOG_RECORDS = 500;
 
@@ -369,6 +375,7 @@
     private final INetworkManagementService mNwService;
     private final NetlinkTracker mNetlinkTracker;
     private final WakeupMessage mProvisioningTimeoutAlarm;
+    private final WakeupMessage mDhcpActionTimeoutAlarm;
     private final LocalLog mLocalLog;
 
     private NetworkInterface mNetworkInterface;
@@ -445,6 +452,8 @@
 
         mProvisioningTimeoutAlarm = new WakeupMessage(mContext, getHandler(),
                 mTag + ".EVENT_PROVISIONING_TIMEOUT", EVENT_PROVISIONING_TIMEOUT);
+        mDhcpActionTimeoutAlarm = new WakeupMessage(mContext, getHandler(),
+                mTag + ".EVENT_DHCPACTION_TIMEOUT", EVENT_DHCPACTION_TIMEOUT);
 
         // Super simple StateMachine.
         addState(mStoppedState);
@@ -1023,6 +1032,7 @@
         @Override
         public void exit() {
             mProvisioningTimeoutAlarm.cancel();
+            mDhcpActionTimeoutAlarm.cancel();
 
             if (mIpReachabilityMonitor != null) {
                 mIpReachabilityMonitor.stop();
@@ -1042,6 +1052,18 @@
             resetLinkProperties();
         }
 
+        private void startDhcpAction() {
+            mCallback.onPreDhcpAction();
+            final long alarmTime = SystemClock.elapsedRealtime() +
+                    mConfiguration.mRequestedPreDhcpActionMs;
+            mDhcpActionTimeoutAlarm.schedule(alarmTime);
+        }
+
+        private void stopDhcpAction() {
+            mDhcpActionTimeoutAlarm.cancel();
+            mCallback.onPostDhcpAction();
+        }
+
         @Override
         public boolean processMessage(Message msg) {
             switch (msg.what) {
@@ -1104,10 +1126,14 @@
                     handleProvisioningFailure();
                     break;
 
+                case EVENT_DHCPACTION_TIMEOUT:
+                    stopDhcpAction();
+                    break;
+
                 case DhcpClient.CMD_PRE_DHCP_ACTION:
                     if (VDBG) { Log.d(mTag, "onPreDhcpAction()"); }
-                    if (mConfiguration.mRequestedPreDhcpAction) {
-                        mCallback.onPreDhcpAction();
+                    if (mConfiguration.mRequestedPreDhcpActionMs > 0) {
+                        startDhcpAction();
                     } else {
                         sendMessage(EVENT_PRE_DHCP_ACTION_COMPLETE);
                     }
@@ -1123,17 +1149,23 @@
                         mDhcpClient.sendMessage(DhcpClient.EVENT_LINKADDRESS_CONFIGURED);
                     } else {
                         Log.e(mTag, "Failed to set IPv4 address!");
+                        dispatchCallback(ProvisioningChange.LOST_PROVISIONING,
+                                new LinkProperties(mLinkProperties));
                         transitionTo(mStoppingState);
                     }
                     break;
                 }
 
+                // This message is only received when:
+                //
+                //     a) initial address acquisition succeeds,
+                //     b) renew succeeds,
+                //     c) renew fails,
+                //
+                // but never when initial address acquisition fails. The latter
+                // condition is now governed by the provisioning timeout.
                 case DhcpClient.CMD_POST_DHCP_ACTION: {
-                    // Note that onPostDhcpAction() is likely to be
-                    // asynchronous, and thus there is no guarantee that we
-                    // will be able to observe any of its effects here.
-                    if (VDBG) { Log.d(mTag, "onPostDhcpAction()"); }
-                    mCallback.onPostDhcpAction();
+                    stopDhcpAction();
 
                     final DhcpResults dhcpResults = (DhcpResults) msg.obj;
                     switch (msg.arg1) {
diff --git a/services/print/java/com/android/server/print/PrintManagerService.java b/services/print/java/com/android/server/print/PrintManagerService.java
index 4d02928..f2c995b 100644
--- a/services/print/java/com/android/server/print/PrintManagerService.java
+++ b/services/print/java/com/android/server/print/PrintManagerService.java
@@ -727,7 +727,7 @@
 
                 @Override
                 public void onPackageModified(String packageName) {
-                    if (!mUserManager.isUserUnlocked(getChangingUserId())) return;
+                    if (!mUserManager.isUserUnlockingOrUnlocked(getChangingUserId())) return;
                     UserState userState = getOrCreateUserStateLocked(getChangingUserId(), false);
 
                     synchronized (mLock) {
@@ -742,7 +742,7 @@
 
                 @Override
                 public void onPackageRemoved(String packageName, int uid) {
-                    if (!mUserManager.isUserUnlocked(getChangingUserId())) return;
+                    if (!mUserManager.isUserUnlockingOrUnlocked(getChangingUserId())) return;
                     UserState userState = getOrCreateUserStateLocked(getChangingUserId(), false);
 
                     synchronized (mLock) {
@@ -757,7 +757,7 @@
                 @Override
                 public boolean onHandleForceStop(Intent intent, String[] stoppedPackages,
                         int uid, boolean doit) {
-                    if (!mUserManager.isUserUnlocked(getChangingUserId())) return false;
+                    if (!mUserManager.isUserUnlockingOrUnlocked(getChangingUserId())) return false;
                     synchronized (mLock) {
                         // A background user/profile's print jobs are running but there is
                         // no UI shown. Hence, if the packages of such a user change we need
@@ -795,7 +795,7 @@
 
                 @Override
                 public void onPackageAdded(String packageName, int uid) {
-                    if (!mUserManager.isUserUnlocked(getChangingUserId())) return;
+                    if (!mUserManager.isUserUnlockingOrUnlocked(getChangingUserId())) return;
                     synchronized (mLock) {
                         if (hasPrintService(packageName)) {
                             UserState userState = getOrCreateUserStateLocked(getChangingUserId(),
@@ -812,7 +812,7 @@
         }
 
         private UserState getOrCreateUserStateLocked(int userId, boolean lowPriority) {
-            if (!mUserManager.isUserUnlocked(userId)) {
+            if (!mUserManager.isUserUnlockingOrUnlocked(userId)) {
                 throw new IllegalStateException(
                         "User " + userId + " must be unlocked for printing to be available");
             }
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 bc43576..13518b5 100644
--- a/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest.java
+++ b/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest.java
@@ -1061,6 +1061,12 @@
         i.putExtra(Intent.EXTRA_REPLACING, true);
         return i;
     }
+    private Intent genPackageDataClear(String packageName, int userId) {
+        Intent i = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED);
+        i.setData(Uri.parse("package:" + packageName));
+        i.putExtra(Intent.EXTRA_USER_HANDLE, userId);
+        return i;
+    }
 
     private ShortcutInfo parceled(ShortcutInfo si) {
         Parcel p = Parcel.obtain();
@@ -4159,6 +4165,79 @@
         assertFalse(bitmapDirectoryExists(CALLING_PACKAGE_3, USER_10));
     }
 
+    /** Almost ame as testHandlePackageDelete, except it doesn't uninstall packages. */
+    public void testHandlePackageClearData() {
+        final Icon bmp32x32 = Icon.createWithBitmap(BitmapFactory.decodeResource(
+                getTestContext().getResources(), R.drawable.black_32x32));
+        setCaller(CALLING_PACKAGE_1, USER_0);
+        assertTrue(mManager.addDynamicShortcuts(list(
+                makeShortcutWithIcon("s1", bmp32x32), makeShortcutWithIcon("s2", bmp32x32)
+        )));
+
+        setCaller(CALLING_PACKAGE_2, USER_0);
+        assertTrue(mManager.addDynamicShortcuts(list(makeShortcutWithIcon("s1", bmp32x32))));
+
+        setCaller(CALLING_PACKAGE_3, USER_0);
+        assertTrue(mManager.addDynamicShortcuts(list(makeShortcutWithIcon("s1", bmp32x32))));
+
+        setCaller(CALLING_PACKAGE_1, USER_10);
+        assertTrue(mManager.addDynamicShortcuts(list(makeShortcutWithIcon("s1", bmp32x32))));
+
+        setCaller(CALLING_PACKAGE_2, USER_10);
+        assertTrue(mManager.addDynamicShortcuts(list(makeShortcutWithIcon("s1", bmp32x32))));
+
+        setCaller(CALLING_PACKAGE_3, USER_10);
+        assertTrue(mManager.addDynamicShortcuts(list(makeShortcutWithIcon("s1", bmp32x32))));
+
+        assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_1, "s1", USER_0));
+        assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_2, "s1", USER_0));
+        assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_3, "s1", USER_0));
+        assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_1, "s1", USER_10));
+        assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_2, "s1", USER_10));
+        assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_3, "s1", USER_10));
+
+        assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_1, USER_0));
+        assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_2, USER_0));
+        assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_3, USER_0));
+        assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_1, USER_10));
+        assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_2, USER_10));
+        assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_3, USER_10));
+
+        mService.mPackageMonitor.onReceive(getTestContext(),
+                genPackageDataClear(CALLING_PACKAGE_1, USER_0));
+
+        assertNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_1, "s1", USER_0));
+        assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_2, "s1", USER_0));
+        assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_3, "s1", USER_0));
+        assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_1, "s1", USER_10));
+        assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_2, "s1", USER_10));
+        assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_3, "s1", USER_10));
+
+        assertFalse(bitmapDirectoryExists(CALLING_PACKAGE_1, USER_0));
+        assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_2, USER_0));
+        assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_3, USER_0));
+        assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_1, USER_10));
+        assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_2, USER_10));
+        assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_3, USER_10));
+
+        mService.mPackageMonitor.onReceive(getTestContext(),
+                genPackageDataClear(CALLING_PACKAGE_2, USER_10));
+
+        assertNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_1, "s1", USER_0));
+        assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_2, "s1", USER_0));
+        assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_3, "s1", USER_0));
+        assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_1, "s1", USER_10));
+        assertNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_2, "s1", USER_10));
+        assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_3, "s1", USER_10));
+
+        assertFalse(bitmapDirectoryExists(CALLING_PACKAGE_1, USER_0));
+        assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_2, USER_0));
+        assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_3, USER_0));
+        assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_1, USER_10));
+        assertFalse(bitmapDirectoryExists(CALLING_PACKAGE_2, USER_10));
+        assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_3, USER_10));
+    }
+
     public void testHandlePackageUpdate() throws Throwable {
 
         // Set up shortcuts and launchers.
diff --git a/tests/HwAccelerationTest/AndroidManifest.xml b/tests/HwAccelerationTest/AndroidManifest.xml
index b9e9ac8..3785cdc 100644
--- a/tests/HwAccelerationTest/AndroidManifest.xml
+++ b/tests/HwAccelerationTest/AndroidManifest.xml
@@ -383,6 +383,15 @@
         </activity>
 
         <activity
+                android:name="VideoViewCaptureActivity"
+                android:label="SurfaceView/GetBitmap with Video source">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="com.android.test.hwui.TEST" />
+            </intent-filter>
+        </activity>
+
+        <activity
                 android:name="GLTextureViewActivity"
                 android:label="TextureView/OpenGL">
             <intent-filter>
diff --git a/tests/HwAccelerationTest/res/drawable/default_wallpaper.png b/tests/HwAccelerationTest/res/drawable/default_wallpaper.png
index 187a6c0..91ad252 100644
--- a/tests/HwAccelerationTest/res/drawable/default_wallpaper.png
+++ b/tests/HwAccelerationTest/res/drawable/default_wallpaper.png
Binary files differ
diff --git a/tests/HwAccelerationTest/res/raw/colorgrid_video.mp4 b/tests/HwAccelerationTest/res/raw/colorgrid_video.mp4
new file mode 100644
index 0000000..1be8bee
--- /dev/null
+++ b/tests/HwAccelerationTest/res/raw/colorgrid_video.mp4
Binary files differ
diff --git a/tests/HwAccelerationTest/src/com/android/test/hwui/GetBitmapSurfaceViewActivity.java b/tests/HwAccelerationTest/src/com/android/test/hwui/GetBitmapSurfaceViewActivity.java
index f658b7c..6fe2cb4 100644
--- a/tests/HwAccelerationTest/src/com/android/test/hwui/GetBitmapSurfaceViewActivity.java
+++ b/tests/HwAccelerationTest/src/com/android/test/hwui/GetBitmapSurfaceViewActivity.java
@@ -23,6 +23,7 @@
 import android.os.Environment;
 import android.view.Gravity;
 import android.view.PixelCopy;
+import android.view.Surface;
 import android.view.SurfaceHolder;
 import android.view.SurfaceView;
 import android.view.View;
@@ -87,9 +88,42 @@
             android.util.Log.e("TextureView", "Cannot set preview texture target!", t);
         }
 
+        setCameraDisplayOrientation(this, 0, mCamera);
         mCamera.startPreview();
     }
 
+    public static void setCameraDisplayOrientation(Activity activity,
+            int cameraId, android.hardware.Camera camera) {
+        android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
+        android.hardware.Camera.getCameraInfo(cameraId, info);
+        int rotation = activity.getWindowManager().getDefaultDisplay()
+                .getRotation();
+        int degrees = 0;
+        switch (rotation) {
+            case Surface.ROTATION_0:
+                degrees = 0;
+                break;
+            case Surface.ROTATION_90:
+                degrees = 90;
+                break;
+            case Surface.ROTATION_180:
+                degrees = 180;
+                break;
+            case Surface.ROTATION_270:
+                degrees = 270;
+                break;
+        }
+
+        int result;
+        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
+            result = (info.orientation + degrees) % 360;
+            result = (360 - result) % 360; // compensate the mirror
+        } else { // back-facing
+            result = (info.orientation - degrees + 360) % 360;
+        }
+        camera.setDisplayOrientation(result);
+    }
+
     @Override
     public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
     }
diff --git a/tests/HwAccelerationTest/src/com/android/test/hwui/VideoViewCaptureActivity.java b/tests/HwAccelerationTest/src/com/android/test/hwui/VideoViewCaptureActivity.java
new file mode 100644
index 0000000..b87be80
--- /dev/null
+++ b/tests/HwAccelerationTest/src/com/android/test/hwui/VideoViewCaptureActivity.java
@@ -0,0 +1,89 @@
+/*
+ * 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.test.hwui;
+
+import android.app.Activity;
+import android.graphics.Bitmap;
+import android.net.Uri;
+import android.os.Bundle;
+import android.os.Environment;
+import android.view.PixelCopy;
+import android.view.View;
+import android.widget.Button;
+import android.widget.FrameLayout;
+import android.widget.LinearLayout;
+import android.widget.Toast;
+import android.widget.VideoView;
+
+import java.io.FileOutputStream;
+
+public class VideoViewCaptureActivity extends Activity {
+    private VideoView mVideoView;
+    private int mVideoWidth, mVideoHeight;
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        mVideoView = new VideoView(this);
+        mVideoView.setOnPreparedListener(mp -> {
+            mp.setLooping(true);
+            mVideoWidth = mp.getVideoWidth();
+            mVideoHeight = mp.getVideoHeight();
+            mVideoView.start();
+        });
+
+        Uri uri = Uri.parse("android.resource://com.android.test.hwui/" + R.raw.colorgrid_video);
+        mVideoView.setVideoURI(uri);
+
+        Button button = new Button(this);
+        button.setText("Copy bitmap to /sdcard/surfaceview.png");
+        button.setOnClickListener((View v) -> {
+            final Bitmap b = Bitmap.createBitmap(
+                    mVideoWidth, mVideoHeight,
+                    Bitmap.Config.ARGB_8888);
+            PixelCopy.request(mVideoView, b,
+                    (int result) -> {
+                        if (result != PixelCopy.SUCCESS) {
+                            Toast.makeText(VideoViewCaptureActivity.this,
+                                    "Failed to copy", Toast.LENGTH_SHORT).show();
+                            return;
+                        }
+                        try {
+                            try (FileOutputStream out = new FileOutputStream(
+                                    Environment.getExternalStorageDirectory() + "/surfaceview.png");) {
+                                b.compress(Bitmap.CompressFormat.PNG, 100, out);
+                            }
+                        } catch (Exception e) {
+                            // Ignore
+                        }
+                    }, mVideoView.getHandler());
+        });
+
+        FrameLayout content = new FrameLayout(this);
+        LinearLayout layout = new LinearLayout(this);
+        layout.setOrientation(LinearLayout.VERTICAL);
+        layout.addView(button, LinearLayout.LayoutParams.MATCH_PARENT,
+                LinearLayout.LayoutParams.WRAP_CONTENT);
+        layout.addView(mVideoView, LinearLayout.LayoutParams.MATCH_PARENT,
+                LinearLayout.LayoutParams.MATCH_PARENT);
+
+        content.addView(layout, new FrameLayout.LayoutParams(
+                FrameLayout.LayoutParams.MATCH_PARENT,
+                FrameLayout.LayoutParams.MATCH_PARENT));
+        setContentView(content);
+    }
+}
diff --git a/tools/aapt/Bundle.h b/tools/aapt/Bundle.h
index ca06ac4..653c1b4 100644
--- a/tools/aapt/Bundle.h
+++ b/tools/aapt/Bundle.h
@@ -55,7 +55,7 @@
           mCompressionMethod(0), mJunkPath(false), mOutputAPKFile(NULL),
           mManifestPackageNameOverride(NULL), mInstrumentationPackageNameOverride(NULL),
           mAutoAddOverlay(false), mGenDependencies(false), mNoVersionVectors(false),
-          mCrunchedOutputDir(NULL), mProguardFile(NULL),
+          mCrunchedOutputDir(NULL), mProguardFile(NULL), mMainDexProguardFile(NULL),
           mAndroidManifestFile(NULL), mPublicOutputFile(NULL),
           mRClassDir(NULL), mResourceIntermediatesDir(NULL), mManifestMinSdkVersion(NULL),
           mMinSdkVersion(NULL), mTargetSdkVersion(NULL), mMaxSdkVersion(NULL),
@@ -146,6 +146,8 @@
     void setCrunchedOutputDir(const char* dir) { mCrunchedOutputDir = dir; }
     const char* getProguardFile() const { return mProguardFile; }
     void setProguardFile(const char* file) { mProguardFile = file; }
+    const char* getMainDexProguardFile() const { return mMainDexProguardFile; }
+    void setMainDexProguardFile(const char* file) { mMainDexProguardFile = file; }
     const android::Vector<const char*>& getResourceSourceDirs() const { return mResourceSourceDirs; }
     void addResourceSourceDir(const char* dir) { mResourceSourceDirs.insertAt(dir,0); }
     const char* getAndroidManifestFile() const { return mAndroidManifestFile; }
@@ -299,6 +301,7 @@
     bool        mNoVersionVectors;
     const char* mCrunchedOutputDir;
     const char* mProguardFile;
+    const char* mMainDexProguardFile;
     const char* mAndroidManifestFile;
     const char* mPublicOutputFile;
     const char* mRClassDir;
diff --git a/tools/aapt/Command.cpp b/tools/aapt/Command.cpp
index db40416..9976d00 100644
--- a/tools/aapt/Command.cpp
+++ b/tools/aapt/Command.cpp
@@ -2631,6 +2631,12 @@
         goto bail;
     }
 
+    // Write out the Main Dex ProGuard file
+    err = writeMainDexProguardFile(bundle, assets);
+    if (err < 0) {
+        goto bail;
+    }
+
     // Write the apk
     if (outputAPKFile) {
         // Gather all resources and add them to the APK Builder. The builder will then
diff --git a/tools/aapt/Main.cpp b/tools/aapt/Main.cpp
index c424cc5..984d98e 100644
--- a/tools/aapt/Main.cpp
+++ b/tools/aapt/Main.cpp
@@ -67,6 +67,7 @@
         "        [--max-res-version VAL] \\\n"
         "        [-I base-package [-I base-package ...]] \\\n"
         "        [-A asset-source-dir]  [-G class-list-file] [-P public-definitions-file] \\\n"
+        "        [-D main-dex-class-list-file] \\\n"
         "        [-S resource-sources [-S resource-sources ...]] \\\n"
         "        [-F apk-file] [-J R-file-dir] \\\n"
         "        [--product product1,product2,...] \\\n"
@@ -120,6 +121,7 @@
         "       localization=\"suggested\"\n"
         "   -A  additional directory in which to find raw asset files\n"
         "   -G  A file to output proguard options into.\n"
+        "   -D  A file to output proguard options for the main dex into.\n"
         "   -F  specify the apk file to output\n"
         "   -I  add an existing package to base include set\n"
         "   -J  specify where to output R.java resource constant definitions\n"
@@ -390,6 +392,17 @@
                 convertPath(argv[0]);
                 bundle.setProguardFile(argv[0]);
                 break;
+            case 'D':
+                argc--;
+                argv++;
+                if (!argc) {
+                    fprintf(stderr, "ERROR: No argument supplied for '-D' option\n");
+                    wantUsage = true;
+                    goto bail;
+                }
+                convertPath(argv[0]);
+                bundle.setMainDexProguardFile(argv[0]);
+                break;
             case 'I':
                 argc--;
                 argv++;
diff --git a/tools/aapt/Main.h b/tools/aapt/Main.h
index e84c4c5..a493842 100644
--- a/tools/aapt/Main.h
+++ b/tools/aapt/Main.h
@@ -54,6 +54,7 @@
         bool includePrivate, bool emitCallback);
 
 extern android::status_t writeProguardFile(Bundle* bundle, const sp<AaptAssets>& assets);
+extern android::status_t writeMainDexProguardFile(Bundle* bundle, const sp<AaptAssets>& assets);
 
 extern bool isValidResourceType(const String8& type);
 
diff --git a/tools/aapt/Resource.cpp b/tools/aapt/Resource.cpp
index 18a1943..8e7045b 100644
--- a/tools/aapt/Resource.cpp
+++ b/tools/aapt/Resource.cpp
@@ -2832,7 +2832,7 @@
 }
 
 status_t
-writeProguardForAndroidManifest(ProguardKeepSet* keep, const sp<AaptAssets>& assets)
+writeProguardForAndroidManifest(ProguardKeepSet* keep, const sp<AaptAssets>& assets, bool mainDex)
 {
     status_t err;
     ResXMLTree tree;
@@ -2844,6 +2844,7 @@
     sp<AaptGroup> assGroup;
     sp<AaptFile> assFile;
     String8 pkg;
+    String8 defaultProcess;
 
     // First, look for a package file to parse.  This is required to
     // be able to generate the resource information.
@@ -2900,6 +2901,15 @@
                     addProguardKeepRule(keep, agent, pkg.string(),
                             assFile->getPrintableSource(), tree.getLineNumber());
                 }
+
+                if (mainDex) {
+                    defaultProcess = AaptXml::getAttribute(tree,
+                            "http://schemas.android.com/apk/res/android", "process", &error);
+                    if (error != "") {
+                        fprintf(stderr, "ERROR: %s\n", error.string());
+                        return -1;
+                    }
+                }
             } else if (tag == "instrumentation") {
                 keepTag = true;
             }
@@ -2916,7 +2926,23 @@
                 fprintf(stderr, "ERROR: %s\n", error.string());
                 return -1;
             }
-            if (name.length() > 0) {
+
+            keepTag = name.length() > 0;
+
+            if (keepTag && mainDex) {
+                String8 componentProcess = AaptXml::getAttribute(tree,
+                        "http://schemas.android.com/apk/res/android", "process", &error);
+                if (error != "") {
+                    fprintf(stderr, "ERROR: %s\n", error.string());
+                    return -1;
+                }
+
+                const String8& process =
+                        componentProcess.length() > 0 ? componentProcess : defaultProcess;
+                keepTag = process.length() > 0 && process.find(":") != 0;
+            }
+
+            if (keepTag) {
                 addProguardKeepRule(keep, name, pkg.string(),
                         assFile->getPrintableSource(), tree.getLineNumber());
             }
@@ -3099,30 +3125,12 @@
 }
 
 status_t
-writeProguardFile(Bundle* bundle, const sp<AaptAssets>& assets)
+writeProguardSpec(const char* filename, const ProguardKeepSet& keep, status_t err)
 {
-    status_t err = -1;
-
-    if (!bundle->getProguardFile()) {
-        return NO_ERROR;
-    }
-
-    ProguardKeepSet keep;
-
-    err = writeProguardForAndroidManifest(&keep, assets);
-    if (err < 0) {
-        return err;
-    }
-
-    err = writeProguardForLayouts(&keep, assets);
-    if (err < 0) {
-        return err;
-    }
-
-    FILE* fp = fopen(bundle->getProguardFile(), "w+");
+    FILE* fp = fopen(filename, "w+");
     if (fp == NULL) {
         fprintf(stderr, "ERROR: Unable to open class file %s: %s\n",
-                bundle->getProguardFile(), strerror(errno));
+                filename, strerror(errno));
         return UNKNOWN_ERROR;
     }
 
@@ -3141,6 +3149,49 @@
     return err;
 }
 
+status_t
+writeProguardFile(Bundle* bundle, const sp<AaptAssets>& assets)
+{
+    status_t err = -1;
+
+    if (!bundle->getProguardFile()) {
+        return NO_ERROR;
+    }
+
+    ProguardKeepSet keep;
+
+    err = writeProguardForAndroidManifest(&keep, assets, false);
+    if (err < 0) {
+        return err;
+    }
+
+    err = writeProguardForLayouts(&keep, assets);
+    if (err < 0) {
+        return err;
+    }
+
+    return writeProguardSpec(bundle->getProguardFile(), keep, err);
+}
+
+status_t
+writeMainDexProguardFile(Bundle* bundle, const sp<AaptAssets>& assets)
+{
+    status_t err = -1;
+
+    if (!bundle->getMainDexProguardFile()) {
+        return NO_ERROR;
+    }
+
+    ProguardKeepSet keep;
+
+    err = writeProguardForAndroidManifest(&keep, assets, true);
+    if (err < 0) {
+        return err;
+    }
+
+    return writeProguardSpec(bundle->getMainDexProguardFile(), keep, err);
+}
+
 // Loops through the string paths and writes them to the file pointer
 // Each file path is written on its own line with a terminating backslash.
 status_t writePathsToFile(const sp<FilePathStore>& files, FILE* fp)
diff --git a/tools/aapt2/link/Link.cpp b/tools/aapt2/link/Link.cpp
index 8c8bffa..4997120 100644
--- a/tools/aapt2/link/Link.cpp
+++ b/tools/aapt2/link/Link.cpp
@@ -1459,6 +1459,21 @@
         return 1;
     }
 
+    // Expand all argument-files passed into the command line. These start with '@'.
+    std::vector<std::string> argList;
+    for (const std::string& arg : flags.getArgs()) {
+        if (util::stringStartsWith<char>(arg, "@")) {
+            const std::string path = arg.substr(1, arg.size() - 1);
+            std::string error;
+            if (!file::appendArgsFromFile(path, &argList, &error)) {
+                context.getDiagnostics()->error(DiagMessage(path) << error);
+                return 1;
+            }
+        } else {
+            argList.push_back(arg);
+        }
+    }
+
     if (verbose) {
         context.setVerbose(verbose);
     }
@@ -1568,7 +1583,7 @@
     }
 
     LinkCommand cmd(&context, options);
-    return cmd.run(flags.getArgs());
+    return cmd.run(argList);
 }
 
 } // namespace aapt
diff --git a/tools/aapt2/util/Files.cpp b/tools/aapt2/util/Files.cpp
index bb093ab..f5e49f1 100644
--- a/tools/aapt2/util/Files.cpp
+++ b/tools/aapt2/util/Files.cpp
@@ -18,6 +18,7 @@
 #include "util/Util.h"
 
 #include <algorithm>
+#include <android-base/file.h>
 #include <cerrno>
 #include <cstdio>
 #include <dirent.h>
@@ -190,6 +191,23 @@
     return std::move(fileMap);
 }
 
+bool appendArgsFromFile(const StringPiece& path, std::vector<std::string>* outArgList,
+                        std::string* outError) {
+    std::string contents;
+    if (!android::base::ReadFileToString(path.toString(), &contents)) {
+        if (outError) *outError = "failed to read argument-list file";
+        return false;
+    }
+
+    for (StringPiece line : util::tokenize<char>(contents, ' ')) {
+        line = util::trimWhitespace(line);
+        if (!line.empty()) {
+            outArgList->push_back(line.toString());
+        }
+    }
+    return true;
+}
+
 bool FileFilter::setPattern(const StringPiece& pattern) {
     mPatternTokens = util::splitAndLowercase(pattern, ':');
     return true;
diff --git a/tools/aapt2/util/Files.h b/tools/aapt2/util/Files.h
index c2e6115..4d8a1fe 100644
--- a/tools/aapt2/util/Files.h
+++ b/tools/aapt2/util/Files.h
@@ -95,6 +95,12 @@
  */
 Maybe<android::FileMap> mmapPath(const StringPiece& path, std::string* outError);
 
+/**
+ * Reads the file at path and appends each line to the outArgList vector.
+ */
+bool appendArgsFromFile(const StringPiece& path, std::vector<std::string>* outArgList,
+                        std::string* outError);
+
 /*
  * Filter that determines which resource files/directories are
  * processed by AAPT. Takes a pattern string supplied by the user.
diff --git a/tools/fonts/fontchain_lint.py b/tools/fonts/fontchain_lint.py
index 81ab3cc..fe7c3b9 100755
--- a/tools/fonts/fontchain_lint.py
+++ b/tools/fonts/fontchain_lint.py
@@ -330,7 +330,7 @@
         0x2764, # HEAVY BLACK HEART
     }
     assert missing_text_chars == set(), (
-        'Text style version of some emoji characters are missing.')
+        'Text style version of some emoji characters are missing: ' + repr(missing_text_chars))
 
 
 # Setting reverse to true returns a dictionary that maps the values to sets of
@@ -411,6 +411,20 @@
     _emoji_zwj_sequences = parse_unicode_datafile(
         path.join(ucd_path, 'emoji-zwj-sequences.txt'))
 
+    # filter modern pentathlon, as it seems likely to be removed from final spec
+    def is_excluded(n):
+        return n == 0x1f93b
+
+    def contains_excluded(t):
+        if type(t) == int:
+            return is_excluded(t)
+        return any(is_excluded(cp) for cp in t)
+
+    # filter modern pentathlon, as it seems likely to be removed from final spec
+    _emoji_properties['Emoji'] = set(
+        t for t in _emoji_properties['Emoji'] if not contains_excluded(t))
+    _emoji_sequences = dict(
+        (t, v) for (t, v) in _emoji_sequences.items() if not contains_excluded(t))
 
 def flag_sequence(territory_code):
     return tuple(0x1F1E6 + ord(ch) - ord('A') for ch in territory_code)
diff --git a/tools/layoutlib/Android.mk b/tools/layoutlib/Android.mk
index 663e1e2..f87f6c5 100644
--- a/tools/layoutlib/Android.mk
+++ b/tools/layoutlib/Android.mk
@@ -16,8 +16,6 @@
 LOCAL_PATH := $(my-dir)
 include $(CLEAR_VARS)
 
-LOCAL_JAVA_LANGUAGE_VERSION := 1.8
-
 #
 # Define rules to build temp_layoutlib.jar, which contains a subset of
 # the classes in framework.jar.  The layoutlib_create tool is used to
diff --git a/tools/layoutlib/bridge/Android.mk b/tools/layoutlib/bridge/Android.mk
index 16e5913..3dd8002 100644
--- a/tools/layoutlib/bridge/Android.mk
+++ b/tools/layoutlib/bridge/Android.mk
@@ -18,7 +18,6 @@
 
 LOCAL_SRC_FILES := $(call all-java-files-under,src)
 LOCAL_JAVA_RESOURCE_DIRS := resources
-LOCAL_JAVA_LANGUAGE_VERSION := 1.8
 
 LOCAL_JAVA_LIBRARIES := \
 	layoutlib_api-prebuilt \
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeContext.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeContext.java
index 80e230c..f87269b 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeContext.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeContext.java
@@ -861,7 +861,9 @@
                         resValue = mRenderResources.resolveResValue(resValue);
 
                         if (defaultPropMap != null) {
-                            defaultPropMap.put(attrName,
+                            defaultPropMap.put(
+                                    frameworkAttr ? SdkConstants.PREFIX_ANDROID + attrName :
+                                            attrName,
                                     new Property(preResolve, resValue.getValue()));
                         }
 
@@ -932,7 +934,8 @@
             @Nullable StyleResourceValue style, int[] attrs) throws Resources.NotFoundException {
         List<Pair<String, Boolean>> attributes = searchAttrs(attrs);
 
-        BridgeTypedArray ta = Resources_Delegate.newTypeArray(mSystemResources, attrs.length, false);
+        BridgeTypedArray ta =
+                Resources_Delegate.newTypeArray(mSystemResources, attrs.length, false);
 
         PropertiesMap defaultPropMap = new PropertiesMap();
         // for each attribute, get its name so that we can search it in the style
@@ -943,11 +946,11 @@
                 // look for the value in the given style
                 ResourceValue resValue;
                 String attrName = attribute.getFirst();
+                boolean frameworkAttr = attribute.getSecond();
                 if (style != null) {
-                    resValue = mRenderResources.findItemInStyle(style, attrName,
-                            attribute.getSecond());
+                    resValue = mRenderResources.findItemInStyle(style, attrName, frameworkAttr);
                 } else {
-                    resValue = mRenderResources.findItemInTheme(attrName, attribute.getSecond());
+                    resValue = mRenderResources.findItemInTheme(attrName, frameworkAttr);
                 }
 
                 if (resValue != null) {
@@ -955,8 +958,10 @@
                     String preResolve = resValue.getValue();
                     // resolve it to make sure there are no references left.
                     resValue = mRenderResources.resolveResValue(resValue);
-                    ta.bridgeSetValue(i, attrName, attribute.getSecond(), resValue);
-                    defaultPropMap.put(attrName, new Property(preResolve, resValue.getValue()));
+                    ta.bridgeSetValue(i, attrName, frameworkAttr, resValue);
+                    defaultPropMap.put(
+                            frameworkAttr ? SdkConstants.ANDROID_PREFIX + attrName : attrName,
+                            new Property(preResolve, resValue.getValue()));
                 }
             }
         }
diff --git a/tools/layoutlib/bridge/tests/Android.mk b/tools/layoutlib/bridge/tests/Android.mk
index 5c062d0..8a81d0b 100644
--- a/tools/layoutlib/bridge/tests/Android.mk
+++ b/tools/layoutlib/bridge/tests/Android.mk
@@ -16,8 +16,6 @@
 
 include $(CLEAR_VARS)
 
-LOCAL_JAVA_LANGUAGE_VERSION := 1.8
-
 # Only compile source java files in this lib.
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 LOCAL_JAVA_RESOURCE_DIRS := res
diff --git a/tools/layoutlib/create/Android.mk b/tools/layoutlib/create/Android.mk
index 47377ae..c7f2c41 100644
--- a/tools/layoutlib/create/Android.mk
+++ b/tools/layoutlib/create/Android.mk
@@ -16,8 +16,6 @@
 LOCAL_PATH := $(call my-dir)
 include $(CLEAR_VARS)
 
-LOCAL_JAVA_LANGUAGE_VERSION := 1.8
-
 LOCAL_SRC_FILES := $(call all-java-files-under,src)
 
 LOCAL_JAR_MANIFEST := manifest.txt
diff --git a/tools/layoutlib/create/tests/Android.mk b/tools/layoutlib/create/tests/Android.mk
index c59528e..dafb9c6 100644
--- a/tools/layoutlib/create/tests/Android.mk
+++ b/tools/layoutlib/create/tests/Android.mk
@@ -15,8 +15,6 @@
 LOCAL_PATH := $(call my-dir)
 include $(CLEAR_VARS)
 
-LOCAL_JAVA_LANGUAGE_VERSION := 1.8
-
 # Only compile source java files in this lib.
 LOCAL_SRC_FILES := $(call all-java-files-under, com)