Merge "Don't show alert window notifications when in Vr mode." into oc-dev
diff --git a/api/current.txt b/api/current.txt
index a8e5da8..2723f4d 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -12429,7 +12429,9 @@
     method public static android.graphics.Bitmap createBitmap(int, int, android.graphics.Bitmap.Config);
     method public static android.graphics.Bitmap createBitmap(android.util.DisplayMetrics, int, int, android.graphics.Bitmap.Config);
     method public static android.graphics.Bitmap createBitmap(int, int, android.graphics.Bitmap.Config, boolean);
+    method public static android.graphics.Bitmap createBitmap(int, int, android.graphics.Bitmap.Config, boolean, android.graphics.ColorSpace);
     method public static android.graphics.Bitmap createBitmap(android.util.DisplayMetrics, int, int, android.graphics.Bitmap.Config, boolean);
+    method public static android.graphics.Bitmap createBitmap(android.util.DisplayMetrics, int, int, android.graphics.Bitmap.Config, boolean, android.graphics.ColorSpace);
     method public static android.graphics.Bitmap createBitmap(int[], int, int, int, int, android.graphics.Bitmap.Config);
     method public static android.graphics.Bitmap createBitmap(android.util.DisplayMetrics, int[], int, int, int, int, android.graphics.Bitmap.Config);
     method public static android.graphics.Bitmap createBitmap(int[], int, int, android.graphics.Bitmap.Config);
@@ -15950,7 +15952,7 @@
     method public java.lang.String getSerial();
     method public boolean releaseInterface(android.hardware.usb.UsbInterface);
     method public android.hardware.usb.UsbRequest requestWait();
-    method public android.hardware.usb.UsbRequest requestWait(int);
+    method public android.hardware.usb.UsbRequest requestWait(long) throws java.util.concurrent.TimeoutException;
     method public boolean setConfiguration(android.hardware.usb.UsbConfiguration);
     method public boolean setInterface(android.hardware.usb.UsbInterface);
   }
@@ -21478,40 +21480,6 @@
     method public default void onRoutingChanged(android.media.AudioRouting);
   }
 
-  public final class BufferingParams implements android.os.Parcelable {
-    method public int describeContents();
-    method public int getInitialBufferingMode();
-    method public int getInitialBufferingWatermarkKB();
-    method public int getInitialBufferingWatermarkMs();
-    method public int getRebufferingMode();
-    method public int getRebufferingWatermarkHighKB();
-    method public int getRebufferingWatermarkHighMs();
-    method public int getRebufferingWatermarkLowKB();
-    method public int getRebufferingWatermarkLowMs();
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final int BUFFERING_MODE_NONE = 0; // 0x0
-    field public static final int BUFFERING_MODE_SIZE_ONLY = 2; // 0x2
-    field public static final int BUFFERING_MODE_TIME_ONLY = 1; // 0x1
-    field public static final int BUFFERING_MODE_TIME_THEN_SIZE = 3; // 0x3
-    field public static final android.os.Parcelable.Creator<android.media.BufferingParams> CREATOR;
-  }
-
-  public static class BufferingParams.Builder {
-    ctor public BufferingParams.Builder();
-    ctor public BufferingParams.Builder(android.media.BufferingParams);
-    method public android.media.BufferingParams build();
-    method public android.media.BufferingParams.Builder setInitialBufferingMode(int);
-    method public android.media.BufferingParams.Builder setInitialBufferingWatermarkKB(int);
-    method public android.media.BufferingParams.Builder setInitialBufferingWatermarkMs(int);
-    method public android.media.BufferingParams.Builder setRebufferingMode(int);
-    method public android.media.BufferingParams.Builder setRebufferingWatermarkHighKB(int);
-    method public android.media.BufferingParams.Builder setRebufferingWatermarkHighMs(int);
-    method public android.media.BufferingParams.Builder setRebufferingWatermarkLowKB(int);
-    method public android.media.BufferingParams.Builder setRebufferingWatermarkLowMs(int);
-    method public android.media.BufferingParams.Builder setRebufferingWatermarksKB(int, int);
-    method public android.media.BufferingParams.Builder setRebufferingWatermarksMs(int, int);
-  }
-
   public class CamcorderProfile {
     method public static android.media.CamcorderProfile get(int);
     method public static android.media.CamcorderProfile get(int, int);
@@ -22816,9 +22784,7 @@
     method public android.media.VolumeShaper createVolumeShaper(android.media.VolumeShaper.Configuration);
     method public void deselectTrack(int) throws java.lang.IllegalStateException;
     method public int getAudioSessionId();
-    method public android.media.BufferingParams getBufferingParams();
     method public int getCurrentPosition();
-    method public android.media.BufferingParams getDefaultBufferingParams();
     method public android.media.MediaPlayer.DrmInfo getDrmInfo();
     method public java.lang.String getDrmPropertyString(java.lang.String) throws android.media.MediaPlayer.NoDrmSchemeException;
     method public int getDuration();
@@ -22849,7 +22815,6 @@
     method public void setAudioSessionId(int) throws java.lang.IllegalArgumentException, java.lang.IllegalStateException;
     method public deprecated void setAudioStreamType(int);
     method public void setAuxEffectSendLevel(float);
-    method public void setBufferingParams(android.media.BufferingParams);
     method public void setDataSource(android.content.Context, android.net.Uri) throws java.io.IOException, java.lang.IllegalArgumentException, java.lang.IllegalStateException, java.lang.SecurityException;
     method public void setDataSource(android.content.Context, android.net.Uri, java.util.Map<java.lang.String, java.lang.String>, java.util.List<java.net.HttpCookie>) throws java.io.IOException, java.lang.IllegalArgumentException, java.lang.IllegalStateException, java.lang.SecurityException;
     method public void setDataSource(android.content.Context, android.net.Uri, java.util.Map<java.lang.String, java.lang.String>) throws java.io.IOException, java.lang.IllegalArgumentException, java.lang.IllegalStateException, java.lang.SecurityException;
@@ -39528,6 +39493,7 @@
     field public static final java.lang.String KEY_GSM_ROAMING_NETWORKS_STRING_ARRAY = "gsm_roaming_networks_string_array";
     field public static final java.lang.String KEY_HAS_IN_CALL_NOISE_SUPPRESSION_BOOL = "has_in_call_noise_suppression_bool";
     field public static final java.lang.String KEY_HIDE_CARRIER_NETWORK_SETTINGS_BOOL = "hide_carrier_network_settings_bool";
+    field public static final java.lang.String KEY_HIDE_ENHANCED_4G_LTE_BOOL = "hide_enhanced_4g_lte_bool";
     field public static final java.lang.String KEY_HIDE_IMS_APN_BOOL = "hide_ims_apn_bool";
     field public static final java.lang.String KEY_HIDE_PREFERRED_NETWORK_TYPE_BOOL = "hide_preferred_network_type_bool";
     field public static final java.lang.String KEY_HIDE_SIM_LOCK_SETTINGS_BOOL = "hide_sim_lock_settings_bool";
@@ -40153,7 +40119,6 @@
     method public boolean isVoicemailVibrationEnabled(android.telecom.PhoneAccountHandle);
     method public boolean isWorldPhone();
     method public void listen(android.telephony.PhoneStateListener, int);
-    method public deprecated boolean sendDialerCode(java.lang.String);
     method public void sendDialerSpecialCode(java.lang.String);
     method public java.lang.String sendEnvelopeWithStatus(java.lang.String);
     method public void sendUssdRequest(java.lang.String, android.telephony.TelephonyManager.UssdResponseCallback, android.os.Handler);
diff --git a/api/system-current.txt b/api/system-current.txt
index 4bf1d6b..895a5d4 100644
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -13192,7 +13192,9 @@
     method public static android.graphics.Bitmap createBitmap(int, int, android.graphics.Bitmap.Config);
     method public static android.graphics.Bitmap createBitmap(android.util.DisplayMetrics, int, int, android.graphics.Bitmap.Config);
     method public static android.graphics.Bitmap createBitmap(int, int, android.graphics.Bitmap.Config, boolean);
+    method public static android.graphics.Bitmap createBitmap(int, int, android.graphics.Bitmap.Config, boolean, android.graphics.ColorSpace);
     method public static android.graphics.Bitmap createBitmap(android.util.DisplayMetrics, int, int, android.graphics.Bitmap.Config, boolean);
+    method public static android.graphics.Bitmap createBitmap(android.util.DisplayMetrics, int, int, android.graphics.Bitmap.Config, boolean, android.graphics.ColorSpace);
     method public static android.graphics.Bitmap createBitmap(int[], int, int, int, int, android.graphics.Bitmap.Config);
     method public static android.graphics.Bitmap createBitmap(android.util.DisplayMetrics, int[], int, int, int, int, android.graphics.Bitmap.Config);
     method public static android.graphics.Bitmap createBitmap(int[], int, int, android.graphics.Bitmap.Config);
@@ -17440,7 +17442,7 @@
     method public java.lang.String getSerial();
     method public boolean releaseInterface(android.hardware.usb.UsbInterface);
     method public android.hardware.usb.UsbRequest requestWait();
-    method public android.hardware.usb.UsbRequest requestWait(int);
+    method public android.hardware.usb.UsbRequest requestWait(long) throws java.util.concurrent.TimeoutException;
     method public boolean resetDevice();
     method public boolean setConfiguration(android.hardware.usb.UsbConfiguration);
     method public boolean setInterface(android.hardware.usb.UsbInterface);
@@ -23303,40 +23305,6 @@
     method public default void onRoutingChanged(android.media.AudioRouting);
   }
 
-  public final class BufferingParams implements android.os.Parcelable {
-    method public int describeContents();
-    method public int getInitialBufferingMode();
-    method public int getInitialBufferingWatermarkKB();
-    method public int getInitialBufferingWatermarkMs();
-    method public int getRebufferingMode();
-    method public int getRebufferingWatermarkHighKB();
-    method public int getRebufferingWatermarkHighMs();
-    method public int getRebufferingWatermarkLowKB();
-    method public int getRebufferingWatermarkLowMs();
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final int BUFFERING_MODE_NONE = 0; // 0x0
-    field public static final int BUFFERING_MODE_SIZE_ONLY = 2; // 0x2
-    field public static final int BUFFERING_MODE_TIME_ONLY = 1; // 0x1
-    field public static final int BUFFERING_MODE_TIME_THEN_SIZE = 3; // 0x3
-    field public static final android.os.Parcelable.Creator<android.media.BufferingParams> CREATOR;
-  }
-
-  public static class BufferingParams.Builder {
-    ctor public BufferingParams.Builder();
-    ctor public BufferingParams.Builder(android.media.BufferingParams);
-    method public android.media.BufferingParams build();
-    method public android.media.BufferingParams.Builder setInitialBufferingMode(int);
-    method public android.media.BufferingParams.Builder setInitialBufferingWatermarkKB(int);
-    method public android.media.BufferingParams.Builder setInitialBufferingWatermarkMs(int);
-    method public android.media.BufferingParams.Builder setRebufferingMode(int);
-    method public android.media.BufferingParams.Builder setRebufferingWatermarkHighKB(int);
-    method public android.media.BufferingParams.Builder setRebufferingWatermarkHighMs(int);
-    method public android.media.BufferingParams.Builder setRebufferingWatermarkLowKB(int);
-    method public android.media.BufferingParams.Builder setRebufferingWatermarkLowMs(int);
-    method public android.media.BufferingParams.Builder setRebufferingWatermarksKB(int, int);
-    method public android.media.BufferingParams.Builder setRebufferingWatermarksMs(int, int);
-  }
-
   public class CamcorderProfile {
     method public static android.media.CamcorderProfile get(int);
     method public static android.media.CamcorderProfile get(int, int);
@@ -24641,9 +24609,7 @@
     method public android.media.VolumeShaper createVolumeShaper(android.media.VolumeShaper.Configuration);
     method public void deselectTrack(int) throws java.lang.IllegalStateException;
     method public int getAudioSessionId();
-    method public android.media.BufferingParams getBufferingParams();
     method public int getCurrentPosition();
-    method public android.media.BufferingParams getDefaultBufferingParams();
     method public android.media.MediaPlayer.DrmInfo getDrmInfo();
     method public java.lang.String getDrmPropertyString(java.lang.String) throws android.media.MediaPlayer.NoDrmSchemeException;
     method public int getDuration();
@@ -24674,7 +24640,6 @@
     method public void setAudioSessionId(int) throws java.lang.IllegalArgumentException, java.lang.IllegalStateException;
     method public deprecated void setAudioStreamType(int);
     method public void setAuxEffectSendLevel(float);
-    method public void setBufferingParams(android.media.BufferingParams);
     method public void setDataSource(android.content.Context, android.net.Uri) throws java.io.IOException, java.lang.IllegalArgumentException, java.lang.IllegalStateException, java.lang.SecurityException;
     method public void setDataSource(android.content.Context, android.net.Uri, java.util.Map<java.lang.String, java.lang.String>, java.util.List<java.net.HttpCookie>) throws java.io.IOException, java.lang.IllegalArgumentException, java.lang.IllegalStateException, java.lang.SecurityException;
     method public void setDataSource(android.content.Context, android.net.Uri, java.util.Map<java.lang.String, java.lang.String>) throws java.io.IOException, java.lang.IllegalArgumentException, java.lang.IllegalStateException, java.lang.SecurityException;
@@ -42975,6 +42940,7 @@
     field public static final java.lang.String KEY_GSM_ROAMING_NETWORKS_STRING_ARRAY = "gsm_roaming_networks_string_array";
     field public static final java.lang.String KEY_HAS_IN_CALL_NOISE_SUPPRESSION_BOOL = "has_in_call_noise_suppression_bool";
     field public static final java.lang.String KEY_HIDE_CARRIER_NETWORK_SETTINGS_BOOL = "hide_carrier_network_settings_bool";
+    field public static final java.lang.String KEY_HIDE_ENHANCED_4G_LTE_BOOL = "hide_enhanced_4g_lte_bool";
     field public static final java.lang.String KEY_HIDE_IMS_APN_BOOL = "hide_ims_apn_bool";
     field public static final java.lang.String KEY_HIDE_PREFERRED_NETWORK_TYPE_BOOL = "hide_preferred_network_type_bool";
     field public static final java.lang.String KEY_HIDE_SIM_LOCK_SETTINGS_BOOL = "hide_sim_lock_settings_bool";
@@ -43653,7 +43619,6 @@
     method public boolean isWorldPhone();
     method public void listen(android.telephony.PhoneStateListener, int);
     method public boolean needsOtaServiceProvisioning();
-    method public deprecated boolean sendDialerCode(java.lang.String);
     method public void sendDialerSpecialCode(java.lang.String);
     method public java.lang.String sendEnvelopeWithStatus(java.lang.String);
     method public void sendUssdRequest(java.lang.String, android.telephony.TelephonyManager.UssdResponseCallback, android.os.Handler);
diff --git a/api/test-current.txt b/api/test-current.txt
index 82d5080..67416fb 100644
--- a/api/test-current.txt
+++ b/api/test-current.txt
@@ -12479,7 +12479,9 @@
     method public static android.graphics.Bitmap createBitmap(int, int, android.graphics.Bitmap.Config);
     method public static android.graphics.Bitmap createBitmap(android.util.DisplayMetrics, int, int, android.graphics.Bitmap.Config);
     method public static android.graphics.Bitmap createBitmap(int, int, android.graphics.Bitmap.Config, boolean);
+    method public static android.graphics.Bitmap createBitmap(int, int, android.graphics.Bitmap.Config, boolean, android.graphics.ColorSpace);
     method public static android.graphics.Bitmap createBitmap(android.util.DisplayMetrics, int, int, android.graphics.Bitmap.Config, boolean);
+    method public static android.graphics.Bitmap createBitmap(android.util.DisplayMetrics, int, int, android.graphics.Bitmap.Config, boolean, android.graphics.ColorSpace);
     method public static android.graphics.Bitmap createBitmap(int[], int, int, int, int, android.graphics.Bitmap.Config);
     method public static android.graphics.Bitmap createBitmap(android.util.DisplayMetrics, int[], int, int, int, int, android.graphics.Bitmap.Config);
     method public static android.graphics.Bitmap createBitmap(int[], int, int, android.graphics.Bitmap.Config);
@@ -16005,7 +16007,7 @@
     method public java.lang.String getSerial();
     method public boolean releaseInterface(android.hardware.usb.UsbInterface);
     method public android.hardware.usb.UsbRequest requestWait();
-    method public android.hardware.usb.UsbRequest requestWait(int);
+    method public android.hardware.usb.UsbRequest requestWait(long) throws java.util.concurrent.TimeoutException;
     method public boolean setConfiguration(android.hardware.usb.UsbConfiguration);
     method public boolean setInterface(android.hardware.usb.UsbInterface);
   }
@@ -21591,40 +21593,6 @@
     method public default void onRoutingChanged(android.media.AudioRouting);
   }
 
-  public final class BufferingParams implements android.os.Parcelable {
-    method public int describeContents();
-    method public int getInitialBufferingMode();
-    method public int getInitialBufferingWatermarkKB();
-    method public int getInitialBufferingWatermarkMs();
-    method public int getRebufferingMode();
-    method public int getRebufferingWatermarkHighKB();
-    method public int getRebufferingWatermarkHighMs();
-    method public int getRebufferingWatermarkLowKB();
-    method public int getRebufferingWatermarkLowMs();
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final int BUFFERING_MODE_NONE = 0; // 0x0
-    field public static final int BUFFERING_MODE_SIZE_ONLY = 2; // 0x2
-    field public static final int BUFFERING_MODE_TIME_ONLY = 1; // 0x1
-    field public static final int BUFFERING_MODE_TIME_THEN_SIZE = 3; // 0x3
-    field public static final android.os.Parcelable.Creator<android.media.BufferingParams> CREATOR;
-  }
-
-  public static class BufferingParams.Builder {
-    ctor public BufferingParams.Builder();
-    ctor public BufferingParams.Builder(android.media.BufferingParams);
-    method public android.media.BufferingParams build();
-    method public android.media.BufferingParams.Builder setInitialBufferingMode(int);
-    method public android.media.BufferingParams.Builder setInitialBufferingWatermarkKB(int);
-    method public android.media.BufferingParams.Builder setInitialBufferingWatermarkMs(int);
-    method public android.media.BufferingParams.Builder setRebufferingMode(int);
-    method public android.media.BufferingParams.Builder setRebufferingWatermarkHighKB(int);
-    method public android.media.BufferingParams.Builder setRebufferingWatermarkHighMs(int);
-    method public android.media.BufferingParams.Builder setRebufferingWatermarkLowKB(int);
-    method public android.media.BufferingParams.Builder setRebufferingWatermarkLowMs(int);
-    method public android.media.BufferingParams.Builder setRebufferingWatermarksKB(int, int);
-    method public android.media.BufferingParams.Builder setRebufferingWatermarksMs(int, int);
-  }
-
   public class CamcorderProfile {
     method public static android.media.CamcorderProfile get(int);
     method public static android.media.CamcorderProfile get(int, int);
@@ -22929,9 +22897,7 @@
     method public android.media.VolumeShaper createVolumeShaper(android.media.VolumeShaper.Configuration);
     method public void deselectTrack(int) throws java.lang.IllegalStateException;
     method public int getAudioSessionId();
-    method public android.media.BufferingParams getBufferingParams();
     method public int getCurrentPosition();
-    method public android.media.BufferingParams getDefaultBufferingParams();
     method public android.media.MediaPlayer.DrmInfo getDrmInfo();
     method public java.lang.String getDrmPropertyString(java.lang.String) throws android.media.MediaPlayer.NoDrmSchemeException;
     method public int getDuration();
@@ -22962,7 +22928,6 @@
     method public void setAudioSessionId(int) throws java.lang.IllegalArgumentException, java.lang.IllegalStateException;
     method public deprecated void setAudioStreamType(int);
     method public void setAuxEffectSendLevel(float);
-    method public void setBufferingParams(android.media.BufferingParams);
     method public void setDataSource(android.content.Context, android.net.Uri) throws java.io.IOException, java.lang.IllegalArgumentException, java.lang.IllegalStateException, java.lang.SecurityException;
     method public void setDataSource(android.content.Context, android.net.Uri, java.util.Map<java.lang.String, java.lang.String>, java.util.List<java.net.HttpCookie>) throws java.io.IOException, java.lang.IllegalArgumentException, java.lang.IllegalStateException, java.lang.SecurityException;
     method public void setDataSource(android.content.Context, android.net.Uri, java.util.Map<java.lang.String, java.lang.String>) throws java.io.IOException, java.lang.IllegalArgumentException, java.lang.IllegalStateException, java.lang.SecurityException;
@@ -39727,6 +39692,7 @@
     field public static final java.lang.String KEY_GSM_ROAMING_NETWORKS_STRING_ARRAY = "gsm_roaming_networks_string_array";
     field public static final java.lang.String KEY_HAS_IN_CALL_NOISE_SUPPRESSION_BOOL = "has_in_call_noise_suppression_bool";
     field public static final java.lang.String KEY_HIDE_CARRIER_NETWORK_SETTINGS_BOOL = "hide_carrier_network_settings_bool";
+    field public static final java.lang.String KEY_HIDE_ENHANCED_4G_LTE_BOOL = "hide_enhanced_4g_lte_bool";
     field public static final java.lang.String KEY_HIDE_IMS_APN_BOOL = "hide_ims_apn_bool";
     field public static final java.lang.String KEY_HIDE_PREFERRED_NETWORK_TYPE_BOOL = "hide_preferred_network_type_bool";
     field public static final java.lang.String KEY_HIDE_SIM_LOCK_SETTINGS_BOOL = "hide_sim_lock_settings_bool";
@@ -40352,7 +40318,6 @@
     method public boolean isVoicemailVibrationEnabled(android.telecom.PhoneAccountHandle);
     method public boolean isWorldPhone();
     method public void listen(android.telephony.PhoneStateListener, int);
-    method public deprecated boolean sendDialerCode(java.lang.String);
     method public void sendDialerSpecialCode(java.lang.String);
     method public java.lang.String sendEnvelopeWithStatus(java.lang.String);
     method public void sendUssdRequest(java.lang.String, android.telephony.TelephonyManager.UssdResponseCallback, android.os.Handler);
diff --git a/core/java/android/app/ActivityManager.java b/core/java/android/app/ActivityManager.java
index 4004bd6..e288387 100644
--- a/core/java/android/app/ActivityManager.java
+++ b/core/java/android/app/ActivityManager.java
@@ -1118,6 +1118,16 @@
     }
 
     /**
+     * Returns true if the system supports running activities on secondary displays.
+     * @hide
+     */
+    static public boolean supportsMultiDisplay() {
+        return !isLowRamDeviceStatic()
+                && Resources.getSystem().getBoolean(
+                    com.android.internal.R.bool.config_supportsMultiDisplay);
+    }
+
+    /**
      * Return the maximum number of actions that will be displayed in the picture-in-picture UI when
      * the user interacts with the activity currently in picture-in-picture mode.
      */
diff --git a/core/java/android/app/Notification.java b/core/java/android/app/Notification.java
index 6d7486b..7f26f4f 100644
--- a/core/java/android/app/Notification.java
+++ b/core/java/android/app/Notification.java
@@ -3667,7 +3667,6 @@
             contentView.setTextViewText(R.id.text, null);
             contentView.setViewVisibility(R.id.text_line_1, View.GONE);
             contentView.setTextViewText(R.id.text_line_1, null);
-            contentView.setViewVisibility(R.id.progress, View.GONE);
         }
 
         /**
diff --git a/core/java/android/app/ResourcesManager.java b/core/java/android/app/ResourcesManager.java
index 3191eec..d620a81 100644
--- a/core/java/android/app/ResourcesManager.java
+++ b/core/java/android/app/ResourcesManager.java
@@ -44,8 +44,6 @@
 
 import java.lang.ref.WeakReference;
 import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.Map;
 import java.util.Objects;
 import java.util.WeakHashMap;
 import java.util.function.Predicate;
@@ -116,7 +114,7 @@
      * A cache of DisplayId, Resources to Display. These display adjustments associated with these
      * {@link Display}s will change as the resources change.
      */
-    private final ArrayMap<Pair<Integer, ResourcesKey>, WeakReference<Display>> mResourceDisplays =
+    private final ArrayMap<Pair<Integer, Resources>, WeakReference<Display>> mResourceDisplays =
         new ArrayMap<>();
 
     public static ResourcesManager getInstance() {
@@ -139,7 +137,10 @@
             for (int i = 0; i < mResourceImpls.size();) {
                 final ResourcesKey key = mResourceImpls.keyAt(i);
                 if (key.isPathReferenced(path)) {
-                    cleanupResourceImpl(key);
+                    final ResourcesImpl res = mResourceImpls.removeAt(i).get();
+                    if (res != null) {
+                        res.flushLayoutCache();
+                    }
                     count++;
                 } else {
                     i++;
@@ -250,14 +251,8 @@
      * @param resources The {@link Resources} backing the display adjustments.
      */
     public Display getAdjustedDisplay(final int displayId, Resources resources) {
+        final Pair<Integer, Resources> key = Pair.create(displayId, resources);
         synchronized (this) {
-            // Note that the ResourcesKey might be {@code null} in the case that the
-            // {@link Resources} is actually from {@link Resources#getSystem}. In this case, it is
-            // not managed by {@link ResourcesManager}, but we still want to cache the display
-            // object.
-            final Pair<Integer, ResourcesKey> key = Pair.create(displayId,
-                    findKeyForResourceImplLocked(resources.getImpl()));
-
             WeakReference<Display> wd = mResourceDisplays.get(key);
             if (wd != null) {
                 final Display display = wd.get();
@@ -278,32 +273,6 @@
         }
     }
 
-    private void cleanupResourceImpl(ResourcesKey removedKey) {
-        // Remove any resource to display mapping based on this key.
-        final Iterator<Map.Entry<Pair<Integer, ResourcesKey>, WeakReference<Display>>> iter =
-                mResourceDisplays.entrySet().iterator();
-        while (iter.hasNext()) {
-            final Map.Entry<Pair<Integer, ResourcesKey>, WeakReference<Display>> entry =
-                    iter.next();
-            final ResourcesKey key = entry.getKey().second;
-
-            // Do not touch system resource displays (indicated by a {@code null} key) or
-            // non-matching keys.
-            if (key == null || !key.equals(removedKey)) {
-                continue;
-            }
-
-            iter.remove();
-        }
-
-        // Remove resource key to resource impl mapping and flush cache
-        final ResourcesImpl res = mResourceImpls.remove(removedKey).get();
-
-        if (res != null) {
-            res.flushLayoutCache();
-        }
-    }
-
     /**
      * Creates an AssetManager from the paths within the ResourcesKey.
      *
diff --git a/core/java/android/app/WaitResult.java b/core/java/android/app/WaitResult.java
index af196cf..898d0ca 100644
--- a/core/java/android/app/WaitResult.java
+++ b/core/java/android/app/WaitResult.java
@@ -20,6 +20,8 @@
 import android.os.Parcel;
 import android.os.Parcelable;
 
+import java.io.PrintWriter;
+
 /**
  * Information returned after waiting for an activity start.
  *
@@ -69,4 +71,13 @@
         thisTime = source.readLong();
         totalTime = source.readLong();
     }
+
+    public void dump(PrintWriter pw, String prefix) {
+        pw.println(prefix + "WaitResult:");
+        pw.println(prefix + "  result=" + result);
+        pw.println(prefix + "  timeout=" + timeout);
+        pw.println(prefix + "  who=" + who);
+        pw.println(prefix + "  thisTime=" + thisTime);
+        pw.println(prefix + "  totalTime=" + totalTime);
+    }
 }
\ No newline at end of file
diff --git a/core/java/android/hardware/usb/UsbDeviceConnection.java b/core/java/android/hardware/usb/UsbDeviceConnection.java
index ffd6ec3..7a0272d 100644
--- a/core/java/android/hardware/usb/UsbDeviceConnection.java
+++ b/core/java/android/hardware/usb/UsbDeviceConnection.java
@@ -20,6 +20,7 @@
 import android.annotation.Nullable;
 import android.annotation.SystemApi;
 import android.content.Context;
+import android.os.Build;
 import android.os.ParcelFileDescriptor;
 
 import com.android.internal.util.Preconditions;
@@ -27,7 +28,9 @@
 import dalvik.system.CloseGuard;
 
 import java.io.FileDescriptor;
+import java.nio.BufferOverflowException;
 import java.nio.ByteBuffer;
+import java.util.concurrent.TimeoutException;
 
 /**
  * This class is used for sending and receiving data and control messages to a USB device.
@@ -268,16 +271,29 @@
      *
      * @return a completed USB request, or null if an error occurred
      *
-     * @throws IllegalArgumentException if the number of bytes read or written is more than the
-     *                                  limit of the request's buffer. The number of bytes is
-     *                                  determined by the {@code length} parameter of
+     * @throws IllegalArgumentException Before API {@value Build.VERSION_CODES#O}: if the number of
+     *                                  bytes read or written is more than the limit of the
+     *                                  request's buffer. The number of bytes is determined by the
+     *                                  {@code length} parameter of
      *                                  {@link UsbRequest#queue(ByteBuffer, int)}
+     * @throws BufferOverflowException In API {@value Build.VERSION_CODES#O} and after: if the
+     *                                 number of bytes read or written is more than the limit of the
+     *                                 request's buffer. The number of bytes is determined by the
+     *                                 {@code length} parameter of
+     *                                 {@link UsbRequest#queue(ByteBuffer, int)}
      */
     public UsbRequest requestWait() {
-        // -1 is special value indicating infinite wait
-        UsbRequest request = native_request_wait(-1);
+        UsbRequest request = null;
+        try {
+            // -1 is special value indicating infinite wait
+            request = native_request_wait(-1);
+        } catch (TimeoutException e) {
+            // Does not happen, infinite timeout
+        }
+
         if (request != null) {
-            request.dequeue();
+            request.dequeue(
+                    mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.O);
         }
         return request;
     }
@@ -290,24 +306,25 @@
      * android.hardware.usb.UsbRequest#getClientData} can be useful in determining how to process
      * the result of this function.</p>
      * <p>Android processes {@link UsbRequest UsbRequests} asynchronously. Hence it is not
-     * guaranteed that {@link #requestWait(int) requestWait(0)} returns a request that has been
+     * guaranteed that {@link #requestWait(long) requestWait(0)} returns a request that has been
      * queued right before even if the request could have been processed immediately.</p>
      *
      * @param timeout timeout in milliseconds. If 0 this method does not wait.
      *
-     * @return a completed USB request, or {@code null} if an error or time out occurred
+     * @return a completed USB request, or {@code null} if an error occurred
      *
-     * @throws IllegalArgumentException if the number of bytes read or written is more than the
-     *                                  limit of the request's buffer. The number of bytes is
-     *                                  determined by the {@code length} parameter of
-     *                                  {@link UsbRequest#queue(ByteBuffer, int)}
+     * @throws BufferOverflowException if the number of bytes read or written is more than the
+     *                                 limit of the request's buffer. The number of bytes is
+     *                                 determined by the {@code length} parameter of
+     *                                 {@link UsbRequest#queue(ByteBuffer, int)}
+     * @throws TimeoutException if no request was received in {@code timeout} milliseconds.
      */
-    public UsbRequest requestWait(int timeout) {
+    public UsbRequest requestWait(long timeout) throws TimeoutException {
         timeout = Preconditions.checkArgumentNonnegative(timeout, "timeout");
 
         UsbRequest request = native_request_wait(timeout);
         if (request != null) {
-            request.dequeue();
+            request.dequeue(true);
         }
         return request;
     }
@@ -350,7 +367,7 @@
             int index, byte[] buffer, int offset, int length, int timeout);
     private native int native_bulk_request(int endpoint, byte[] buffer,
             int offset, int length, int timeout);
-    private native UsbRequest native_request_wait(int timeout);
+    private native UsbRequest native_request_wait(long timeout) throws TimeoutException;
     private native String native_get_serial();
     private native boolean native_reset_device();
 }
diff --git a/core/java/android/hardware/usb/UsbRequest.java b/core/java/android/hardware/usb/UsbRequest.java
index 239a2df..90990b7 100644
--- a/core/java/android/hardware/usb/UsbRequest.java
+++ b/core/java/android/hardware/usb/UsbRequest.java
@@ -17,11 +17,13 @@
 package android.hardware.usb;
 
 import android.annotation.Nullable;
+import android.util.Log;
 
 import com.android.internal.util.Preconditions;
 
 import dalvik.system.CloseGuard;
 
+import java.nio.BufferOverflowException;
 import java.nio.ByteBuffer;
 
 /**
@@ -276,7 +278,7 @@
         return wasQueued;
     }
 
-    /* package */ void dequeue() {
+    /* package */ void dequeue(boolean useBufferOverflowInsteadOfIllegalArg) {
         boolean isSend = (mEndpoint.getDirection() == UsbConstants.USB_DIR_OUT);
         int bytesTransferred;
 
@@ -313,7 +315,18 @@
                     bytesTransferred = native_dequeue_array(mBuffer.array(), mLength, isSend);
                 }
                 if (bytesTransferred >= 0) {
-                    mBuffer.position(Math.min(bytesTransferred, mLength));
+                    int bytesToStore = Math.min(bytesTransferred, mLength);
+                    try {
+                        mBuffer.position(bytesToStore);
+                    } catch (IllegalArgumentException e) {
+                        if (useBufferOverflowInsteadOfIllegalArg) {
+                            Log.e(TAG, "Buffer " + mBuffer + " does not have enough space to read "
+                                    + bytesToStore + " bytes", e);
+                            throw new BufferOverflowException();
+                        } else {
+                            throw e;
+                        }
+                    }
                 }
             }
 
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index 660d53a..cac643fc 100755
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -7091,6 +7091,8 @@
             INSTANT_APP_SETTINGS.add(ENABLED_INPUT_METHODS);
 
             INSTANT_APP_SETTINGS.add(ANDROID_ID);
+
+            INSTANT_APP_SETTINGS.add(PACKAGE_VERIFIER_USER_CONSENT);
         }
 
         /**
diff --git a/core/java/android/text/method/DateTimeKeyListener.java b/core/java/android/text/method/DateTimeKeyListener.java
index 551db55..1593db5 100644
--- a/core/java/android/text/method/DateTimeKeyListener.java
+++ b/core/java/android/text/method/DateTimeKeyListener.java
@@ -68,7 +68,7 @@
         final LinkedHashSet<Character> chars = new LinkedHashSet<>();
         // First add the digits. Then, add all the character in AM and PM markers. Finally, add all
         // the non-pattern characters seen in the patterns for "yMdhms" and "yMdHms".
-        boolean success = NumberKeyListener.addDigits(chars, locale)
+        final boolean success = NumberKeyListener.addDigits(chars, locale)
                           && NumberKeyListener.addAmPmChars(chars, locale)
                           && NumberKeyListener.addFormatCharsFromSkeleton(
                               chars, locale, SKELETON_12HOUR, SYMBOLS_TO_IGNORE)
@@ -76,7 +76,14 @@
                               chars, locale, SKELETON_24HOUR, SYMBOLS_TO_IGNORE);
         if (success) {
             mCharacters = NumberKeyListener.collectionToArray(chars);
-            mNeedsAdvancedInput = !ArrayUtils.containsAll(CHARACTERS, mCharacters);
+            if (locale != null && "en".equals(locale.getLanguage())) {
+                // For backward compatibility reasons, assume we don't need advanced input for
+                // English locales, although English locales literally also need a comma and perhaps
+                // uppercase letters for AM and PM.
+                mNeedsAdvancedInput = false;
+            } else {
+                mNeedsAdvancedInput = !ArrayUtils.containsAll(CHARACTERS, mCharacters);
+            }
         } else {
             mCharacters = CHARACTERS;
             mNeedsAdvancedInput = false;
diff --git a/core/java/android/text/method/TimeKeyListener.java b/core/java/android/text/method/TimeKeyListener.java
index 5b1db11..f11f400 100644
--- a/core/java/android/text/method/TimeKeyListener.java
+++ b/core/java/android/text/method/TimeKeyListener.java
@@ -68,7 +68,7 @@
         final LinkedHashSet<Character> chars = new LinkedHashSet<>();
         // First add the digits. Then, add all the character in AM and PM markers. Finally, add all
         // the non-pattern characters seen in the patterns for "hms" and "Hms".
-        boolean success = NumberKeyListener.addDigits(chars, locale)
+        final boolean success = NumberKeyListener.addDigits(chars, locale)
                           && NumberKeyListener.addAmPmChars(chars, locale)
                           && NumberKeyListener.addFormatCharsFromSkeleton(
                               chars, locale, SKELETON_12HOUR, SYMBOLS_TO_IGNORE)
@@ -76,7 +76,14 @@
                               chars, locale, SKELETON_24HOUR, SYMBOLS_TO_IGNORE);
         if (success) {
             mCharacters = NumberKeyListener.collectionToArray(chars);
-            mNeedsAdvancedInput = !ArrayUtils.containsAll(CHARACTERS, mCharacters);
+            if (locale != null && "en".equals(locale.getLanguage())) {
+                // For backward compatibility reasons, assume we don't need advanced input for
+                // English locales, although English locales may need uppercase letters for
+                // AM and PM.
+                mNeedsAdvancedInput = false;
+            } else {
+                mNeedsAdvancedInput = !ArrayUtils.containsAll(CHARACTERS, mCharacters);
+            }
         } else {
             mCharacters = CHARACTERS;
             mNeedsAdvancedInput = false;
diff --git a/core/java/android/view/SurfaceView.java b/core/java/android/view/SurfaceView.java
index 076b33c..31911cb 100644
--- a/core/java/android/view/SurfaceView.java
+++ b/core/java/android/view/SurfaceView.java
@@ -683,7 +683,8 @@
                     mTranslator.translateRectInAppWindowToScreen(mScreenRect);
                 }
 
-                if (!isHardwareAccelerated() || !mRtHandlingPositionUpdates) {
+                if (mSurfaceControl != null
+                        && (!isHardwareAccelerated() || !mRtHandlingPositionUpdates)) {
                     try {
                         if (DEBUG) Log.d(TAG, String.format("%d updateSurfacePosition UI, " +
                                 "postion = [%d, %d, %d, %d]", System.identityHashCode(this),
diff --git a/core/java/android/view/ViewRootImpl.java b/core/java/android/view/ViewRootImpl.java
index 58ef0af..4a7b16e 100644
--- a/core/java/android/view/ViewRootImpl.java
+++ b/core/java/android/view/ViewRootImpl.java
@@ -1249,6 +1249,13 @@
         mIsAmbientMode = ambient;
     }
 
+    void setWindowVisibility(int visibility) {
+        if (visibility != mAttachInfo.mWindowVisibility) {
+            mAttachInfo.mWindowVisibility = visibility;
+            mView.dispatchWindowVisibilityChanged(visibility);
+        }
+    }
+
     void setWindowStopped(boolean stopped) {
         if (mStopped != stopped) {
             mStopped = stopped;
@@ -1263,6 +1270,7 @@
                 if (renderer != null) {
                     renderer.destroyHardwareResources(mView);
                 }
+                mView.dispatchWindowVisibilityChanged(View.GONE);
             }
         }
     }
@@ -1297,7 +1305,8 @@
     }
 
     int getHostVisibility() {
-        return (mAppVisible || mForceDecorViewVisibility) ? mView.getVisibility() : View.GONE;
+        return (mAppVisible || mForceDecorViewVisibility) && !mStopped
+            ? mView.getVisibility() : View.GONE;
     }
 
     /**
@@ -1654,8 +1663,8 @@
         }
 
         if (viewVisibilityChanged) {
-            mAttachInfo.mWindowVisibility = viewVisibility;
-            host.dispatchWindowVisibilityChanged(viewVisibility);
+            setWindowVisibility(viewVisibility);
+
             if (viewUserVisibilityChanged) {
                 host.dispatchVisibilityAggregated(viewVisibility == View.VISIBLE);
             }
diff --git a/core/jni/android/graphics/Bitmap.cpp b/core/jni/android/graphics/Bitmap.cpp
index de5e505..3a03af6 100755
--- a/core/jni/android/graphics/Bitmap.cpp
+++ b/core/jni/android/graphics/Bitmap.cpp
@@ -44,6 +44,14 @@
 static jmethodID gBitmap_reinitMethodID;
 static jmethodID gBitmap_getAllocationByteCountMethodID;
 
+static jfieldID gTransferParams_aFieldID;
+static jfieldID gTransferParams_bFieldID;
+static jfieldID gTransferParams_cFieldID;
+static jfieldID gTransferParams_dFieldID;
+static jfieldID gTransferParams_eFieldID;
+static jfieldID gTransferParams_fFieldID;
+static jfieldID gTransferParams_gFieldID;
+
 namespace android {
 
 class BitmapWrapper {
@@ -685,6 +693,22 @@
     return NULL;
 }
 
+static void ToF16_SA8(void* dst, const void* src, int width) {
+    SkASSERT(width > 0);
+    uint64_t* d = (uint64_t*)dst;
+    const uint8_t* s = (const uint8_t*)src;
+
+    for (int i = 0; i < width; i++) {
+        uint8_t c = *s++;
+        SkPM4f a;
+        a.fVec[SkPM4f::R] = 0.0f;
+        a.fVec[SkPM4f::G] = 0.0f;
+        a.fVec[SkPM4f::B] = 0.0f;
+        a.fVec[SkPM4f::A] = c / 255.0f;
+        *d++ = a.toF16();
+    }
+}
+
 ///////////////////////////////////////////////////////////////////////////////
 ///////////////////////////////////////////////////////////////////////////////
 
@@ -696,7 +720,8 @@
 
 static jobject Bitmap_creator(JNIEnv* env, jobject, jintArray jColors,
                               jint offset, jint stride, jint width, jint height,
-                              jint configHandle, jboolean isMutable) {
+                              jint configHandle, jboolean isMutable,
+                              jfloatArray xyzD50, jobject transferParameters) {
     SkColorType colorType = GraphicsJNI::legacyBitmapConfigToColorType(configHandle);
     if (NULL != jColors) {
         size_t n = env->GetArrayLength(jColors);
@@ -712,8 +737,37 @@
     }
 
     SkBitmap bitmap;
-    bitmap.setInfo(SkImageInfo::Make(width, height, colorType, kPremul_SkAlphaType,
-            GraphicsJNI::colorSpaceForType(colorType)));
+    sk_sp<SkColorSpace> colorSpace;
+
+    if (colorType != kN32_SkColorType || xyzD50 == nullptr || transferParameters == nullptr) {
+        colorSpace = GraphicsJNI::colorSpaceForType(colorType);
+    } else {
+        SkColorSpaceTransferFn p;
+        p.fA = (float) env->GetDoubleField(transferParameters, gTransferParams_aFieldID);
+        p.fB = (float) env->GetDoubleField(transferParameters, gTransferParams_bFieldID);
+        p.fC = (float) env->GetDoubleField(transferParameters, gTransferParams_cFieldID);
+        p.fD = (float) env->GetDoubleField(transferParameters, gTransferParams_dFieldID);
+        p.fE = (float) env->GetDoubleField(transferParameters, gTransferParams_eFieldID);
+        p.fF = (float) env->GetDoubleField(transferParameters, gTransferParams_fFieldID);
+        p.fG = (float) env->GetDoubleField(transferParameters, gTransferParams_gFieldID);
+
+        SkMatrix44 xyzMatrix(SkMatrix44::kIdentity_Constructor);
+        jfloat* array = env->GetFloatArrayElements(xyzD50, NULL);
+        xyzMatrix.setFloat(0, 0, array[0]);
+        xyzMatrix.setFloat(1, 0, array[1]);
+        xyzMatrix.setFloat(2, 0, array[2]);
+        xyzMatrix.setFloat(0, 1, array[3]);
+        xyzMatrix.setFloat(1, 1, array[4]);
+        xyzMatrix.setFloat(2, 1, array[5]);
+        xyzMatrix.setFloat(0, 2, array[6]);
+        xyzMatrix.setFloat(1, 2, array[7]);
+        xyzMatrix.setFloat(2, 2, array[8]);
+        env->ReleaseFloatArrayElements(xyzD50, array, 0);
+
+        colorSpace = SkColorSpace::MakeRGB(p, xyzMatrix);
+    }
+
+    bitmap.setInfo(SkImageInfo::Make(width, height, colorType, kPremul_SkAlphaType, colorSpace));
 
     sk_sp<Bitmap> nativeBitmap = Bitmap::allocateHeapBitmap(&bitmap, NULL);
     if (!nativeBitmap) {
@@ -739,6 +793,9 @@
         SkPixmap srcPixmap = srcUnlocker.pixmap();
 
         SkImageInfo dstInfo = src.info().makeColorType(dstCT);
+        if (dstCT == kRGBA_F16_SkColorType) {
+             dstInfo = dstInfo.makeColorSpace(SkColorSpace::MakeSRGBLinear());
+        }
         if (!dst->setInfo(dstInfo)) {
             return false;
         }
@@ -763,6 +820,14 @@
                 }
                 return true;
             }
+            case kRGBA_F16_SkColorType: {
+               for (int y = 0; y < src.height(); y++) {
+                   const uint8_t* srcRow = srcPixmap.addr8(0, y);
+                   void* dstRow = dst->getAddr(0, y);
+                   ToF16_SA8(dstRow, srcRow, src.width());
+               }
+               return true;
+           }
             default:
                 return false;
         }
@@ -1562,6 +1627,13 @@
     return createJavaGraphicBuffer(env, buffer);
 }
 
+static void Bitmap_copyColorSpace(JNIEnv* env, jobject, jlong srcBitmapPtr, jlong dstBitmapPtr) {
+    LocalScopedBitmap srcBitmapHandle(srcBitmapPtr);
+    LocalScopedBitmap dstBitmapHandle(dstBitmapPtr);
+
+    dstBitmapHandle->bitmap().setColorSpace(srcBitmapHandle->bitmap().info().refColorSpace());
+}
+
 ///////////////////////////////////////////////////////////////////////////////
 static jclass make_globalref(JNIEnv* env, const char classname[])
 {
@@ -1579,7 +1651,7 @@
 }
 
 static const JNINativeMethod gBitmapMethods[] = {
-    {   "nativeCreate",             "([IIIIIIZ)Landroid/graphics/Bitmap;",
+    {   "nativeCreate",             "([IIIIIIZ[FLandroid/graphics/ColorSpace$Rgb$TransferParameters;)Landroid/graphics/Bitmap;",
         (void*)Bitmap_creator },
     {   "nativeCopy",               "(JIZ)Landroid/graphics/Bitmap;",
         (void*)Bitmap_copy },
@@ -1628,10 +1700,21 @@
         (void*) Bitmap_createGraphicBufferHandle },
     {   "nativeGetColorSpace",      "(J[F[F)Z", (void*)Bitmap_getColorSpace },
     {   "nativeIsSRGB",             "(J)Z", (void*)Bitmap_isSRGB },
+    {   "nativeCopyColorSpace",     "(JJ)V",
+        (void*)Bitmap_copyColorSpace },
 };
 
 int register_android_graphics_Bitmap(JNIEnv* env)
 {
+    jclass transfer_params_class = FindClassOrDie(env, "android/graphics/ColorSpace$Rgb$TransferParameters");
+    gTransferParams_aFieldID = GetFieldIDOrDie(env, transfer_params_class, "a", "D");
+    gTransferParams_bFieldID = GetFieldIDOrDie(env, transfer_params_class, "b", "D");
+    gTransferParams_cFieldID = GetFieldIDOrDie(env, transfer_params_class, "c", "D");
+    gTransferParams_dFieldID = GetFieldIDOrDie(env, transfer_params_class, "d", "D");
+    gTransferParams_eFieldID = GetFieldIDOrDie(env, transfer_params_class, "e", "D");
+    gTransferParams_fFieldID = GetFieldIDOrDie(env, transfer_params_class, "f", "D");
+    gTransferParams_gFieldID = GetFieldIDOrDie(env, transfer_params_class, "g", "D");
+
     gBitmap_class = make_globalref(env, "android/graphics/Bitmap");
     gBitmap_nativePtr = getFieldIDCheck(env, gBitmap_class, "mNativePtr", "J");
     gBitmap_constructorMethodID = env->GetMethodID(gBitmap_class, "<init>", "(JIIIZZ[BLandroid/graphics/NinePatch$InsetStruct;)V");
diff --git a/core/jni/android_hardware_UsbDeviceConnection.cpp b/core/jni/android_hardware_UsbDeviceConnection.cpp
index 6814506..ba08bce 100644
--- a/core/jni/android_hardware_UsbDeviceConnection.cpp
+++ b/core/jni/android_hardware_UsbDeviceConnection.cpp
@@ -220,7 +220,7 @@
 }
 
 static jobject
-android_hardware_UsbDeviceConnection_request_wait(JNIEnv *env, jobject thiz, jint timeoutMillis)
+android_hardware_UsbDeviceConnection_request_wait(JNIEnv *env, jobject thiz, jlong timeoutMillis)
 {
     struct usb_device* device = get_device_from_object(env, thiz);
     if (!device) {
@@ -243,8 +243,17 @@
                                - currentTime).count());
 
             int error = errno;
+            if (request != NULL) {
+                break;
+            }
+
             currentTime = steady_clock::now();
-            if (request != NULL || error != EAGAIN || currentTime >= endTime) {
+            if (currentTime >= endTime) {
+                jniThrowException(env, "java/util/concurrent/TimeoutException", "");
+                break;
+            }
+
+            if (error != EAGAIN) {
                 break;
             }
         };
@@ -300,7 +309,7 @@
                                         (void *)android_hardware_UsbDeviceConnection_control_request},
     {"native_bulk_request",     "(I[BIII)I",
                                         (void *)android_hardware_UsbDeviceConnection_bulk_request},
-    {"native_request_wait",             "(I)Landroid/hardware/usb/UsbRequest;",
+    {"native_request_wait",             "(J)Landroid/hardware/usb/UsbRequest;",
                                         (void *)android_hardware_UsbDeviceConnection_request_wait},
     { "native_get_serial",      "()Ljava/lang/String;",
                                         (void*)android_hardware_UsbDeviceConnection_get_serial },
diff --git a/core/res/res/layout/notification_template_material_ambient.xml b/core/res/res/layout/notification_template_material_ambient.xml
index 026bc6e..74f0e57 100644
--- a/core/res/res/layout/notification_template_material_ambient.xml
+++ b/core/res/res/layout/notification_template_material_ambient.xml
@@ -33,6 +33,7 @@
             android:layout_gravity="top"
             android:layout_marginTop="@dimen/notification_content_margin_top"
             android:layout_marginBottom="@dimen/notification_action_list_height"
+            android:paddingTop="10dp"
             android:clipToPadding="false"
             android:orientation="vertical">
 
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index 379c376..89c3943 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -2961,5 +2961,8 @@
   <java-symbol type="string" name="etws_primary_default_message_test" />
 
   <java-symbol type="string" name="etws_primary_default_message_others" />
+
   <java-symbol type="bool" name="config_quickSettingsSupported" />
+
+  <java-symbol type="style" name="Theme.DeviceDefault.QuickSettings" />
 </resources>
diff --git a/graphics/java/android/graphics/Bitmap.java b/graphics/java/android/graphics/Bitmap.java
index ed587bb..91906850 100644
--- a/graphics/java/android/graphics/Bitmap.java
+++ b/graphics/java/android/graphics/Bitmap.java
@@ -20,6 +20,7 @@
 import android.annotation.ColorInt;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
+import android.annotation.Size;
 import android.os.Parcel;
 import android.os.Parcelable;
 import android.os.Trace;
@@ -78,8 +79,6 @@
     /** @hide */
     public int mDensity = getDefaultDensity();
 
-    private static volatile Matrix sScaleMatrix;
-
     private static volatile int sDefaultDensity = -1;
 
     /**
@@ -606,7 +605,7 @@
      * setting the new bitmap's config to the one specified, and then copying
      * this bitmap's pixels into the new bitmap. If the conversion is not
      * supported, or the allocator fails, then this returns NULL.  The returned
-     * bitmap initially has the same density as the original.
+     * bitmap has the same density and color space as the original.
      *
      * @param config    The desired config for the resulting bitmap
      * @param isMutable True if the resulting bitmap should be mutable (i.e.
@@ -629,7 +628,8 @@
 
     /**
      * Creates a new immutable bitmap backed by ashmem which can efficiently
-     * be passed between processes.
+     * be passed between processes. The bitmap is assumed to be in the sRGB
+     * color space.
      *
      * @hide
      */
@@ -645,7 +645,8 @@
 
     /**
      * Creates a new immutable bitmap backed by ashmem which can efficiently
-     * be passed between processes.
+     * be passed between processes. The bitmap is assumed to be in the sRGB
+     * color space.
      *
      * @hide
      */
@@ -666,7 +667,7 @@
      *         currently PIXEL_FORMAT_RGBA_8888 is the only supported format
      * @hide
      */
-    public static Bitmap createHardwareBitmap(GraphicBuffer graphicBuffer) {
+    public static Bitmap createHardwareBitmap(@NonNull GraphicBuffer graphicBuffer) {
         return nativeCreateHardwareBitmap(graphicBuffer);
     }
 
@@ -683,50 +684,34 @@
      * @return The new scaled bitmap or the source bitmap if no scaling is required.
      * @throws IllegalArgumentException if width is <= 0, or height is <= 0
      */
-    public static Bitmap createScaledBitmap(Bitmap src, int dstWidth, int dstHeight,
+    public static Bitmap createScaledBitmap(@NonNull Bitmap src, int dstWidth, int dstHeight,
             boolean filter) {
-        Matrix m;
-        synchronized (Bitmap.class) {
-            // small pool of just 1 matrix
-            m = sScaleMatrix;
-            sScaleMatrix = null;
-        }
-
-        if (m == null) {
-            m = new Matrix();
-        }
+        Matrix m = new Matrix();
 
         final int width = src.getWidth();
         final int height = src.getHeight();
-        final float sx = dstWidth  / (float)width;
-        final float sy = dstHeight / (float)height;
-        m.setScale(sx, sy);
-        Bitmap b = Bitmap.createBitmap(src, 0, 0, width, height, m, filter);
-
-        synchronized (Bitmap.class) {
-            // do we need to check for null? why not just assign everytime?
-            if (sScaleMatrix == null) {
-                sScaleMatrix = m;
-            }
+        if (width != dstWidth || height != dstHeight) {
+            final float sx = dstWidth / (float) width;
+            final float sy = dstHeight / (float) height;
+            m.setScale(sx, sy);
         }
-
-        return b;
+        return Bitmap.createBitmap(src, 0, 0, width, height, m, filter);
     }
 
     /**
      * Returns an immutable bitmap from the source bitmap. The new bitmap may
      * be the same object as source, or a copy may have been made.  It is
-     * initialized with the same density as the original bitmap.
+     * initialized with the same density and color space as the original bitmap.
      */
-    public static Bitmap createBitmap(Bitmap src) {
+    public static Bitmap createBitmap(@NonNull Bitmap src) {
         return createBitmap(src, 0, 0, src.getWidth(), src.getHeight());
     }
 
     /**
      * Returns an immutable bitmap from the specified subset of the source
      * bitmap. The new bitmap may be the same object as source, or a copy may
-     * have been made. It is initialized with the same density as the original
-     * bitmap.
+     * have been made. It is initialized with the same density and color space
+     * as the original bitmap.
      *
      * @param source   The bitmap we are subsetting
      * @param x        The x coordinate of the first pixel in source
@@ -738,7 +723,7 @@
      *         outside of the dimensions of the source bitmap, or width is <= 0,
      *         or height is <= 0
      */
-    public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height) {
+    public static Bitmap createBitmap(@NonNull Bitmap source, int x, int y, int width, int height) {
         return createBitmap(source, x, y, width, height, null, false);
     }
 
@@ -746,7 +731,8 @@
      * Returns an immutable bitmap from subset of the source bitmap,
      * transformed by the optional matrix. The new bitmap may be the
      * same object as source, or a copy may have been made. It is
-     * initialized with the same density as the original bitmap.
+     * initialized with the same density and color space as the original
+     * bitmap.
      *
      * If the source bitmap is immutable and the requested subset is the
      * same as the source bitmap itself, then the source bitmap is
@@ -766,8 +752,8 @@
      *         outside of the dimensions of the source bitmap, or width is <= 0,
      *         or height is <= 0
      */
-    public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height,
-            Matrix m, boolean filter) {
+    public static Bitmap createBitmap(@NonNull Bitmap source, int x, int y, int width, int height,
+            @Nullable Matrix m, boolean filter) {
 
         checkXYSign(x, y);
         checkWidthHeight(width, height);
@@ -847,6 +833,8 @@
             }
         }
 
+        nativeCopyColorSpace(source.mNativePtr, bitmap.mNativePtr);
+
         // The new bitmap was created from a known bitmap source so assume that
         // they use the same density
         bitmap.mDensity = source.mDensity;
@@ -866,7 +854,8 @@
 
     /**
      * Returns a mutable bitmap with the specified width and height.  Its
-     * initial density is as per {@link #getDensity}.
+     * initial density is as per {@link #getDensity}. The newly created
+     * bitmap is in the {@link ColorSpace.Named#SRGB sRGB} color space.
      *
      * @param width    The width of the bitmap
      * @param height   The height of the bitmap
@@ -874,13 +863,15 @@
      * @throws IllegalArgumentException if the width or height are <= 0, or if
      *         Config is Config.HARDWARE, because hardware bitmaps are always immutable
      */
-    public static Bitmap createBitmap(int width, int height, Config config) {
+    public static Bitmap createBitmap(int width, int height, @NonNull Config config) {
         return createBitmap(width, height, config, true);
     }
 
     /**
      * Returns a mutable bitmap with the specified width and height.  Its
      * initial density is determined from the given {@link DisplayMetrics}.
+     * The newly created bitmap is in the {@link ColorSpace.Named#SRGB sRGB}
+     * color space.
      *
      * @param display  Display metrics for the display this bitmap will be
      *                 drawn on.
@@ -890,13 +881,33 @@
      * @throws IllegalArgumentException if the width or height are <= 0, or if
      *         Config is Config.HARDWARE, because hardware bitmaps are always immutable
      */
-    public static Bitmap createBitmap(DisplayMetrics display, int width,
-            int height, Config config) {
+    public static Bitmap createBitmap(@Nullable DisplayMetrics display, int width,
+            int height, @NonNull Config config) {
         return createBitmap(display, width, height, config, true);
     }
 
     /**
      * Returns a mutable bitmap with the specified width and height.  Its
+     * initial density is as per {@link #getDensity}. The newly created
+     * bitmap is in the {@link ColorSpace.Named#SRGB sRGB} color space.
+     *
+     * @param width    The width of the bitmap
+     * @param height   The height of the bitmap
+     * @param config   The bitmap config to create.
+     * @param hasAlpha If the bitmap is ARGB_8888 or RGBA_16F this flag can be used to
+     *                 mark the bitmap as opaque. Doing so will clear the bitmap in black
+     *                 instead of transparent.
+     *
+     * @throws IllegalArgumentException if the width or height are <= 0, or if
+     *         Config is Config.HARDWARE, because hardware bitmaps are always immutable
+     */
+    public static Bitmap createBitmap(int width, int height,
+            @NonNull Config config, boolean hasAlpha) {
+        return createBitmap(null, width, height, config, hasAlpha);
+    }
+
+    /**
+     * Returns a mutable bitmap with the specified width and height.  Its
      * initial density is as per {@link #getDensity}.
      *
      * @param width    The width of the bitmap
@@ -905,17 +916,26 @@
      * @param hasAlpha If the bitmap is ARGB_8888 or RGBA_16F this flag can be used to
      *                 mark the bitmap as opaque. Doing so will clear the bitmap in black
      *                 instead of transparent.
+     * @param colorSpace The color space of the bitmap. If null,
+     *                   {@link ColorSpace.Named#SRGB sRGB} is assumed. This argument is
+     *                   ignored if the config is not {@link Config#ARGB_8888}.
      *
-     * @throws IllegalArgumentException if the width or height are <= 0, or if
-     *         Config is Config.HARDWARE, because hardware bitmaps are always immutable
+     * @throws IllegalArgumentException if the width or height are <= 0, if
+     *         Config is Config.HARDWARE (because hardware bitmaps are always
+     *         immutable), if the specified color space is not {@link ColorSpace.Model#RGB RGB},
+     *         or if the specified color space's transfer function is not an
+     *         {@link ColorSpace.Rgb.TransferParameters ICC parametric curve}
      */
-    public static Bitmap createBitmap(int width, int height, Config config, boolean hasAlpha) {
-        return createBitmap(null, width, height, config, hasAlpha);
+    public static Bitmap createBitmap(int width, int height, @NonNull Config config,
+            boolean hasAlpha, @Nullable ColorSpace colorSpace) {
+        return createBitmap(null, width, height, config, hasAlpha, colorSpace);
     }
 
     /**
      * Returns a mutable bitmap with the specified width and height.  Its
      * initial density is determined from the given {@link DisplayMetrics}.
+     * The newly created bitmap is in the {@link ColorSpace.Named#SRGB sRGB}
+     * color space.
      *
      * @param display  Display metrics for the display this bitmap will be
      *                 drawn on.
@@ -929,15 +949,63 @@
      * @throws IllegalArgumentException if the width or height are <= 0, or if
      *         Config is Config.HARDWARE, because hardware bitmaps are always immutable
      */
-    public static Bitmap createBitmap(DisplayMetrics display, int width, int height,
-            Config config, boolean hasAlpha) {
+    public static Bitmap createBitmap(@Nullable DisplayMetrics display, int width, int height,
+            @NonNull Config config, boolean hasAlpha) {
+        return createBitmap(display, width, height, config, hasAlpha, null);
+    }
+
+    /**
+     * Returns a mutable bitmap with the specified width and height.  Its
+     * initial density is determined from the given {@link DisplayMetrics}.
+     * The newly created bitmap is in the {@link ColorSpace.Named#SRGB sRGB}
+     * color space.
+     *
+     * @param display  Display metrics for the display this bitmap will be
+     *                 drawn on.
+     * @param width    The width of the bitmap
+     * @param height   The height of the bitmap
+     * @param config   The bitmap config to create.
+     * @param hasAlpha If the bitmap is ARGB_8888 or RGBA_16F this flag can be used to
+     *                 mark the bitmap as opaque. Doing so will clear the bitmap in black
+     *                 instead of transparent.
+     * @param colorSpace The color space of the bitmap. If null,
+     *                   {@link ColorSpace.Named#SRGB sRGB} is assumed. This argument is
+     *                   ignored if the config is not {@link Config#ARGB_8888}.
+     *
+     * @throws IllegalArgumentException if the width or height are <= 0, if
+     *         Config is Config.HARDWARE (because hardware bitmaps are always
+     *         immutable), if the specified color space is not {@link ColorSpace.Model#RGB RGB},
+     *         or if the specified color space's transfer function is not an
+     *         {@link ColorSpace.Rgb.TransferParameters ICC parametric curve}
+     */
+    public static Bitmap createBitmap(@Nullable DisplayMetrics display, int width, int height,
+            @NonNull Config config, boolean hasAlpha, @Nullable ColorSpace colorSpace) {
         if (width <= 0 || height <= 0) {
             throw new IllegalArgumentException("width and height must be > 0");
         }
         if (config == Config.HARDWARE) {
             throw new IllegalArgumentException("can't create mutable bitmap with Config.HARDWARE");
         }
-        Bitmap bm = nativeCreate(null, 0, width, width, height, config.nativeInt, true);
+
+        Bitmap bm;
+        if (colorSpace == null || config != Config.ARGB_8888) {
+            bm = nativeCreate(null, 0, width, width, height, config.nativeInt, true, null, null);
+        } else {
+            if (!(colorSpace instanceof ColorSpace.Rgb)) {
+                throw new IllegalArgumentException("colorSpace must be an RGB color space");
+            }
+            ColorSpace.Rgb rgb = (ColorSpace.Rgb) colorSpace;
+            ColorSpace.Rgb.TransferParameters parameters = rgb.getTransferParameters();
+            if (parameters == null) {
+                throw new IllegalArgumentException("colorSpace must use an ICC "
+                        + "parametric transfer function");
+            }
+
+            ColorSpace.Rgb d50 = (ColorSpace.Rgb) ColorSpace.adapt(rgb, ColorSpace.ILLUMINANT_D50);
+            bm = nativeCreate(null, 0, width, width, height, config.nativeInt, true,
+                    d50.getTransform(), parameters);
+        }
+
         if (display != null) {
             bm.mDensity = display.densityDpi;
         }
@@ -954,9 +1022,10 @@
     /**
      * Returns a immutable bitmap with the specified width and height, with each
      * pixel value set to the corresponding value in the colors array.  Its
-     * initial density is as per {@link #getDensity}.
+     * initial density is as per {@link #getDensity}. The newly created
+     * bitmap is in the {@link ColorSpace.Named#SRGB sRGB} color space.
      *
-     * @param colors   Array of {@link Color} used to initialize the pixels.
+     * @param colors   Array of sRGB {@link Color colors} used to initialize the pixels.
      * @param offset   Number of values to skip before the first color in the
      *                 array of colors.
      * @param stride   Number of colors in the array between rows (must be >=
@@ -969,8 +1038,8 @@
      * @throws IllegalArgumentException if the width or height are <= 0, or if
      *         the color array's length is less than the number of pixels.
      */
-    public static Bitmap createBitmap(int colors[], int offset, int stride,
-            int width, int height, Config config) {
+    public static Bitmap createBitmap(@NonNull @ColorInt int[] colors, int offset, int stride,
+            int width, int height, @NonNull Config config) {
         return createBitmap(null, colors, offset, stride, width, height, config);
     }
 
@@ -978,10 +1047,12 @@
      * Returns a immutable bitmap with the specified width and height, with each
      * pixel value set to the corresponding value in the colors array.  Its
      * initial density is determined from the given {@link DisplayMetrics}.
+     * The newly created bitmap is in the {@link ColorSpace.Named#SRGB sRGB}
+     * color space.
      *
      * @param display  Display metrics for the display this bitmap will be
      *                 drawn on.
-     * @param colors   Array of {@link Color} used to initialize the pixels.
+     * @param colors   Array of sRGB {@link Color colors} used to initialize the pixels.
      * @param offset   Number of values to skip before the first color in the
      *                 array of colors.
      * @param stride   Number of colors in the array between rows (must be >=
@@ -994,8 +1065,9 @@
      * @throws IllegalArgumentException if the width or height are <= 0, or if
      *         the color array's length is less than the number of pixels.
      */
-    public static Bitmap createBitmap(DisplayMetrics display, int colors[],
-            int offset, int stride, int width, int height, Config config) {
+    public static Bitmap createBitmap(@NonNull DisplayMetrics display,
+            @NonNull @ColorInt int[] colors, int offset, int stride,
+            int width, int height, @NonNull Config config) {
 
         checkWidthHeight(width, height);
         if (Math.abs(stride) < width) {
@@ -1011,7 +1083,7 @@
             throw new IllegalArgumentException("width and height must be > 0");
         }
         Bitmap bm = nativeCreate(colors, offset, stride, width, height,
-                            config.nativeInt, false);
+                            config.nativeInt, false, null, null);
         if (display != null) {
             bm.mDensity = display.densityDpi;
         }
@@ -1021,9 +1093,10 @@
     /**
      * Returns a immutable bitmap with the specified width and height, with each
      * pixel value set to the corresponding value in the colors array.  Its
-     * initial density is as per {@link #getDensity}.
+     * initial density is as per {@link #getDensity}. The newly created
+     * bitmap is in the {@link ColorSpace.Named#SRGB sRGB} color space.
      *
-     * @param colors   Array of {@link Color} used to initialize the pixels.
+     * @param colors   Array of sRGB {@link Color colors} used to initialize the pixels.
      *                 This array must be at least as large as width * height.
      * @param width    The width of the bitmap
      * @param height   The height of the bitmap
@@ -1033,7 +1106,8 @@
      * @throws IllegalArgumentException if the width or height are <= 0, or if
      *         the color array's length is less than the number of pixels.
      */
-    public static Bitmap createBitmap(int colors[], int width, int height, Config config) {
+    public static Bitmap createBitmap(@NonNull @ColorInt int[] colors,
+            int width, int height, Config config) {
         return createBitmap(null, colors, 0, width, width, height, config);
     }
 
@@ -1041,10 +1115,12 @@
      * Returns a immutable bitmap with the specified width and height, with each
      * pixel value set to the corresponding value in the colors array.  Its
      * initial density is determined from the given {@link DisplayMetrics}.
+     * The newly created bitmap is in the {@link ColorSpace.Named#SRGB sRGB}
+     * color space.
      *
      * @param display  Display metrics for the display this bitmap will be
      *                 drawn on.
-     * @param colors   Array of {@link Color} used to initialize the pixels.
+     * @param colors   Array of sRGB {@link Color colors} used to initialize the pixels.
      *                 This array must be at least as large as width * height.
      * @param width    The width of the bitmap
      * @param height   The height of the bitmap
@@ -1054,8 +1130,8 @@
      * @throws IllegalArgumentException if the width or height are <= 0, or if
      *         the color array's length is less than the number of pixels.
      */
-    public static Bitmap createBitmap(DisplayMetrics display, int colors[],
-            int width, int height, Config config) {
+    public static Bitmap createBitmap(@Nullable DisplayMetrics display,
+            @NonNull @ColorInt int colors[], int width, int height, @NonNull Config config) {
         return createBitmap(display, colors, 0, width, width, height, config);
     }
 
@@ -1806,7 +1882,9 @@
 
     private static native Bitmap nativeCreate(int[] colors, int offset,
                                               int stride, int width, int height,
-                                              int nativeConfig, boolean mutable);
+                                              int nativeConfig, boolean mutable,
+                                              @Nullable @Size(9) float[] xyzD50,
+                                              @Nullable ColorSpace.Rgb.TransferParameters p);
     private static native Bitmap nativeCopy(long nativeSrcBitmap, int nativeConfig,
                                             boolean isMutable);
     private static native Bitmap nativeCopyAshmem(long nativeSrcBitmap);
@@ -1865,4 +1943,5 @@
     private static native GraphicBuffer nativeCreateGraphicBufferHandle(long nativeBitmap);
     private static native boolean nativeGetColorSpace(long nativePtr, float[] xyz, float[] params);
     private static native boolean nativeIsSRGB(long nativePtr);
+    private static native void nativeCopyColorSpace(long srcBitmap, long dstBitmap);
 }
diff --git a/libs/hwui/SkiaCanvas.cpp b/libs/hwui/SkiaCanvas.cpp
index 13d7e09..9f649ea 100644
--- a/libs/hwui/SkiaCanvas.cpp
+++ b/libs/hwui/SkiaCanvas.cpp
@@ -58,8 +58,10 @@
 }
 
 SkiaCanvas::SkiaCanvas(const SkBitmap& bitmap) {
+    sk_sp<SkColorSpace> cs = bitmap.refColorSpace();
     mCanvasOwned = std::unique_ptr<SkCanvas>(new SkCanvas(bitmap));
-    mCanvasWrapper = SkCreateColorSpaceXformCanvas(mCanvasOwned.get(), SkColorSpace::MakeSRGB());
+    mCanvasWrapper = SkCreateColorSpaceXformCanvas(mCanvasOwned.get(),
+            cs == nullptr ? SkColorSpace::MakeSRGB() : std::move(cs));
     mCanvas = mCanvasWrapper.get();
 }
 
@@ -97,9 +99,10 @@
 };
 
 void SkiaCanvas::setBitmap(const SkBitmap& bitmap) {
+    sk_sp<SkColorSpace> cs = bitmap.refColorSpace();
     std::unique_ptr<SkCanvas> newCanvas = std::unique_ptr<SkCanvas>(new SkCanvas(bitmap));
-    std::unique_ptr<SkCanvas> newCanvasWrapper =
-            SkCreateColorSpaceXformCanvas(newCanvas.get(), SkColorSpace::MakeSRGB());
+    std::unique_ptr<SkCanvas> newCanvasWrapper = SkCreateColorSpaceXformCanvas(newCanvas.get(),
+            cs == nullptr ? SkColorSpace::MakeSRGB() : std::move(cs));
 
     if (!bitmap.isNull()) {
         // Copy the canvas matrix & clip state.
diff --git a/libs/hwui/hwui/Bitmap.cpp b/libs/hwui/hwui/Bitmap.cpp
index 729c7b8..d7f75fc 100644
--- a/libs/hwui/hwui/Bitmap.cpp
+++ b/libs/hwui/hwui/Bitmap.cpp
@@ -322,6 +322,12 @@
     return sk_sp<Bitmap>(new Bitmap(graphicBuffer.get(), info));
 }
 
+void Bitmap::setColorSpace(sk_sp<SkColorSpace> colorSpace) {
+    // TODO: See todo in reconfigure() below
+    SkImageInfo* myInfo = const_cast<SkImageInfo*>(&this->info());
+    *myInfo = info().makeColorSpace(std::move(colorSpace));
+}
+
 void Bitmap::reconfigure(const SkImageInfo& newInfo, size_t rowBytes, SkColorTable* ctable) {
     if (kIndex_8_SkColorType != newInfo.colorType()) {
         ctable = nullptr;
diff --git a/libs/hwui/hwui/Bitmap.h b/libs/hwui/hwui/Bitmap.h
index 518be03..da45f76 100644
--- a/libs/hwui/hwui/Bitmap.h
+++ b/libs/hwui/hwui/Bitmap.h
@@ -16,6 +16,7 @@
 #pragma once
 
 #include <SkBitmap.h>
+#include <SkColorSpace.h>
 #include <SkColorTable.h>
 #include <SkImageInfo.h>
 #include <SkPixelRef.h>
@@ -82,6 +83,7 @@
 
     void reconfigure(const SkImageInfo& info, size_t rowBytes, SkColorTable* ctable);
     void reconfigure(const SkImageInfo& info);
+    void setColorSpace(sk_sp<SkColorSpace> colorSpace);
     void setAlphaType(SkAlphaType alphaType);
 
     void getSkBitmap(SkBitmap* outBitmap);
diff --git a/media/java/android/media/BufferingParams.java b/media/java/android/media/BufferingParams.java
index fdcd6ba..681271b 100644
--- a/media/java/android/media/BufferingParams.java
+++ b/media/java/android/media/BufferingParams.java
@@ -63,6 +63,7 @@
  * </ul>
  * </ul>
  * <p>Users should use {@link Builder} to change {@link BufferingParams}.
+ * @hide
  */
 public final class BufferingParams implements Parcelable {
     /**
diff --git a/media/java/android/media/MediaPlayer.java b/media/java/android/media/MediaPlayer.java
index 1ee05b8..e6f3cfb 100644
--- a/media/java/android/media/MediaPlayer.java
+++ b/media/java/android/media/MediaPlayer.java
@@ -46,7 +46,6 @@
 import android.widget.VideoView;
 import android.graphics.SurfaceTexture;
 import android.media.AudioManager;
-import android.media.BufferingParams;
 import android.media.MediaDrm;
 import android.media.MediaFormat;
 import android.media.MediaMetricsSet;
@@ -493,11 +492,6 @@
  *     <td>{} </p></td>
  *     <td>This method can be called in any state and calling it does not change
  *         the object state. </p></td></tr>
- * <tr><td>setBufferingParams</p></td>
- *     <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted, Error}</p></td>
- *     <td>{Idle} </p></td>
- *     <td>This method does not change the object state.
- *         </p></td></tr>
  * <tr><td>setPlaybackParams</p></td>
  *     <td>{Initialized, Prepared, Started, Paused, PlaybackCompleted, Error}</p></td>
  *     <td>{Idle, Stopped} </p></td>
@@ -1529,6 +1523,7 @@
      * @return the default buffering management params supported by the source component.
      * @throws IllegalStateException if the internal player engine has not been
      * initialized, or {@code setDataSource} has not been called.
+     * @hide
      */
     @NonNull
     public native BufferingParams getDefaultBufferingParams();
@@ -1540,6 +1535,7 @@
      * @return the current buffering management params used by the source component.
      * @throws IllegalStateException if the internal player engine has not been
      * initialized, or {@code setDataSource} has not been called.
+     * @hide
      */
     @NonNull
     public native BufferingParams getBufferingParams();
@@ -1557,6 +1553,7 @@
      * @throws IllegalStateException if the internal player engine has not been
      * initialized or has been released, or {@code setDataSource} has not been called.
      * @throws IllegalArgumentException if params is invalid or not supported.
+     * @hide
      */
     public native void setBufferingParams(@NonNull BufferingParams params);
 
diff --git a/packages/SystemUI/res/layout/status_bar_notification_shelf.xml b/packages/SystemUI/res/layout/status_bar_notification_shelf.xml
index 6db16fe..7bfbd3c 100644
--- a/packages/SystemUI/res/layout/status_bar_notification_shelf.xml
+++ b/packages/SystemUI/res/layout/status_bar_notification_shelf.xml
@@ -19,7 +19,6 @@
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="@dimen/notification_shelf_height"
-    android:contentDescription="@string/notification_shelf_content_description"
     android:focusable="true"
     android:clickable="true"
     >
diff --git a/packages/SystemUI/res/values/strings.xml b/packages/SystemUI/res/values/strings.xml
index 43aeaa3..7bd9526 100644
--- a/packages/SystemUI/res/values/strings.xml
+++ b/packages/SystemUI/res/values/strings.xml
@@ -412,7 +412,7 @@
     <string name="accessibility_notifications_button">Notifications.</string>
 
     <!-- Content description of overflow icon container of the notifications for accessibility (not shown on the screen)[CHAR LIMIT=NONE] -->
-    <string name="notification_shelf_content_description">Notification overflow container</string>
+    <string name="accessibility_overflow_action">See all notifications</string>
 
     <!-- Content description of the button for removing a notification in the notification panel for accessibility (not shown on the screen). [CHAR LIMIT=NONE] -->
     <string name="accessibility_remove_notification">Clear notification.</string>
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardStatusView.java b/packages/SystemUI/src/com/android/keyguard/KeyguardStatusView.java
index 80b4da8..b2b0ee4 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardStatusView.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardStatusView.java
@@ -301,7 +301,7 @@
 
     private void updateDozeVisibleViews() {
         for (View child : mVisibleInDoze) {
-            child.setAlpha(mDark && mPulsing ? 0.5f : 1);
+            child.setAlpha(mDark && mPulsing ? 0.8f : 1);
         }
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/Dependency.java b/packages/SystemUI/src/com/android/systemui/Dependency.java
index 79190cb..429e859 100644
--- a/packages/SystemUI/src/com/android/systemui/Dependency.java
+++ b/packages/SystemUI/src/com/android/systemui/Dependency.java
@@ -265,7 +265,7 @@
     }
 
     @Override
-    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
+    public synchronized void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
         super.dump(fd, pw, args);
         pw.println("Dumping existing controllers:");
         mDependencies.values().stream().filter(obj -> obj instanceof Dumpable)
@@ -273,7 +273,7 @@
     }
 
     @Override
-    protected void onConfigurationChanged(Configuration newConfig) {
+    protected synchronized void onConfigurationChanged(Configuration newConfig) {
         super.onConfigurationChanged(newConfig);
         mDependencies.values().stream().filter(obj -> obj instanceof ConfigurationChangedReceiver)
                 .forEach(o -> ((ConfigurationChangedReceiver) o).onConfigurationChanged(newConfig));
@@ -287,7 +287,7 @@
         return getDependencyInner(key);
     }
 
-    private <T> T getDependencyInner(Object key) {
+    private synchronized <T> T getDependencyInner(Object key) {
         @SuppressWarnings("unchecked")
         T obj = (T) mDependencies.get(key);
         if (obj == null) {
diff --git a/packages/SystemUI/src/com/android/systemui/plugins/PluginDependencyProvider.java b/packages/SystemUI/src/com/android/systemui/plugins/PluginDependencyProvider.java
index 59f6d56..c58d889 100644
--- a/packages/SystemUI/src/com/android/systemui/plugins/PluginDependencyProvider.java
+++ b/packages/SystemUI/src/com/android/systemui/plugins/PluginDependencyProvider.java
@@ -34,7 +34,9 @@
     }
 
     public <T> void allowPluginDependency(Class<T> cls, T obj) {
-        mDependencies.put(cls, obj);
+        synchronized (mDependencies) {
+            mDependencies.put(cls, obj);
+        }
     }
 
     @Override
@@ -42,9 +44,11 @@
         if (!mManager.dependsOn(p, cls)) {
             throw new IllegalArgumentException(p.getClass() + " does not depend on " + cls);
         }
-        if (!mDependencies.containsKey(cls)) {
-            throw new IllegalArgumentException("Unknown dependency " + cls);
+        synchronized (mDependencies) {
+            if (!mDependencies.containsKey(cls)) {
+                throw new IllegalArgumentException("Unknown dependency " + cls);
+            }
+            return (T) mDependencies.get(cls);
         }
-        return (T) mDependencies.get(cls);
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/settings/BrightnessDialog.java b/packages/SystemUI/src/com/android/systemui/settings/BrightnessDialog.java
index 901d47d..7d847a3 100644
--- a/packages/SystemUI/src/com/android/systemui/settings/BrightnessDialog.java
+++ b/packages/SystemUI/src/com/android/systemui/settings/BrightnessDialog.java
@@ -18,8 +18,11 @@
 
 import android.app.Activity;
 import android.os.Bundle;
+import android.view.ContextThemeWrapper;
 import android.view.Gravity;
 import android.view.KeyEvent;
+import android.view.LayoutInflater;
+import android.view.View;
 import android.view.Window;
 import android.view.WindowManager;
 import android.widget.ImageView;
@@ -43,7 +46,13 @@
         window.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
         window.requestFeature(Window.FEATURE_NO_TITLE);
 
-        setContentView(R.layout.quick_settings_brightness_dialog);
+        // Use a dialog theme as the activity theme, but inflate the content as
+        // the QS content.
+        ContextThemeWrapper themedContext = new ContextThemeWrapper(this,
+                com.android.internal.R.style.Theme_DeviceDefault_QuickSettings);
+        View v = LayoutInflater.from(themedContext).inflate(
+                R.layout.quick_settings_brightness_dialog, null);
+        setContentView(v);
 
         final ImageView icon = (ImageView) findViewById(R.id.brightness_icon);
         final ToggleSliderView slider = (ToggleSliderView) findViewById(R.id.brightness_slider);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShelf.java b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShelf.java
index 715dc82..51345c2 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShelf.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShelf.java
@@ -22,6 +22,7 @@
 import android.util.AttributeSet;
 import android.view.View;
 import android.view.ViewGroup;
+import android.view.accessibility.AccessibilityNodeInfo;
 
 import com.android.systemui.Interpolators;
 import com.android.systemui.R;
@@ -577,7 +578,7 @@
         setClickable(mInteractive);
         setFocusable(mInteractive);
         setImportantForAccessibility(mInteractive ? View.IMPORTANT_FOR_ACCESSIBILITY_YES
-                : View.IMPORTANT_FOR_ACCESSIBILITY_NO);
+                : View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
     }
 
     @Override
@@ -604,6 +605,19 @@
     }
 
     @Override
+    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
+        super.onInitializeAccessibilityNodeInfo(info);
+        if (mInteractive) {
+            info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_EXPAND);
+            AccessibilityNodeInfo.AccessibilityAction unlock
+                    = new AccessibilityNodeInfo.AccessibilityAction(
+                    AccessibilityNodeInfo.ACTION_CLICK,
+                    getContext().getString(R.string.accessibility_overflow_action));
+            info.addAction(unlock);
+        }
+    }
+
+    @Override
     public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft,
             int oldTop, int oldRight, int oldBottom) {
         updateRelativeOffset();
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationViewWrapperTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationViewWrapperTest.java
index 0dad52f..7a72afd 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationViewWrapperTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationViewWrapperTest.java
@@ -24,7 +24,6 @@
 import com.android.systemui.statusbar.ExpandableNotificationRow;
 
 import org.junit.Before;
-import org.junit.Ignore;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
@@ -38,7 +37,6 @@
         mContext = InstrumentationRegistry.getTargetContext();
     }
 
-    @Ignore("Broken")
     @Test
     public void constructor_doesntUseViewContext() throws Exception {
         new TestableNotificationViewWrapper(mContext, null /* view */, null /* row */);
diff --git a/proto/src/metrics_constants.proto b/proto/src/metrics_constants.proto
index b59e00d..579c54c 100644
--- a/proto/src/metrics_constants.proto
+++ b/proto/src/metrics_constants.proto
@@ -3901,6 +3901,11 @@
     // FIELD: Action for a nav button event
     FIELD_NAV_ACTION = 933;
 
+    // OPEN: Settings > Security > Nexus Imprint > [Fingerprint] > Delete
+    // CATEGORY: SETTINGS
+    // OS: O
+    FINGERPRINT_REMOVE_SIDECAR = 934;
+
     // ---- End O Constants, all O constants go above this line ----
 
     // Add new aosp constants above this line.
diff --git a/services/backup/java/com/android/server/backup/BackupManagerService.java b/services/backup/java/com/android/server/backup/BackupManagerService.java
index 413746f..d647c63 100644
--- a/services/backup/java/com/android/server/backup/BackupManagerService.java
+++ b/services/backup/java/com/android/server/backup/BackupManagerService.java
@@ -3109,13 +3109,6 @@
             if (!mCancelAll && mStatus == BackupTransport.TRANSPORT_OK &&
                     mPendingFullBackups != null && !mPendingFullBackups.isEmpty()) {
                 Slog.d(TAG, "Starting full backups for: " + mPendingFullBackups);
-                CountDownLatch latch = new CountDownLatch(1);
-                String[] fullBackups =
-                        mPendingFullBackups.toArray(new String[mPendingFullBackups.size()]);
-                PerformFullTransportBackupTask task =
-                        new PerformFullTransportBackupTask(/*fullBackupRestoreObserver*/ null,
-                                fullBackups, /*updateSchedule*/ false, /*runningJob*/ null, latch,
-                                mObserver, mMonitor, mUserInitiated);
                 // Acquiring wakelock for PerformFullTransportBackupTask before its start.
                 mWakelock.acquire();
                 (new Thread(mFullBackupTask, "full-transport-requested")).start();
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index e1b6bd4..f4e3b31 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -13766,6 +13766,7 @@
         final boolean supportsMultiWindow = ActivityManager.supportsMultiWindow();
         final boolean supportsSplitScreenMultiWindow =
                 ActivityManager.supportsSplitScreenMultiWindow();
+        final boolean supportsMultiDisplay = ActivityManager.supportsMultiDisplay();
         final String debugApp = Settings.Global.getString(resolver, DEBUG_APP);
         final boolean waitForDebugger = Settings.Global.getInt(resolver, WAIT_FOR_DEBUGGER, 0) != 0;
         final boolean alwaysFinishActivities =
@@ -13803,6 +13804,7 @@
             }
             mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
             mSupportsPictureInPicture = supportsPictureInPicture;
+            mSupportsMultiDisplay = supportsMultiDisplay;
             mWindowManager.setForceResizableTasks(mForceResizableActivities);
             mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
             // This happens before any activities are started, so we can change global configuration
@@ -13831,8 +13833,6 @@
                     com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
             }
             mWaitForNetworkTimeoutMs = waitForNetworkTimeoutMs;
-            mSupportsMultiDisplay = res.getBoolean(
-                    com.android.internal.R.bool.config_supportsMultiDisplay);
         }
     }
 
diff --git a/services/core/java/com/android/server/am/ActivityManagerShellCommand.java b/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
index 6011418..2b3a19a 100644
--- a/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
+++ b/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
@@ -2386,7 +2386,7 @@
         if (res == null) {
             return -1;
         }
-        pw.println(res.getBoolean(com.android.internal.R.bool.config_supportsMultiWindow));
+        pw.println(ActivityManager.supportsMultiWindow());
         return 0;
     }
 
@@ -2395,8 +2395,7 @@
         if (res == null) {
             return -1;
         }
-        pw.println(
-                res.getBoolean(com.android.internal.R.bool.config_supportsSplitScreenMultiWindow));
+        pw.println(ActivityManager.supportsSplitScreenMultiWindow());
         return 0;
     }
 
@@ -2405,7 +2404,7 @@
         if (res == null) {
             return -1;
         }
-        pw.println(res.getBoolean(com.android.internal.R.bool.config_supportsMultiDisplay));
+        pw.println(ActivityManager.supportsMultiDisplay());
         return 0;
     }
 
diff --git a/services/core/java/com/android/server/am/ActivityMetricsLogger.java b/services/core/java/com/android/server/am/ActivityMetricsLogger.java
index 5edfb06..2881787 100644
--- a/services/core/java/com/android/server/am/ActivityMetricsLogger.java
+++ b/services/core/java/com/android/server/am/ActivityMetricsLogger.java
@@ -102,7 +102,7 @@
         mLastLogTimeSecs = now;
 
         ActivityStack stack = mSupervisor.getStack(DOCKED_STACK_ID);
-        if (stack != null && stack.getStackVisibilityLocked(null) != STACK_INVISIBLE) {
+        if (stack != null && stack.shouldBeVisible(null) != STACK_INVISIBLE) {
             mWindowState = WINDOW_STATE_SIDE_BY_SIDE;
             return;
         }
diff --git a/services/core/java/com/android/server/am/ActivityRecord.java b/services/core/java/com/android/server/am/ActivityRecord.java
index 6e7ad17..2b953ad 100644
--- a/services/core/java/com/android/server/am/ActivityRecord.java
+++ b/services/core/java/com/android/server/am/ActivityRecord.java
@@ -505,7 +505,8 @@
                     else TimeUtils.formatDuration(startTime, now, pw);
                     pw.println();
         }
-        final boolean waitingVisible = mStackSupervisor.mWaitingVisibleActivities.contains(this);
+        final boolean waitingVisible =
+                mStackSupervisor.mActivitiesWaitingForVisibleActivity.contains(this);
         if (lastVisibleTime != 0 || waitingVisible || nowVisible) {
             pw.print(prefix); pw.print("waitingVisible="); pw.print(waitingVisible);
                     pw.print(" nowVisible="); pw.print(nowVisible);
@@ -1912,13 +1913,14 @@
                     // If this activity was already idle, then we now need to make sure we perform
                     // the full stop of any activities that are waiting to do so. This is because
                     // we won't do that while they are still waiting for this one to become visible.
-                    final int size = mStackSupervisor.mWaitingVisibleActivities.size();
+                    final int size = mStackSupervisor.mActivitiesWaitingForVisibleActivity.size();
                     if (size > 0) {
                         for (int i = 0; i < size; i++) {
-                            ActivityRecord r = mStackSupervisor.mWaitingVisibleActivities.get(i);
+                            final ActivityRecord r =
+                                    mStackSupervisor.mActivitiesWaitingForVisibleActivity.get(i);
                             if (DEBUG_SWITCH) Log.v(TAG_SWITCH, "Was waiting for visible: " + r);
                         }
-                        mStackSupervisor.mWaitingVisibleActivities.clear();
+                        mStackSupervisor.mActivitiesWaitingForVisibleActivity.clear();
                         mStackSupervisor.scheduleIdleLocked();
                     }
                 }
@@ -1959,7 +1961,7 @@
         // First find the real culprit...  if this activity is waiting for
         // another activity to start or has stopped, then the key dispatching
         // timeout should not be caused by this.
-        if (mStackSupervisor.mWaitingVisibleActivities.contains(this) || stopped) {
+        if (mStackSupervisor.mActivitiesWaitingForVisibleActivity.contains(this) || stopped) {
             final ActivityStack stack = mStackSupervisor.getFocusedStack();
             // Try to use the one which is closest to top.
             ActivityRecord r = stack.mResumedActivity;
diff --git a/services/core/java/com/android/server/am/ActivityStack.java b/services/core/java/com/android/server/am/ActivityStack.java
index f13b11e..4ee1a207 100644
--- a/services/core/java/com/android/server/am/ActivityStack.java
+++ b/services/core/java/com/android/server/am/ActivityStack.java
@@ -116,7 +116,6 @@
 import android.util.SparseArray;
 import android.view.Display;
 
-import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.app.IVoiceInteractor;
 import com.android.internal.os.BatteryStatsImpl;
 import com.android.server.Watchdog;
@@ -1349,7 +1348,7 @@
             } else if (prev.app != null) {
                 if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Enqueue pending stop if needed: " + prev
                         + " wasStopping=" + wasStopping + " visible=" + prev.visible);
-                if (mStackSupervisor.mWaitingVisibleActivities.remove(prev)) {
+                if (mStackSupervisor.mActivitiesWaitingForVisibleActivity.remove(prev)) {
                     if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(TAG_PAUSE,
                             "Complete pause, no longer waiting: " + prev);
                 }
@@ -1560,12 +1559,18 @@
         return true;
     }
 
+    /** Returns true if the stack is currently considered visible. */
+    boolean isVisible() {
+        return mWindowContainerController != null && mWindowContainerController.isVisible();
+    }
+
     /**
-     * Returns stack's visibility: {@link #STACK_INVISIBLE}, {@link #STACK_VISIBLE} or
-     * {@link #STACK_VISIBLE_ACTIVITY_BEHIND}.
+     * Returns what the stack visibility should be: {@link #STACK_INVISIBLE}, {@link #STACK_VISIBLE}
+     * or {@link #STACK_VISIBLE_ACTIVITY_BEHIND}.
+     *
      * @param starting The currently starting activity or null if there is none.
      */
-    int getStackVisibilityLocked(ActivityRecord starting) {
+    int shouldBeVisible(ActivityRecord starting) {
         if (!isAttached()) {
             return STACK_INVISIBLE;
         }
@@ -1715,7 +1720,7 @@
             // If the top activity is not fullscreen, then we need to
             // make sure any activities under it are now visible.
             boolean aboveTop = top != null;
-            final int stackVisibility = getStackVisibilityLocked(starting);
+            final int stackVisibility = shouldBeVisible(starting);
             final boolean stackInvisible = stackVisibility != STACK_VISIBLE;
             final boolean stackVisibleBehind = stackVisibility == STACK_VISIBLE_ACTIVITY_BEHIND;
             boolean behindFullscreenActivity = stackInvisible;
@@ -2097,7 +2102,7 @@
         // activities as we need to display their starting window until they are done initializing.
         boolean behindFullscreenActivity = false;
 
-        if (getStackVisibilityLocked(null) == STACK_INVISIBLE) {
+        if (shouldBeVisible(null) == STACK_INVISIBLE) {
             // The stack is not visible, so no activity in it should be displaying a starting
             // window. Mark all activities below top and behind fullscreen.
             aboveTop = false;
@@ -2262,7 +2267,7 @@
         mStackSupervisor.mStoppingActivities.remove(next);
         mStackSupervisor.mGoingToSleepActivities.remove(next);
         next.sleeping = false;
-        mStackSupervisor.mWaitingVisibleActivities.remove(next);
+        mStackSupervisor.mActivitiesWaitingForVisibleActivity.remove(next);
 
         if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "Resuming " + next);
 
@@ -2324,9 +2329,9 @@
         }
 
         if (prev != null && prev != next) {
-            if (!mStackSupervisor.mWaitingVisibleActivities.contains(prev)
+            if (!mStackSupervisor.mActivitiesWaitingForVisibleActivity.contains(prev)
                     && next != null && !next.nowVisible) {
-                mStackSupervisor.mWaitingVisibleActivities.add(prev);
+                mStackSupervisor.mActivitiesWaitingForVisibleActivity.add(prev);
                 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
                         "Resuming top, waiting visible to hide: " + prev);
             } else {
@@ -2342,13 +2347,13 @@
                     prev.setVisibility(false);
                     if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
                             "Not waiting for visible to hide: " + prev + ", waitingVisible="
-                            + mStackSupervisor.mWaitingVisibleActivities.contains(prev)
+                            + mStackSupervisor.mActivitiesWaitingForVisibleActivity.contains(prev)
                             + ", nowVisible=" + next.nowVisible);
                 } else {
                     if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
                             "Previous already visible but still waiting to hide: " + prev
                             + ", waitingVisible="
-                            + mStackSupervisor.mWaitingVisibleActivities.contains(prev)
+                            + mStackSupervisor.mActivitiesWaitingForVisibleActivity.contains(prev)
                             + ", nowVisible=" + next.nowVisible);
                 }
             }
@@ -3617,8 +3622,8 @@
         mWindowManager.prepareAppTransition(transit, false);
         r.setVisibility(false);
         mWindowManager.executeAppTransition();
-        if (!mStackSupervisor.mWaitingVisibleActivities.contains(r)) {
-            mStackSupervisor.mWaitingVisibleActivities.add(r);
+        if (!mStackSupervisor.mActivitiesWaitingForVisibleActivity.contains(r)) {
+            mStackSupervisor.mActivitiesWaitingForVisibleActivity.add(r);
         }
     }
 
@@ -3650,7 +3655,7 @@
         // make sure the record is cleaned out of other places.
         mStackSupervisor.mStoppingActivities.remove(r);
         mStackSupervisor.mGoingToSleepActivities.remove(r);
-        mStackSupervisor.mWaitingVisibleActivities.remove(r);
+        mStackSupervisor.mActivitiesWaitingForVisibleActivity.remove(r);
         if (mResumedActivity == r) {
             mResumedActivity = null;
         }
@@ -3870,11 +3875,9 @@
             r.app = null;
         }
 
-        // Make sure this record is no longer in the pending finishes list.
-        // This could happen, for example, if we are trimming activities
-        // down to the max limit while they are still waiting to finish.
-        mStackSupervisor.mFinishingActivities.remove(r);
-        mStackSupervisor.mWaitingVisibleActivities.remove(r);
+        // Inform supervisor the activity has been removed.
+        mStackSupervisor.cleanupActivity(r);
+
 
         // Remove any pending results.
         if (r.finishing && r.pendingResults != null) {
@@ -4184,7 +4187,7 @@
         if (hasVisibleBehindActivity() &&
                 !mHandler.hasMessages(RELEASE_BACKGROUND_RESOURCES_TIMEOUT_MSG)) {
             if (r == topRunningActivityLocked()
-                    && getStackVisibilityLocked(null) == STACK_VISIBLE) {
+                    && shouldBeVisible(null) == STACK_VISIBLE) {
                 // Don't release the top activity if it has requested to run behind the next
                 // activity and the stack is currently visible.
                 return;
@@ -4253,8 +4256,8 @@
                 "mStoppingActivities");
         removeHistoryRecordsForAppLocked(mStackSupervisor.mGoingToSleepActivities, app,
                 "mGoingToSleepActivities");
-        removeHistoryRecordsForAppLocked(mStackSupervisor.mWaitingVisibleActivities, app,
-                "mWaitingVisibleActivities");
+        removeHistoryRecordsForAppLocked(mStackSupervisor.mActivitiesWaitingForVisibleActivity, app,
+                "mActivitiesWaitingForVisibleActivity");
         removeHistoryRecordsForAppLocked(mStackSupervisor.mFinishingActivities, app,
                 "mFinishingActivities");
 
diff --git a/services/core/java/com/android/server/am/ActivityStackSupervisor.java b/services/core/java/com/android/server/am/ActivityStackSupervisor.java
index 30e33c8..0ea834a 100644
--- a/services/core/java/com/android/server/am/ActivityStackSupervisor.java
+++ b/services/core/java/com/android/server/am/ActivityStackSupervisor.java
@@ -153,6 +153,7 @@
 import android.provider.Settings;
 import android.provider.Settings.SettingNotFoundException;
 import android.service.voice.IVoiceInteractionSession;
+import android.text.TextUtils;
 import android.util.ArrayMap;
 import android.util.ArraySet;
 import android.util.EventLog;
@@ -164,7 +165,6 @@
 import android.view.InputEvent;
 import android.view.Surface;
 
-import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.content.ReferrerIntent;
 import com.android.internal.logging.MetricsLogger;
 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
@@ -174,7 +174,6 @@
 import com.android.internal.widget.LockPatternUtils;
 import com.android.server.LocalServices;
 import com.android.server.am.ActivityStack.ActivityState;
-import com.android.server.wm.StackWindowController;
 import com.android.server.wm.WindowManagerService;
 
 import java.io.FileDescriptor;
@@ -346,10 +345,12 @@
 
     /** List of activities that are waiting for a new activity to become visible before completing
      * whatever operation they are supposed to do. */
-    final ArrayList<ActivityRecord> mWaitingVisibleActivities = new ArrayList<>();
+    // TODO: Remove mActivitiesWaitingForVisibleActivity list and just remove activity from
+    // mStoppingActivities when something else comes up.
+    final ArrayList<ActivityRecord> mActivitiesWaitingForVisibleActivity = new ArrayList<>();
 
-    /** List of processes waiting to find out about the next visible activity. */
-    final ArrayList<WaitResult> mWaitingActivityVisible = new ArrayList<>();
+    /** List of processes waiting to find out when a specific activity becomes visible. */
+    private final ArrayList<WaitInfo> mWaitingForActivityVisible = new ArrayList<>();
 
     /** List of processes waiting to find out about the next launched activity. */
     final ArrayList<WaitResult> mWaitingActivityLaunched = new ArrayList<>();
@@ -1003,7 +1004,7 @@
                 final ActivityStack stack = stacks.get(stackNdx);
                 final ActivityRecord r = stack.mResumedActivity;
                 if (r != null) {
-                    if (!r.nowVisible || mWaitingVisibleActivities.contains(r)) {
+                    if (!r.nowVisible || mActivitiesWaitingForVisibleActivity.contains(r)) {
                         return false;
                     }
                     foundResumed = true;
@@ -1083,22 +1084,41 @@
         }
     }
 
+    void waitActivityVisible(ComponentName name, WaitResult result) {
+        final WaitInfo waitInfo = new WaitInfo(name, result);
+        mWaitingForActivityVisible.add(waitInfo);
+    }
+
+    void cleanupActivity(ActivityRecord r) {
+        // Make sure this record is no longer in the pending finishes list.
+        // This could happen, for example, if we are trimming activities
+        // down to the max limit while they are still waiting to finish.
+        mFinishingActivities.remove(r);
+        mActivitiesWaitingForVisibleActivity.remove(r);
+
+        for (int i = mWaitingForActivityVisible.size() - 1; i >= 0; --i) {
+            if (mWaitingForActivityVisible.get(i).matches(r)) {
+                mWaitingForActivityVisible.remove(i);
+            }
+        }
+    }
+
     void reportActivityVisibleLocked(ActivityRecord r) {
         sendWaitingVisibleReportLocked(r);
     }
 
     void sendWaitingVisibleReportLocked(ActivityRecord r) {
         boolean changed = false;
-        for (int i = mWaitingActivityVisible.size()-1; i >= 0; i--) {
-            WaitResult w = mWaitingActivityVisible.get(i);
-            if (w.who == null) {
+        for (int i = mWaitingForActivityVisible.size() - 1; i >= 0; --i) {
+            final WaitInfo w = mWaitingForActivityVisible.get(i);
+            if (w.matches(r)) {
+                final WaitResult result = w.getResult();
                 changed = true;
-                w.timeout = false;
-                if (r != null) {
-                    w.who = new ComponentName(r.info.packageName, r.info.name);
-                }
-                w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
-                w.thisTime = w.totalTime;
+                result.timeout = false;
+                result.who = w.getComponent();
+                result.totalTime = SystemClock.uptimeMillis() - result.thisTime;
+                result.thisTime = result.totalTime;
+                mWaitingForActivityVisible.remove(w);
             }
         }
         if (changed) {
@@ -2184,7 +2204,7 @@
             for (int j = stacks.size() - 1; j >= 0; --j) {
                 final ActivityStack stack = stacks.get(j);
                 if (stack != currentFocus && stack.isFocusable()
-                        && stack.getStackVisibilityLocked(null) != STACK_INVISIBLE) {
+                        && stack.shouldBeVisible(null) != STACK_INVISIBLE) {
                     return stack;
                 }
             }
@@ -2345,7 +2365,7 @@
             }
             ActivityStack fullscreenStack = getStack(FULLSCREEN_WORKSPACE_STACK_ID);
             final boolean isFullscreenStackVisible = fullscreenStack != null &&
-                    fullscreenStack.getStackVisibilityLocked(null) == STACK_VISIBLE;
+                    fullscreenStack.shouldBeVisible(null) == STACK_VISIBLE;
             // If we are moving from the pinned stack, then the animation takes care of updating
             // the picture-in-picture mode.
             final boolean schedulePictureInPictureModeChange = (fromStackId != PINNED_STACK_ID);
@@ -2520,7 +2540,7 @@
             final ActivityStack fullscreenStack = getStack(FULLSCREEN_WORKSPACE_STACK_ID);
             if (fullscreenStack != null) {
                 final boolean isFullscreenStackVisible =
-                        fullscreenStack.getStackVisibilityLocked(null) == STACK_VISIBLE;
+                        fullscreenStack.shouldBeVisible(null) == STACK_VISIBLE;
                 for (int i = 0; i < tasks.size(); i++) {
                     // Insert the task either at the top of the fullscreen stack if it is hidden,
                     // or to the bottom if it is currently visible
@@ -3421,13 +3441,11 @@
         final boolean nowVisible = allResumedActivitiesVisible();
         for (int activityNdx = mStoppingActivities.size() - 1; activityNdx >= 0; --activityNdx) {
             ActivityRecord s = mStoppingActivities.get(activityNdx);
-            // TODO: Remove mWaitingVisibleActivities list and just remove activity from
-            // mStoppingActivities when something else comes up.
-            boolean waitingVisible = mWaitingVisibleActivities.contains(s);
+            boolean waitingVisible = mActivitiesWaitingForVisibleActivity.contains(s);
             if (DEBUG_STATES) Slog.v(TAG, "Stopping " + s + ": nowVisible=" + nowVisible
                     + " waitingVisible=" + waitingVisible + " finishing=" + s.finishing);
             if (waitingVisible && nowVisible) {
-                mWaitingVisibleActivities.remove(s);
+                mActivitiesWaitingForVisibleActivity.remove(s);
                 waitingVisible = false;
                 if (s.finishing) {
                     // If this activity is finishing, it is sitting on top of
@@ -3520,6 +3538,13 @@
                 pw.print(":"); pw.println(Arrays.toString(packages.valueAt(i)));
             }
         }
+        if (!mWaitingForActivityVisible.isEmpty()) {
+            pw.print(prefix); pw.println("mWaitingForActivityVisible=");
+            for (int i = 0; i < mWaitingForActivityVisible.size(); ++i) {
+                pw.print(prefix); pw.print(prefix); mWaitingForActivityVisible.get(i).dump(pw, prefix);
+            }
+        }
+
         pw.println(" mLockTaskModeTasks" + mLockTaskModeTasks);
         mKeyguardController.dump(pw, prefix);
     }
@@ -3554,7 +3579,7 @@
                 for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
                     ActivityStack stack = stacks.get(stackNdx);
                     if (!dumpVisibleStacksOnly ||
-                            stack.getStackVisibilityLocked(null) == STACK_VISIBLE) {
+                            stack.shouldBeVisible(null) == STACK_VISIBLE) {
                         activities.addAll(stack.getDumpActivitiesLocked(name));
                     }
                 }
@@ -3642,9 +3667,9 @@
                 false, dumpPackage, true, "  Activities waiting to finish:", null);
         printed |= dumpHistoryList(fd, pw, mStoppingActivities, "  ", "Stop", false, !dumpAll,
                 false, dumpPackage, true, "  Activities waiting to stop:", null);
-        printed |= dumpHistoryList(fd, pw, mWaitingVisibleActivities, "  ", "Wait", false, !dumpAll,
-                false, dumpPackage, true, "  Activities waiting for another to become visible:",
-                null);
+        printed |= dumpHistoryList(fd, pw, mActivitiesWaitingForVisibleActivity, "  ", "Wait",
+                false, !dumpAll, false, dumpPackage, true,
+                "  Activities waiting for another to become visible:", null);
         printed |= dumpHistoryList(fd, pw, mGoingToSleepActivities, "  ", "Sleep", false, !dumpAll,
                 false, dumpPackage, true, "  Activities waiting to sleep:", null);
         printed |= dumpHistoryList(fd, pw, mGoingToSleepActivities, "  ", "Sleep", false, !dumpAll,
@@ -3861,7 +3886,7 @@
         info.displayId = DEFAULT_DISPLAY;
         info.stackId = stack.mStackId;
         info.userId = stack.mCurrentUser;
-        info.visible = stack.getStackVisibilityLocked(null) == STACK_VISIBLE;
+        info.visible = stack.shouldBeVisible(null) == STACK_VISIBLE;
         info.position = display != null
                 ? display.mStacks.indexOf(stack)
                 : 0;
@@ -4980,7 +5005,7 @@
             for (int j = display.mStacks.size() - 1; j >= 0; j--) {
                 final ActivityStack stack = display.mStacks.get(j);
                 // Get top activity from a visible stack and add it to the list.
-                if (stack.getStackVisibilityLocked(null /* starting */)
+                if (stack.shouldBeVisible(null /* starting */)
                         == ActivityStack.STACK_VISIBLE) {
                     final ActivityRecord top = stack.topActivity();
                     if (top != null) {
@@ -4995,4 +5020,38 @@
         }
         return topActivityTokens;
     }
+
+    /**
+     * Internal container to store a match qualifier alongside a WaitResult.
+     */
+    static class WaitInfo {
+        private final ComponentName mTargetComponent;
+        private final WaitResult mResult;
+
+        public WaitInfo(ComponentName targetComponent, WaitResult result) {
+            this.mTargetComponent = targetComponent;
+            this.mResult = result;
+        }
+
+        public boolean matches(ActivityRecord record) {
+            return mTargetComponent == null ||
+                    (TextUtils.equals(mTargetComponent.getPackageName(), record.info.packageName)
+                            && TextUtils.equals(mTargetComponent.getClassName(), record.info.name));
+        }
+
+        public WaitResult getResult() {
+            return mResult;
+        }
+
+        public ComponentName getComponent() {
+            return mTargetComponent;
+        }
+
+        public void dump(PrintWriter pw, String prefix) {
+            pw.println(prefix + "WaitInfo:");
+            pw.println(prefix + "  mTargetComponent=" + mTargetComponent);
+            pw.println(prefix + "  mResult=");
+            mResult.dump(pw, prefix);
+        }
+    }
 }
diff --git a/services/core/java/com/android/server/am/ActivityStarter.java b/services/core/java/com/android/server/am/ActivityStarter.java
index bb5f588..a30591b 100644
--- a/services/core/java/com/android/server/am/ActivityStarter.java
+++ b/services/core/java/com/android/server/am/ActivityStarter.java
@@ -74,7 +74,6 @@
 import static com.android.server.am.ActivityRecord.APPLICATION_ACTIVITY_TYPE;
 import static com.android.server.am.ActivityRecord.ASSISTANT_ACTIVITY_TYPE;
 import static com.android.server.am.ActivityRecord.HOME_ACTIVITY_TYPE;
-import static com.android.server.am.ActivityRecord.RECENTS_ACTIVITY_TYPE;
 import static com.android.server.am.ActivityStack.ActivityState.RESUMED;
 import static com.android.server.am.ActivityStack.STACK_INVISIBLE;
 import static com.android.server.am.ActivityStackSupervisor.CREATE_IF_NEEDED;
@@ -118,14 +117,11 @@
 import android.service.voice.IVoiceInteractionSession;
 import android.util.EventLog;
 import android.util.Slog;
-import android.view.Display;
 
 import com.android.internal.app.HeavyWeightSwitcherActivity;
 import com.android.internal.app.IVoiceInteractor;
-import com.android.server.LocalServices;
 import com.android.server.am.ActivityStackSupervisor.PendingActivityLaunch;
 import com.android.server.pm.InstantAppResolver;
-import com.android.server.vr.VrManagerInternal;
 import com.android.server.wm.WindowManagerService;
 
 import java.util.ArrayList;
@@ -152,7 +148,6 @@
 
     // Share state variable among methods when starting an activity.
     private ActivityRecord mStartActivity;
-    private ActivityRecord mReusedActivity;
     private Intent mIntent;
     private int mCallingUid;
     private ActivityOptions mOptions;
@@ -520,7 +515,7 @@
         doPendingActivityLaunchesLocked(false);
 
         return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags, true,
-                options, inTask);
+                options, inTask, outActivity);
     }
 
     /**
@@ -562,31 +557,17 @@
             startedActivityStackId = targetStack.mStackId;
         }
 
-        // If we launched the activity from a no display activity that was launched from the home
-        // screen, we also need to start recents to un-minimize the docked stack, since the
-        // noDisplay activity will be finished shortly after.
-        // Note that some apps have trampoline activities without noDisplay being set. In that case,
-        // we have another heuristic in DockedStackDividerController.notifyAppTransitionStarting
-        // that tries to detect that case.
-        // TODO: We should prevent noDisplay activities from affecting task/stack ordering and
-        // visibility instead of using this flag.
-        final boolean noDisplayActivityOverHome = sourceRecord != null
-                && sourceRecord.noDisplay
-                && sourceRecord.getTask().getTaskToReturnTo() == HOME_ACTIVITY_TYPE;
-        if (startedActivityStackId == DOCKED_STACK_ID
-                && (prevFocusedStackId == HOME_STACK_ID || noDisplayActivityOverHome)) {
+        if (startedActivityStackId == DOCKED_STACK_ID) {
             final ActivityStack homeStack = mSupervisor.getStack(HOME_STACK_ID);
-            final ActivityRecord topActivityHomeStack = homeStack != null
-                    ? homeStack.topRunningActivityLocked() : null;
-            if (topActivityHomeStack == null
-                    || topActivityHomeStack.mActivityType != RECENTS_ACTIVITY_TYPE) {
+            final boolean homeStackVisible = homeStack != null && homeStack.isVisible();
+            if (homeStackVisible) {
                 // We launch an activity while being in home stack, which means either launcher or
                 // recents into docked stack. We don't want the launched activity to be alone in a
                 // docked stack, so we want to immediately launch recents too.
                 if (DEBUG_RECENTS) Slog.d(TAG, "Scheduling recents launch.");
                 mWindowManager.showRecentApps(true /* fromHome */);
-                return;
             }
+            return;
         }
 
         if (startedActivityStackId == PINNED_STACK_ID
@@ -821,15 +802,19 @@
                     }
                 }
                 if (res == START_TASK_TO_FRONT) {
-                    ActivityRecord r = stack.topRunningActivityLocked();
+                    final ActivityRecord r = outRecord[0];
+
+                    // ActivityRecord may represent a different activity, but it should not be in
+                    // the resumed state.
                     if (r.nowVisible && r.state == RESUMED) {
                         outResult.timeout = false;
-                        outResult.who = new ComponentName(r.info.packageName, r.info.name);
+                        outResult.who = r.realActivity;
                         outResult.totalTime = 0;
                         outResult.thisTime = 0;
                     } else {
                         outResult.thisTime = SystemClock.uptimeMillis();
-                        mSupervisor.mWaitingActivityVisible.add(outResult);
+                        mSupervisor.waitActivityVisible(r.realActivity, outResult);
+                        // Note: the timeout variable is not currently not ever set.
                         do {
                             try {
                                 mService.wait();
@@ -840,9 +825,7 @@
                 }
             }
 
-            final ActivityRecord launchedActivity = mReusedActivity != null
-                    ? mReusedActivity : outRecord[0];
-            mSupervisor.mActivityMetricsLogger.notifyActivityLaunched(res, launchedActivity);
+            mSupervisor.mActivityMetricsLogger.notifyActivityLaunched(res, outRecord[0]);
             return res;
         }
     }
@@ -954,12 +937,13 @@
 
     private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
             IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
-            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask) {
+            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
+            ActivityRecord[] outActivity) {
         int result = START_CANCELED;
         try {
             mService.mWindowManager.deferSurfaceLayout();
             result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
-                    startFlags, doResume, options, inTask);
+                    startFlags, doResume, options, inTask, outActivity);
         } finally {
             // If we are not able to proceed, disassociate the activity from the task. Leaving an
             // activity in an incomplete state can lead to issues, such as performing operations
@@ -979,7 +963,8 @@
     // Note: This method should only be called from {@link startActivity}.
     private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
             IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
-            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask) {
+            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
+            ActivityRecord[] outActivity) {
 
         setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession,
                 voiceInteractor);
@@ -990,16 +975,16 @@
 
         mIntent.setFlags(mLaunchFlags);
 
-        mReusedActivity = getReusableIntentActivity();
+        ActivityRecord reusedActivity = getReusableIntentActivity();
 
         final int preferredLaunchStackId =
                 (mOptions != null) ? mOptions.getLaunchStackId() : INVALID_STACK_ID;
 
-        if (mReusedActivity != null) {
+        if (reusedActivity != null) {
             // When the flags NEW_TASK and CLEAR_TASK are set, then the task gets reused but
             // still needs to be a lock task mode violation since the task gets cleared out and
             // the device would otherwise leave the locked task.
-            if (mSupervisor.isLockTaskModeViolation(mReusedActivity.getTask(),
+            if (mSupervisor.isLockTaskModeViolation(reusedActivity.getTask(),
                     (mLaunchFlags & (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK))
                             == (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK))) {
                 mSupervisor.showLockTaskToast();
@@ -1008,12 +993,12 @@
             }
 
             if (mStartActivity.getTask() == null) {
-                mStartActivity.setTask(mReusedActivity.getTask());
+                mStartActivity.setTask(reusedActivity.getTask());
             }
-            if (mReusedActivity.getTask().intent == null) {
+            if (reusedActivity.getTask().intent == null) {
                 // This task was started because of movement of the activity based on affinity...
                 // Now that we are actually launching it, we can assign the base intent.
-                mReusedActivity.getTask().setIntent(mStartActivity);
+                reusedActivity.getTask().setIntent(mStartActivity);
             }
 
             // This code path leads to delivering a new intent, we want to make sure we schedule it
@@ -1022,7 +1007,7 @@
             if ((mLaunchFlags & FLAG_ACTIVITY_CLEAR_TOP) != 0
                     || isDocumentLaunchesIntoExisting(mLaunchFlags)
                     || mLaunchSingleInstance || mLaunchSingleTask) {
-                final TaskRecord task = mReusedActivity.getTask();
+                final TaskRecord task = reusedActivity.getTask();
 
                 // In this situation we want to remove all activities from the task up to the one
                 // being started. In most cases this means we are resetting the task to its initial
@@ -1030,12 +1015,12 @@
                 final ActivityRecord top = task.performClearTaskForReuseLocked(mStartActivity,
                         mLaunchFlags);
 
-                // The above code can remove {@code mReusedActivity} from the task, leading to the
+                // The above code can remove {@code reusedActivity} from the task, leading to the
                 // the {@code ActivityRecord} removing its reference to the {@code TaskRecord}. The
                 // task reference is needed in the call below to
                 // {@link setTargetStackAndMoveToFrontIfNeeded}.
-                if (mReusedActivity.getTask() == null) {
-                    mReusedActivity.setTask(task);
+                if (reusedActivity.getTask() == null) {
+                    reusedActivity.setTask(task);
                 }
 
                 if (top != null) {
@@ -1052,7 +1037,10 @@
 
             sendPowerHintForLaunchStartIfNeeded(false /* forceSend */);
 
-            mReusedActivity = setTargetStackAndMoveToFrontIfNeeded(mReusedActivity);
+            reusedActivity = setTargetStackAndMoveToFrontIfNeeded(reusedActivity);
+            if (outActivity.length > 0) {
+                outActivity[0] = reusedActivity;
+            }
 
             if ((mStartFlags & START_FLAG_ONLY_IF_NEEDED) != 0) {
                 // We don't need to start a new activity, and the client said not to do anything
@@ -1061,7 +1049,7 @@
                 resumeTargetStackIfNeeded();
                 return START_RETURN_INTENT_TO_CALLER;
             }
-            setTaskFromIntentActivity(mReusedActivity);
+            setTaskFromIntentActivity(reusedActivity);
 
             if (!mAddingToTask && mReuseTask == null) {
                 // We didn't do anything...  but it was needed (a.k.a., client don't use that
@@ -1963,7 +1951,7 @@
             final boolean resume = doResume && mPendingActivityLaunches.isEmpty();
             try {
                 startActivity(pal.r, pal.sourceRecord, null, null, pal.startFlags, resume, null,
-                        null);
+                        null, null /*outRecords*/);
             } catch (Exception e) {
                 Slog.e(TAG, "Exception during pending activity launch pal=" + pal, e);
                 pal.sendErrorResult(e.getMessage());
@@ -2150,7 +2138,7 @@
                 // activity into parent's stack, because we can't find a better place.
                 final ActivityStack dockedStack = mSupervisor.getStack(DOCKED_STACK_ID);
                 if (dockedStack != null
-                        && dockedStack.getStackVisibilityLocked(r) == STACK_INVISIBLE) {
+                        && dockedStack.shouldBeVisible(r) == STACK_INVISIBLE) {
                     // There is a docked stack, but it isn't visible, so we can't launch into that.
                     return null;
                 } else {
diff --git a/services/core/java/com/android/server/fingerprint/FingerprintService.java b/services/core/java/com/android/server/fingerprint/FingerprintService.java
index 2b85570..656e01a 100644
--- a/services/core/java/com/android/server/fingerprint/FingerprintService.java
+++ b/services/core/java/com/android/server/fingerprint/FingerprintService.java
@@ -1,4 +1,4 @@
-/**
+/*
  * Copyright (C) 2014 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
@@ -16,6 +16,12 @@
 
 package com.android.server.fingerprint;
 
+import static android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
+import static android.Manifest.permission.INTERACT_ACROSS_USERS;
+import static android.Manifest.permission.MANAGE_FINGERPRINT;
+import static android.Manifest.permission.RESET_FINGERPRINT_LOCKOUT;
+import static android.Manifest.permission.USE_FINGERPRINT;
+
 import android.Manifest;
 import android.app.ActivityManager;
 import android.app.ActivityManager.RunningAppProcessInfo;
@@ -30,8 +36,14 @@
 import android.content.IntentFilter;
 import android.content.pm.PackageManager;
 import android.content.pm.UserInfo;
+import android.hardware.biometrics.fingerprint.V2_1.IBiometricsFingerprint;
+import android.hardware.biometrics.fingerprint.V2_1.IBiometricsFingerprintClientCallback;
+import android.hardware.fingerprint.Fingerprint;
+import android.hardware.fingerprint.FingerprintManager;
 import android.hardware.fingerprint.IFingerprintClientActiveCallback;
+import android.hardware.fingerprint.IFingerprintService;
 import android.hardware.fingerprint.IFingerprintServiceLockoutResetCallback;
+import android.hardware.fingerprint.IFingerprintServiceReceiver;
 import android.os.Binder;
 import android.os.Bundle;
 import android.os.DeadObjectException;
@@ -42,12 +54,12 @@
 import android.os.IRemoteCallback;
 import android.os.PowerManager;
 import android.os.PowerManager.WakeLock;
-import android.security.KeyStore;
 import android.os.RemoteException;
 import android.os.SELinux;
 import android.os.SystemClock;
 import android.os.UserHandle;
 import android.os.UserManager;
+import android.security.KeyStore;
 import android.service.fingerprint.FingerprintActionStatsProto;
 import android.service.fingerprint.FingerprintServiceDumpProto;
 import android.service.fingerprint.FingerprintUserStatsProto;
@@ -64,19 +76,6 @@
 import org.json.JSONException;
 import org.json.JSONObject;
 
-import android.hardware.biometrics.fingerprint.V2_1.IBiometricsFingerprint;
-import android.hardware.biometrics.fingerprint.V2_1.IBiometricsFingerprintClientCallback;
-import android.hardware.fingerprint.Fingerprint;
-import android.hardware.fingerprint.FingerprintManager;
-import android.hardware.fingerprint.IFingerprintService;
-import android.hardware.fingerprint.IFingerprintServiceReceiver;
-
-import static android.Manifest.permission.INTERACT_ACROSS_USERS;
-import static android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
-import static android.Manifest.permission.MANAGE_FINGERPRINT;
-import static android.Manifest.permission.RESET_FINGERPRINT_LOCKOUT;
-import static android.Manifest.permission.USE_FINGERPRINT;
-
 import java.io.File;
 import java.io.FileDescriptor;
 import java.io.PrintWriter;
@@ -121,7 +120,7 @@
     private static final int MAX_FAILED_ATTEMPTS = 5;
     private static final long CANCEL_TIMEOUT_LIMIT = 3000; // max wait for onCancel() from HAL,in ms
     private final String mKeyguardPackage;
-    private int mCurrentUserId = UserHandle.USER_CURRENT;
+    private int mCurrentUserId = UserHandle.USER_NULL;
     private final FingerprintUtils mFingerprintUtils = FingerprintUtils.getInstance();
     private Context mContext;
     private long mHalDeviceId;
@@ -208,10 +207,6 @@
     public void serviceDied(long cookie) {
         Slog.v(TAG, "fingerprint HAL died");
         MetricsLogger.count(mContext, "fingerprintd_died", 1);
-        synchronized (this) {
-            mDaemon = null;
-        }
-        mCurrentUserId = UserHandle.USER_CURRENT;
         handleError(mHalDeviceId, FingerprintManager.FINGERPRINT_ERROR_HW_UNAVAILABLE,
                 0 /*vendorCode */);
     }
@@ -300,6 +295,7 @@
             synchronized (this) {
                 mDaemon = null;
                 mHalDeviceId = 0;
+                mCurrentUserId = UserHandle.USER_NULL;
             }
         }
     }
@@ -538,15 +534,16 @@
         final long token = Binder.clearCallingIdentity();
         try {
             // Allow current user or profiles of the current user...
-            for (int profileId : um.getEnabledProfileIds(mCurrentUserId)) {
+            for (int profileId : um.getEnabledProfileIds(ActivityManager.getCurrentUser())) {
                 if (profileId == userId) {
                     return true;
                 }
             }
-            return false;
         } finally {
             Binder.restoreCallingIdentity(token);
         }
+
+        return false;
     }
 
     private boolean isForegroundActivity(int uid, int pid) {
@@ -635,7 +632,7 @@
             } catch (RemoteException re) {
                 // If the remote is dead, stop notifying it
                 mClientActiveCallbacks.remove(callbacks.get(i));
-           }
+            }
         }
     }
 
@@ -982,7 +979,6 @@
                     startRemove(token, fingerId, groupId, userId, receiver, restricted);
                 }
             });
-
         }
 
         public void enumerate(final IBinder token, final int userId,
@@ -995,7 +991,6 @@
                     startEnumerate(token, userId, receiver, restricted);
                 }
             });
-
         }
 
         @Override // Binder call
@@ -1004,8 +999,14 @@
                     Binder.getCallingUid(), Binder.getCallingPid())) {
                 return false;
             }
-            IBiometricsFingerprint daemon = getFingerprintDaemon();
-            return daemon != null && mHalDeviceId != 0;
+
+            final long token = Binder.clearCallingIdentity();
+            try {
+                IBiometricsFingerprint daemon = getFingerprintDaemon();
+                return daemon != null && mHalDeviceId != 0;
+            } finally {
+                Binder.restoreCallingIdentity(token);
+            }
         }
 
         @Override // Binder call
@@ -1029,9 +1030,6 @@
                     Binder.getCallingUid(), Binder.getCallingPid())) {
                 return Collections.emptyList();
             }
-            if (!isCurrentUserOrProfile(userId)) {
-                return Collections.emptyList();
-            }
 
             return FingerprintService.this.getEnrolledFingerprints(userId);
         }
@@ -1043,9 +1041,6 @@
                 return false;
             }
 
-            if (!isCurrentUserOrProfile(userId)) {
-                return false;
-            }
             return FingerprintService.this.hasEnrolledFingerprints(userId);
         }
 
@@ -1085,6 +1080,7 @@
                 Binder.restoreCallingIdentity(ident);
             }
         }
+
         @Override // Binder call
         public void resetTimeout(byte [] token) {
             checkPermission(RESET_FINGERPRINT_LOCKOUT);
diff --git a/services/core/java/com/android/server/notification/RankingHelper.java b/services/core/java/com/android/server/notification/RankingHelper.java
index b63b05f..b789d5c 100644
--- a/services/core/java/com/android/server/notification/RankingHelper.java
+++ b/services/core/java/com/android/server/notification/RankingHelper.java
@@ -152,7 +152,8 @@
         if (type != XmlPullParser.START_TAG) return;
         String tag = parser.getName();
         if (!TAG_RANKING.equals(tag)) return;
-        mRecords.clear();
+        // Clobber groups and channels with the xml, but don't delete other data that wasn't present
+        // at the time of serialization.
         mRestoredWithoutUids.clear();
         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
             tag = parser.getName();
diff --git a/services/core/java/com/android/server/vr/CompatibilityDisplay.java b/services/core/java/com/android/server/vr/CompatibilityDisplay.java
index ae1d50f..ee615fd 100644
--- a/services/core/java/com/android/server/vr/CompatibilityDisplay.java
+++ b/services/core/java/com/android/server/vr/CompatibilityDisplay.java
@@ -8,7 +8,7 @@
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
-import android.graphics.ImageFormat;
+import android.graphics.PixelFormat;
 import android.hardware.display.DisplayManager;
 import android.hardware.display.VirtualDisplay;
 import android.media.ImageReader;
@@ -279,7 +279,7 @@
      */
     private void startImageReader() {
         if (mImageReader == null) {
-            mImageReader = ImageReader.newInstance(WIDTH, HEIGHT, ImageFormat.RAW_PRIVATE,
+            mImageReader = ImageReader.newInstance(WIDTH, HEIGHT, PixelFormat.RGBA_8888,
                 2 /* maxImages */);
         }
         synchronized (mVdLock) {
diff --git a/services/core/java/com/android/server/webkit/WebViewUpdater.java b/services/core/java/com/android/server/webkit/WebViewUpdater.java
index 56311a3..37479c8 100644
--- a/services/core/java/com/android/server/webkit/WebViewUpdater.java
+++ b/services/core/java/com/android/server/webkit/WebViewUpdater.java
@@ -315,15 +315,6 @@
             }
         }
 
-        // Could not find any installed and enabled package either, use the most stable and
-        // default-available provider.
-        // TODO(gsennton) remove this when we have a functional WebView stub.
-        for (ProviderAndPackageInfo providerAndPackage : providers) {
-            if (providerAndPackage.provider.availableByDefault) {
-                return providerAndPackage.packageInfo;
-            }
-        }
-
         // This should never happen during normal operation (only with modified system images).
         mAnyWebViewInstalled = false;
         throw new WebViewPackageMissingException("Could not find a loadable WebView package");
diff --git a/services/core/java/com/android/server/wm/StackWindowController.java b/services/core/java/com/android/server/wm/StackWindowController.java
index 635527e..5d0384e 100644
--- a/services/core/java/com/android/server/wm/StackWindowController.java
+++ b/services/core/java/com/android/server/wm/StackWindowController.java
@@ -94,6 +94,12 @@
         }
     }
 
+    public boolean isVisible() {
+        synchronized (mWindowMap) {
+            return mContainer != null && mContainer.isVisible();
+        }
+    }
+
     public void reparent(int displayId, Rect outStackBounds) {
         synchronized (mWindowMap) {
             if (mContainer == null) {
@@ -363,7 +369,7 @@
     }
 
     /** Calls directly into activity manager so window manager lock shouldn't held. */
-    public void updatePictureInPictureModeForPinnedStackAnimation(Rect targetStackBounds) {
+    void updatePictureInPictureModeForPinnedStackAnimation(Rect targetStackBounds) {
         if (mListener != null) {
             mListener.updatePictureInPictureModeForPinnedStackAnimation(targetStackBounds);
         }
diff --git a/services/tests/notification/src/com/android/server/notification/RankingHelperTest.java b/services/tests/notification/src/com/android/server/notification/RankingHelperTest.java
index ad593be..885eb2e 100644
--- a/services/tests/notification/src/com/android/server/notification/RankingHelperTest.java
+++ b/services/tests/notification/src/com/android/server/notification/RankingHelperTest.java
@@ -490,6 +490,19 @@
     }
 
     @Test
+    public void testLoadingOldChannelsDoesNotDeleteNewlyCreatedChannels() throws Exception {
+        ByteArrayOutputStream baos = writeXmlAndPurge(PKG, UID, false,
+                NotificationChannel.DEFAULT_CHANNEL_ID, "bananas");
+        mHelper.createNotificationChannel(PKG, UID,
+                new NotificationChannel("bananas", "bananas", IMPORTANCE_LOW), true);
+
+        loadStreamXml(baos);
+
+        // Should still have the newly created channel that wasn't in the xml.
+        assertTrue(mHelper.getNotificationChannel(PKG, UID, "bananas", false) != null);
+    }
+
+    @Test
     public void testCreateChannel_blocked() throws Exception {
         mHelper.setImportance(PKG, UID, NotificationManager.IMPORTANCE_NONE);
 
diff --git a/services/tests/servicestests/src/com/android/server/webkit/WebViewUpdateServiceTest.java b/services/tests/servicestests/src/com/android/server/webkit/WebViewUpdateServiceTest.java
index 925f414..9c8007a 100644
--- a/services/tests/servicestests/src/com/android/server/webkit/WebViewUpdateServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/webkit/WebViewUpdateServiceTest.java
@@ -1219,14 +1219,11 @@
 
         runWebViewBootPreparationOnMainSync();
 
-        checkPreparationPhasesForPackage(testPackageName, 1 /* first preparation phase */);
-        // TODO(gsennton) change this logic to use the code below when we have created a functional
-        // stub.
-        //Mockito.verify(mTestSystemImpl, Mockito.never()).onWebViewProviderChanged(
-        //        Matchers.anyObject());
-        //WebViewProviderResponse response = mWebViewUpdateServiceImpl.waitForAndGetProvider();
-        //assertEquals(WebViewFactory.LIBLOAD_FAILED_LISTING_WEBVIEW_PACKAGES, response.status);
-        //assertEquals(null, mWebViewUpdateServiceImpl.getCurrentWebViewPackage());
+        Mockito.verify(mTestSystemImpl, Mockito.never()).onWebViewProviderChanged(
+                Matchers.anyObject());
+        WebViewProviderResponse response = mWebViewUpdateServiceImpl.waitForAndGetProvider();
+        assertEquals(WebViewFactory.LIBLOAD_FAILED_LISTING_WEBVIEW_PACKAGES, response.status);
+        assertEquals(null, mWebViewUpdateServiceImpl.getCurrentWebViewPackage());
     }
 
     @Test
diff --git a/telephony/java/android/telephony/CarrierConfigManager.java b/telephony/java/android/telephony/CarrierConfigManager.java
index bb83633..0b4a3e8 100644
--- a/telephony/java/android/telephony/CarrierConfigManager.java
+++ b/telephony/java/android/telephony/CarrierConfigManager.java
@@ -771,6 +771,13 @@
     public static final String KEY_EDITABLE_ENHANCED_4G_LTE_BOOL = "editable_enhanced_4g_lte_bool";
 
     /**
+     * Determines whether the Enhanced 4G LTE toggle will be shown in the settings. When this
+     * option is {@code true}, the toggle will be hidden regardless of whether the device and
+     * carrier supports 4G LTE or not.
+     */
+    public static final String KEY_HIDE_ENHANCED_4G_LTE_BOOL = "hide_enhanced_4g_lte_bool";
+
+    /**
      * Determine whether IMS apn can be shown.
      */
     public static final String KEY_HIDE_IMS_APN_BOOL = "hide_ims_apn_bool";
@@ -1529,6 +1536,7 @@
         sDefaults.putInt(KEY_IMS_CONFERENCE_SIZE_LIMIT_INT, 5);
         sDefaults.putBoolean(KEY_DISPLAY_HD_AUDIO_PROPERTY_BOOL, true);
         sDefaults.putBoolean(KEY_EDITABLE_ENHANCED_4G_LTE_BOOL, true);
+        sDefaults.putBoolean(KEY_HIDE_ENHANCED_4G_LTE_BOOL, false);
         sDefaults.putBoolean(KEY_HIDE_IMS_APN_BOOL, false);
         sDefaults.putBoolean(KEY_HIDE_PREFERRED_NETWORK_TYPE_BOOL, false);
         sDefaults.putBoolean(KEY_ALLOW_EMERGENCY_VIDEO_CALLS_BOOL, false);
diff --git a/telephony/java/android/telephony/TelephonyManager.java b/telephony/java/android/telephony/TelephonyManager.java
index 8357a2b..1fd1929 100644
--- a/telephony/java/android/telephony/TelephonyManager.java
+++ b/telephony/java/android/telephony/TelephonyManager.java
@@ -3106,30 +3106,6 @@
     }
 
     /**
-     * Send the special dialer code. The IPC caller must be the current default dialer.
-     * <p>
-     * Requires Permission:
-     *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
-     *
-     * @param inputCode The special dialer code to send which follows the format of *#*#<code>#*#*
-     * @return true if sent sucessfully, false otherwise
-     * @deprecated use {@link #sendDialerSpecialCode(String)} ()} instead.
-     */
-    public boolean sendDialerCode(String inputCode) {
-        try {
-            final ITelephony telephony = getITelephony();
-            if (telephony == null) {
-                Log.e(TAG, "Telephony service unavailable");
-                return false;
-            }
-            return telephony.sendDialerCode(mContext.getOpPackageName(), inputCode);
-        } catch (RemoteException | NullPointerException ex) {
-            // This could happen before phone restarts due to crashing
-            return false;
-        }
-    }
-
-    /**
      * Send the special dialer code. The IPC caller must be the current default dialer or has
      * carrier privileges.
      * @see #hasCarrierPrivileges
diff --git a/telephony/java/com/android/internal/telephony/ITelephony.aidl b/telephony/java/com/android/internal/telephony/ITelephony.aidl
index cd15c44..db7e417 100644
--- a/telephony/java/com/android/internal/telephony/ITelephony.aidl
+++ b/telephony/java/com/android/internal/telephony/ITelephony.aidl
@@ -530,9 +530,6 @@
             in String number, in int port, in String text, in PendingIntent sentIntent);
 
     // Send the special dialer code. The IPC caller must be the current default dialer.
-    boolean sendDialerCode(String callingPackageName, String inputCode);
-
-    // Send the special dialer code. The IPC caller must be the current default dialer.
     void sendDialerSpecialCode(String callingPackageName, String inputCode);
 
     /**
diff --git a/tools/aapt2/link/Link.cpp b/tools/aapt2/link/Link.cpp
index a33fd06..407eb52 100644
--- a/tools/aapt2/link/Link.cpp
+++ b/tools/aapt2/link/Link.cpp
@@ -2151,7 +2151,7 @@
   }
 
   AxisConfigFilter filter;
-  if (configs.empty()) {
+  if (!configs.empty()) {
     for (const std::string& config_arg : configs) {
       for (const StringPiece& config_str : util::Tokenize(config_arg, ',')) {
         ConfigDescription config;