Merge "Allow home app being instrumented while starting home from PhoneWindowManager"
diff --git a/Android.bp b/Android.bp
index 035420f..56547b2 100644
--- a/Android.bp
+++ b/Android.bp
@@ -886,66 +886,6 @@
     output_extension: "srcjar",
 }
 
-// AIDL interfaces between the core system and the networking mainline module.
-aidl_interface {
-    name: "networkstack-aidl-interfaces",
-    local_include_dir: "core/java",
-    srcs: [
-        "core/java/android/net/ApfCapabilitiesParcelable.aidl",
-        "core/java/android/net/DhcpResultsParcelable.aidl",
-        "core/java/android/net/INetworkMonitor.aidl",
-        "core/java/android/net/INetworkMonitorCallbacks.aidl",
-        "core/java/android/net/INetworkStackConnector.aidl",
-        "core/java/android/net/INetworkStackStatusCallback.aidl",
-        "core/java/android/net/InitialConfigurationParcelable.aidl",
-        "core/java/android/net/PrivateDnsConfigParcel.aidl",
-        "core/java/android/net/ProvisioningConfigurationParcelable.aidl",
-        "core/java/android/net/StaticIpConfigurationParcelable.aidl",
-        "core/java/android/net/TcpKeepalivePacketDataParcelable.aidl",
-        "core/java/android/net/dhcp/DhcpServingParamsParcel.aidl",
-        "core/java/android/net/dhcp/IDhcpServer.aidl",
-        "core/java/android/net/dhcp/IDhcpServerCallbacks.aidl",
-        "core/java/android/net/ip/IIpClient.aidl",
-        "core/java/android/net/ip/IIpClientCallbacks.aidl",
-        "core/java/android/net/IIpMemoryStore.aidl",
-        "core/java/android/net/IIpMemoryStoreCallbacks.aidl",
-        "core/java/android/net/ipmemorystore/**/*.aidl",
-    ],
-    backend: {
-        ndk: {
-            enabled: false,
-        },
-        cpp: {
-            enabled: false,
-        },
-    },
-    api_dir: "aidl/networkstack",
-}
-
-aidl_interface {
-    name: "ipmemorystore-aidl-interfaces",
-    local_include_dir: "core/java",
-    srcs: [
-        "core/java/android/net/IIpMemoryStore.aidl",
-        "core/java/android/net/IIpMemoryStoreCallbacks.aidl",
-        "core/java/android/net/ipmemorystore/**/*.aidl",
-    ],
-}
-
-aidl_interface {
-    name: "networkstack-aidl-framework",
-    local_include_dir: "core/java",
-    srcs: [
-        "core/java/android/net/TcpKeepalivePacketDataParcelable.aidl",
-    ],
-    api_dir: "aidl/networkstack",
-    backend: {
-        java: {
-            sdk_version: "28",
-        },
-    },
-}
-
 filegroup {
     name: "framework-annotations",
     srcs: [
diff --git a/api/current.txt b/api/current.txt
index 14fb910..a961295 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -5848,8 +5848,8 @@
     field public static final int INTERRUPTION_FILTER_NONE = 3; // 0x3
     field public static final int INTERRUPTION_FILTER_PRIORITY = 2; // 0x2
     field public static final int INTERRUPTION_FILTER_UNKNOWN = 0; // 0x0
-    field public static final String META_DATA_AUTOMATIC_RULE_TYPE = "android.app.automatic.ruleType";
-    field public static final String META_DATA_RULE_INSTANCE_LIMIT = "android.app.zen.automatic.ruleInstanceLimit";
+    field public static final String META_DATA_AUTOMATIC_RULE_TYPE = "android.service.zen.automatic.ruleType";
+    field public static final String META_DATA_RULE_INSTANCE_LIMIT = "android.service.zen.automatic.ruleInstanceLimit";
   }
 
   public static class NotificationManager.Policy implements android.os.Parcelable {
@@ -23249,7 +23249,7 @@
     method public static boolean isHapticPlaybackSupported();
     method public boolean isMicrophoneMute();
     method public boolean isMusicActive();
-    method public static boolean isOffloadedPlaybackSupported(@NonNull android.media.AudioFormat);
+    method public static boolean isOffloadedPlaybackSupported(@NonNull android.media.AudioFormat, @NonNull android.media.AudioAttributes);
     method public boolean isSpeakerphoneOn();
     method public boolean isStreamMute(int);
     method public boolean isVolumeFixed();
@@ -23484,11 +23484,11 @@
     method public void release();
     method public void removeOnRoutingChangedListener(android.media.AudioRouting.OnRoutingChangedListener);
     method @Deprecated public void removeOnRoutingChangedListener(android.media.AudioRecord.OnRoutingChangedListener);
-    method public boolean setMicrophoneDirection(int);
-    method public boolean setMicrophoneFieldDimension(@FloatRange(from=-1.0, to=1.0) float);
     method public int setNotificationMarkerPosition(int);
     method public int setPositionNotificationPeriod(int);
     method public boolean setPreferredDevice(android.media.AudioDeviceInfo);
+    method public boolean setPreferredMicrophoneDirection(int);
+    method public boolean setPreferredMicrophoneFieldDimension(@FloatRange(from=-1.0, to=1.0) float);
     method public void setRecordPositionUpdateListener(android.media.AudioRecord.OnRecordPositionUpdateListener);
     method public void setRecordPositionUpdateListener(android.media.AudioRecord.OnRecordPositionUpdateListener, android.os.Handler);
     method public void startRecording() throws java.lang.IllegalStateException;
@@ -23760,12 +23760,6 @@
     field public static final int QUALITY_MEDIUM = 1; // 0x1
   }
 
-  public abstract class DataSourceCallback implements java.io.Closeable {
-    ctor public DataSourceCallback();
-    method public abstract long getSize() throws java.io.IOException;
-    method public abstract int readAt(long, @NonNull byte[], int, int) throws java.io.IOException;
-  }
-
   public class DataSourceDesc {
     method public long getEndPosition();
     method @Nullable public String getMediaId();
@@ -23782,7 +23776,6 @@
     method @NonNull public android.media.DataSourceDesc.Builder setDataSource(@NonNull android.net.Uri, @Nullable java.util.Map<java.lang.String,java.lang.String>, @Nullable java.util.List<java.net.HttpCookie>);
     method @NonNull public android.media.DataSourceDesc.Builder setDataSource(@NonNull android.os.ParcelFileDescriptor);
     method @NonNull public android.media.DataSourceDesc.Builder setDataSource(@NonNull android.os.ParcelFileDescriptor, long, long);
-    method @NonNull public android.media.DataSourceDesc.Builder setDataSource(@NonNull android.media.DataSourceCallback);
     method @NonNull public android.media.DataSourceDesc.Builder setEndPosition(long);
     method @NonNull public android.media.DataSourceDesc.Builder setMediaId(@Nullable String);
     method @NonNull public android.media.DataSourceDesc.Builder setStartPosition(long);
@@ -25554,8 +25547,8 @@
     method @NonNull public Object clearNextDataSources();
     method public void clearPendingCommands();
     method public void close();
-    method @NonNull public Object deselectTrack(int);
-    method @NonNull public Object deselectTrack(@NonNull android.media.DataSourceDesc, int);
+    method @NonNull public Object deselectTrack(@NonNull android.media.MediaPlayer2.TrackInfo);
+    method @NonNull public Object deselectTrack(@NonNull android.media.DataSourceDesc, @NonNull android.media.MediaPlayer2.TrackInfo);
     method @NonNull public android.media.AudioAttributes getAudioAttributes();
     method public int getAudioSessionId();
     method public long getBufferedPosition();
@@ -25570,8 +25563,8 @@
     method public float getPlayerVolume();
     method @Nullable public android.media.AudioDeviceInfo getPreferredDevice();
     method @Nullable public android.media.AudioDeviceInfo getRoutedDevice();
-    method public int getSelectedTrack(int);
-    method public int getSelectedTrack(@NonNull android.media.DataSourceDesc, int);
+    method @Nullable public android.media.MediaPlayer2.TrackInfo getSelectedTrack(int);
+    method @Nullable public android.media.MediaPlayer2.TrackInfo getSelectedTrack(@NonNull android.media.DataSourceDesc, int);
     method public int getState();
     method @NonNull public android.media.SyncParams getSyncParams();
     method @Nullable public android.media.MediaTimestamp getTimestamp();
@@ -25589,8 +25582,8 @@
     method public void reset();
     method @NonNull public Object seekTo(long);
     method @NonNull public Object seekTo(long, int);
-    method @NonNull public Object selectTrack(int);
-    method @NonNull public Object selectTrack(@NonNull android.media.DataSourceDesc, int);
+    method @NonNull public Object selectTrack(@NonNull android.media.MediaPlayer2.TrackInfo);
+    method @NonNull public Object selectTrack(@NonNull android.media.DataSourceDesc, @NonNull android.media.MediaPlayer2.TrackInfo);
     method @NonNull public Object setAudioAttributes(@NonNull android.media.AudioAttributes);
     method @NonNull public Object setAudioSessionId(int);
     method @NonNull public Object setAuxEffectSendLevel(float);
@@ -25683,11 +25676,11 @@
     field public static final int SEEK_PREVIOUS_SYNC = 0; // 0x0
   }
 
-  public static class MediaPlayer2.DrmEventCallback {
+  public abstract static class MediaPlayer2.DrmEventCallback {
     ctor public MediaPlayer2.DrmEventCallback();
     method public void onDrmConfig(@NonNull android.media.MediaPlayer2, @NonNull android.media.DataSourceDesc, @NonNull android.media.MediaDrm);
-    method @Nullable public android.media.MediaPlayer2.DrmPreparationInfo onDrmInfo(@NonNull android.media.MediaPlayer2, @NonNull android.media.DataSourceDesc, @NonNull android.media.MediaPlayer2.DrmInfo);
-    method @NonNull public byte[] onDrmKeyRequest(@NonNull android.media.MediaPlayer2, @NonNull android.media.DataSourceDesc, @NonNull android.media.MediaDrm.KeyRequest);
+    method @Nullable public abstract android.media.MediaPlayer2.DrmPreparationInfo onDrmInfo(@NonNull android.media.MediaPlayer2, @NonNull android.media.DataSourceDesc, @NonNull android.media.MediaPlayer2.DrmInfo);
+    method @NonNull public abstract byte[] onDrmKeyRequest(@NonNull android.media.MediaPlayer2, @NonNull android.media.DataSourceDesc, @NonNull android.media.MediaDrm.KeyRequest);
     method public void onDrmPrepared(@NonNull android.media.MediaPlayer2, @NonNull android.media.DataSourceDesc, int, @Nullable byte[]);
   }
 
@@ -25697,17 +25690,22 @@
   }
 
   public static final class MediaPlayer2.DrmPreparationInfo {
+    method @Nullable public byte[] getInitData();
+    method @Nullable public byte[] getKeySetId();
+    method public int getKeyType();
+    method @Nullable public String getMimeType();
+    method @Nullable public java.util.Map<java.lang.String,java.lang.String> getOptionalParameters();
+    method @NonNull public java.util.UUID getUuid();
   }
 
   public static final class MediaPlayer2.DrmPreparationInfo.Builder {
-    ctor public MediaPlayer2.DrmPreparationInfo.Builder();
+    ctor public MediaPlayer2.DrmPreparationInfo.Builder(@NonNull java.util.UUID);
     method @NonNull public android.media.MediaPlayer2.DrmPreparationInfo build();
     method @NonNull public android.media.MediaPlayer2.DrmPreparationInfo.Builder setInitData(@Nullable byte[]);
     method @NonNull public android.media.MediaPlayer2.DrmPreparationInfo.Builder setKeySetId(@Nullable byte[]);
     method @NonNull public android.media.MediaPlayer2.DrmPreparationInfo.Builder setKeyType(int);
     method @NonNull public android.media.MediaPlayer2.DrmPreparationInfo.Builder setMimeType(@Nullable String);
     method @NonNull public android.media.MediaPlayer2.DrmPreparationInfo.Builder setOptionalParameters(@Nullable java.util.Map<java.lang.String,java.lang.String>);
-    method @NonNull public android.media.MediaPlayer2.DrmPreparationInfo.Builder setUuid(@NonNull java.util.UUID);
   }
 
   public static class MediaPlayer2.EventCallback {
@@ -25717,7 +25715,7 @@
     method public void onError(@NonNull android.media.MediaPlayer2, @NonNull android.media.DataSourceDesc, int, int);
     method public void onInfo(@NonNull android.media.MediaPlayer2, @NonNull android.media.DataSourceDesc, int, int);
     method public void onMediaTimeDiscontinuity(@NonNull android.media.MediaPlayer2, @NonNull android.media.DataSourceDesc, @NonNull android.media.MediaTimestamp);
-    method public void onSubtitleData(@NonNull android.media.MediaPlayer2, @NonNull android.media.DataSourceDesc, @NonNull android.media.SubtitleData);
+    method public void onSubtitleData(@NonNull android.media.MediaPlayer2, @NonNull android.media.DataSourceDesc, @NonNull android.media.MediaPlayer2.SubtitleData);
     method public void onTimedMetaDataAvailable(@NonNull android.media.MediaPlayer2, @NonNull android.media.DataSourceDesc, @NonNull android.media.TimedMetaData);
     method public void onVideoSizeChanged(@NonNull android.media.MediaPlayer2, @NonNull android.media.DataSourceDesc, @NonNull android.util.Size);
   }
@@ -25741,6 +25739,13 @@
     ctor public MediaPlayer2.NoDrmSchemeException(@Nullable String);
   }
 
+  public static final class MediaPlayer2.SubtitleData {
+    method @NonNull public byte[] getData();
+    method public long getDurationUs();
+    method public long getStartTimeUs();
+    method @NonNull public android.media.MediaPlayer2.TrackInfo getTrackInfo();
+  }
+
   public static class MediaPlayer2.TrackInfo {
     method @Nullable public android.media.MediaFormat getFormat();
     method @NonNull public String getLanguage();
@@ -25782,8 +25787,6 @@
     method public void setLocation(float, float);
     method public void setMaxDuration(int) throws java.lang.IllegalArgumentException;
     method public void setMaxFileSize(long) throws java.lang.IllegalArgumentException;
-    method public boolean setMicrophoneDirection(int);
-    method public boolean setMicrophoneFieldDimension(@FloatRange(from=-1.0, to=1.0) float);
     method public void setNextOutputFile(java.io.FileDescriptor) throws java.io.IOException;
     method public void setNextOutputFile(java.io.File) throws java.io.IOException;
     method public void setOnErrorListener(android.media.MediaRecorder.OnErrorListener);
@@ -25794,6 +25797,8 @@
     method public void setOutputFile(String) throws java.lang.IllegalStateException;
     method public void setOutputFormat(int) throws java.lang.IllegalStateException;
     method public boolean setPreferredDevice(android.media.AudioDeviceInfo);
+    method public boolean setPreferredMicrophoneDirection(int);
+    method public boolean setPreferredMicrophoneFieldDimension(@FloatRange(from=-1.0, to=1.0) float);
     method public void setPreviewDisplay(android.view.Surface);
     method public void setProfile(android.media.CamcorderProfile);
     method public void setVideoEncoder(int) throws java.lang.IllegalStateException;
@@ -26137,11 +26142,11 @@
   }
 
   public interface MicrophoneDirection {
-    method public boolean setMicrophoneDirection(int);
-    method public boolean setMicrophoneFieldDimension(@FloatRange(from=-1.0, to=1.0) float);
-    field public static final int MIC_DIRECTION_BACK = 2; // 0x2
+    method public boolean setPreferredMicrophoneDirection(int);
+    method public boolean setPreferredMicrophoneFieldDimension(@FloatRange(from=-1.0, to=1.0) float);
+    field public static final int MIC_DIRECTION_AWAY_FROM_USER = 2; // 0x2
     field public static final int MIC_DIRECTION_EXTERNAL = 3; // 0x3
-    field public static final int MIC_DIRECTION_FRONT = 1; // 0x1
+    field public static final int MIC_DIRECTION_TOWARDS_USER = 1; // 0x1
     field public static final int MIC_DIRECTION_UNSPECIFIED = 0; // 0x0
   }
 
@@ -28734,8 +28739,8 @@
 
   public final class DnsResolver {
     method @NonNull public static android.net.DnsResolver getInstance();
-    method public <T> void query(@Nullable android.net.Network, @NonNull byte[], int, @NonNull java.util.concurrent.Executor, @NonNull android.net.DnsResolver.AnswerCallback<T>);
-    method public <T> void query(@Nullable android.net.Network, @NonNull String, int, int, int, @NonNull java.util.concurrent.Executor, @NonNull android.net.DnsResolver.AnswerCallback<T>);
+    method public <T> void query(@Nullable android.net.Network, @NonNull byte[], int, @NonNull java.util.concurrent.Executor, @Nullable android.os.CancellationSignal, @NonNull android.net.DnsResolver.AnswerCallback<T>);
+    method public <T> void query(@Nullable android.net.Network, @NonNull String, int, int, int, @NonNull java.util.concurrent.Executor, @Nullable android.os.CancellationSignal, @NonNull android.net.DnsResolver.AnswerCallback<T>);
     field public static final int CLASS_IN = 1; // 0x1
     field public static final int FLAG_EMPTY = 0; // 0x0
     field public static final int FLAG_NO_CACHE_LOOKUP = 4; // 0x4
@@ -38751,8 +38756,7 @@
     field public static final String MIME_TYPE = "mime_type";
     field public static final String ORIGINAL_DOCUMENT_ID = "original_document_id";
     field public static final String OWNER_PACKAGE_NAME = "owner_package_name";
-    field public static final String PRIMARY_DIRECTORY = "primary_directory";
-    field public static final String SECONDARY_DIRECTORY = "secondary_directory";
+    field public static final String RELATIVE_PATH = "relative_path";
     field public static final String SIZE = "_size";
     field public static final String TITLE = "title";
     field public static final String WIDTH = "width";
@@ -45021,7 +45025,7 @@
     method public String getCountryIso();
     method public int getDataRoaming();
     method public CharSequence getDisplayName();
-    method @Nullable public String getGroupUuid();
+    method @Nullable public android.os.ParcelUuid getGroupUuid();
     method public String getIccId();
     method public int getIconTint();
     method @Deprecated public int getMcc();
@@ -45041,7 +45045,9 @@
   public class SubscriptionManager {
     method public void addOnOpportunisticSubscriptionsChangedListener(@NonNull java.util.concurrent.Executor, @NonNull android.telephony.SubscriptionManager.OnOpportunisticSubscriptionsChangedListener);
     method public void addOnSubscriptionsChangedListener(android.telephony.SubscriptionManager.OnSubscriptionsChangedListener);
+    method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void addSubscriptionsIntoGroup(@NonNull java.util.List<java.lang.Integer>, @NonNull android.os.ParcelUuid);
     method public boolean canManageSubscription(android.telephony.SubscriptionInfo);
+    method @NonNull @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public android.os.ParcelUuid createSubscriptionGroup(@NonNull java.util.List<java.lang.Integer>);
     method @Deprecated public static android.telephony.SubscriptionManager from(android.content.Context);
     method public java.util.List<android.telephony.SubscriptionInfo> getAccessibleSubscriptionInfoList();
     method @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public android.telephony.SubscriptionInfo getActiveSubscriptionInfo(int);
@@ -45057,16 +45063,15 @@
     method public static int getSlotIndex(int);
     method @Nullable public int[] getSubscriptionIds(int);
     method @NonNull public java.util.List<android.telephony.SubscriptionPlan> getSubscriptionPlans(int);
-    method @Nullable @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public java.util.List<android.telephony.SubscriptionInfo> getSubscriptionsInGroup(int);
+    method @NonNull @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public java.util.List<android.telephony.SubscriptionInfo> getSubscriptionsInGroup(@NonNull android.os.ParcelUuid);
     method @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public boolean isActiveSubscriptionId(int);
     method public boolean isNetworkRoaming(int);
     method public static boolean isUsableSubscriptionId(int);
     method public static boolean isValidSubscriptionId(int);
     method public void removeOnOpportunisticSubscriptionsChangedListener(@NonNull android.telephony.SubscriptionManager.OnOpportunisticSubscriptionsChangedListener);
     method public void removeOnSubscriptionsChangedListener(android.telephony.SubscriptionManager.OnSubscriptionsChangedListener);
-    method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public boolean removeSubscriptionsFromGroup(@NonNull int[]);
+    method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void removeSubscriptionsFromGroup(@NonNull java.util.List<java.lang.Integer>, @NonNull android.os.ParcelUuid);
     method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public boolean setOpportunistic(boolean, int);
-    method @Nullable @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public String setSubscriptionGroup(@NonNull int[]);
     method public void setSubscriptionOverrideCongested(int, boolean, long);
     method public void setSubscriptionOverrideUnmetered(int, boolean, long);
     method public void setSubscriptionPlans(int, @NonNull java.util.List<android.telephony.SubscriptionPlan>);
diff --git a/api/removed.txt b/api/removed.txt
index fa07094..fe3e866 100644
--- a/api/removed.txt
+++ b/api/removed.txt
@@ -524,6 +524,8 @@
   public static interface MediaStore.MediaColumns extends android.provider.BaseColumns {
     field @Deprecated public static final String HASH = "_hash";
     field @Deprecated public static final String IS_TRASHED = "is_trashed";
+    field @Deprecated public static final String PRIMARY_DIRECTORY = "primary_directory";
+    field @Deprecated public static final String SECONDARY_DIRECTORY = "secondary_directory";
   }
 
   @Deprecated public static class MediaStore.PendingParams {
diff --git a/api/system-current.txt b/api/system-current.txt
index 12a64c7..32d167f 100644
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -12,6 +12,7 @@
     field public static final String ACCESS_MTP = "android.permission.ACCESS_MTP";
     field public static final String ACCESS_NETWORK_CONDITIONS = "android.permission.ACCESS_NETWORK_CONDITIONS";
     field public static final String ACCESS_NOTIFICATIONS = "android.permission.ACCESS_NOTIFICATIONS";
+    field public static final String ACCESS_SHARED_LIBRARIES = "android.permission.ACCESS_SHARED_LIBRARIES";
     field public static final String ACCESS_SHORTCUTS = "android.permission.ACCESS_SHORTCUTS";
     field public static final String ACCESS_SURFACE_FLINGER = "android.permission.ACCESS_SURFACE_FLINGER";
     field public static final String ACTIVITY_EMBEDDING = "android.permission.ACTIVITY_EMBEDDING";
@@ -117,6 +118,7 @@
     field public static final String MODIFY_QUIET_MODE = "android.permission.MODIFY_QUIET_MODE";
     field public static final String MOVE_PACKAGE = "android.permission.MOVE_PACKAGE";
     field public static final String NETWORK_MANAGED_PROVISIONING = "android.permission.NETWORK_MANAGED_PROVISIONING";
+    field public static final String NETWORK_SCAN = "android.permission.NETWORK_SCAN";
     field public static final String NETWORK_SETUP_WIZARD = "android.permission.NETWORK_SETUP_WIZARD";
     field public static final String NOTIFICATION_DURING_SETUP = "android.permission.NOTIFICATION_DURING_SETUP";
     field public static final String NOTIFY_TV_INPUTS = "android.permission.NOTIFY_TV_INPUTS";
@@ -186,7 +188,6 @@
     field public static final String SUBSTITUTE_NOTIFICATION_APP_NAME = "android.permission.SUBSTITUTE_NOTIFICATION_APP_NAME";
     field public static final String SUBSTITUTE_SHARE_TARGET_APP_NAME_AND_ICON = "android.permission.SUBSTITUTE_SHARE_TARGET_APP_NAME_AND_ICON";
     field public static final String SUSPEND_APPS = "android.permission.SUSPEND_APPS";
-    field public static final String TEST_MANAGE_ROLLBACKS = "android.permission.TEST_MANAGE_ROLLBACKS";
     field public static final String TETHER_PRIVILEGED = "android.permission.TETHER_PRIVILEGED";
     field public static final String TV_INPUT_HARDWARE = "android.permission.TV_INPUT_HARDWARE";
     field public static final String TV_VIRTUAL_REMOTE_CONTROLLER = "android.permission.TV_VIRTUAL_REMOTE_CONTROLLER";
@@ -1063,7 +1064,7 @@
   public final class AppPredictor {
     method public void destroy();
     method public void notifyAppTargetEvent(@NonNull android.app.prediction.AppTargetEvent);
-    method public void notifyLocationShown(@NonNull String, @NonNull java.util.List<android.app.prediction.AppTargetId>);
+    method public void notifyLaunchLocationShown(@NonNull String, @NonNull java.util.List<android.app.prediction.AppTargetId>);
     method public void registerPredictionUpdates(@NonNull java.util.concurrent.Executor, @NonNull android.app.prediction.AppPredictor.Callback);
     method public void requestPredictionUpdate();
     method @Nullable public void sortTargets(@NonNull java.util.List<android.app.prediction.AppTarget>, @NonNull java.util.concurrent.Executor, @NonNull java.util.function.Consumer<java.util.List<android.app.prediction.AppTarget>>);
@@ -1075,8 +1076,6 @@
   }
 
   public final class AppTarget implements android.os.Parcelable {
-    ctor public AppTarget(@NonNull android.app.prediction.AppTargetId, @NonNull String, @Nullable String, @NonNull android.os.UserHandle);
-    ctor public AppTarget(@NonNull android.app.prediction.AppTargetId, @NonNull android.content.pm.ShortcutInfo, @Nullable String);
     method public int describeContents();
     method @Nullable public String getClassName();
     method @NonNull public android.app.prediction.AppTargetId getId();
@@ -1088,6 +1087,15 @@
     field @NonNull public static final android.os.Parcelable.Creator<android.app.prediction.AppTarget> CREATOR;
   }
 
+  public static final class AppTarget.Builder {
+    ctor public AppTarget.Builder(@NonNull android.app.prediction.AppTargetId);
+    method @NonNull public android.app.prediction.AppTarget build();
+    method @NonNull public android.app.prediction.AppTarget.Builder setClassName(@NonNull String);
+    method @NonNull public android.app.prediction.AppTarget.Builder setRank(@IntRange(from=0) int);
+    method @NonNull public android.app.prediction.AppTarget.Builder setTarget(@NonNull String, @NonNull android.os.UserHandle);
+    method @NonNull public android.app.prediction.AppTarget.Builder setTarget(@NonNull android.content.pm.ShortcutInfo);
+  }
+
   public final class AppTargetEvent implements android.os.Parcelable {
     method public int describeContents();
     method public int getAction();
@@ -1486,9 +1494,9 @@
 
   public class OverlayManager {
     method @Nullable public android.content.om.OverlayInfo getOverlayInfo(@NonNull String, @NonNull android.os.UserHandle);
-    method public java.util.List<android.content.om.OverlayInfo> getOverlayInfosForTarget(@Nullable String, int);
-    method public boolean setEnabled(@Nullable String, boolean, int);
-    method public boolean setEnabledExclusiveInCategory(@Nullable String, int);
+    method @NonNull @RequiresPermission(anyOf={"android.permission.INTERACT_ACROSS_USERS", "android.permission.INTERACT_ACROSS_USERS_FULL"}) public java.util.List<android.content.om.OverlayInfo> getOverlayInfosForTarget(@NonNull String, @NonNull android.os.UserHandle);
+    method @RequiresPermission(anyOf={"android.permission.INTERACT_ACROSS_USERS", "android.permission.INTERACT_ACROSS_USERS_FULL"}) public void setEnabled(@NonNull String, boolean, @NonNull android.os.UserHandle);
+    method @RequiresPermission(anyOf={"android.permission.INTERACT_ACROSS_USERS", "android.permission.INTERACT_ACROSS_USERS_FULL"}) public void setEnabledExclusiveInCategory(@NonNull String, @NonNull android.os.UserHandle);
   }
 
 }
@@ -1614,6 +1622,7 @@
     method public abstract java.util.List<android.content.IntentFilter> getAllIntentFilters(String);
     method @NonNull @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS) public android.content.pm.ApplicationInfo getApplicationInfoAsUser(@NonNull String, int, @NonNull android.os.UserHandle) throws android.content.pm.PackageManager.NameNotFoundException;
     method @NonNull public android.content.pm.dex.ArtManager getArtManager();
+    method @NonNull @RequiresPermission(android.Manifest.permission.ACCESS_SHARED_LIBRARIES) public java.util.List<android.content.pm.SharedLibraryInfo> getDeclaredSharedLibraries(@NonNull String, int);
     method @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL) public abstract String getDefaultBrowserPackageNameAsUser(int);
     method @Nullable @RequiresPermission(android.Manifest.permission.SET_HARMFUL_APP_WARNINGS) public CharSequence getHarmfulAppWarning(@NonNull String);
     method public String getIncidentReportApproverPackageName();
@@ -1844,9 +1853,9 @@
   }
 
   public final class RollbackManager {
-    method @RequiresPermission(anyOf={android.Manifest.permission.MANAGE_ROLLBACKS, android.Manifest.permission.TEST_MANAGE_ROLLBACKS}) public void commitRollback(int, @NonNull java.util.List<android.content.pm.VersionedPackage>, @NonNull android.content.IntentSender);
-    method @RequiresPermission(anyOf={android.Manifest.permission.MANAGE_ROLLBACKS, android.Manifest.permission.TEST_MANAGE_ROLLBACKS}) @NonNull public java.util.List<android.content.rollback.RollbackInfo> getAvailableRollbacks();
-    method @RequiresPermission(anyOf={android.Manifest.permission.MANAGE_ROLLBACKS, android.Manifest.permission.TEST_MANAGE_ROLLBACKS}) @NonNull public java.util.List<android.content.rollback.RollbackInfo> getRecentlyCommittedRollbacks();
+    method @RequiresPermission(anyOf={android.Manifest.permission.MANAGE_ROLLBACKS, "android.permission.TEST_MANAGE_ROLLBACKS"}) public void commitRollback(int, @NonNull java.util.List<android.content.pm.VersionedPackage>, @NonNull android.content.IntentSender);
+    method @RequiresPermission(anyOf={android.Manifest.permission.MANAGE_ROLLBACKS, "android.permission.TEST_MANAGE_ROLLBACKS"}) @NonNull public java.util.List<android.content.rollback.RollbackInfo> getAvailableRollbacks();
+    method @RequiresPermission(anyOf={android.Manifest.permission.MANAGE_ROLLBACKS, "android.permission.TEST_MANAGE_ROLLBACKS"}) @NonNull public java.util.List<android.content.rollback.RollbackInfo> getRecentlyCommittedRollbacks();
     field public static final String EXTRA_STATUS = "android.content.rollback.extra.STATUS";
     field public static final String EXTRA_STATUS_MESSAGE = "android.content.rollback.extra.STATUS_MESSAGE";
     field public static final int STATUS_FAILURE = 1; // 0x1
@@ -4028,7 +4037,6 @@
 package android.net {
 
   public class CaptivePortal implements android.os.Parcelable {
-    ctor public CaptivePortal(@NonNull android.os.IBinder);
     method public void logEvent(int, @NonNull String);
     method public void useNetwork();
     field public static final int APP_RETURN_DISMISSED = 0; // 0x0
@@ -4039,12 +4047,12 @@
   public class ConnectivityManager {
     method @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD) public android.net.SocketKeepalive createNattKeepalive(@NonNull android.net.Network, @NonNull java.io.FileDescriptor, @NonNull java.net.InetAddress, @NonNull java.net.InetAddress, @NonNull java.util.concurrent.Executor, @NonNull android.net.SocketKeepalive.Callback);
     method @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD) public android.net.SocketKeepalive createSocketKeepalive(@NonNull android.net.Network, @NonNull java.net.Socket, @NonNull java.util.concurrent.Executor, @NonNull android.net.SocketKeepalive.Callback);
-    method public boolean getAvoidBadWifi();
     method @RequiresPermission(android.Manifest.permission.LOCAL_MAC_ADDRESS) public String getCaptivePortalServerUrl();
     method @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED) public void getLatestTetheringEntitlementResult(int, boolean, @NonNull java.util.concurrent.Executor, @NonNull android.net.ConnectivityManager.OnTetheringEntitlementResultListener);
     method @RequiresPermission(anyOf={android.Manifest.permission.TETHER_PRIVILEGED, android.Manifest.permission.WRITE_SETTINGS}) public boolean isTetheringSupported();
     method @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED) public void registerTetheringEventCallback(@NonNull java.util.concurrent.Executor, @NonNull android.net.ConnectivityManager.OnTetheringEventCallback);
     method @RequiresPermission(anyOf={"android.permission.NETWORK_SETTINGS", android.Manifest.permission.NETWORK_SETUP_WIZARD, "android.permission.NETWORK_STACK"}) public void setAirplaneMode(boolean);
+    method @RequiresPermission(anyOf={android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, "android.permission.NETWORK_STACK"}) public boolean shouldAvoidBadWifi();
     method @RequiresPermission(android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK) public void startCaptivePortalApp(@NonNull android.net.Network, @NonNull android.os.Bundle);
     method @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED) public void startTethering(int, boolean, android.net.ConnectivityManager.OnStartTetheringCallback);
     method @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED) public void startTethering(int, boolean, android.net.ConnectivityManager.OnStartTetheringCallback, android.os.Handler);
@@ -4930,7 +4938,6 @@
     method public int getCellularDataNetworkType();
     method public int getCellularSignalStrengthDb();
     method public int getCellularSignalStrengthDbm();
-    method public boolean getIsSameRegisteredCell();
     method public int getLinkSpeedMbps();
     method public int getProbeElapsedTimeSinceLastUpdateMillis();
     method public int getProbeMcsRateSinceLastUpdate();
@@ -4954,6 +4961,7 @@
     method public long getTotalTxBad();
     method public long getTotalTxRetries();
     method public long getTotalTxSuccess();
+    method public boolean isSameRegisteredCell();
     method public void writeToParcel(android.os.Parcel, int);
     field @NonNull public static final android.os.Parcelable.Creator<android.net.wifi.WifiUsabilityStatsEntry> CREATOR;
     field public static final int PROBE_STATUS_FAILURE = 3; // 0x3
@@ -6036,6 +6044,7 @@
     field public static final String ACTION_ENTERPRISE_PRIVACY_SETTINGS = "android.settings.ENTERPRISE_PRIVACY_SETTINGS";
     field public static final String ACTION_LOCATION_CONTROLLER_EXTRA_PACKAGE_SETTINGS = "android.settings.LOCATION_CONTROLLER_EXTRA_PACKAGE_SETTINGS";
     field public static final String ACTION_MANAGE_DOMAIN_URLS = "android.settings.MANAGE_DOMAIN_URLS";
+    field public static final String ACTION_NOTIFICATION_POLICY_ACCESS_DETAIL_SETTINGS = "android.settings.NOTIFICATION_POLICY_ACCESS_DETAIL_SETTINGS";
     field public static final String ACTION_REQUEST_ENABLE_CONTENT_CAPTURE = "android.settings.REQUEST_ENABLE_CONTENT_CAPTURE";
     field public static final String ACTION_SHOW_ADMIN_SUPPORT_DETAILS = "android.settings.SHOW_ADMIN_SUPPORT_DETAILS";
   }
@@ -6293,7 +6302,7 @@
     method @NonNull public final android.os.IBinder onBind(@NonNull android.content.Intent);
     method public void onCreatePredictionSession(@NonNull android.app.prediction.AppPredictionContext, @NonNull android.app.prediction.AppPredictionSessionId);
     method @MainThread public void onDestroyPredictionSession(@NonNull android.app.prediction.AppPredictionSessionId);
-    method @MainThread public abstract void onLocationShown(@NonNull android.app.prediction.AppPredictionSessionId, @NonNull String, @NonNull java.util.List<android.app.prediction.AppTargetId>);
+    method @MainThread public abstract void onLaunchLocationShown(@NonNull android.app.prediction.AppPredictionSessionId, @NonNull String, @NonNull java.util.List<android.app.prediction.AppTargetId>);
     method @MainThread public abstract void onRequestPredictionUpdate(@NonNull android.app.prediction.AppPredictionSessionId);
     method @MainThread public abstract void onSortAppTargets(@NonNull android.app.prediction.AppPredictionSessionId, @NonNull java.util.List<android.app.prediction.AppTarget>, @NonNull android.os.CancellationSignal, @NonNull java.util.function.Consumer<java.util.List<android.app.prediction.AppTarget>>);
     method @MainThread public void onStartPredictionUpdates();
diff --git a/api/test-current.txt b/api/test-current.txt
index 417a9ed..07944fa 100644
--- a/api/test-current.txt
+++ b/api/test-current.txt
@@ -461,7 +461,7 @@
     method public void destroy();
     method public android.app.prediction.AppPredictionSessionId getSessionId();
     method public void notifyAppTargetEvent(@NonNull android.app.prediction.AppTargetEvent);
-    method public void notifyLocationShown(@NonNull String, @NonNull java.util.List<android.app.prediction.AppTargetId>);
+    method public void notifyLaunchLocationShown(@NonNull String, @NonNull java.util.List<android.app.prediction.AppTargetId>);
     method public void registerPredictionUpdates(@NonNull java.util.concurrent.Executor, @NonNull android.app.prediction.AppPredictor.Callback);
     method public void requestPredictionUpdate();
     method @Nullable public void sortTargets(@NonNull java.util.List<android.app.prediction.AppTarget>, @NonNull java.util.concurrent.Executor, @NonNull java.util.function.Consumer<java.util.List<android.app.prediction.AppTarget>>);
@@ -473,7 +473,6 @@
   }
 
   public final class AppTarget implements android.os.Parcelable {
-    ctor public AppTarget(@NonNull android.app.prediction.AppTargetId, @NonNull String, @Nullable String, @NonNull android.os.UserHandle);
     method public int describeContents();
     method @Nullable public String getClassName();
     method @NonNull public android.app.prediction.AppTargetId getId();
@@ -485,6 +484,15 @@
     field @NonNull public static final android.os.Parcelable.Creator<android.app.prediction.AppTarget> CREATOR;
   }
 
+  public static final class AppTarget.Builder {
+    ctor public AppTarget.Builder(@NonNull android.app.prediction.AppTargetId);
+    method @NonNull public android.app.prediction.AppTarget build();
+    method @NonNull public android.app.prediction.AppTarget.Builder setClassName(@NonNull String);
+    method @NonNull public android.app.prediction.AppTarget.Builder setRank(@IntRange(from=0) int);
+    method @NonNull public android.app.prediction.AppTarget.Builder setTarget(@NonNull String, @NonNull android.os.UserHandle);
+    method @NonNull public android.app.prediction.AppTarget.Builder setTarget(@NonNull android.content.pm.ShortcutInfo);
+  }
+
   public final class AppTargetEvent implements android.os.Parcelable {
     method public int describeContents();
     method public int getAction();
@@ -1078,10 +1086,6 @@
     method public android.media.BufferingParams.Builder setResumePlaybackMarkMs(int);
   }
 
-  public class CallbackDataSourceDesc extends android.media.DataSourceDesc {
-    method @NonNull public android.media.DataSourceCallback getDataSourceCallback();
-  }
-
   public class FileDataSourceDesc extends android.media.DataSourceDesc {
     method public long getLength();
     method public long getOffset();
@@ -1207,7 +1211,6 @@
 package android.net {
 
   public class CaptivePortal implements android.os.Parcelable {
-    ctor public CaptivePortal(@NonNull android.os.IBinder);
     method public void logEvent(int, @NonNull String);
     method public void useNetwork();
     field public static final int APP_RETURN_DISMISSED = 0; // 0x0
@@ -2258,7 +2261,7 @@
     method @NonNull public final android.os.IBinder onBind(@NonNull android.content.Intent);
     method public void onCreatePredictionSession(@NonNull android.app.prediction.AppPredictionContext, @NonNull android.app.prediction.AppPredictionSessionId);
     method @MainThread public void onDestroyPredictionSession(@NonNull android.app.prediction.AppPredictionSessionId);
-    method @MainThread public abstract void onLocationShown(@NonNull android.app.prediction.AppPredictionSessionId, @NonNull String, @NonNull java.util.List<android.app.prediction.AppTargetId>);
+    method @MainThread public abstract void onLaunchLocationShown(@NonNull android.app.prediction.AppPredictionSessionId, @NonNull String, @NonNull java.util.List<android.app.prediction.AppTargetId>);
     method @MainThread public abstract void onRequestPredictionUpdate(@NonNull android.app.prediction.AppPredictionSessionId);
     method @MainThread public abstract void onSortAppTargets(@NonNull android.app.prediction.AppPredictionSessionId, @NonNull java.util.List<android.app.prediction.AppTarget>, @NonNull android.os.CancellationSignal, @NonNull java.util.function.Consumer<java.util.List<android.app.prediction.AppTarget>>);
     method @MainThread public void onStartPredictionUpdates();
diff --git a/cmds/statsd/src/atoms.proto b/cmds/statsd/src/atoms.proto
index 1735b05..d6ea7e6 100644
--- a/cmds/statsd/src/atoms.proto
+++ b/cmds/statsd/src/atoms.proto
@@ -40,6 +40,7 @@
 import "frameworks/base/core/proto/android/server/location/enums.proto";
 import "frameworks/base/core/proto/android/service/procstats_enum.proto";
 import "frameworks/base/core/proto/android/service/usb.proto";
+import "frameworks/base/core/proto/android/stats/connectivity/network_stack.proto";
 import "frameworks/base/core/proto/android/stats/enums.proto";
 import "frameworks/base/core/proto/android/stats/docsui/docsui_enums.proto";
 import "frameworks/base/core/proto/android/stats/devicepolicy/device_policy.proto";
@@ -252,6 +253,7 @@
         StyleUIChanged style_ui_changed = 179;
         PrivacyIndicatorsInteracted privacy_indicators_interacted = 180;
         AppInstallOnExternalStorageReported app_install_on_external_storage_reported = 181;
+        NetworkStackReported network_stack_reported = 182;
     }
 
     // Pulled events will start at field 10000.
@@ -5851,3 +5853,14 @@
     // Size of the system ion heap in bytes.
     optional int64 size_in_bytes = 1;
 }
+
+/**
+ * Push network stack events.
+ *
+ * Log from:
+ *     frameworks/base/packages/NetworkStack/
+ */
+message NetworkStackReported {
+    optional int32 eventId = 1;
+    optional android.stats.connectivity.NetworkStackEventData network_stack_event = 2 [(log_mode) = MODE_BYTES];
+}
diff --git a/config/hiddenapi-greylist.txt b/config/hiddenapi-greylist.txt
index 76d69cd..79cdb77 100644
--- a/config/hiddenapi-greylist.txt
+++ b/config/hiddenapi-greylist.txt
@@ -1680,7 +1680,6 @@
 Lcom/android/internal/widget/LockPatternUtils;->patternToString(Ljava/util/List;)Ljava/lang/String;
 Lcom/android/internal/widget/LockPatternUtils;->reportFailedPasswordAttempt(I)V
 Lcom/android/internal/widget/LockPatternUtils;->reportSuccessfulPasswordAttempt(I)V
-Lcom/android/internal/widget/LockPatternUtils;->saveLockPassword(Ljava/lang/String;Ljava/lang/String;II)V
 Lcom/android/internal/widget/LockPatternUtils;->setLockoutAttemptDeadline(II)J
 Lcom/android/internal/widget/LockPatternUtils;->setLong(Ljava/lang/String;JI)V
 Lcom/android/internal/widget/LockPatternUtils;->setOwnerInfo(Ljava/lang/String;I)V
diff --git a/core/java/android/app/ApplicationPackageManager.java b/core/java/android/app/ApplicationPackageManager.java
index 7a0639e..404e520 100644
--- a/core/java/android/app/ApplicationPackageManager.java
+++ b/core/java/android/app/ApplicationPackageManager.java
@@ -536,6 +536,19 @@
         }
     }
 
+    @NonNull
+    @Override
+    public List<SharedLibraryInfo> getDeclaredSharedLibraries(@NonNull String packageName,
+            @InstallFlags int flags) {
+        try {
+            ParceledListSlice<SharedLibraryInfo> sharedLibraries = mPM.getDeclaredSharedLibraries(
+                    packageName, flags, mContext.getUserId());
+            return sharedLibraries != null ? sharedLibraries.getList() : Collections.emptyList();
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
     /** @hide */
     @Override
     public @NonNull String getServicesSystemSharedLibraryPackageName() {
diff --git a/core/java/android/app/AutomaticZenRule.java b/core/java/android/app/AutomaticZenRule.java
index ec2825e..7180c01 100644
--- a/core/java/android/app/AutomaticZenRule.java
+++ b/core/java/android/app/AutomaticZenRule.java
@@ -231,7 +231,7 @@
      * Sets the zen policy.
      */
     public void setZenPolicy(ZenPolicy zenPolicy) {
-        this.mZenPolicy = zenPolicy;
+        this.mZenPolicy = (zenPolicy == null ? null : zenPolicy.copy());
     }
 
     /**
diff --git a/core/java/android/app/NotificationManager.java b/core/java/android/app/NotificationManager.java
index 1aacf96..0bec21f 100644
--- a/core/java/android/app/NotificationManager.java
+++ b/core/java/android/app/NotificationManager.java
@@ -315,7 +315,8 @@
      * This tag should contain a localized name of the type of the zen rule provided by the
      * activity.
      */
-    public static final String META_DATA_AUTOMATIC_RULE_TYPE = "android.app.automatic.ruleType";
+    public static final String META_DATA_AUTOMATIC_RULE_TYPE =
+            "android.service.zen.automatic.ruleType";
 
     /**
      * An optional {@code meta-data} tag for activities that handle
@@ -325,7 +326,7 @@
      * can be created for this rule type. Omit or enter a value <= 0 to allow unlimited instances.
      */
     public static final String META_DATA_RULE_INSTANCE_LIMIT =
-            "android.app.zen.automatic.ruleInstanceLimit";
+            "android.service.zen.automatic.ruleInstanceLimit";
 
     /** Value signifying that the user has not expressed a per-app visibility override value.
      * @hide */
diff --git a/core/java/android/app/admin/DevicePolicyManager.java b/core/java/android/app/admin/DevicePolicyManager.java
index 20e85e6..3660ddc 100644
--- a/core/java/android/app/admin/DevicePolicyManager.java
+++ b/core/java/android/app/admin/DevicePolicyManager.java
@@ -4358,6 +4358,7 @@
 
     /**
      * Disable text entry into notifications on secure keyguard screens (e.g. PIN/Pattern/Password).
+     * This flag has no effect starting from version {@link android.os.Build.VERSION_CODES#N}
      */
     public static final int KEYGUARD_DISABLE_REMOTE_INPUT = 1 << 6;
 
diff --git a/core/java/android/app/admin/SecurityLog.java b/core/java/android/app/admin/SecurityLog.java
index 6386573..19f4335 100644
--- a/core/java/android/app/admin/SecurityLog.java
+++ b/core/java/android/app/admin/SecurityLog.java
@@ -136,8 +136,11 @@
     public static final int TAG_APP_PROCESS_START = SecurityLogTags.SECURITY_APP_PROCESS_START;
 
     /**
-     * Indicates that keyguard has been dismissed.
+     * Indicates that keyguard has been dismissed. This event is only logged if the device
+     * has a secure keyguard. It is logged regardless of how keyguard is dismissed, including
+     * via PIN/pattern/password, biometrics or via a trust agent.
      * There is no extra payload in the log event.
+     * @see #TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT
      */
     public static final int TAG_KEYGUARD_DISMISSED = SecurityLogTags.SECURITY_KEYGUARD_DISMISSED;
 
diff --git a/core/java/android/app/prediction/AppPredictor.java b/core/java/android/app/prediction/AppPredictor.java
index 3e4e8dc..3f2f209 100644
--- a/core/java/android/app/prediction/AppPredictor.java
+++ b/core/java/android/app/prediction/AppPredictor.java
@@ -131,14 +131,14 @@
      * @param launchLocation The launch location where the targets are shown to the user.
      * @param targetIds List of {@link AppTargetId}s that are shown to the user.
      */
-    public void notifyLocationShown(@NonNull String launchLocation,
+    public void notifyLaunchLocationShown(@NonNull String launchLocation,
             @NonNull List<AppTargetId> targetIds) {
         if (mIsClosed.get()) {
             throw new IllegalStateException("This client has already been destroyed.");
         }
 
         try {
-            mPredictionManager.notifyLocationShown(mSessionId, launchLocation,
+            mPredictionManager.notifyLaunchLocationShown(mSessionId, launchLocation,
                     new ParceledListSlice<>(targetIds));
         } catch (RemoteException e) {
             Log.e(TAG, "Failed to notify location shown event", e);
diff --git a/core/java/android/app/prediction/AppTarget.java b/core/java/android/app/prediction/AppTarget.java
index bb1b96c..826c149 100644
--- a/core/java/android/app/prediction/AppTarget.java
+++ b/core/java/android/app/prediction/AppTarget.java
@@ -43,20 +43,13 @@
 
     private final ShortcutInfo mShortcutInfo;
 
-    private int mRank;
+    private final int mRank;
 
     /**
-     * Creates an instance of AppTarget that represent a launchable component.
-     *
-     * @param id A unique id for this launchable target.
-     * @param packageName Package name of the target.
-     * @param className Class name of the target.
-     * @param user The UserHandle of the user which this target belongs to.
-     *
+     * @deprecated use the Builder class
      * @hide
      */
-    @SystemApi
-    @TestApi
+    @Deprecated
     public AppTarget(@NonNull AppTargetId id, @NonNull String packageName,
             @Nullable String className, @NonNull UserHandle user) {
         mId = id;
@@ -65,18 +58,14 @@
         mPackageName = Preconditions.checkNotNull(packageName);
         mClassName = className;
         mUser = Preconditions.checkNotNull(user);
+        mRank = 0;
     }
 
     /**
-     * Creates an instance of AppTarget that represent a launchable shortcut.
-     *
-     * @param id A unique id for this launchable target.
-     * @param shortcutInfo The {@link ShortcutInfo} that is represented with this target.
-     * @param className Class name fo the target.
-     *
+     * @deprecated use the Builder class
      * @hide
      */
-    @SystemApi
+    @Deprecated
     public AppTarget(@NonNull AppTargetId id, @NonNull ShortcutInfo shortcutInfo,
             @Nullable String className) {
         mId = id;
@@ -85,6 +74,17 @@
         mPackageName = mShortcutInfo.getPackage();
         mUser = mShortcutInfo.getUserHandle();
         mClassName = className;
+        mRank = 0;
+    }
+
+    private AppTarget(AppTargetId id, String packageName, UserHandle user,
+            ShortcutInfo shortcutInfo, String className, int rank) {
+        mId = id;
+        mShortcutInfo = shortcutInfo;
+        mPackageName = packageName;
+        mClassName = className;
+        mUser = user;
+        mRank = rank;
     }
 
     private AppTarget(Parcel parcel) {
@@ -142,17 +142,6 @@
     }
 
     /**
-     * Sets the rank of the for the target.
-     * @hide
-     */
-    public void setRank(@IntRange(from = 0) int rank) {
-        if (rank < 0) {
-            throw new IllegalArgumentException("rank cannot be a negative value");
-        }
-        mRank = rank;
-    }
-
-    /**
      * Returns the rank for the target. Rank of an AppTarget is a non-negative integer that
      * represents the importance of this target compared to other candidate targets. A smaller value
      * means higher importance in the list.
@@ -196,6 +185,101 @@
         dest.writeInt(mRank);
     }
 
+    /**
+     * A builder for app targets.
+     * @hide
+     */
+    @SystemApi
+    @TestApi
+    public static final class Builder {
+
+        @NonNull
+        private final AppTargetId mId;
+
+        private String mPackageName;
+        private UserHandle mUser;
+        private ShortcutInfo mShortcutInfo;
+
+        private String mClassName;
+        private int mRank;
+
+        /**
+         * @param id A unique id for this launchable target.
+         * @hide
+         */
+        @SystemApi
+        @TestApi
+        public Builder(@NonNull AppTargetId id) {
+            mId = id;
+        }
+
+        /**
+         * Sets the target to be an app.
+         *
+         * @param packageName PackageName of the app
+         * @param user The UserHandle of the user which this target belongs to.
+         *
+         * @throws IllegalArgumentException is the target is already set
+         */
+        @NonNull
+        public Builder setTarget(@NonNull String packageName, @NonNull UserHandle user) {
+            if (mPackageName == null) {
+                throw new IllegalArgumentException("Target is already set");
+            }
+            mPackageName = Preconditions.checkNotNull(packageName);
+            mUser = Preconditions.checkNotNull(user);
+            return this;
+        }
+
+        /**
+         * Sets the target to be a ShortcutInfo.
+         *
+         * @throws IllegalArgumentException is the target is already set
+         */
+        @NonNull
+        public Builder setTarget(@NonNull ShortcutInfo info) {
+            setTarget(info.getPackage(), info.getUserHandle());
+            mShortcutInfo = Preconditions.checkNotNull(info);
+            return this;
+        }
+
+        /**
+         * Sets the className for the target
+         */
+        @NonNull
+        public Builder setClassName(@NonNull String className) {
+            mClassName = Preconditions.checkNotNull(className);
+            return this;
+        }
+
+        /**
+         * Sets the rank of the for the target.
+         */
+        @NonNull
+        public Builder setRank(@IntRange(from = 0) int rank) {
+            if (rank < 0) {
+                throw new IllegalArgumentException("rank cannot be a negative value");
+            }
+            mRank = rank;
+            return this;
+        }
+
+        /**
+         * Builds a new AppTarget instance.
+         *
+         * @throws IllegalStateException if no target is set
+         * @see #setTarget(ShortcutInfo)
+         * @see #setTarget(String, UserHandle)
+         */
+        @NonNull
+        public AppTarget build() {
+            if (mPackageName == null) {
+                throw new IllegalStateException("No target set");
+            }
+            return new AppTarget(mId, mPackageName, mUser, mShortcutInfo, mClassName, mRank);
+        }
+    }
+
     public static final @android.annotation.NonNull Parcelable.Creator<AppTarget> CREATOR =
             new Parcelable.Creator<AppTarget>() {
                 public AppTarget createFromParcel(Parcel parcel) {
diff --git a/core/java/android/app/prediction/IPredictionManager.aidl b/core/java/android/app/prediction/IPredictionManager.aidl
index 114a1ff..587e3fd 100644
--- a/core/java/android/app/prediction/IPredictionManager.aidl
+++ b/core/java/android/app/prediction/IPredictionManager.aidl
@@ -33,7 +33,7 @@
 
     void notifyAppTargetEvent(in AppPredictionSessionId sessionId, in AppTargetEvent event);
 
-    void notifyLocationShown(in AppPredictionSessionId sessionId, in String launchLocation,
+    void notifyLaunchLocationShown(in AppPredictionSessionId sessionId, in String launchLocation,
             in ParceledListSlice targetIds);
 
     void sortAppTargets(in AppPredictionSessionId sessionId, in ParceledListSlice targets,
diff --git a/core/java/android/content/om/OverlayManager.java b/core/java/android/content/om/OverlayManager.java
index ceea043..f2716fe 100644
--- a/core/java/android/content/om/OverlayManager.java
+++ b/core/java/android/content/om/OverlayManager.java
@@ -18,6 +18,7 @@
 
 import android.annotation.NonNull;
 import android.annotation.Nullable;
+import android.annotation.RequiresPermission;
 import android.annotation.SystemApi;
 import android.annotation.SystemService;
 import android.content.Context;
@@ -61,40 +62,57 @@
      * Request that an overlay package is enabled and any other overlay packages with the same
      * target package and category are disabled.
      *
+     * If a set of overlay packages share the same category, single call to this method is
+     * equivalent to multiple calls to {@link #setEnabled(String, boolean, UserHandle)}.
+     *
      * @param packageName the name of the overlay package to enable.
-     * @param userId The user for which to change the overlay.
-     * @return true if the system successfully registered the request, false otherwise.
+     * @param user The user for which to change the overlay.
      *
      * @hide
      */
     @SystemApi
-    public boolean setEnabledExclusiveInCategory(@Nullable final String packageName,
-            int userId) {
+    @RequiresPermission(anyOf = {
+            "android.permission.INTERACT_ACROSS_USERS",
+            "android.permission.INTERACT_ACROSS_USERS_FULL"
+    })
+    public void setEnabledExclusiveInCategory(@NonNull final String packageName,
+            @NonNull UserHandle user) {
         try {
-            return mService.setEnabledExclusiveInCategory(packageName, userId);
+            if (!mService.setEnabledExclusiveInCategory(packageName, user.getIdentifier())) {
+                throw new IllegalStateException("setEnabledExclusiveInCategory failed");
+            }
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
         }
     }
 
     /**
-     * Request that an overlay package is enabled.
+     * Request that an overlay package is enabled or disabled.
+     *
+     * While {@link #setEnabledExclusiveInCategory(String, UserHandle)} doesn't support disabling
+     * every overlay in a category, this method allows you to disable everything.
      *
      * @param packageName the name of the overlay package to enable.
      * @param enable {@code false} if the overlay should be turned off.
-     * @param userId The user for which to change the overlay.
-     * @return true if the system successfully registered the request, false otherwise.
+     * @param user The user for which to change the overlay.
      *
      * @hide
      */
     @SystemApi
-    public boolean setEnabled(@Nullable final String packageName, final boolean enable,
-            int userId) {
+    @RequiresPermission(anyOf = {
+            "android.permission.INTERACT_ACROSS_USERS",
+            "android.permission.INTERACT_ACROSS_USERS_FULL"
+    })
+    public void setEnabled(@NonNull final String packageName, final boolean enable,
+            @NonNull UserHandle user) {
         try {
-            return mService.setEnabled(packageName, enable, userId);
+            if (!mService.setEnabled(packageName, enable, user.getIdentifier())) {
+                throw new IllegalStateException("setEnabled failed");
+            }
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
         }
+        return;
     }
 
     /**
@@ -113,7 +131,7 @@
     public OverlayInfo getOverlayInfo(@NonNull final String packageName,
             @NonNull final UserHandle userHandle) {
         try {
-            return mService.getOverlayInfo(packageName, userHandle.myUserId());
+            return mService.getOverlayInfo(packageName, userHandle.getIdentifier());
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
         }
@@ -125,17 +143,22 @@
      * overlay priority with the highest priority at the end of the list.
      *
      * @param targetPackageName The name of the target package.
-     * @param userId The user to get the OverlayInfos for.
+     * @param user The user to get the OverlayInfos for.
      * @return A list of OverlayInfo objects; if no overlays exist for the
      *         requested package, an empty list is returned.
      *
      * @hide
      */
     @SystemApi
-    public List<OverlayInfo> getOverlayInfosForTarget(@Nullable final String targetPackageName,
-            int userId) {
+    @RequiresPermission(anyOf = {
+            "android.permission.INTERACT_ACROSS_USERS",
+            "android.permission.INTERACT_ACROSS_USERS_FULL"
+    })
+    @NonNull
+    public List<OverlayInfo> getOverlayInfosForTarget(@NonNull final String targetPackageName,
+            @NonNull UserHandle user) {
         try {
-            return mService.getOverlayInfosForTarget(targetPackageName, userId);
+            return mService.getOverlayInfosForTarget(targetPackageName, user.getIdentifier());
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
         }
diff --git a/core/java/android/content/pm/IPackageManager.aidl b/core/java/android/content/pm/IPackageManager.aidl
index 464e866..c798270 100644
--- a/core/java/android/content/pm/IPackageManager.aidl
+++ b/core/java/android/content/pm/IPackageManager.aidl
@@ -714,6 +714,8 @@
 
     ParceledListSlice getSharedLibraries(in String packageName, int flags, int userId);
 
+    ParceledListSlice getDeclaredSharedLibraries(in String packageName, int flags, int userId);
+
     boolean canRequestPackageInstalls(String packageName, int userId);
 
     void deletePreloadsFileCache();
diff --git a/core/java/android/content/pm/PackageManager.java b/core/java/android/content/pm/PackageManager.java
index 73e6f67..961faa0c 100644
--- a/core/java/android/content/pm/PackageManager.java
+++ b/core/java/android/content/pm/PackageManager.java
@@ -4239,6 +4239,24 @@
             @InstallFlags int flags, @UserIdInt int userId);
 
     /**
+     * Get the list of shared libraries declared by a package.
+     *
+     * @param packageName the package name to query
+     * @param flags the flags to filter packages
+     * @return the shared library list
+     *
+     * @hide
+     */
+    @NonNull
+    @RequiresPermission(Manifest.permission.ACCESS_SHARED_LIBRARIES)
+    @SystemApi
+    public List<SharedLibraryInfo> getDeclaredSharedLibraries(@NonNull String packageName,
+            @InstallFlags int flags) {
+        throw new UnsupportedOperationException(
+                "getDeclaredSharedLibraries() not implemented in subclass");
+    }
+
+    /**
      * Get the name of the package hosting the services shared library.
      *
      * @return The library host package.
diff --git a/core/java/android/net/CaptivePortal.java b/core/java/android/net/CaptivePortal.java
index 3e4e35a..1339432 100644
--- a/core/java/android/net/CaptivePortal.java
+++ b/core/java/android/net/CaptivePortal.java
@@ -64,8 +64,6 @@
     private final IBinder mBinder;
 
     /** @hide */
-    @SystemApi
-    @TestApi
     public CaptivePortal(@NonNull IBinder binder) {
         mBinder = binder;
     }
diff --git a/core/java/android/net/ConnectivityManager.java b/core/java/android/net/ConnectivityManager.java
index 1632235..428c2e7 100644
--- a/core/java/android/net/ConnectivityManager.java
+++ b/core/java/android/net/ConnectivityManager.java
@@ -4101,9 +4101,12 @@
      * @hide
      */
     @SystemApi
-    public boolean getAvoidBadWifi() {
+    @RequiresPermission(anyOf = {
+            NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
+            android.Manifest.permission.NETWORK_STACK})
+    public boolean shouldAvoidBadWifi() {
         try {
-            return mService.getAvoidBadWifi();
+            return mService.shouldAvoidBadWifi();
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
         }
diff --git a/core/java/android/net/DnsResolver.java b/core/java/android/net/DnsResolver.java
index 93b8cf8..5980251 100644
--- a/core/java/android/net/DnsResolver.java
+++ b/core/java/android/net/DnsResolver.java
@@ -16,6 +16,7 @@
 
 package android.net;
 
+import static android.net.NetworkUtils.resNetworkCancel;
 import static android.net.NetworkUtils.resNetworkQuery;
 import static android.net.NetworkUtils.resNetworkResult;
 import static android.net.NetworkUtils.resNetworkSend;
@@ -26,6 +27,7 @@
 import android.annotation.IntDef;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
+import android.os.CancellationSignal;
 import android.os.Looper;
 import android.system.ErrnoException;
 import android.util.Log;
@@ -191,11 +193,18 @@
      * @param query blob message
      * @param flags flags as a combination of the FLAGS_* constants
      * @param executor The {@link Executor} that the callback should be executed on.
+     * @param cancellationSignal used by the caller to signal if the query should be
+     *    cancelled. May be {@code null}.
      * @param callback an {@link AnswerCallback} which will be called to notify the caller
-     *         of the result of dns query.
+     *    of the result of dns query.
      */
     public <T> void query(@Nullable Network network, @NonNull byte[] query, @QueryFlag int flags,
-            @NonNull @CallbackExecutor Executor executor, @NonNull AnswerCallback<T> callback) {
+            @NonNull @CallbackExecutor Executor executor,
+            @Nullable CancellationSignal cancellationSignal,
+            @NonNull AnswerCallback<T> callback) {
+        if (cancellationSignal != null && cancellationSignal.isCanceled()) {
+            return;
+        }
         final FileDescriptor queryfd;
         try {
             queryfd = resNetworkSend((network != null
@@ -205,6 +214,7 @@
             return;
         }
 
+        maybeAddCancellationSignal(cancellationSignal, queryfd);
         registerFDListener(executor, queryfd, callback);
     }
 
@@ -219,12 +229,19 @@
      * @param nsType dns resource record (RR) type as one of the TYPE_* constants
      * @param flags flags as a combination of the FLAGS_* constants
      * @param executor The {@link Executor} that the callback should be executed on.
+     * @param cancellationSignal used by the caller to signal if the query should be
+     *    cancelled. May be {@code null}.
      * @param callback an {@link AnswerCallback} which will be called to notify the caller
-     *         of the result of dns query.
+     *    of the result of dns query.
      */
     public <T> void query(@Nullable Network network, @NonNull String domain,
             @QueryClass int nsClass, @QueryType int nsType, @QueryFlag int flags,
-            @NonNull @CallbackExecutor Executor executor, @NonNull AnswerCallback<T> callback) {
+            @NonNull @CallbackExecutor Executor executor,
+            @Nullable CancellationSignal cancellationSignal,
+            @NonNull AnswerCallback<T> callback) {
+        if (cancellationSignal != null && cancellationSignal.isCanceled()) {
+            return;
+        }
         final FileDescriptor queryfd;
         try {
             queryfd = resNetworkQuery((network != null
@@ -233,6 +250,8 @@
             callback.onQueryException(e);
             return;
         }
+
+        maybeAddCancellationSignal(cancellationSignal, queryfd);
         registerFDListener(executor, queryfd, callback);
     }
 
@@ -264,6 +283,17 @@
                 });
     }
 
+    private void maybeAddCancellationSignal(@Nullable CancellationSignal cancellationSignal,
+            @NonNull FileDescriptor queryfd) {
+        if (cancellationSignal == null) return;
+        cancellationSignal.setOnCancelListener(
+                () -> {
+                    Looper.getMainLooper().getQueue()
+                            .removeOnFileDescriptorEventListener(queryfd);
+                    resNetworkCancel(queryfd);
+            });
+    }
+
     private static class DnsAddressAnswer extends DnsPacket {
         private static final String TAG = "DnsResolver.DnsAddressAnswer";
         private static final boolean DBG = false;
diff --git a/core/java/android/net/IConnectivityManager.aidl b/core/java/android/net/IConnectivityManager.aidl
index 24e6a85..61648dc 100644
--- a/core/java/android/net/IConnectivityManager.aidl
+++ b/core/java/android/net/IConnectivityManager.aidl
@@ -182,7 +182,7 @@
     void startCaptivePortalApp(in Network network);
     void startCaptivePortalAppInternal(in Network network, in Bundle appExtras);
 
-    boolean getAvoidBadWifi();
+    boolean shouldAvoidBadWifi();
     int getMultipathPreference(in Network Network);
 
     NetworkRequest getDefaultRequest();
diff --git a/core/java/android/net/NetworkUtils.java b/core/java/android/net/NetworkUtils.java
index ed410e2..5188866 100644
--- a/core/java/android/net/NetworkUtils.java
+++ b/core/java/android/net/NetworkUtils.java
@@ -177,6 +177,12 @@
     public static native byte[] resNetworkResult(FileDescriptor fd) throws ErrnoException;
 
     /**
+     * DNS resolver series jni method.
+     * Attempts to cancel the in-progress query associated with the {@code fd}.
+     */
+    public static native void resNetworkCancel(FileDescriptor fd);
+
+    /**
      * Add an entry into the ARP cache.
      */
     public static void addArpEntry(Inet4Address ipv4Addr, MacAddress ethAddr, String ifname,
diff --git a/core/java/android/os/VibrationEffect.java b/core/java/android/os/VibrationEffect.java
index c74cbff..7958ddd 100644
--- a/core/java/android/os/VibrationEffect.java
+++ b/core/java/android/os/VibrationEffect.java
@@ -23,7 +23,7 @@
 import android.content.ContentResolver;
 import android.content.Context;
 import android.hardware.vibrator.V1_0.EffectStrength;
-import android.hardware.vibrator.V1_2.Effect;
+import android.hardware.vibrator.V1_3.Effect;
 import android.net.Uri;
 import android.util.MathUtils;
 
@@ -94,6 +94,18 @@
      */
     public static final int EFFECT_HEAVY_CLICK = Effect.HEAVY_CLICK;
 
+    /**
+     * A texture effect meant to replicate soft ticks.
+     *
+     * Unlike normal effects, texture effects are meant to be called repeatedly, generally in
+     * response to some motion, in order to replicate the feeling of some texture underneath the
+     * user's fingers.
+     *
+     * @see #get(int)
+     * @hide
+     */
+    public static final int EFFECT_TEXTURE_TICK = Effect.TEXTURE_TICK;
+
     /** {@hide} */
     @TestApi
     public static final int EFFECT_STRENGTH_LIGHT = EffectStrength.LIGHT;
@@ -746,6 +758,7 @@
                 case EFFECT_CLICK:
                 case EFFECT_DOUBLE_CLICK:
                 case EFFECT_TICK:
+                case EFFECT_TEXTURE_TICK:
                 case EFFECT_THUD:
                 case EFFECT_POP:
                 case EFFECT_HEAVY_CLICK:
@@ -798,7 +811,7 @@
             out.writeInt(mEffectStrength);
         }
 
-        public static final @android.annotation.NonNull Parcelable.Creator<Prebaked> CREATOR =
+        public static final @NonNull Parcelable.Creator<Prebaked> CREATOR =
             new Parcelable.Creator<Prebaked>() {
                 @Override
                 public Prebaked createFromParcel(Parcel in) {
@@ -813,7 +826,7 @@
             };
     }
 
-    public static final @android.annotation.NonNull Parcelable.Creator<VibrationEffect> CREATOR =
+    public static final @NonNull Parcelable.Creator<VibrationEffect> CREATOR =
             new Parcelable.Creator<VibrationEffect>() {
                 @Override
                 public VibrationEffect createFromParcel(Parcel in) {
diff --git a/core/java/android/provider/MediaStore.java b/core/java/android/provider/MediaStore.java
index 1486333..368ba3c 100644
--- a/core/java/android/provider/MediaStore.java
+++ b/core/java/android/provider/MediaStore.java
@@ -873,7 +873,7 @@
      */
     public interface MediaColumns extends BaseColumns {
         /**
-         * Path to the media item on disk.
+         * Absolute filesystem path to the media item on disk.
          * <p>
          * Note that apps may not have filesystem permissions to directly access
          * this path. Instead of trying to open this path directly, apps should
@@ -920,6 +920,10 @@
 
         /**
          * The display name of the media item.
+         * <p>
+         * For example, an item stored at
+         * {@code /storage/0000-0000/DCIM/Vacation/IMG1024.JPG} would have a
+         * display name of {@code IMG1024.JPG}.
          */
         @Column(Cursor.FIELD_TYPE_STRING)
         public static final String DISPLAY_NAME = "_display_name";
@@ -985,7 +989,8 @@
 
         /**
          * Flag indicating if a media item is pending, and still being inserted
-         * by its owner.
+         * by its owner. While this flag is set, only the owner of the item can
+         * open the underlying file; requests from other apps will be rejected.
          *
          * @see MediaStore#setIncludePending(Uri)
          */
@@ -1033,17 +1038,53 @@
         public static final String OWNER_PACKAGE_NAME = "owner_package_name";
 
         /**
-         * The primary directory name this media exists under. The value may be
-         * {@code NULL} if the media doesn't have a primary directory name.
+         * Relative path of this media item within the storage device where it
+         * is persisted. For example, an item stored at
+         * {@code /storage/0000-0000/DCIM/Vacation/IMG1024.JPG} would have a
+         * path of {@code DCIM/Vacation}.
+         * <p>
+         * This value should only be used for organizational purposes, and you
+         * should not attempt to construct or access a raw filesystem path using
+         * this value. If you need to open a media item, use an API like
+         * {@link ContentResolver#openFileDescriptor(Uri, String)}.
+         * <p>
+         * When this value is set to {@code NULL} during an
+         * {@link ContentResolver#insert} operation, the newly created item will
+         * be placed in a relevant default location based on the type of media
+         * being inserted. For example, a {@code image/jpeg} item will be placed
+         * under {@link Environment#DIRECTORY_PICTURES}.
+         * <p>
+         * You can modify this column during an {@link ContentResolver#update}
+         * call, which will move the underlying file on disk.
+         * <p>
+         * In both cases above, content must be placed under a top-level
+         * directory that is relevant to the media type. For example, attempting
+         * to place a {@code audio/mpeg} file under
+         * {@link Environment#DIRECTORY_PICTURES} will be rejected.
          */
         @Column(Cursor.FIELD_TYPE_STRING)
+        public static final String RELATIVE_PATH = "relative_path";
+
+        /**
+         * The primary directory name this media exists under. The value may be
+         * {@code NULL} if the media doesn't have a primary directory name.
+         *
+         * @removed
+         * @deprecated Replaced by {@link #RELATIVE_PATH}.
+         */
+        @Column(Cursor.FIELD_TYPE_STRING)
+        @Deprecated
         public static final String PRIMARY_DIRECTORY = "primary_directory";
 
         /**
          * The secondary directory name this media exists under. The value may
          * be {@code NULL} if the media doesn't have a secondary directory name.
+         *
+         * @removed
+         * @deprecated Replaced by {@link #RELATIVE_PATH}.
          */
         @Column(Cursor.FIELD_TYPE_STRING)
+        @Deprecated
         public static final String SECONDARY_DIRECTORY = "secondary_directory";
 
         /**
@@ -3344,6 +3385,10 @@
      * substantial changes, and that data should be rescanned.
      * <p>
      * No other assumptions should be made about the meaning of the version.
+     *
+     * @param volumeName specific volume to obtain an opaque version string for.
+     *            Must be one of the values returned from
+     *            {@link #getAllVolumeNames(Context)}.
      */
     public static @NonNull String getVersion(@NonNull Context context, @NonNull String volumeName) {
         final ContentResolver resolver = context.getContentResolver();
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index 7d66b90..d4908ca 100644
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -1261,6 +1261,25 @@
             = "android.settings.NOTIFICATION_POLICY_ACCESS_SETTINGS";
 
     /**
+     * Activity Action: Show do not disturb setting page for app.
+     * <p>
+     * Users can grant and deny access to Do Not Disturb configuration for an app from here.
+     * See {@link android.app.NotificationManager#isNotificationPolicyAccessGranted()} for more
+     * details.
+     * <p>
+     * Input: Intent's data URI set with an application name, using the
+     * "package" schema (like "package:com.my.app").
+     * <p>
+     * Output: Nothing.
+     *
+     * @hide
+     */
+    @SystemApi
+    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
+    public static final String ACTION_NOTIFICATION_POLICY_ACCESS_DETAIL_SETTINGS =
+            "android.settings.NOTIFICATION_POLICY_ACCESS_DETAIL_SETTINGS";
+
+    /**
      * @hide
      */
     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
diff --git a/core/java/android/service/appprediction/AppPredictionService.java b/core/java/android/service/appprediction/AppPredictionService.java
index ff13e03..c1323bc 100644
--- a/core/java/android/service/appprediction/AppPredictionService.java
+++ b/core/java/android/service/appprediction/AppPredictionService.java
@@ -86,11 +86,12 @@
         }
 
         @Override
-        public void notifyLocationShown(AppPredictionSessionId sessionId, String launchLocation,
-                ParceledListSlice targetIds) {
+        public void notifyLaunchLocationShown(AppPredictionSessionId sessionId,
+                String launchLocation, ParceledListSlice targetIds) {
             mHandler.sendMessage(
-                    obtainMessage(AppPredictionService::onLocationShown, AppPredictionService.this,
-                            sessionId, launchLocation, targetIds.getList()));
+                    obtainMessage(AppPredictionService::onLaunchLocationShown,
+                            AppPredictionService.this, sessionId, launchLocation,
+                            targetIds.getList()));
         }
 
         @Override
@@ -158,7 +159,7 @@
      * Called by a client app to indication a particular location has been shown to the user.
      */
     @MainThread
-    public abstract void onLocationShown(@NonNull AppPredictionSessionId sessionId,
+    public abstract void onLaunchLocationShown(@NonNull AppPredictionSessionId sessionId,
             @NonNull String launchLocation, @NonNull List<AppTargetId> targetIds);
 
     private void doCreatePredictionSession(@NonNull AppPredictionContext context,
diff --git a/core/java/android/service/appprediction/IPredictionService.aidl b/core/java/android/service/appprediction/IPredictionService.aidl
index 3a6d166..0f3df85 100644
--- a/core/java/android/service/appprediction/IPredictionService.aidl
+++ b/core/java/android/service/appprediction/IPredictionService.aidl
@@ -35,7 +35,7 @@
 
     void notifyAppTargetEvent(in AppPredictionSessionId sessionId, in AppTargetEvent event);
 
-    void notifyLocationShown(in AppPredictionSessionId sessionId,  in String launchLocation,
+    void notifyLaunchLocationShown(in AppPredictionSessionId sessionId,  in String launchLocation,
             in ParceledListSlice targetIds);
 
     void sortAppTargets(in AppPredictionSessionId sessionId, in ParceledListSlice targets,
diff --git a/core/java/android/view/accessibility/AccessibilityManager.java b/core/java/android/view/accessibility/AccessibilityManager.java
index 384cdbb..d12777f 100644
--- a/core/java/android/view/accessibility/AccessibilityManager.java
+++ b/core/java/android/view/accessibility/AccessibilityManager.java
@@ -848,7 +848,7 @@
         if (mRequestPreparerLists == null) {
             mRequestPreparerLists = new SparseArray<>(1);
         }
-        int id = preparer.getView().getAccessibilityViewId();
+        int id = preparer.getAccessibilityViewId();
         List<AccessibilityRequestPreparer> requestPreparerList = mRequestPreparerLists.get(id);
         if (requestPreparerList == null) {
             requestPreparerList = new ArrayList<>(1);
@@ -864,7 +864,7 @@
         if (mRequestPreparerLists == null) {
             return;
         }
-        int viewId = preparer.getView().getAccessibilityViewId();
+        int viewId = preparer.getAccessibilityViewId();
         List<AccessibilityRequestPreparer> requestPreparerList = mRequestPreparerLists.get(viewId);
         if (requestPreparerList != null) {
             requestPreparerList.remove(preparer);
diff --git a/core/java/android/view/accessibility/AccessibilityRequestPreparer.java b/core/java/android/view/accessibility/AccessibilityRequestPreparer.java
index 4dcb187..8108d37 100644
--- a/core/java/android/view/accessibility/AccessibilityRequestPreparer.java
+++ b/core/java/android/view/accessibility/AccessibilityRequestPreparer.java
@@ -51,6 +51,7 @@
     public @interface RequestTypes {}
 
     private final WeakReference<View> mViewRef;
+    private final int mAccessibilityViewId;
     private final int mRequestTypes;
 
     /**
@@ -68,6 +69,7 @@
             throw new IllegalStateException("View must be attached to a window");
         }
         mViewRef = new WeakReference<>(view);
+        mAccessibilityViewId = view.getAccessibilityViewId();
         mRequestTypes = requestTypes;
         view.addOnAttachStateChangeListener(new ViewAttachStateListener());
     }
@@ -118,4 +120,8 @@
             v.removeOnAttachStateChangeListener(this);
         }
     }
+
+    int getAccessibilityViewId() {
+        return mAccessibilityViewId;
+    }
 }
diff --git a/core/java/com/android/internal/app/ChooserActivity.java b/core/java/com/android/internal/app/ChooserActivity.java
index f3aac15..702b507 100644
--- a/core/java/com/android/internal/app/ChooserActivity.java
+++ b/core/java/com/android/internal/app/ChooserActivity.java
@@ -877,10 +877,17 @@
         }
         mChooserRowAdapter = new ChooserRowAdapter(mChooserListAdapter);
         mChooserRowAdapter.registerDataSetObserver(new OffsetDataSetObserver(adapterView));
-        adapterView.setAdapter(mChooserRowAdapter);
         if (listView != null) {
             listView.setItemsCanFocus(true);
+            listView.addOnLayoutChangeListener(
+                    (v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> {
+                        if (mChooserRowAdapter.calculateMaxTargetsPerRow(right - left)) {
+                            adapterView.setAdapter(mChooserRowAdapter);
+                        }
+                    });
         }
+
+        adapterView.setAdapter(mChooserRowAdapter);
     }
 
     @Override
@@ -1270,11 +1277,10 @@
         }
         mAppPredictor.notifyAppTargetEvent(
                 new AppTargetEvent.Builder(
-                    new AppTarget(
-                        new AppTargetId(shortcutId),
-                        componentName.getPackageName(),
-                        componentName.getClassName(),
-                        getUser()),
+                    new AppTarget.Builder(new AppTargetId(shortcutId))
+                        .setTarget(componentName.getPackageName(), getUser())
+                        .setClassName(componentName.getClassName())
+                        .build(),
                     AppTargetEvent.ACTION_LAUNCH
                 ).setLaunchLocation(LAUNCH_LOCATON_DIRECT_SHARE)
                 .build());
@@ -2063,7 +2069,7 @@
     class ChooserRowAdapter extends BaseAdapter {
         private ChooserListAdapter mChooserListAdapter;
         private final LayoutInflater mLayoutInflater;
-        private int mAnimationCount = 0;
+        private int mCalculatedMaxTargetsPerRow = MAX_TARGETS_PER_ROW_LANDSCAPE;
 
         private DirectShareViewHolder mDirectShareViewHolder;
 
@@ -2071,6 +2077,9 @@
         private static final int VIEW_TYPE_NORMAL = 1;
         private static final int VIEW_TYPE_CONTENT_PREVIEW = 2;
 
+        private static final int MAX_TARGETS_PER_ROW_PORTRAIT = 4;
+        private static final int MAX_TARGETS_PER_ROW_LANDSCAPE = 8;
+
         public ChooserRowAdapter(ChooserListAdapter wrappedAdapter) {
             mChooserListAdapter = wrappedAdapter;
             mLayoutInflater = LayoutInflater.from(ChooserActivity.this);
@@ -2090,9 +2099,40 @@
             });
         }
 
+        /**
+         * Determine how many targets can comfortably fit in a single row.
+         *
+         * @param width The new row width to use for recalculation
+         * @return true if the numbers of targets per row has changed
+         */
+        public boolean calculateMaxTargetsPerRow(int width) {
+            int targetWidth = getResources().getDimensionPixelSize(
+                    R.dimen.chooser_target_width);
+
+            if (targetWidth == 0 || width == 0) {
+                return false;
+            }
+
+            int margin = getResources().getDimensionPixelSize(
+                    R.dimen.chooser_edge_margin_normal);
+
+            int newCount =  (width - margin * 2) / targetWidth;
+            if (newCount != mCalculatedMaxTargetsPerRow) {
+                mCalculatedMaxTargetsPerRow = newCount;
+                return true;
+            }
+
+            return false;
+        }
+
         private int getMaxTargetsPerRow() {
-            // this will soon hold logic for portrait/landscape
-            return 4;
+            int maxTargets = MAX_TARGETS_PER_ROW_PORTRAIT;
+            if (getResources().getConfiguration().orientation
+                    == Configuration.ORIENTATION_LANDSCAPE) {
+                maxTargets = MAX_TARGETS_PER_ROW_LANDSCAPE;
+            }
+
+            return Math.min(maxTargets, mCalculatedMaxTargetsPerRow);
         }
 
         @Override
@@ -2159,9 +2199,7 @@
                 holder = (RowViewHolder) convertView.getTag();
             }
 
-            bindViewHolder(position, holder,
-                    viewType == VIEW_TYPE_DIRECT_SHARE
-                            ? ChooserListAdapter.MAX_SERVICE_TARGETS : getMaxTargetsPerRow());
+            bindViewHolder(position, holder);
 
             return holder.getViewGroup();
         }
@@ -2278,7 +2316,7 @@
             }
         }
 
-        void bindViewHolder(int rowPosition, RowViewHolder holder, int columnCount) {
+        void bindViewHolder(int rowPosition, RowViewHolder holder) {
             final int start = getFirstRowPosition(rowPosition);
             final int startType = mChooserListAdapter.getPositionTargetType(start);
 
@@ -2295,6 +2333,7 @@
                 setVertPadding(row, 0, 0);
             }
 
+            int columnCount = holder.getColumnCount();
             int end = start + columnCount - 1;
             while (mChooserListAdapter.getPositionTargetType(end) != startType && end >= start) {
                 end--;
@@ -2329,36 +2368,15 @@
             for (int i = 0; i < columnCount; i++) {
                 final View v = holder.getView(i);
                 if (start + i <= end) {
-                    setCellVisibility(holder, i, View.VISIBLE);
+                    holder.setViewVisibility(i, View.VISIBLE);
                     holder.setItemIndex(i, start + i);
                     mChooserListAdapter.bindView(holder.getItemIndex(i), v);
                 } else {
-                    setCellVisibility(holder, i, View.INVISIBLE);
+                    holder.setViewVisibility(i, View.INVISIBLE);
                 }
             }
         }
 
-        private void setCellVisibility(RowViewHolder holder, int i, int visibility) {
-            final View v = holder.getView(i);
-            if (visibility == View.VISIBLE) {
-                holder.setViewVisibility(i, true);
-                v.setVisibility(visibility);
-                v.setAlpha(1.0f);
-            } else if (visibility == View.INVISIBLE && holder.getViewVisibility(i)) {
-                holder.setViewVisibility(i, false);
-
-                ValueAnimator fadeAnim = ObjectAnimator.ofFloat(v, "alpha", 1.0f, 0f);
-                fadeAnim.setDuration(NO_DIRECT_SHARE_ANIM_IN_MILLIS);
-                fadeAnim.setInterpolator(new AccelerateInterpolator(1.0f));
-                fadeAnim.addListener(new AnimatorListenerAdapter() {
-                    public void onAnimationEnd(Animator animation) {
-                        v.setVisibility(View.INVISIBLE);
-                    }
-                });
-                fadeAnim.start();
-            }
-        }
-
         private void setVertPadding(ViewGroup row, int top, int bottom) {
             row.setPadding(row.getPaddingLeft(), top, row.getPaddingRight(), bottom);
         }
@@ -2394,13 +2412,11 @@
         protected int mMeasuredRowHeight;
         private int[] mItemIndices;
         protected final View[] mCells;
-        private final boolean[] mCellVisibility;
         private final int mColumnCount;
 
         RowViewHolder(int cellCount) {
             this.mCells = new View[cellCount];
             this.mItemIndices = new int[cellCount];
-            this.mCellVisibility = new boolean[cellCount];
             this.mColumnCount = cellCount;
         }
 
@@ -2410,18 +2426,12 @@
 
         abstract ViewGroup getRow(int index);
 
+        abstract void setViewVisibility(int i, int visibility);
+
         public int getColumnCount() {
             return mColumnCount;
         }
 
-        public void setViewVisibility(int index, boolean visibility) {
-            mCellVisibility[index] = visibility;
-        }
-
-        public boolean getViewVisibility(int index) {
-            return mCellVisibility[index];
-        }
-
         public void measure() {
             final int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
             getViewGroup().measure(spec, spec);
@@ -2477,6 +2487,10 @@
 
             return mRow;
         }
+
+        public void setViewVisibility(int i, int visibility) {
+            getView(i).setVisibility(visibility);
+        }
     }
 
     class DirectShareViewHolder extends RowViewHolder {
@@ -2489,12 +2503,15 @@
         private int mDirectShareCurrHeight = 0;
         private int mDirectShareMaxHeight = 0;
 
+        private final boolean[] mCellVisibility;
+
         DirectShareViewHolder(ViewGroup parent, List<ViewGroup> rows, int cellCountPerRow) {
             super(rows.size() * cellCountPerRow);
 
             this.mParent = parent;
             this.mRows = rows;
             this.mCellCountPerRow = cellCountPerRow;
+            this.mCellVisibility = new boolean[rows.size() * cellCountPerRow];
         }
 
         public ViewGroup addView(int index, View v) {
@@ -2533,6 +2550,27 @@
             return mDirectShareCurrHeight;
         }
 
+        public void setViewVisibility(int i, int visibility) {
+            final View v = getView(i);
+            if (visibility == View.VISIBLE) {
+                mCellVisibility[i] = true;
+                v.setVisibility(visibility);
+                v.setAlpha(1.0f);
+            } else if (visibility == View.INVISIBLE && mCellVisibility[i]) {
+                mCellVisibility[i] = false;
+
+                ValueAnimator fadeAnim = ObjectAnimator.ofFloat(v, "alpha", 1.0f, 0f);
+                fadeAnim.setDuration(NO_DIRECT_SHARE_ANIM_IN_MILLIS);
+                fadeAnim.setInterpolator(new AccelerateInterpolator(1.0f));
+                fadeAnim.addListener(new AnimatorListenerAdapter() {
+                    public void onAnimationEnd(Animator animation) {
+                        v.setVisibility(View.INVISIBLE);
+                    }
+                });
+                fadeAnim.start();
+            }
+        }
+
         public void handleScroll(AbsListView view, int y, int oldy, int maxTargetsPerRow) {
             // only expand if we have more than 4 targets, and delay that decision until
             // they start to scroll
diff --git a/core/java/com/android/internal/widget/ILockSettings.aidl b/core/java/com/android/internal/widget/ILockSettings.aidl
index 41e2fc8..b36c3fa 100644
--- a/core/java/com/android/internal/widget/ILockSettings.aidl
+++ b/core/java/com/android/internal/widget/ILockSettings.aidl
@@ -42,7 +42,7 @@
     long getLong(in String key, in long defaultValue, in int userId);
     @UnsupportedAppUsage
     String getString(in String key, in String defaultValue, in int userId);
-    void setLockCredential(in byte[] credential, int type, in byte[] savedCredential, int requestedQuality, int userId);
+    void setLockCredential(in byte[] credential, int type, in byte[] savedCredential, int requestedQuality, int userId, boolean allowUntrustedChange);
     void resetKeyStore(int userId);
     VerifyCredentialResponse checkCredential(in byte[] credential, int type, int userId,
             in ICheckCredentialProgressCallback progressCallback);
diff --git a/core/java/com/android/internal/widget/LockPatternUtils.java b/core/java/com/android/internal/widget/LockPatternUtils.java
index 30f4d6f..dd48c15 100644
--- a/core/java/com/android/internal/widget/LockPatternUtils.java
+++ b/core/java/com/android/internal/widget/LockPatternUtils.java
@@ -669,17 +669,25 @@
     /**
      * Clear any lock pattern or password.
      */
-    public void clearLock(byte[] savedCredential, int userHandle) {
+    public boolean clearLock(byte[] savedCredential, int userHandle) {
+        return clearLock(savedCredential, userHandle, false);
+    }
+
+    /**
+     * Clear any lock pattern or password, with the option to ignore incorrect existing credential.
+     */
+    public boolean clearLock(byte[] savedCredential, int userHandle, boolean allowUntrustedChange) {
         final int currentQuality = getKeyguardStoredPasswordQuality(userHandle);
         setKeyguardStoredPasswordQuality(PASSWORD_QUALITY_UNSPECIFIED, userHandle);
 
         try{
             getLockSettings().setLockCredential(null, CREDENTIAL_TYPE_NONE,
-                    savedCredential, PASSWORD_QUALITY_UNSPECIFIED, userHandle);
+                    savedCredential, PASSWORD_QUALITY_UNSPECIFIED, userHandle,
+                    allowUntrustedChange);
         } catch (Exception e) {
             Log.e(TAG, "Failed to clear lock", e);
             setKeyguardStoredPasswordQuality(currentQuality, userHandle);
-            return;
+            return false;
         }
 
         if (userHandle == UserHandle.USER_SYSTEM) {
@@ -689,6 +697,7 @@
         }
 
         onAfterChangingPassword(userHandle);
+        return true;
     }
 
     /**
@@ -726,19 +735,28 @@
     /**
      * Save a lock pattern.
      * @param pattern The new pattern to save.
+     * @param savedPattern The previously saved pattern, converted to byte[] format
      * @param userId the user whose pattern is to be saved.
+     *
+     * @return whether this was successful or not.
      */
-    public void saveLockPattern(List<LockPatternView.Cell> pattern, int userId) {
-        this.saveLockPattern(pattern, null, userId);
+    public boolean saveLockPattern(List<LockPatternView.Cell> pattern, byte[] savedPattern,
+            int userId) {
+        return saveLockPattern(pattern, savedPattern, userId, false);
     }
+
     /**
      * Save a lock pattern.
      * @param pattern The new pattern to save.
      * @param savedPattern The previously saved pattern, converted to byte[] format
      * @param userId the user whose pattern is to be saved.
+     * @param allowUntrustedChange whether we want to allow saving a new password if the existing
+     * password being provided is incorrect.
+     *
+     * @return whether this was successful or not.
      */
-    public void saveLockPattern(List<LockPatternView.Cell> pattern, byte[] savedPattern,
-            int userId) {
+    public boolean saveLockPattern(List<LockPatternView.Cell> pattern, byte[] savedPattern,
+            int userId, boolean allowUntrustedChange) {
         if (!hasSecureLockScreen()) {
             throw new UnsupportedOperationException(
                     "This operation requires the lock screen feature.");
@@ -753,11 +771,11 @@
         setKeyguardStoredPasswordQuality(PASSWORD_QUALITY_SOMETHING, userId);
         try {
             getLockSettings().setLockCredential(bytePattern, CREDENTIAL_TYPE_PATTERN, savedPattern,
-                    PASSWORD_QUALITY_SOMETHING, userId);
+                    PASSWORD_QUALITY_SOMETHING, userId, allowUntrustedChange);
         } catch (Exception e) {
             Log.e(TAG, "Couldn't save lock pattern", e);
             setKeyguardStoredPasswordQuality(currentQuality, userId);
-            return;
+            return false;
         }
         // Update the device encryption password.
         if (userId == UserHandle.USER_SYSTEM
@@ -771,6 +789,7 @@
 
         reportPatternWasChosen(userId);
         onAfterChangingPassword(userId);
+        return true;
     }
 
     private void updateCryptoUserInfo(int userId) {
@@ -873,17 +892,20 @@
      * password.
      * @param password The password to save
      * @param savedPassword The previously saved lock password, or null if none
-     * @param requestedQuality {@see DevicePolicyManager#getPasswordQuality(android.content.ComponentName)}
+     * @param requestedQuality {@see DevicePolicyManager#getPasswordQuality(
+     * android.content.ComponentName)}
      * @param userHandle The userId of the user to change the password for
      *
+     * @return whether this was successful or not.
+     *
      * @deprecated Pass password as a byte array
      */
     @Deprecated
-    public void saveLockPassword(String password, String savedPassword, int requestedQuality,
+    public boolean saveLockPassword(String password, String savedPassword, int requestedQuality,
             int userHandle) {
         byte[] passwordBytes = password != null ? password.getBytes() : null;
         byte[] savedPasswordBytes = savedPassword != null ? savedPassword.getBytes() : null;
-        saveLockPassword(passwordBytes, savedPasswordBytes, requestedQuality, userHandle);
+        return saveLockPassword(passwordBytes, savedPasswordBytes, requestedQuality, userHandle);
     }
 
     /**
@@ -893,11 +915,34 @@
      * @param password The password to save
      * @param savedPassword The previously saved lock password, or null if none
      * @param requestedQuality {@see DevicePolicyManager#getPasswordQuality(
-     *          android.content.ComponentName)}
+     * android.content.ComponentName)}
      * @param userHandle The userId of the user to change the password for
+     *
+     * @return whether this was successful or not.
      */
-    public void saveLockPassword(byte[] password, byte[] savedPassword, int requestedQuality,
+    public boolean saveLockPassword(byte[] password, byte[] savedPassword, int requestedQuality,
             int userHandle) {
+        return saveLockPassword(password, savedPassword, requestedQuality,
+                userHandle, false);
+    }
+
+    /**
+     * Save a lock password.  Does not ensure that the password is as good
+     * as the requested mode, but will adjust the mode to be as good as the
+     * password.
+     * @param password The password to save
+     * @param savedPassword The previously saved lock password, or null if none
+     * @param requestedQuality {@see DevicePolicyManager#getPasswordQuality(
+     * android.content.ComponentName)}
+     * @param userHandle The userId of the user to change the password for
+     * @param allowUntrustedChange whether we want to allow saving a new password if the existing
+     * password being provided is incorrect.
+     *
+     * @return whether this method saved the new password successfully or not. This flow will fail
+     * and return false if the given credential is wrong and allowUntrustedChange is false.
+     */
+    public boolean saveLockPassword(byte[] password, byte[] savedPassword,
+            int requestedQuality, int userHandle, boolean allowUntrustedChange) {
         if (!hasSecureLockScreen()) {
             throw new UnsupportedOperationException(
                     "This operation requires the lock screen feature.");
@@ -919,16 +964,17 @@
         setKeyguardStoredPasswordQuality(newKeyguardQuality, userHandle);
         try {
             getLockSettings().setLockCredential(password, CREDENTIAL_TYPE_PASSWORD, savedPassword,
-                    requestedQuality, userHandle);
+                    requestedQuality, userHandle, allowUntrustedChange);
         } catch (Exception e) {
             Log.e(TAG, "Unable to save lock password", e);
             setKeyguardStoredPasswordQuality(currentQuality, userHandle);
-            return;
+            return false;
         }
 
         updateEncryptionPasswordIfNeeded(password, passwordQuality, userHandle);
         updatePasswordHistory(password, userHandle);
         onAfterChangingPassword(userHandle);
+        return true;
     }
 
     /**
diff --git a/core/jni/android_media_AudioRecord.cpp b/core/jni/android_media_AudioRecord.cpp
index 02dffdc2..342aba0 100644
--- a/core/jni/android_media_AudioRecord.cpp
+++ b/core/jni/android_media_AudioRecord.cpp
@@ -821,18 +821,18 @@
     return jStatus;
 }
 
-static int android_media_AudioRecord_set_microphone_direction(JNIEnv *env, jobject thiz,
-                                                              jint direction) {
+static int android_media_AudioRecord_set_preferred_microphone_direction(
+                                JNIEnv *env, jobject thiz, jint direction) {
     sp<AudioRecord> lpRecorder = getAudioRecord(env, thiz);
     if (lpRecorder == NULL) {
         jniThrowException(env, "java/lang/IllegalStateException",
-            "Unable to retrieve AudioRecord pointer for setMicrophoneDirection()");
+            "Unable to retrieve AudioRecord pointer for setPreferredMicrophoneDirection()");
         return (jint)AUDIO_JAVA_ERROR;
     }
 
     jint jStatus = AUDIO_JAVA_SUCCESS;
-    status_t status =
-        lpRecorder->setMicrophoneDirection(static_cast<audio_microphone_direction_t>(direction));
+    status_t status = lpRecorder->setPreferredMicrophoneDirection(
+                            static_cast<audio_microphone_direction_t>(direction));
     if (status != NO_ERROR) {
         jStatus = nativeToJavaStatus(status);
     }
@@ -840,17 +840,17 @@
     return jStatus;
 }
 
-static int android_media_AudioRecord_set_microphone_field_dimension(JNIEnv *env, jobject thiz,
-                                                                    jfloat zoom) {
+static int android_media_AudioRecord_set_preferred_microphone_field_dimension(
+                                JNIEnv *env, jobject thiz, jfloat zoom) {
     sp<AudioRecord> lpRecorder = getAudioRecord(env, thiz);
     if (lpRecorder == NULL) {
         jniThrowException(env, "java/lang/IllegalStateException",
-            "Unable to retrieve AudioRecord pointer for setMicrophoneFieldDimension()");
+            "Unable to retrieve AudioRecord pointer for setPreferredMicrophoneFieldDimension()");
         return (jint)AUDIO_JAVA_ERROR;
     }
 
     jint jStatus = AUDIO_JAVA_SUCCESS;
-    status_t status = lpRecorder->setMicrophoneFieldDimension(zoom);
+    status_t status = lpRecorder->setPreferredMicrophoneFieldDimension(zoom);
     if (status != NO_ERROR) {
         jStatus = nativeToJavaStatus(status);
     }
@@ -913,10 +913,10 @@
     {"native_get_active_microphones", "(Ljava/util/ArrayList;)I",
                                         (void *)android_media_AudioRecord_get_active_microphones},
     {"native_getPortId", "()I", (void *)android_media_AudioRecord_get_port_id},
-    {"native_set_microphone_direction", "(I)I",
-                                (void *)android_media_AudioRecord_set_microphone_direction},
-    {"native_set_microphone_field_dimension", "(F)I",
-                                (void *)android_media_AudioRecord_set_microphone_field_dimension},
+    {"native_set_preferred_microphone_direction", "(I)I",
+                        (void *)android_media_AudioRecord_set_preferred_microphone_direction},
+    {"native_set_preferred_microphone_field_dimension", "(F)I",
+                        (void *)android_media_AudioRecord_set_preferred_microphone_field_dimension},
 };
 
 // field names found in android/media/AudioRecord.java
diff --git a/core/jni/android_media_AudioSystem.cpp b/core/jni/android_media_AudioSystem.cpp
index 1a90ebf..c8f81e2 100644
--- a/core/jni/android_media_AudioSystem.cpp
+++ b/core/jni/android_media_AudioSystem.cpp
@@ -2038,13 +2038,13 @@
 
 static jboolean
 android_media_AudioSystem_isOffloadSupported(JNIEnv *env, jobject thiz,
-        jint encoding, jint sampleRate, jint channelMask, jint channelIndexMask)
+        jint encoding, jint sampleRate, jint channelMask, jint channelIndexMask, jint streamType)
 {
     audio_offload_info_t format = AUDIO_INFO_INITIALIZER;
     format.format = (audio_format_t) audioFormatToNative(encoding);
     format.sample_rate = (uint32_t) sampleRate;
     format.channel_mask = nativeChannelMaskFromJavaChannelMasks(channelMask, channelIndexMask);
-    format.stream_type = AUDIO_STREAM_MUSIC;
+    format.stream_type = (audio_stream_type_t) streamType;
     format.has_video = false;
     format.is_streaming = false;
     // offload duration unknown at this point:
@@ -2292,7 +2292,7 @@
                                     (void *)android_media_AudioSystem_registerRecordingCallback},
     {"systemReady", "()I", (void *)android_media_AudioSystem_systemReady},
     {"getStreamVolumeDB", "(III)F", (void *)android_media_AudioSystem_getStreamVolumeDB},
-    {"native_is_offload_supported", "(IIII)Z", (void *)android_media_AudioSystem_isOffloadSupported},
+    {"native_is_offload_supported", "(IIIII)Z", (void *)android_media_AudioSystem_isOffloadSupported},
     {"getMicrophones", "(Ljava/util/ArrayList;)I", (void *)android_media_AudioSystem_getMicrophones},
     {"getSurroundFormats", "(Ljava/util/Map;Z)I", (void *)android_media_AudioSystem_getSurroundFormats},
     {"setSurroundFormatEnabled", "(IZ)I", (void *)android_media_AudioSystem_setSurroundFormatEnabled},
diff --git a/core/jni/android_net_NetUtils.cpp b/core/jni/android_net_NetUtils.cpp
index cfb2dd1..d7a981e 100644
--- a/core/jni/android_net_NetUtils.cpp
+++ b/core/jni/android_net_NetUtils.cpp
@@ -487,6 +487,11 @@
     return answer;
 }
 
+static void android_net_utils_resNetworkCancel(JNIEnv *env, jobject thiz, jobject javaFd) {
+    int fd = jniGetFDFromFileDescriptor(env, javaFd);
+    resNetworkCancel(fd);
+}
+
 static jobject android_net_utils_getTcpRepairWindow(JNIEnv *env, jobject thiz, jobject javaFd) {
     if (javaFd == NULL) {
         jniThrowNullPointerException(env, NULL);
@@ -546,6 +551,7 @@
     { "resNetworkSend", "(I[BII)Ljava/io/FileDescriptor;", (void*) android_net_utils_resNetworkSend },
     { "resNetworkQuery", "(ILjava/lang/String;III)Ljava/io/FileDescriptor;", (void*) android_net_utils_resNetworkQuery },
     { "resNetworkResult", "(Ljava/io/FileDescriptor;)[B", (void*) android_net_utils_resNetworkResult },
+    { "resNetworkCancel", "(Ljava/io/FileDescriptor;)V", (void*) android_net_utils_resNetworkCancel },
 };
 
 int register_android_net_NetworkUtils(JNIEnv* env)
diff --git a/core/proto/android/stats/connectivity/Android.bp b/core/proto/android/stats/connectivity/Android.bp
new file mode 100644
index 0000000..5aa4ddb
--- /dev/null
+++ b/core/proto/android/stats/connectivity/Android.bp
@@ -0,0 +1,25 @@
+// Copyright (C) 2019 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+java_library_static {
+    name: "networkstackprotosnano",
+    proto: {
+        type: "nano",
+    },
+    srcs: [
+        "network_stack.proto",
+    ],
+    sdk_version: "system_current",
+    no_framework_libs: true,
+}
\ No newline at end of file
diff --git a/core/proto/android/stats/connectivity/network_stack.proto b/core/proto/android/stats/connectivity/network_stack.proto
new file mode 100644
index 0000000..7d9aa1c
--- /dev/null
+++ b/core/proto/android/stats/connectivity/network_stack.proto
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+syntax = "proto2";
+
+package android.stats.connectivity;
+option java_multiple_files = true;
+option java_outer_classname = "NetworkStackProto";
+
+message NetworkStackEventData {
+
+}
+
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index 5427147..305fc97 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -1989,6 +1989,12 @@
     <permission android:name="android.permission.BIND_INCALL_SERVICE"
         android:protectionLevel="signature|privileged" />
 
+    <!-- Allows the app to request network scans from telephony.
+         <p>Not for use by third-party applications.
+         @SystemApi @hide-->
+    <permission android:name="android.permission.NETWORK_SCAN"
+        android:protectionLevel="signature|privileged" />
+
     <!-- Must be required by a link {@link android.telephony.VisualVoicemailService} to ensure that
          only the system can bind to it.
          <p>Protection level: signature|privileged
@@ -3927,7 +3933,7 @@
     <permission android:name="android.permission.MANAGE_ROLLBACKS"
         android:protectionLevel="signature|verifier" />
 
-    <!-- @SystemApi @TestApi @hide Allows testing apk level rollbacks. -->
+    <!-- @TestApi @hide Allows testing apk level rollbacks. -->
     <permission android:name="android.permission.TEST_MANAGE_ROLLBACKS"
         android:protectionLevel="signature" />
 
@@ -4484,6 +4490,11 @@
     <permission android:name="android.permission.SUBSTITUTE_SHARE_TARGET_APP_NAME_AND_ICON"
                 android:protectionLevel="signature|privileged" />
 
+    <!-- @SystemApi Allows an application to access shared libraries.
+         @hide -->
+    <permission android:name="android.permission.ACCESS_SHARED_LIBRARIES"
+                android:protectionLevel="signature|installer" />
+
     <application android:process="system"
                  android:persistent="true"
                  android:hasCode="false"
diff --git a/core/res/res/layout/chooser_row.xml b/core/res/res/layout/chooser_row.xml
index d4585eb..742d7eed 100644
--- a/core/res/res/layout/chooser_row.xml
+++ b/core/res/res/layout/chooser_row.xml
@@ -21,8 +21,8 @@
               android:layout_width="match_parent"
               android:layout_height="100dp"
               android:gravity="start|top"
-              android:paddingStart="@dimen/chooser_grid_padding"
-              android:paddingEnd="@dimen/chooser_grid_padding">
+              android:paddingStart="@dimen/chooser_edge_margin_normal"
+              android:paddingEnd="@dimen/chooser_edge_margin_normal">
   <TextView
       android:id="@+id/chooser_row_text_option"
       android:layout_width="match_parent"
diff --git a/core/res/res/layout/resolve_grid_item.xml b/core/res/res/layout/resolve_grid_item.xml
index a24f892..4a3dfba 100644
--- a/core/res/res/layout/resolve_grid_item.xml
+++ b/core/res/res/layout/resolve_grid_item.xml
@@ -18,7 +18,7 @@
 -->
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
               android:orientation="vertical"
-              android:layout_width="76dp"
+              android:layout_width="@dimen/chooser_target_width"
               android:layout_height="wrap_content"
               android:minHeight="100dp"
               android:gravity="center"
diff --git a/core/res/res/values/dimens.xml b/core/res/res/values/dimens.xml
index 7134eed..023fbad 100644
--- a/core/res/res/values/dimens.xml
+++ b/core/res/res/values/dimens.xml
@@ -578,7 +578,6 @@
     <dimen name="default_magnifier_horizontal_offset">0dp</dimen>
     <item type="dimen" format="float" name="default_magnifier_zoom">1.25</item>
 
-    <dimen name="chooser_grid_padding">0dp</dimen>
     <!-- Spacing around the background change frome service to non-service -->
     <dimen name="chooser_service_spacing">8dp</dimen>
 
@@ -725,4 +724,5 @@
     <dimen name="chooser_preview_width">-1px</dimen>
     <dimen name="resolver_icon_size">42dp</dimen>
     <dimen name="resolver_badge_size">18dp</dimen>
+    <dimen name="chooser_target_width">76dp</dimen>
 </resources>
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index 4ab9edb..93c8458 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -2762,6 +2762,7 @@
   <java-symbol type="string" name="chooser_no_direct_share_targets" />
   <java-symbol type="drawable" name="chooser_row_layer_list" />
   <java-symbol type="dimen" name="chooser_view_spacing" />
+  <java-symbol type="dimen" name="chooser_target_width" />
   <java-symbol type="dimen" name="chooser_edge_margin_thin" />
   <java-symbol type="dimen" name="chooser_edge_margin_normal" />
   <java-symbol type="dimen" name="chooser_preview_image_font_size"/>
diff --git a/graphics/java/android/graphics/Paint.java b/graphics/java/android/graphics/Paint.java
index 346c7ab..c485461 100644
--- a/graphics/java/android/graphics/Paint.java
+++ b/graphics/java/android/graphics/Paint.java
@@ -229,7 +229,8 @@
     public static final int VERTICAL_TEXT_FLAG = 0x1000;
 
     // These flags are always set on a new/reset paint, even if flags 0 is passed.
-    static final int HIDDEN_DEFAULT_PAINT_FLAGS = DEV_KERN_TEXT_FLAG | EMBEDDED_BITMAP_TEXT_FLAG;
+    static final int HIDDEN_DEFAULT_PAINT_FLAGS = DEV_KERN_TEXT_FLAG | EMBEDDED_BITMAP_TEXT_FLAG
+            | FILTER_BITMAP_FLAG;
 
     /**
      * Font hinter option that disables font hinting.
diff --git a/libs/hwui/renderthread/VulkanManager.cpp b/libs/hwui/renderthread/VulkanManager.cpp
index 9916da5..b8ebf3b 100644
--- a/libs/hwui/renderthread/VulkanManager.cpp
+++ b/libs/hwui/renderthread/VulkanManager.cpp
@@ -439,34 +439,47 @@
     LOG_ALWAYS_FATAL_IF(!bufferInfo->dequeued);
 
     if (bufferInfo->dequeue_fence != -1) {
-        int fence_clone = dup(bufferInfo->dequeue_fence);
-        if (fence_clone == -1) {
-            ALOGE("dup(fence) failed, stalling until signalled: %s (%d)", strerror(errno), errno);
-            sync_wait(bufferInfo->dequeue_fence, -1 /* forever */);
-        } else {
-            VkSemaphoreCreateInfo semaphoreInfo;
-            semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
-            semaphoreInfo.pNext = nullptr;
-            semaphoreInfo.flags = 0;
-            VkSemaphore semaphore;
-            VkResult err = mCreateSemaphore(mDevice, &semaphoreInfo, nullptr, &semaphore);
-            LOG_ALWAYS_FATAL_IF(VK_SUCCESS != err, "Failed to create import semaphore, err: %d",
-                                err);
+        struct sync_file_info* finfo = sync_file_info(bufferInfo->dequeue_fence);
+        bool isSignalPending = false;
+        if (finfo != NULL) {
+            isSignalPending = finfo->status != 1;
+            sync_file_info_free(finfo);
+        }
+        if (isSignalPending) {
+            int fence_clone = dup(bufferInfo->dequeue_fence);
+            if (fence_clone == -1) {
+                ALOGE("dup(fence) failed, stalling until signalled: %s (%d)", strerror(errno),
+                      errno);
+                sync_wait(bufferInfo->dequeue_fence, -1 /* forever */);
+            } else {
+                VkSemaphoreCreateInfo semaphoreInfo;
+                semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
+                semaphoreInfo.pNext = nullptr;
+                semaphoreInfo.flags = 0;
+                VkSemaphore semaphore;
+                VkResult err = mCreateSemaphore(mDevice, &semaphoreInfo, nullptr, &semaphore);
+                LOG_ALWAYS_FATAL_IF(VK_SUCCESS != err, "Failed to create import semaphore, err: %d",
+                                    err);
 
-            VkImportSemaphoreFdInfoKHR importInfo;
-            importInfo.sType = VK_STRUCTURE_TYPE_IMPORT_SEMAPHORE_FD_INFO_KHR;
-            importInfo.pNext = nullptr;
-            importInfo.semaphore = semaphore;
-            importInfo.flags = VK_SEMAPHORE_IMPORT_TEMPORARY_BIT;
-            importInfo.handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
-            importInfo.fd = fence_clone;
+                VkImportSemaphoreFdInfoKHR importInfo;
+                importInfo.sType = VK_STRUCTURE_TYPE_IMPORT_SEMAPHORE_FD_INFO_KHR;
+                importInfo.pNext = nullptr;
+                importInfo.semaphore = semaphore;
+                importInfo.flags = VK_SEMAPHORE_IMPORT_TEMPORARY_BIT;
+                importInfo.handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
+                importInfo.fd = fence_clone;
 
-            err = mImportSemaphoreFdKHR(mDevice, &importInfo);
-            LOG_ALWAYS_FATAL_IF(VK_SUCCESS != err, "Failed to import semaphore, err: %d", err);
+                err = mImportSemaphoreFdKHR(mDevice, &importInfo);
+                LOG_ALWAYS_FATAL_IF(VK_SUCCESS != err, "Failed to import semaphore, err: %d", err);
 
-            GrBackendSemaphore backendSemaphore;
-            backendSemaphore.initVulkan(semaphore);
-            bufferInfo->skSurface->wait(1, &backendSemaphore);
+                GrBackendSemaphore backendSemaphore;
+                backendSemaphore.initVulkan(semaphore);
+                bufferInfo->skSurface->wait(1, &backendSemaphore);
+                // The following flush blocks the GPU immediately instead of waiting for other
+                // drawing ops. It seems dequeue_fence is not respected otherwise.
+                //TODO: remove the flush after finding why backendSemaphore is not working.
+                bufferInfo->skSurface->flush();
+            }
         }
     }
 
diff --git a/libs/hwui/renderthread/VulkanSurface.cpp b/libs/hwui/renderthread/VulkanSurface.cpp
index c03c3a8..a98eb32 100644
--- a/libs/hwui/renderthread/VulkanSurface.cpp
+++ b/libs/hwui/renderthread/VulkanSurface.cpp
@@ -256,11 +256,44 @@
         vkPixelFormat = VK_FORMAT_R16G16B16A16_SFLOAT;
     }
 
-    uint64_t producerUsage =
-            AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE;
-    uint64_t consumerUsage;
-    native_window_get_consumer_usage(window, &consumerUsage);
-    windowInfo.windowUsageFlags = consumerUsage | producerUsage;
+    if (nullptr != vkManager.mGetPhysicalDeviceImageFormatProperties2) {
+        VkPhysicalDeviceExternalImageFormatInfo externalImageFormatInfo;
+        externalImageFormatInfo.sType =
+                VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO;
+        externalImageFormatInfo.pNext = nullptr;
+        externalImageFormatInfo.handleType =
+                VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID;
+
+        VkPhysicalDeviceImageFormatInfo2 imageFormatInfo;
+        imageFormatInfo.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2;
+        imageFormatInfo.pNext = &externalImageFormatInfo;
+        imageFormatInfo.format = vkPixelFormat;
+        imageFormatInfo.type = VK_IMAGE_TYPE_2D;
+        imageFormatInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
+        imageFormatInfo.usage = usageFlags;
+        imageFormatInfo.flags = 0;
+
+        VkAndroidHardwareBufferUsageANDROID hwbUsage;
+        hwbUsage.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_USAGE_ANDROID;
+        hwbUsage.pNext = nullptr;
+
+        VkImageFormatProperties2 imgFormProps;
+        imgFormProps.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2;
+        imgFormProps.pNext = &hwbUsage;
+
+        res = vkManager.mGetPhysicalDeviceImageFormatProperties2(vkManager.mPhysicalDevice,
+                                                                 &imageFormatInfo, &imgFormProps);
+        if (VK_SUCCESS != res) {
+            ALOGE("Failed to query GetPhysicalDeviceImageFormatProperties2");
+            return nullptr;
+        }
+
+        windowInfo.windowUsageFlags = hwbUsage.androidHardwareBufferUsage;
+
+    } else {
+        ALOGE("VulkanSurface::Create() vkmGetPhysicalDeviceImageFormatProperties2 is missing");
+        return nullptr;
+    }
 
     /*
      * Now we attempt to modify the window!
diff --git a/media/Android.bp b/media/Android.bp
index 86dc509..3480181 100644
--- a/media/Android.bp
+++ b/media/Android.bp
@@ -90,7 +90,6 @@
         "apex/java/android/media/DataSourceDesc.java",
         "apex/java/android/media/UriDataSourceDesc.java",
         "apex/java/android/media/FileDataSourceDesc.java",
-        "apex/java/android/media/CallbackDataSourceDesc.java",
         "apex/java/android/media/Media2Utils.java",
         "apex/java/android/media/MediaPlayer2Utils.java",
         "apex/java/android/media/MediaPlayer2.java",
@@ -98,6 +97,7 @@
         "apex/java/android/media/Media2HTTPConnection.java",
         "apex/java/android/media/RoutingDelegate.java",
         "apex/java/android/media/BufferingParams.java",
+        "apex/java/android/media/ProxyDataSourceCallback.java",
     ],
 }
 
diff --git a/media/apex/java/android/media/CallbackDataSourceDesc.java b/media/apex/java/android/media/CallbackDataSourceDesc.java
deleted file mode 100644
index d9db62e..0000000
--- a/media/apex/java/android/media/CallbackDataSourceDesc.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.media;
-
-import android.annotation.NonNull;
-import android.annotation.TestApi;
-
-/**
- * Structure of data source descriptor for sources using callback.
- *
- * Used by {@link MediaPlayer2#setDataSource}, {@link MediaPlayer2#setNextDataSource} and
- * {@link MediaPlayer2#setNextDataSources} to set data source for playback.
- *
- * <p>Users should use {@link Builder} to create {@link CallbackDataSourceDesc}.
- * @hide
- */
-@TestApi
-public class CallbackDataSourceDesc extends DataSourceDesc {
-    private DataSourceCallback mDataSourceCallback;
-
-    CallbackDataSourceDesc(String mediaId, long startPositionMs, long endPositionMs,
-            DataSourceCallback dataSourceCallback) {
-        super(mediaId, startPositionMs, endPositionMs);
-        mDataSourceCallback = dataSourceCallback;
-    }
-
-    /**
-     * Return the DataSourceCallback of this data source.
-     * @return the DataSourceCallback of this data source
-     */
-    public @NonNull DataSourceCallback getDataSourceCallback() {
-        return mDataSourceCallback;
-    }
-}
diff --git a/media/apex/java/android/media/DataSourceCallback.java b/media/apex/java/android/media/DataSourceCallback.java
index 6515bd6..c297ecd 100644
--- a/media/apex/java/android/media/DataSourceCallback.java
+++ b/media/apex/java/android/media/DataSourceCallback.java
@@ -32,8 +32,12 @@
  * you don't need to do your own synchronization unless you're modifying the
  * DataSourceCallback from another thread while it's being used by the framework.</p>
  *
+ * @hide
  */
 public abstract class DataSourceCallback implements Closeable {
+
+    public static final int END_OF_STREAM = -1;
+
     /**
      * Called to request data from the given position.
      *
@@ -49,7 +53,7 @@
      * @param offset the offset within buffer to read the data into.
      * @param size the number of bytes to read.
      * @throws IOException on fatal errors.
-     * @return the number of bytes read, or -1 if end of stream is reached.
+     * @return the number of bytes read, or {@link #END_OF_STREAM} if end of stream is reached.
      */
     public abstract int readAt(long position, @NonNull byte[] buffer, int offset, int size)
             throws IOException;
diff --git a/media/apex/java/android/media/DataSourceDesc.java b/media/apex/java/android/media/DataSourceDesc.java
index be80c22..d00ff2a 100644
--- a/media/apex/java/android/media/DataSourceDesc.java
+++ b/media/apex/java/android/media/DataSourceDesc.java
@@ -125,7 +125,6 @@
         private static final int SOURCE_TYPE_UNKNOWN = 0;
         private static final int SOURCE_TYPE_URI = 1;
         private static final int SOURCE_TYPE_FILE = 2;
-        private static final int SOURCE_TYPE_CALLBACK = 3;
 
         private int mSourceType = SOURCE_TYPE_UNKNOWN;
         private String mMediaId;
@@ -142,9 +141,6 @@
         private long mOffset = 0;
         private long mLength = FileDataSourceDesc.FD_LENGTH_UNKNOWN;
 
-        // For CallbackDataSourceDesc
-        private DataSourceCallback mDataSourceCallback;
-
         /**
          * Constructs a new BuilderBase with the defaults.
          */
@@ -173,9 +169,6 @@
                 mUri = ((UriDataSourceDesc) dsd).getUri();
                 mHeader = ((UriDataSourceDesc) dsd).getHeaders();
                 mCookies = ((UriDataSourceDesc) dsd).getCookies();
-            } else if (dsd instanceof CallbackDataSourceDesc) {
-                mSourceType = SOURCE_TYPE_CALLBACK;
-                mDataSourceCallback = ((CallbackDataSourceDesc) dsd).getDataSourceCallback();
             } else {
                 throw new IllegalStateException("Unknown source type:" + mSourceType);
             }
@@ -204,9 +197,6 @@
             } else if (mSourceType == SOURCE_TYPE_URI) {
                 desc = new UriDataSourceDesc(
                         mMediaId, mStartPositionMs, mEndPositionMs, mUri, mHeader, mCookies);
-            } else if (mSourceType == SOURCE_TYPE_CALLBACK) {
-                desc = new CallbackDataSourceDesc(
-                        mMediaId, mStartPositionMs, mEndPositionMs, mDataSourceCallback);
             } else {
                 throw new IllegalStateException("Unknown source type:" + mSourceType);
             }
@@ -326,7 +316,7 @@
 
         /**
          * Sets the data source (ParcelFileDescriptor) to use. The ParcelFileDescriptor must be
-         * seekable (N.B. a LocalSocket is not seekable). When the {@link FileDataSourceDesc}
+         * seekable (N.B. a LocalSocket is not seekable). When the {@link DataSourceDesc}
          * created by this builder is passed to {@link MediaPlayer2} via
          * {@link MediaPlayer2#setDataSource},
          * {@link MediaPlayer2#setNextDataSource} or
@@ -347,7 +337,7 @@
 
         /**
          * Sets the data source (ParcelFileDescriptor) to use. The ParcelFileDescriptor must be
-         * seekable (N.B. a LocalSocket is not seekable). When the {@link FileDataSourceDesc}
+         * seekable (N.B. a LocalSocket is not seekable). When the {@link DataSourceDesc}
          * created by this builder is passed to {@link MediaPlayer2} via
          * {@link MediaPlayer2#setDataSource},
          * {@link MediaPlayer2#setNextDataSource} or
@@ -367,7 +357,9 @@
         public Builder setDataSource(
                 @NonNull ParcelFileDescriptor pfd, long offset, long length) {
             setSourceType(SOURCE_TYPE_FILE);
-            Media2Utils.checkArgument(pfd != null, "pfd cannot be null.");
+            if (pfd == null) {
+                throw new NullPointerException("pfd cannot be null.");
+            }
             if (offset < 0) {
                 offset = 0;
             }
@@ -380,20 +372,6 @@
             return this;
         }
 
-        /**
-         * Sets the data source (DataSourceCallback) to use.
-         *
-         * @param dscb the DataSourceCallback for the media to play
-         * @return the same Builder instance.
-         * @throws NullPointerException if dscb is null.
-         */
-        public @NonNull Builder setDataSource(@NonNull DataSourceCallback dscb) {
-            setSourceType(SOURCE_TYPE_CALLBACK);
-            Media2Utils.checkArgument(dscb != null, "data source cannot be null.");
-            mDataSourceCallback = dscb;
-            return this;
-        }
-
         private void setSourceType(int type) {
             if (mSourceType != SOURCE_TYPE_UNKNOWN) {
                 throw new IllegalStateException("Source is already set. type=" + mSourceType);
diff --git a/media/apex/java/android/media/MediaPlayer2.java b/media/apex/java/android/media/MediaPlayer2.java
index 68a46ed..19bb258 100644
--- a/media/apex/java/android/media/MediaPlayer2.java
+++ b/media/apex/java/android/media/MediaPlayer2.java
@@ -878,22 +878,27 @@
             throws IOException {
         Media2Utils.checkArgument(dsd != null, "the DataSourceDesc cannot be null");
 
-        if (dsd instanceof CallbackDataSourceDesc) {
-            CallbackDataSourceDesc cbDSD = (CallbackDataSourceDesc) dsd;
-            handleDataSource(isCurrent,
-                             srcId,
-                             cbDSD.getDataSourceCallback(),
-                             cbDSD.getStartPosition(),
-                             cbDSD.getEndPosition());
-        } else if (dsd instanceof FileDataSourceDesc) {
+        if (dsd instanceof FileDataSourceDesc) {
             FileDataSourceDesc fileDSD = (FileDataSourceDesc) dsd;
-            handleDataSource(isCurrent,
-                             srcId,
-                             fileDSD.getParcelFileDescriptor(),
-                             fileDSD.getOffset(),
-                             fileDSD.getLength(),
-                             fileDSD.getStartPosition(),
-                             fileDSD.getEndPosition());
+            ParcelFileDescriptor pfd = fileDSD.getParcelFileDescriptor();
+            if (pfd.getStatSize() == -1) {
+                // Underlying pipeline doesn't understand '-1' size. Create a wrapper for
+                // translation.
+                // TODO: Make native code handle '-1' size.
+                handleDataSource(isCurrent,
+                        srcId,
+                        new ProxyDataSourceCallback(pfd),
+                        fileDSD.getStartPosition(),
+                        fileDSD.getEndPosition());
+            } else {
+                handleDataSource(isCurrent,
+                        srcId,
+                        pfd,
+                        fileDSD.getOffset(),
+                        fileDSD.getLength(),
+                        fileDSD.getStartPosition(),
+                        fileDSD.getEndPosition());
+            }
         } else if (dsd instanceof UriDataSourceDesc) {
             UriDataSourceDesc uriDSD = (UriDataSourceDesc) dsd;
             handleDataSource(isCurrent,
@@ -1963,6 +1968,17 @@
     private native byte[] native_invoke(byte[] request);
 
     /**
+     * @hide
+     */
+    @IntDef(flag = false, prefix = "MEDIA_TRACK_TYPE", value = {
+            TrackInfo.MEDIA_TRACK_TYPE_VIDEO,
+            TrackInfo.MEDIA_TRACK_TYPE_AUDIO,
+            TrackInfo.MEDIA_TRACK_TYPE_SUBTITLE
+    })
+    @Retention(RetentionPolicy.SOURCE)
+    public @interface TrackType {}
+
+    /**
      * Class for MediaPlayer2 to return each audio/video/subtitle track's metadata.
      *
      * @see MediaPlayer2#getTrackInfo
@@ -2009,10 +2025,11 @@
         public static final int MEDIA_TRACK_TYPE_SUBTITLE = 4;
         public static final int MEDIA_TRACK_TYPE_METADATA = 5;
 
+        final int mId;
         final int mTrackType;
         final MediaFormat mFormat;
 
-        static TrackInfo create(Iterator<Value> in) {
+        static TrackInfo create(int idx, Iterator<Value> in) {
             int trackType = in.next().getInt32Value();
             // TODO: build the full MediaFormat; currently we are using createSubtitleFormat
             // even for audio/video tracks, meaning we only set the mime and language.
@@ -2025,11 +2042,12 @@
                 format.setInteger(MediaFormat.KEY_IS_DEFAULT, in.next().getInt32Value());
                 format.setInteger(MediaFormat.KEY_IS_FORCED_SUBTITLE, in.next().getInt32Value());
             }
-            return new TrackInfo(trackType, format);
+            return new TrackInfo(idx, trackType, format);
         }
 
         /** @hide */
-        TrackInfo(int type, MediaFormat format) {
+        TrackInfo(int id, int type, MediaFormat format) {
+            mId = id;
             mTrackType = type;
             mFormat = format;
         }
@@ -2116,7 +2134,7 @@
         }
         TrackInfo[] trackInfo = new TrackInfo[size];
         for (int i = 0; i < size; ++i) {
-            trackInfo[i] = TrackInfo.create(in);
+            trackInfo[i] = TrackInfo.create(i, in);
         }
         return trackInfo;
     }
@@ -2124,54 +2142,56 @@
     /**
      * Returns the index of the audio, video, or subtitle track currently selected for playback.
      * The return value is an index into the array returned by {@link #getTrackInfo}, and can
-     * be used in calls to {@link #selectTrack(int)} or {@link #deselectTrack(int)}.
+     * be used in calls to {@link #selectTrack(TrackInfo)} or {@link #deselectTrack(TrackInfo)}.
      * Same as {@link #getSelectedTrack(DataSourceDesc, int)} with
      * {@code dsd = getCurrentDataSource()}.
      *
      * @param trackType should be one of {@link TrackInfo#MEDIA_TRACK_TYPE_VIDEO},
      * {@link TrackInfo#MEDIA_TRACK_TYPE_AUDIO}, or
      * {@link TrackInfo#MEDIA_TRACK_TYPE_SUBTITLE}
-     * @return index of the audio, video, or subtitle track currently selected for playback;
-     * a negative integer is returned when there is no selected track for {@code trackType} or
+     * @return metadata corresponding to the audio, video, or subtitle track currently selected for
+     * playback; {@code null} is returned when there is no selected track for {@code trackType} or
      * when {@code trackType} is not one of audio, video, or subtitle.
      * @throws IllegalStateException if called after {@link #close()}
      * @throws NullPointerException if current data source is null
      *
      * @see #getTrackInfo()
-     * @see #selectTrack(int)
-     * @see #deselectTrack(int)
+     * @see #selectTrack(TrackInfo)
+     * @see #deselectTrack(TrackInfo)
      */
-    public int getSelectedTrack(int trackType) {
+    @Nullable
+    public TrackInfo getSelectedTrack(@TrackType int trackType) {
         return getSelectedTrack(getCurrentDataSource(), trackType);
     }
 
     /**
      * Returns the index of the audio, video, or subtitle track currently selected for playback.
      * The return value is an index into the array returned by {@link #getTrackInfo}, and can
-     * be used in calls to {@link #selectTrack(DataSourceDesc, int)} or
-     * {@link #deselectTrack(DataSourceDesc, int)}.
+     * be used in calls to {@link #selectTrack(DataSourceDesc, TrackInfo)} or
+     * {@link #deselectTrack(DataSourceDesc, TrackInfo)}.
      *
      * @param dsd the descriptor of data source of which you want to get selected track
      * @param trackType should be one of {@link TrackInfo#MEDIA_TRACK_TYPE_VIDEO},
      * {@link TrackInfo#MEDIA_TRACK_TYPE_AUDIO}, or
      * {@link TrackInfo#MEDIA_TRACK_TYPE_SUBTITLE}
-     * @return index of the audio, video, or subtitle track currently selected for playback;
-     * a negative integer is returned when there is no selected track for {@code trackType} or
+     * @return metadata corresponding to the audio, video, or subtitle track currently selected for
+     * playback; {@code null} is returned when there is no selected track for {@code trackType} or
      * when {@code trackType} is not one of audio, video, or subtitle.
      * @throws IllegalStateException if called after {@link #close()}
      * @throws NullPointerException if dsd is null
      *
      * @see #getTrackInfo(DataSourceDesc)
-     * @see #selectTrack(DataSourceDesc, int)
-     * @see #deselectTrack(DataSourceDesc, int)
+     * @see #selectTrack(DataSourceDesc, TrackInfo)
+     * @see #deselectTrack(DataSourceDesc, TrackInfo)
      */
-    public int getSelectedTrack(@NonNull DataSourceDesc dsd, int trackType) {
+    @Nullable
+    public TrackInfo getSelectedTrack(@NonNull DataSourceDesc dsd, @TrackType int trackType) {
         if (dsd == null) {
             throw new NullPointerException("non-null dsd is expected");
         }
         SourceInfo sourceInfo = getSourceInfo(dsd);
         if (sourceInfo == null) {
-            return -1;
+            return null;
         }
 
         PlayerMessage request = PlayerMessage.newBuilder()
@@ -2181,26 +2201,30 @@
                 .build();
         PlayerMessage response = invoke(request);
         if (response == null) {
-            return -1;
+            return null;
         }
-        return response.getValues(0).getInt32Value();
+        // TODO: return full TrackInfo data from native player instead of index
+        final int idx = response.getValues(0).getInt32Value();
+        final List<TrackInfo> trackInfos = getTrackInfo(dsd);
+        return trackInfos.isEmpty() ? null : trackInfos.get(idx);
     }
 
     /**
      * Selects a track of current data source.
-     * Same as {@link #selectTrack(DataSourceDesc, int)} with
+     * Same as {@link #selectTrack(DataSourceDesc, TrackInfo)} with
      * {@code dsd = getCurrentDataSource()}.
      *
-     * @param index the index of the track to be selected. The valid range of the index
-     * is 0..total number of track - 1. The total number of tracks as well as the type of
-     * each individual track can be found by calling {@link #getTrackInfo()} method.
+     * @param trackInfo metadata corresponding to the track to be selected. A {@code trackInfo}
+     * object can be obtained from {@link #getTrackInfo()}.
      * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
      *
+     * This is an asynchronous call.
+     *
      * @see MediaPlayer2#getTrackInfo()
      */
-    // This is an asynchronous call.
-    public @NonNull Object selectTrack(int index) {
-        return selectTrack(getCurrentDataSource(), index);
+    @NonNull
+    public Object selectTrack(@NonNull TrackInfo trackInfo) {
+        return selectTrack(getCurrentDataSource(), trackInfo);
     }
 
     /**
@@ -2225,38 +2249,40 @@
      * in that an audio track can only be selected in the <em>Prepared</em> state.
      * </p>
      * @param dsd the descriptor of data source of which you want to select track
-     * @param index the index of the track to be selected. The valid range of the index
-     * is 0..total number of track - 1. The total number of tracks as well as the type of
-     * each individual track can be found by calling {@link #getTrackInfo(DataSourceDesc)} method.
+     * @param trackInfo metadata corresponding to the track to be selected. A {@code trackInfo}
+     * object can be obtained from {@link #getTrackInfo()}.
      * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
      *
+     * This is an asynchronous call.
+     *
      * @see MediaPlayer2#getTrackInfo(DataSourceDesc)
      */
-    // This is an asynchronous call.
-    public @NonNull Object selectTrack(@NonNull DataSourceDesc dsd, int index) {
+    @NonNull
+    public Object selectTrack(@NonNull DataSourceDesc dsd, @NonNull TrackInfo trackInfo) {
         return addTask(new Task(CALL_COMPLETED_SELECT_TRACK, false) {
             @Override
             void process() {
-                selectOrDeselectTrack(dsd, index, true /* select */);
+                selectOrDeselectTrack(dsd, trackInfo.mId, true /* select */);
             }
         });
     }
 
     /**
      * Deselect a track of current data source.
-     * Same as {@link #deselectTrack(DataSourceDesc, int)} with
+     * Same as {@link #deselectTrack(DataSourceDesc, TrackInfo)} with
      * {@code dsd = getCurrentDataSource()}.
      *
-     * @param index the index of the track to be deselected. The valid range of the index
-     * is 0..total number of tracks - 1. The total number of tracks as well as the type of
-     * each individual track can be found by calling {@link #getTrackInfo()} method.
+     * @param trackInfo metadata corresponding to the track to be selected. A {@code trackInfo}
+     * object can be obtained from {@link #getTrackInfo()}.
      * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
      *
+     * This is an asynchronous call.
+     *
      * @see MediaPlayer2#getTrackInfo()
      */
-    // This is an asynchronous call.
-    public @NonNull Object deselectTrack(int index) {
-        return deselectTrack(getCurrentDataSource(), index);
+    @NonNull
+    public Object deselectTrack(@NonNull TrackInfo trackInfo) {
+        return deselectTrack(getCurrentDataSource(), trackInfo);
     }
 
     /**
@@ -2267,19 +2293,20 @@
      * selected before, it throws an exception.
      * </p>
      * @param dsd the descriptor of data source of which you want to deselect track
-     * @param index the index of the track to be deselected. The valid range of the index
-     * is 0..total number of tracks - 1. The total number of tracks as well as the type of
-     * each individual track can be found by calling {@link #getTrackInfo} method.
+     * @param trackInfo metadata corresponding to the track to be selected. A {@code trackInfo}
+     * object can be obtained from {@link #getTrackInfo()}.
      * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
      *
+     * This is an asynchronous call.
+     *
      * @see MediaPlayer2#getTrackInfo(DataSourceDesc)
      */
-    // This is an asynchronous call.
-    public @NonNull Object deselectTrack(@NonNull DataSourceDesc dsd, int index) {
+    @NonNull
+    public Object deselectTrack(@NonNull DataSourceDesc dsd, @NonNull TrackInfo trackInfo) {
         return addTask(new Task(CALL_COMPLETED_DESELECT_TRACK, false) {
             @Override
             void process() {
-                selectOrDeselectTrack(dsd, index, false /* select */);
+                selectOrDeselectTrack(dsd, trackInfo.mId, false /* select */);
             }
         });
     }
@@ -2640,11 +2667,13 @@
                             return;
                         }
                         Iterator<Value> in = playerMsg.getValuesList().iterator();
-                        SubtitleData data = new SubtitleData(
-                                in.next().getInt32Value(),  // trackIndex
-                                in.next().getInt64Value(),  // startTimeUs
-                                in.next().getInt64Value(),  // durationUs
-                                in.next().getBytesValue().toByteArray());  // data
+                        final int trackIndex = in.next().getInt32Value();
+                        TrackInfo trackInfo = getTrackInfo(dsd).get(trackIndex);
+                        final long startTimeUs = in.next().getInt64Value();
+                        final long durationTimeUs = in.next().getInt64Value();
+                        final byte[] subData = in.next().getBytesValue().toByteArray();
+                        SubtitleData data = new SubtitleData(trackInfo,
+                                startTimeUs, durationTimeUs, subData);
                         sendEvent(new EventNotifier() {
                             @Override
                             public void notify(EventCallback callback) {
@@ -2765,6 +2794,74 @@
     }
 
     /**
+     * Class encapsulating subtitle data, as received through the
+     * {@link EventCallback#onSubtitleData} interface.
+     * <p>
+     * A {@link SubtitleData} object includes:
+     * <ul>
+     * <li> track metadadta in a {@link TrackInfo} object</li>
+     * <li> the start time (in microseconds) of the data</li>
+     * <li> the duration (in microseconds) of the data</li>
+     * <li> the actual data.</li>
+     * </ul>
+     * The data is stored in a byte-array, and is encoded in one of the supported in-band
+     * subtitle formats. The subtitle encoding is determined by the MIME type of the
+     * {@link TrackInfo} of the subtitle track, one of
+     * {@link MediaFormat#MIMETYPE_TEXT_CEA_608}, {@link MediaFormat#MIMETYPE_TEXT_CEA_708},
+     * {@link MediaFormat#MIMETYPE_TEXT_VTT}.
+     */
+    public static final class SubtitleData {
+
+        private TrackInfo mTrackInfo;
+        private long mStartTimeUs;
+        private long mDurationUs;
+        private byte[] mData;
+
+        private SubtitleData(TrackInfo trackInfo, long startTimeUs, long durationUs, byte[] data) {
+            mTrackInfo = trackInfo;
+            mStartTimeUs = startTimeUs;
+            mDurationUs = durationUs;
+            mData = (data != null ? data : new byte[0]);
+        }
+
+        /**
+         * @return metadata of track which contains this subtitle data
+         */
+        @NonNull
+        public TrackInfo getTrackInfo() {
+            return mTrackInfo;
+        }
+
+        /**
+         * @return media time at which the subtitle should start to be displayed in microseconds
+         */
+        public long getStartTimeUs() {
+            return mStartTimeUs;
+        }
+
+        /**
+         * @return the duration in microsecond during which the subtitle should be displayed
+         */
+        public long getDurationUs() {
+            return mDurationUs;
+        }
+
+        /**
+         * Returns the encoded data for the subtitle content.
+         * Encoding format depends on the subtitle type, refer to
+         * <a href="https://en.wikipedia.org/wiki/CEA-708">CEA 708</a>,
+         * <a href="https://en.wikipedia.org/wiki/EIA-608">CEA/EIA 608</a> and
+         * <a href="https://www.w3.org/TR/webvtt1/">WebVTT</a>, defined by the MIME type
+         * of the subtitle track.
+         * @return the encoded subtitle data
+         */
+        @NonNull
+        public byte[] getData() {
+            return mData;
+        }
+    }
+
+    /**
      * Interface definition for callbacks to be invoked when the player has the corresponding
      * events.
      */
@@ -3439,10 +3536,18 @@
 
         /**
          * Mutable builder to create a {@link MediaPlayer2.DrmPreparationInfo} object.
+         *
+         * {@link Builder#Builder(UUID) UUID} must not be null; {@link #setKeyType keyType}
+         * must be one of {@link MediaDrm#KEY_TYPE_STREAMING} or {@link MediaDrm#KEY_TYPE_OFFLINE}.
+         * <p>
+         * When {@link #setKeyType keyType} is {@link MediaDrm#KEY_TYPE_STREAMING},
+         * {@link #setInitData(byte[]) initData} and {@link #setMimeType(String) mimeType}
+         * must not be null; When {@link #setKeyType keyType} is {@link MediaDrm#KEY_TYPE_OFFLINE},
+         * {@link #setKeySetId(byte[]) keySetId} must not be null.
          */
         public static final class Builder {
 
-            private UUID mUUID;
+            private final UUID mUUID;
             private byte[] mKeySetId;
             private byte[] mInitData;
             private String mMimeType;
@@ -3450,15 +3555,11 @@
             private Map<String, String> mOptionalParameters;
 
             /**
-             * Set UUID of the crypto scheme selected to decrypt content. An UUID can be retrieved
-             * from the source listening to {@link MediaPlayer2.DrmEventCallback#onDrmInfo}.
-             *
-             * @param uuid of selected crypto scheme
-             * @return this
+             * @param uuid UUID of the crypto scheme selected to decrypt content. An UUID can be
+             * retrieved from the source listening to {@link DrmEventCallback#onDrmInfo}.
              */
-            public @NonNull Builder setUuid(@NonNull UUID uuid) {
+            public Builder(@NonNull UUID uuid) {
                 this.mUUID = uuid;
-                return this;
             }
 
             /**
@@ -3531,12 +3632,16 @@
             }
 
             /**
-             * @return an immutable {@link MediaPlayer2.DrmPreparationInfo} representing the
-             *         settings of this builder
+             * @return an immutable {@link DrmPreparationInfo} based on settings of this builder
              */
-            public @NonNull MediaPlayer2.DrmPreparationInfo build() {
-                return new MediaPlayer2.DrmPreparationInfo(mUUID, mKeySetId, mInitData, mMimeType,
-                        mKeyType, mOptionalParameters);
+            @NonNull
+            public DrmPreparationInfo build() {
+                final DrmPreparationInfo info = new DrmPreparationInfo(mUUID, mKeySetId, mInitData,
+                        mMimeType, mKeyType, mOptionalParameters);
+                if (!info.isValid()) {
+                    throw new IllegalArgumentException("invalid DrmPreparationInfo");
+                }
+                return info;
             }
 
         }
@@ -3572,13 +3677,61 @@
             }
             return false;
         }
+
+        /**
+         * @return UUID of the crypto scheme selected to decrypt content.
+         */
+        @NonNull
+        public UUID getUuid() {
+            return mUUID;
+        }
+
+        /**
+         * @return identifier of the persisted offline key.
+         */
+        @Nullable
+        public byte[] getKeySetId() {
+            return mKeySetId;
+        }
+
+        /**
+         * @return container-specific DRM initialization data.
+         */
+        @Nullable
+        public byte[] getInitData() {
+            return mInitData;
+        }
+
+        /**
+         * @return mime type of the content
+         */
+        @Nullable
+        public String getMimeType() {
+            return mMimeType;
+        }
+
+        /**
+         * @return type of the key request.
+         */
+        @MediaPlayer2.MediaDrmKeyType
+        public int getKeyType() {
+            return mKeyType;
+        }
+
+        /**
+         * @return optional parameters to be included in the {@link MediaDrm.KeyRequest}.
+         */
+        @Nullable
+        public Map<String, String> getOptionalParameters() {
+            return mOptionalParameters;
+        }
     }
 
     /**
      * Interface definition for callbacks to be invoked when the player has the corresponding
      * DRM events.
      */
-    public static class DrmEventCallback {
+    public static abstract class DrmEventCallback {
 
         /**
          * Called to indicate DRM info is available. Return a {@link DrmPreparationInfo} object that
@@ -3591,10 +3744,9 @@
          * @return a {@link DrmPreparationInfo} object to initialize DRM playback, or null to skip
          *         DRM initialization
          */
-        public @Nullable DrmPreparationInfo onDrmInfo(@NonNull MediaPlayer2 mp,
-                @NonNull DataSourceDesc dsd, @NonNull DrmInfo drmInfo) {
-            return null;
-        }
+        @Nullable
+        public abstract DrmPreparationInfo onDrmInfo(@NonNull MediaPlayer2 mp,
+                @NonNull DataSourceDesc dsd, @NonNull DrmInfo drmInfo);
 
         /**
          * Called to give the app the opportunity to configure DRM before the session is created.
@@ -3629,10 +3781,9 @@
          *         throwing an {@link RuntimeException} from this callback would trigger an
          *         {@link EventCallback#onError}.
          */
-        public @NonNull byte[] onDrmKeyRequest(@NonNull MediaPlayer2 mp,
-                @NonNull DataSourceDesc dsd, @NonNull MediaDrm.KeyRequest request) {
-            return new byte[0];
-        }
+        @NonNull
+        public abstract byte[] onDrmKeyRequest(@NonNull MediaPlayer2 mp,
+                @NonNull DataSourceDesc dsd, @NonNull MediaDrm.KeyRequest request);
 
         /**
          * Called to notify the client that {@code mp} is ready to decrypt DRM protected data source
@@ -3657,10 +3808,11 @@
     /**
      * Registers the callback to be invoked for various DRM events.
      *
+     * This is a synchronous call.
+     *
      * @param eventCallback the callback that will be run
      * @param executor the executor through which the callback should be invoked
      */
-    // This is a synchronous call.
     public void setDrmEventCallback(@NonNull @CallbackExecutor Executor executor,
             @NonNull DrmEventCallback eventCallback) {
         if (eventCallback == null) {
@@ -3677,8 +3829,9 @@
 
     /**
      * Clear the {@link DrmEventCallback}.
+     *
+     * This is a synchronous call.
      */
-    // This is a synchronous call.
     public void clearDrmEventCallback() {
         synchronized (mDrmEventCallbackLock) {
             mDrmEventCallback = null;
diff --git a/media/apex/java/android/media/MediaPlayer2Utils.java b/media/apex/java/android/media/MediaPlayer2Utils.java
index c6dee22..ac34260 100644
--- a/media/apex/java/android/media/MediaPlayer2Utils.java
+++ b/media/apex/java/android/media/MediaPlayer2Utils.java
@@ -36,6 +36,8 @@
                 .setSampleRate(sampleRate)
                 .setChannelMask(channelMask)
                 .build();
-        return AudioManager.isOffloadedPlaybackSupported(format);
+        //TODO MP2 needs to pass AudioAttributes for this query, instead of using default attr
+        return AudioManager.isOffloadedPlaybackSupported(format,
+                (new AudioAttributes.Builder()).build());
     }
 }
diff --git a/media/apex/java/android/media/ProxyDataSourceCallback.java b/media/apex/java/android/media/ProxyDataSourceCallback.java
new file mode 100644
index 0000000..14d3ce8
--- /dev/null
+++ b/media/apex/java/android/media/ProxyDataSourceCallback.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.media;
+
+import android.os.ParcelFileDescriptor;
+import android.system.ErrnoException;
+import android.system.Os;
+import android.system.OsConstants;
+import android.util.Log;
+
+import java.io.FileDescriptor;
+import java.io.IOException;
+
+/**
+ * A DataSourceCallback that is backed by a ParcelFileDescriptor.
+ */
+class ProxyDataSourceCallback extends DataSourceCallback {
+    private static final String TAG = "TestDataSourceCallback";
+
+    ParcelFileDescriptor mPFD;
+    FileDescriptor mFD;
+
+    ProxyDataSourceCallback(ParcelFileDescriptor pfd) throws IOException {
+        mPFD = pfd.dup();
+        mFD = mPFD.getFileDescriptor();
+    }
+
+    @Override
+    public synchronized int readAt(long position, byte[] buffer, int offset, int size)
+            throws IOException {
+        try {
+            Os.lseek(mFD, position, OsConstants.SEEK_SET);
+            int ret = Os.read(mFD, buffer, offset, size);
+            return (ret == 0) ? END_OF_STREAM : ret;
+        } catch (ErrnoException e) {
+            throw new IOException(e);
+        }
+    }
+
+    @Override
+    public synchronized long getSize() throws IOException {
+        return mPFD.getStatSize();
+    }
+
+    @Override
+    public synchronized void close() {
+        try {
+            mPFD.close();
+        } catch (IOException e) {
+            Log.e(TAG, "Failed to close the PFD.", e);
+        }
+    }
+}
+
diff --git a/media/java/android/media/AudioManager.java b/media/java/android/media/AudioManager.java
index 802cca9..7cb5e00 100644
--- a/media/java/android/media/AudioManager.java
+++ b/media/java/android/media/AudioManager.java
@@ -1489,13 +1489,18 @@
      * it does not indicate whether the resources necessary for the offloaded playback are
      * available at that instant.
      * @param format the audio format (codec, sample rate, channels) being checked.
+     * @param attributes the {@link AudioAttributes} to be used for playback
      * @return true if the given audio format can be offloaded.
      */
-    public static boolean isOffloadedPlaybackSupported(@NonNull AudioFormat format) {
+    public static boolean isOffloadedPlaybackSupported(@NonNull AudioFormat format,
+            @NonNull AudioAttributes attributes) {
         if (format == null) {
-            throw new IllegalArgumentException("Illegal null AudioFormat");
+            throw new NullPointerException("Illegal null AudioFormat");
         }
-        return AudioSystem.isOffloadSupported(format);
+        if (attributes == null) {
+            throw new NullPointerException("Illegal null AudioAttributes");
+        }
+        return AudioSystem.isOffloadSupported(format, attributes);
     }
 
     //====================================================================
diff --git a/media/java/android/media/AudioRecord.java b/media/java/android/media/AudioRecord.java
index 8051236..a7760a80 100644
--- a/media/java/android/media/AudioRecord.java
+++ b/media/java/android/media/AudioRecord.java
@@ -1798,8 +1798,8 @@
      *
      * @return true if sucessful.
      */
-    public boolean setMicrophoneDirection(@DirectionMode int direction) {
-        return native_set_microphone_direction(direction) == AudioSystem.SUCCESS;
+    public boolean setPreferredMicrophoneDirection(@DirectionMode int direction) {
+        return native_set_preferred_microphone_direction(direction) == AudioSystem.SUCCESS;
     }
 
     /**
@@ -1810,10 +1810,11 @@
      * though 0 (no zoom) to 1 (maximum zoom).
      * @return true if sucessful.
      */
-    public boolean setMicrophoneFieldDimension(@FloatRange(from = -1.0, to = 1.0) float zoom) {
+    public boolean setPreferredMicrophoneFieldDimension(
+                            @FloatRange(from = -1.0, to = 1.0) float zoom) {
         Preconditions.checkArgument(
                 zoom >= -1 && zoom <= 1, "Argument must fall between -1 & 1 (inclusive)");
-        return native_set_microphone_field_dimension(zoom) == AudioSystem.SUCCESS;
+        return native_set_preferred_microphone_field_dimension(zoom) == AudioSystem.SUCCESS;
     }
 
     //---------------------------------------------------------
@@ -1969,8 +1970,8 @@
 
     private native int native_getPortId();
 
-    private native int native_set_microphone_direction(int direction);
-    private native int native_set_microphone_field_dimension(float zoom);
+    private native int native_set_preferred_microphone_direction(int direction);
+    private native int native_set_preferred_microphone_field_dimension(float zoom);
 
     //---------------------------------------------------------
     // Utility methods
diff --git a/media/java/android/media/AudioSystem.java b/media/java/android/media/AudioSystem.java
index a976d70..ad255fe 100644
--- a/media/java/android/media/AudioSystem.java
+++ b/media/java/android/media/AudioSystem.java
@@ -1022,13 +1022,14 @@
 
     public static native float getStreamVolumeDB(int stream, int index, int device);
 
-    static boolean isOffloadSupported(@NonNull AudioFormat format) {
+    static boolean isOffloadSupported(@NonNull AudioFormat format, @NonNull AudioAttributes attr) {
         return native_is_offload_supported(format.getEncoding(), format.getSampleRate(),
-                format.getChannelMask(), format.getChannelIndexMask());
+                format.getChannelMask(), format.getChannelIndexMask(),
+                attr.getVolumeControlStream());
     }
 
     private static native boolean native_is_offload_supported(int encoding, int sampleRate,
-            int channelMask, int channelIndexMask);
+            int channelMask, int channelIndexMask, int streamType);
 
     public static native int getMicrophones(ArrayList<MicrophoneInfo> microphonesInfo);
 
diff --git a/media/java/android/media/AudioTrack.java b/media/java/android/media/AudioTrack.java
index 41e059b..325e227 100644
--- a/media/java/android/media/AudioTrack.java
+++ b/media/java/android/media/AudioTrack.java
@@ -914,8 +914,9 @@
         /**
          * Sets whether this track will play through the offloaded audio path.
          * When set to true, at build time, the audio format will be checked against
-         * {@link AudioManager#isOffloadedPlaybackSupported(AudioFormat)} to verify the audio format
-         * used by this track is supported on the device's offload path (if any).
+         * {@link AudioManager#isOffloadedPlaybackSupported(AudioFormat,AudioAttributes)}
+         * to verify the audio format used by this track is supported on the device's offload
+         * path (if any).
          * <br>Offload is only supported for media audio streams, and therefore requires that
          * the usage be {@link AudioAttributes#USAGE_MEDIA}.
          * @param offload true to require the offload path for playback.
@@ -979,7 +980,7 @@
                     throw new UnsupportedOperationException(
                             "Cannot create AudioTrack, offload requires USAGE_MEDIA");
                 }
-                if (!AudioSystem.isOffloadSupported(mFormat)) {
+                if (!AudioSystem.isOffloadSupported(mFormat, mAttributes)) {
                     throw new UnsupportedOperationException(
                             "Cannot create AudioTrack, offload format not supported");
                 }
@@ -3177,7 +3178,8 @@
      * Registers a callback for the notification of stream events.
      * This callback can only be registered for instances operating in offloaded mode
      * (see {@link AudioTrack.Builder#setOffloadedPlayback(boolean)} and
-     * {@link AudioManager#isOffloadedPlaybackSupported(AudioFormat)} for more details).
+     * {@link AudioManager#isOffloadedPlaybackSupported(AudioFormat,AudioAttributes)} for
+     * more details).
      * @param executor {@link Executor} to handle the callbacks.
      * @param eventCallback the callback to receive the stream event notifications.
      */
diff --git a/media/java/android/media/MediaRecorder.java b/media/java/android/media/MediaRecorder.java
index e7b4752..575a0bb 100644
--- a/media/java/android/media/MediaRecorder.java
+++ b/media/java/android/media/MediaRecorder.java
@@ -1537,8 +1537,8 @@
      * @param direction Direction constant.
      * @return true if sucessful.
      */
-    public boolean setMicrophoneDirection(@DirectionMode int direction) {
-        return native_setMicrophoneDirection(direction) == 0;
+    public boolean setPreferredMicrophoneDirection(@DirectionMode int direction) {
+        return native_setPreferredMicrophoneDirection(direction) == 0;
     }
 
     /**
@@ -1549,14 +1549,15 @@
      * though 0 (no zoom) to 1 (maximum zoom).
      * @return true if sucessful.
      */
-    public boolean setMicrophoneFieldDimension(@FloatRange(from = -1.0, to = 1.0) float zoom) {
+    public boolean setPreferredMicrophoneFieldDimension(
+                            @FloatRange(from = -1.0, to = 1.0) float zoom) {
         Preconditions.checkArgument(
                 zoom >= -1 && zoom <= 1, "Argument must fall between -1 & 1 (inclusive)");
-        return native_setMicrophoneFieldDimension(zoom) == 0;
+        return native_setPreferredMicrophoneFieldDimension(zoom) == 0;
     }
 
-    private native int native_setMicrophoneDirection(int direction);
-    private native int native_setMicrophoneFieldDimension(float zoom);
+    private native int native_setPreferredMicrophoneDirection(int direction);
+    private native int native_setPreferredMicrophoneFieldDimension(float zoom);
 
     //--------------------------------------------------------------------------
     // Implementation of AudioRecordingMonitor interface
diff --git a/media/java/android/media/MicrophoneDirection.java b/media/java/android/media/MicrophoneDirection.java
index 2382da5..e4eec44 100644
--- a/media/java/android/media/MicrophoneDirection.java
+++ b/media/java/android/media/MicrophoneDirection.java
@@ -32,13 +32,21 @@
      */
     int MIC_DIRECTION_UNSPECIFIED = 0;
     /**
-     * Optimize capture for audio coming from the screen-side of the device.
+     * Optimize capture for audio coming from the side of the device facing the user.
+     * In the typical case, a device with a single screen, screen-side camera/microphone and
+     * non-screen-side camera/microphone, this will be the screen side (as in a "selfie").
+     * For a different device geometry, it is the side for which the expectation is to be
+     * facing the user.
      */
-    int MIC_DIRECTION_FRONT = 1;
+    int MIC_DIRECTION_TOWARDS_USER = 1;
     /**
-     * Optimize capture for audio coming from the side of the device opposite the screen.
+     * Optimize capture for audio coming from the side of the device pointing away from the user.
+     * In the typical case, a device with a single screen, screen-side camera/microphone and
+     * non-screen-side camera/microphone, this will be the non-screen side.
+     * For a different device geometry, it is the side for which the expectation is to be
+     * facing away from the user. This is the "taking a video of something else" case.
      */
-    int MIC_DIRECTION_BACK = 2;
+    int MIC_DIRECTION_AWAY_FROM_USER = 2;
     /**
      * Optimize capture for audio coming from an off-device microphone.
      */
@@ -47,8 +55,8 @@
     /** @hide */
     /*public*/ @IntDef({
             MIC_DIRECTION_UNSPECIFIED,
-            MIC_DIRECTION_FRONT,
-            MIC_DIRECTION_BACK,
+            MIC_DIRECTION_TOWARDS_USER,
+            MIC_DIRECTION_AWAY_FROM_USER,
             MIC_DIRECTION_EXTERNAL
     })
     @Retention(RetentionPolicy.SOURCE)
@@ -58,18 +66,23 @@
      * which side of the device to optimize capture from. Typically used in conjunction with
      * the camera capturing video.
      *
+     * Usage would include specifying the audio capture to follow camera being used to capture
+     * video.
      * @param direction Direction constant.
      * @return true if sucessful.
      */
-    boolean setMicrophoneDirection(@DirectionMode int direction);
+    boolean setPreferredMicrophoneDirection(@DirectionMode int direction);
 
     /**
      * Specifies the zoom factor (i.e. the field dimension) for the selected microphone
      * (for processing). The selected microphone is determined by the use-case for the stream.
      *
+     * Usage would include specifying the audio focus to follow the zoom specified for the camera
+     * being used to capture video.
+     *
      * @param zoom the desired field dimension of microphone capture. Range is from -1 (wide angle),
      * though 0 (no zoom) to 1 (maximum zoom).
      * @return true if sucessful.
      */
-    boolean setMicrophoneFieldDimension(@FloatRange(from = -1.0, to = 1.0) float zoom);
+    boolean setPreferredMicrophoneFieldDimension(@FloatRange(from = -1.0, to = 1.0) float zoom);
 }
diff --git a/media/java/android/media/session/MediaSession.java b/media/java/android/media/session/MediaSession.java
index cbc6c9d..080094c 100644
--- a/media/java/android/media/session/MediaSession.java
+++ b/media/java/android/media/session/MediaSession.java
@@ -27,12 +27,15 @@
 import android.media.AudioAttributes;
 import android.media.MediaDescription;
 import android.media.MediaMetadata;
+import android.media.MediaParceledListSlice;
 import android.media.Rating;
 import android.media.VolumeProvider;
 import android.media.session.MediaSessionManager.RemoteUserInfo;
 import android.net.Uri;
 import android.os.Bundle;
 import android.os.Handler;
+import android.os.Looper;
+import android.os.Message;
 import android.os.Parcel;
 import android.os.Parcelable;
 import android.os.Process;
@@ -40,6 +43,10 @@
 import android.os.ResultReceiver;
 import android.service.media.MediaBrowserService;
 import android.text.TextUtils;
+import android.util.Log;
+import android.util.Pair;
+import android.view.KeyEvent;
+import android.view.ViewConfiguration;
 
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
@@ -116,12 +123,21 @@
             FLAG_EXCLUSIVE_GLOBAL_PRIORITY })
     public @interface SessionFlags { }
 
-    private final MediaSessionEngine mImpl;
+    private final Object mLock = new Object();
     private final int mMaxBitmapSize;
 
+    private final Token mSessionToken;
+    private final MediaController mController;
+    private final ISession mBinder;
+    private final SessionCallbackLink mCbStub;
+
     // Do not change the name of mCallback. Support lib accesses this by using reflection.
     @UnsupportedAppUsage
-    private Object mCallback;
+    private CallbackMessageHandler mCallback;
+    private VolumeProvider mVolumeProvider;
+    private PlaybackState mPlaybackState;
+
+    private boolean mActive = false;
 
     /**
      * Creates a new session. The session will automatically be registered with
@@ -160,14 +176,15 @@
         if (TextUtils.isEmpty(tag)) {
             throw new IllegalArgumentException("tag cannot be null or empty");
         }
+        mMaxBitmapSize = context.getResources().getDimensionPixelSize(
+                com.android.internal.R.dimen.config_mediaMetadataBitmapMaxSize);
+        mCbStub = new SessionCallbackLink(context, this);
         MediaSessionManager manager = (MediaSessionManager) context
                 .getSystemService(Context.MEDIA_SESSION_SERVICE);
         try {
-            SessionCallbackLink cbLink = new SessionCallbackLink(context);
-            ISession binder = manager.createSession(cbLink, tag, sessionInfo);
-            mImpl = new MediaSessionEngine(context, binder, cbLink);
-            mMaxBitmapSize = context.getResources().getDimensionPixelSize(
-                    com.android.internal.R.dimen.config_mediaMetadataBitmapMaxSize);
+            mBinder = manager.createSession(mCbStub, tag, sessionInfo);
+            mSessionToken = new Token(mBinder.getController());
+            mController = new MediaController(context, mSessionToken);
         } catch (RemoteException e) {
             throw new RuntimeException("Remote error creating session.", e);
         }
@@ -183,8 +200,7 @@
      * @param callback The callback object
      */
     public void setCallback(@Nullable Callback callback) {
-        mCallback = callback == null ? null : new Object();
-        mImpl.setCallback(callback);
+        setCallback(callback, null);
     }
 
     /**
@@ -197,8 +213,24 @@
      * @param handler The handler that events should be posted on.
      */
     public void setCallback(@Nullable Callback callback, @Nullable Handler handler) {
-        mCallback = callback == null ? null : new Object();
-        mImpl.setCallback(callback, handler);
+        synchronized (mLock) {
+            if (mCallback != null) {
+                // We're updating the callback, clear the session from the old one.
+                mCallback.mCallback.mSession = null;
+                mCallback.removeCallbacksAndMessages(null);
+            }
+            if (callback == null) {
+                mCallback = null;
+                return;
+            }
+            if (handler == null) {
+                handler = new Handler();
+            }
+            callback.mSession = this;
+            CallbackMessageHandler msgHandler = new CallbackMessageHandler(handler.getLooper(),
+                    callback);
+            mCallback = msgHandler;
+        }
     }
 
     /**
@@ -209,7 +241,11 @@
      * @param pi The intent to launch to show UI for this Session.
      */
     public void setSessionActivity(@Nullable PendingIntent pi) {
-        mImpl.setSessionActivity(pi);
+        try {
+            mBinder.setLaunchPendingIntent(pi);
+        } catch (RemoteException e) {
+            Log.wtf(TAG, "Failure in setLaunchPendingIntent.", e);
+        }
     }
 
     /**
@@ -221,7 +257,11 @@
      * @param mbr The {@link PendingIntent} to send the media button event to.
      */
     public void setMediaButtonReceiver(@Nullable PendingIntent mbr) {
-        mImpl.setMediaButtonReceiver(mbr);
+        try {
+            mBinder.setMediaButtonReceiver(mbr);
+        } catch (RemoteException e) {
+            Log.wtf(TAG, "Failure in setMediaButtonReceiver.", e);
+        }
     }
 
     /**
@@ -230,7 +270,11 @@
      * @param flags The flags to set for this session.
      */
     public void setFlags(@SessionFlags int flags) {
-        mImpl.setFlags(flags);
+        try {
+            mBinder.setFlags(flags);
+        } catch (RemoteException e) {
+            Log.wtf(TAG, "Failure in setFlags.", e);
+        }
     }
 
     /**
@@ -245,7 +289,14 @@
      * @param attributes The {@link AudioAttributes} for this session's audio.
      */
     public void setPlaybackToLocal(AudioAttributes attributes) {
-        mImpl.setPlaybackToLocal(attributes);
+        if (attributes == null) {
+            throw new IllegalArgumentException("Attributes cannot be null for local playback.");
+        }
+        try {
+            mBinder.setPlaybackToLocal(attributes);
+        } catch (RemoteException e) {
+            Log.wtf(TAG, "Failure in setPlaybackToLocal.", e);
+        }
     }
 
     /**
@@ -260,7 +311,26 @@
      *            not be null.
      */
     public void setPlaybackToRemote(@NonNull VolumeProvider volumeProvider) {
-        mImpl.setPlaybackToRemote(volumeProvider);
+        if (volumeProvider == null) {
+            throw new IllegalArgumentException("volumeProvider may not be null!");
+        }
+        synchronized (mLock) {
+            mVolumeProvider = volumeProvider;
+        }
+        volumeProvider.setCallback(new VolumeProvider.Callback() {
+            @Override
+            public void onVolumeChanged(VolumeProvider volumeProvider) {
+                notifyRemoteVolumeChanged(volumeProvider);
+            }
+        });
+
+        try {
+            mBinder.setPlaybackToRemote(volumeProvider.getVolumeControl(),
+                    volumeProvider.getMaxVolume());
+            mBinder.setCurrentVolume(volumeProvider.getCurrentVolume());
+        } catch (RemoteException e) {
+            Log.wtf(TAG, "Failure in setPlaybackToRemote.", e);
+        }
     }
 
     /**
@@ -272,7 +342,15 @@
      * @param active Whether this session is active or not.
      */
     public void setActive(boolean active) {
-        mImpl.setActive(active);
+        if (mActive == active) {
+            return;
+        }
+        try {
+            mBinder.setActive(active);
+            mActive = active;
+        } catch (RemoteException e) {
+            Log.wtf(TAG, "Failure in setActive.", e);
+        }
     }
 
     /**
@@ -281,7 +359,7 @@
      * @return True if the session is active, false otherwise.
      */
     public boolean isActive() {
-        return mImpl.isActive();
+        return mActive;
     }
 
     /**
@@ -293,7 +371,14 @@
      * @param extras Any extras included with the event
      */
     public void sendSessionEvent(@NonNull String event, @Nullable Bundle extras) {
-        mImpl.sendSessionEvent(event, extras);
+        if (TextUtils.isEmpty(event)) {
+            throw new IllegalArgumentException("event cannot be null or empty");
+        }
+        try {
+            mBinder.sendEvent(event, extras);
+        } catch (RemoteException e) {
+            Log.wtf(TAG, "Error sending event", e);
+        }
     }
 
     /**
@@ -302,7 +387,11 @@
      * but it must be released if your activity or service is being destroyed.
      */
     public void release() {
-        mImpl.close();
+        try {
+            mBinder.destroySession();
+        } catch (RemoteException e) {
+            Log.wtf(TAG, "Error releasing session: ", e);
+        }
     }
 
     /**
@@ -314,7 +403,7 @@
      *         session
      */
     public @NonNull Token getSessionToken() {
-        return mImpl.getSessionToken();
+        return mSessionToken;
     }
 
     /**
@@ -324,7 +413,7 @@
      * @return A controller for this session.
      */
     public @NonNull MediaController getController() {
-        return mImpl.getController();
+        return mController;
     }
 
     /**
@@ -333,7 +422,12 @@
      * @param state The current state of playback
      */
     public void setPlaybackState(@Nullable PlaybackState state) {
-        mImpl.setPlaybackState(state);
+        mPlaybackState = state;
+        try {
+            mBinder.setPlaybackState(state);
+        } catch (RemoteException e) {
+            Log.wtf(TAG, "Dead object in setPlaybackState.", e);
+        }
     }
 
     /**
@@ -345,10 +439,24 @@
      * @see android.media.MediaMetadata.Builder#putBitmap
      */
     public void setMetadata(@Nullable MediaMetadata metadata) {
+        long duration = -1;
+        int fields = 0;
+        MediaDescription description = null;
         if (metadata != null) {
-            metadata = new MediaMetadata.Builder(metadata, mMaxBitmapSize).build();
+            metadata = (new MediaMetadata.Builder(metadata, mMaxBitmapSize)).build();
+            if (metadata.containsKey(MediaMetadata.METADATA_KEY_DURATION)) {
+                duration = metadata.getLong(MediaMetadata.METADATA_KEY_DURATION);
+            }
+            fields = metadata.size();
+            description = metadata.getDescription();
         }
-        mImpl.setMetadata(metadata);
+        String metadataDescription = "size=" + fields + ", description=" + description;
+
+        try {
+            mBinder.setMetadata(metadata, duration, metadataDescription);
+        } catch (RemoteException e) {
+            Log.wtf(TAG, "Dead object in setPlaybackState.", e);
+        }
     }
 
     /**
@@ -363,7 +471,11 @@
      * @param queue A list of items in the play queue.
      */
     public void setQueue(@Nullable List<QueueItem> queue) {
-        mImpl.setQueue(queue);
+        try {
+            mBinder.setQueue(queue == null ? null : new MediaParceledListSlice(queue));
+        } catch (RemoteException e) {
+            Log.wtf("Dead object in setQueue.", e);
+        }
     }
 
     /**
@@ -374,7 +486,11 @@
      * @param title The title of the play queue.
      */
     public void setQueueTitle(@Nullable CharSequence title) {
-        mImpl.setQueueTitle(title);
+        try {
+            mBinder.setQueueTitle(title);
+        } catch (RemoteException e) {
+            Log.wtf("Dead object in setQueueTitle.", e);
+        }
     }
 
     /**
@@ -391,7 +507,11 @@
      * </ul>
      */
     public void setRatingType(@Rating.Style int type) {
-        mImpl.setRatingType(type);
+        try {
+            mBinder.setRatingType(type);
+        } catch (RemoteException e) {
+            Log.e(TAG, "Error in setRatingType.", e);
+        }
     }
 
     /**
@@ -402,7 +522,11 @@
      * @param extras The extras associated with the {@link MediaSession}.
      */
     public void setExtras(@Nullable Bundle extras) {
-        mImpl.setExtras(extras);
+        try {
+            mBinder.setExtras(extras);
+        } catch (RemoteException e) {
+            Log.wtf("Dead object in setExtras.", e);
+        }
     }
 
     /**
@@ -414,7 +538,31 @@
      * @see MediaSessionManager#isTrustedForMediaControl(RemoteUserInfo)
      */
     public final @NonNull RemoteUserInfo getCurrentControllerInfo() {
-        return mImpl.getCurrentControllerInfo();
+        if (mCallback == null || mCallback.mCurrentControllerInfo == null) {
+            throw new IllegalStateException(
+                    "This should be called inside of MediaSession.Callback methods");
+        }
+        return mCallback.mCurrentControllerInfo;
+    }
+
+    /**
+     * Notify the system that the remote volume changed.
+     *
+     * @param provider The provider that is handling volume changes.
+     * @hide
+     */
+    public void notifyRemoteVolumeChanged(VolumeProvider provider) {
+        synchronized (mLock) {
+            if (provider == null || provider != mVolumeProvider) {
+                Log.w(TAG, "Received update from stale volume provider");
+                return;
+            }
+        }
+        try {
+            mBinder.setCurrentVolume(provider.getCurrentVolume());
+        } catch (RemoteException e) {
+            Log.e(TAG, "Error in notifyVolumeChanged", e);
+        }
     }
 
     /**
@@ -426,7 +574,10 @@
      */
     @UnsupportedAppUsage
     public String getCallingPackage() {
-        return mImpl.getCallingPackage();
+        if (mCallback != null && mCallback.mCurrentControllerInfo != null) {
+            return mCallback.mCurrentControllerInfo.getPackageName();
+        }
+        return null;
     }
 
     /**
@@ -435,7 +586,130 @@
      * @hide
      */
     public static boolean isActiveState(int state) {
-        return MediaSessionEngine.isActiveState(state);
+        switch (state) {
+            case PlaybackState.STATE_FAST_FORWARDING:
+            case PlaybackState.STATE_REWINDING:
+            case PlaybackState.STATE_SKIPPING_TO_PREVIOUS:
+            case PlaybackState.STATE_SKIPPING_TO_NEXT:
+            case PlaybackState.STATE_BUFFERING:
+            case PlaybackState.STATE_CONNECTING:
+            case PlaybackState.STATE_PLAYING:
+                return true;
+        }
+        return false;
+    }
+
+    void dispatchPrepare(RemoteUserInfo caller) {
+        postToCallback(caller, CallbackMessageHandler.MSG_PREPARE, null, null);
+    }
+
+    void dispatchPrepareFromMediaId(RemoteUserInfo caller, String mediaId, Bundle extras) {
+        postToCallback(caller, CallbackMessageHandler.MSG_PREPARE_MEDIA_ID, mediaId, extras);
+    }
+
+    void dispatchPrepareFromSearch(RemoteUserInfo caller, String query, Bundle extras) {
+        postToCallback(caller, CallbackMessageHandler.MSG_PREPARE_SEARCH, query, extras);
+    }
+
+    void dispatchPrepareFromUri(RemoteUserInfo caller, Uri uri, Bundle extras) {
+        postToCallback(caller, CallbackMessageHandler.MSG_PREPARE_URI, uri, extras);
+    }
+
+    void dispatchPlay(RemoteUserInfo caller) {
+        postToCallback(caller, CallbackMessageHandler.MSG_PLAY, null, null);
+    }
+
+    void dispatchPlayFromMediaId(RemoteUserInfo caller, String mediaId, Bundle extras) {
+        postToCallback(caller, CallbackMessageHandler.MSG_PLAY_MEDIA_ID, mediaId, extras);
+    }
+
+    void dispatchPlayFromSearch(RemoteUserInfo caller, String query, Bundle extras) {
+        postToCallback(caller, CallbackMessageHandler.MSG_PLAY_SEARCH, query, extras);
+    }
+
+    void dispatchPlayFromUri(RemoteUserInfo caller, Uri uri, Bundle extras) {
+        postToCallback(caller, CallbackMessageHandler.MSG_PLAY_URI, uri, extras);
+    }
+
+    void dispatchSkipToItem(RemoteUserInfo caller, long id) {
+        postToCallback(caller, CallbackMessageHandler.MSG_SKIP_TO_ITEM, id, null);
+    }
+
+    void dispatchPause(RemoteUserInfo caller) {
+        postToCallback(caller, CallbackMessageHandler.MSG_PAUSE, null, null);
+    }
+
+    void dispatchStop(RemoteUserInfo caller) {
+        postToCallback(caller, CallbackMessageHandler.MSG_STOP, null, null);
+    }
+
+    void dispatchNext(RemoteUserInfo caller) {
+        postToCallback(caller, CallbackMessageHandler.MSG_NEXT, null, null);
+    }
+
+    void dispatchPrevious(RemoteUserInfo caller) {
+        postToCallback(caller, CallbackMessageHandler.MSG_PREVIOUS, null, null);
+    }
+
+    void dispatchFastForward(RemoteUserInfo caller) {
+        postToCallback(caller, CallbackMessageHandler.MSG_FAST_FORWARD, null, null);
+    }
+
+    void dispatchRewind(RemoteUserInfo caller) {
+        postToCallback(caller, CallbackMessageHandler.MSG_REWIND, null, null);
+    }
+
+    void dispatchSeekTo(RemoteUserInfo caller, long pos) {
+        postToCallback(caller, CallbackMessageHandler.MSG_SEEK_TO, pos, null);
+    }
+
+    void dispatchRate(RemoteUserInfo caller, Rating rating) {
+        postToCallback(caller, CallbackMessageHandler.MSG_RATE, rating, null);
+    }
+
+    void dispatchSetPlaybackSpeed(RemoteUserInfo caller, float speed) {
+        postToCallback(caller, CallbackMessageHandler.MSG_SET_PLAYBACK_SPEED, speed, null);
+    }
+
+    void dispatchCustomAction(RemoteUserInfo caller, String action, Bundle args) {
+        postToCallback(caller, CallbackMessageHandler.MSG_CUSTOM_ACTION, action, args);
+    }
+
+    void dispatchMediaButton(RemoteUserInfo caller, Intent mediaButtonIntent) {
+        postToCallback(caller, CallbackMessageHandler.MSG_MEDIA_BUTTON, mediaButtonIntent, null);
+    }
+
+    void dispatchMediaButtonDelayed(RemoteUserInfo info, Intent mediaButtonIntent,
+            long delay) {
+        postToCallbackDelayed(info, CallbackMessageHandler.MSG_PLAY_PAUSE_KEY_DOUBLE_TAP_TIMEOUT,
+                mediaButtonIntent, null, delay);
+    }
+
+    void dispatchAdjustVolume(RemoteUserInfo caller, int direction) {
+        postToCallback(caller, CallbackMessageHandler.MSG_ADJUST_VOLUME, direction, null);
+    }
+
+    void dispatchSetVolumeTo(RemoteUserInfo caller, int volume) {
+        postToCallback(caller, CallbackMessageHandler.MSG_SET_VOLUME, volume, null);
+    }
+
+    void dispatchCommand(RemoteUserInfo caller, String command, Bundle args,
+            ResultReceiver resultCb) {
+        Command cmd = new Command(command, args, resultCb);
+        postToCallback(caller, CallbackMessageHandler.MSG_COMMAND, cmd, null);
+    }
+
+    void postToCallback(RemoteUserInfo caller, int what, Object obj, Bundle data) {
+        postToCallbackDelayed(caller, what, obj, data, 0);
+    }
+
+    void postToCallbackDelayed(RemoteUserInfo caller, int what, Object obj, Bundle data,
+            long delay) {
+        synchronized (mLock) {
+            if (mCallback != null) {
+                mCallback.post(caller, what, obj, data, delay);
+            }
+        }
     }
 
     /**
@@ -534,7 +808,9 @@
      */
     public abstract static class Callback {
 
-        MediaSessionEngine.MediaButtonEventDelegate mMediaButtonEventDelegate;
+        private MediaSession mSession;
+        private CallbackMessageHandler mHandler;
+        private boolean mMediaPlayPauseKeyPending;
 
         public Callback() {
         }
@@ -566,12 +842,110 @@
          * @return True if the event was handled, false otherwise.
          */
         public boolean onMediaButtonEvent(@NonNull Intent mediaButtonIntent) {
-            if (mMediaButtonEventDelegate != null) {
-                return mMediaButtonEventDelegate.onMediaButtonIntent(mediaButtonIntent);
+            if (mSession != null && mHandler != null
+                    && Intent.ACTION_MEDIA_BUTTON.equals(mediaButtonIntent.getAction())) {
+                KeyEvent ke = mediaButtonIntent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
+                if (ke != null && ke.getAction() == KeyEvent.ACTION_DOWN) {
+                    PlaybackState state = mSession.mPlaybackState;
+                    long validActions = state == null ? 0 : state.getActions();
+                    switch (ke.getKeyCode()) {
+                        case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
+                        case KeyEvent.KEYCODE_HEADSETHOOK:
+                            if (ke.getRepeatCount() > 0) {
+                                // Consider long-press as a single tap.
+                                handleMediaPlayPauseKeySingleTapIfPending();
+                            } else if (mMediaPlayPauseKeyPending) {
+                                // Consider double tap as the next.
+                                mHandler.removeMessages(CallbackMessageHandler
+                                        .MSG_PLAY_PAUSE_KEY_DOUBLE_TAP_TIMEOUT);
+                                mMediaPlayPauseKeyPending = false;
+                                if ((validActions & PlaybackState.ACTION_SKIP_TO_NEXT) != 0) {
+                                    onSkipToNext();
+                                }
+                            } else {
+                                mMediaPlayPauseKeyPending = true;
+                                mSession.dispatchMediaButtonDelayed(
+                                        mSession.getCurrentControllerInfo(),
+                                        mediaButtonIntent, ViewConfiguration.getDoubleTapTimeout());
+                            }
+                            return true;
+                        default:
+                            // If another key is pressed within double tap timeout, consider the
+                            // pending play/pause as a single tap to handle media keys in order.
+                            handleMediaPlayPauseKeySingleTapIfPending();
+                            break;
+                    }
+
+                    switch (ke.getKeyCode()) {
+                        case KeyEvent.KEYCODE_MEDIA_PLAY:
+                            if ((validActions & PlaybackState.ACTION_PLAY) != 0) {
+                                onPlay();
+                                return true;
+                            }
+                            break;
+                        case KeyEvent.KEYCODE_MEDIA_PAUSE:
+                            if ((validActions & PlaybackState.ACTION_PAUSE) != 0) {
+                                onPause();
+                                return true;
+                            }
+                            break;
+                        case KeyEvent.KEYCODE_MEDIA_NEXT:
+                            if ((validActions & PlaybackState.ACTION_SKIP_TO_NEXT) != 0) {
+                                onSkipToNext();
+                                return true;
+                            }
+                            break;
+                        case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
+                            if ((validActions & PlaybackState.ACTION_SKIP_TO_PREVIOUS) != 0) {
+                                onSkipToPrevious();
+                                return true;
+                            }
+                            break;
+                        case KeyEvent.KEYCODE_MEDIA_STOP:
+                            if ((validActions & PlaybackState.ACTION_STOP) != 0) {
+                                onStop();
+                                return true;
+                            }
+                            break;
+                        case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
+                            if ((validActions & PlaybackState.ACTION_FAST_FORWARD) != 0) {
+                                onFastForward();
+                                return true;
+                            }
+                            break;
+                        case KeyEvent.KEYCODE_MEDIA_REWIND:
+                            if ((validActions & PlaybackState.ACTION_REWIND) != 0) {
+                                onRewind();
+                                return true;
+                            }
+                            break;
+                    }
+                }
             }
             return false;
         }
 
+        private void handleMediaPlayPauseKeySingleTapIfPending() {
+            if (!mMediaPlayPauseKeyPending) {
+                return;
+            }
+            mMediaPlayPauseKeyPending = false;
+            mHandler.removeMessages(CallbackMessageHandler.MSG_PLAY_PAUSE_KEY_DOUBLE_TAP_TIMEOUT);
+            PlaybackState state = mSession.mPlaybackState;
+            long validActions = state == null ? 0 : state.getActions();
+            boolean isPlaying = state != null
+                    && state.getState() == PlaybackState.STATE_PLAYING;
+            boolean canPlay = (validActions & (PlaybackState.ACTION_PLAY_PAUSE
+                    | PlaybackState.ACTION_PLAY)) != 0;
+            boolean canPause = (validActions & (PlaybackState.ACTION_PLAY_PAUSE
+                    | PlaybackState.ACTION_PAUSE)) != 0;
+            if (isPlaying && canPause) {
+                onPause();
+            } else if (!isPlaying && canPlay) {
+                onPlay();
+            }
+        }
+
         /**
          * Override to handle requests to prepare playback. During the preparation, a session should
          * not hold audio focus in order to allow other sessions play seamlessly. The state of
@@ -727,14 +1101,6 @@
          */
         public void onCustomAction(@NonNull String action, @Nullable Bundle extras) {
         }
-
-        /**
-         * @hide
-         */
-        public void onSetMediaButtonEventDelegate(
-                @NonNull MediaSessionEngine.MediaButtonEventDelegate delegate) {
-            mMediaButtonEventDelegate = delegate;
-        }
     }
 
     /**
@@ -747,7 +1113,7 @@
          */
         public static final int UNKNOWN_ID = -1;
 
-        private final MediaSessionEngine.QueueItem mImpl;
+        private final MediaDescription mDescription;
         @UnsupportedAppUsage
         private final long mId;
 
@@ -759,32 +1125,39 @@
          *            play queue and cannot be {@link #UNKNOWN_ID}.
          */
         public QueueItem(MediaDescription description, long id) {
-            mImpl = new MediaSessionEngine.QueueItem(description, id);
+            if (description == null) {
+                throw new IllegalArgumentException("Description cannot be null.");
+            }
+            if (id == UNKNOWN_ID) {
+                throw new IllegalArgumentException("Id cannot be QueueItem.UNKNOWN_ID");
+            }
+            mDescription = description;
             mId = id;
         }
 
         private QueueItem(Parcel in) {
-            mImpl = new MediaSessionEngine.QueueItem(in);
-            mId = mImpl.getQueueId();
+            mDescription = MediaDescription.CREATOR.createFromParcel(in);
+            mId = in.readLong();
         }
 
         /**
          * Get the description for this item.
          */
         public MediaDescription getDescription() {
-            return mImpl.getDescription();
+            return mDescription;
         }
 
         /**
          * Get the queue id for this item.
          */
         public long getQueueId() {
-            return mImpl.getQueueId();
+            return mId;
         }
 
         @Override
         public void writeToParcel(Parcel dest, int flags) {
-            mImpl.writeToParcel(dest, flags);
+            mDescription.writeToParcel(dest, flags);
+            dest.writeLong(mId);
         }
 
         @Override
@@ -795,20 +1168,21 @@
         public static final @android.annotation.NonNull Creator<MediaSession.QueueItem> CREATOR =
                 new Creator<MediaSession.QueueItem>() {
 
-            @Override
-            public MediaSession.QueueItem createFromParcel(Parcel p) {
-                return new MediaSession.QueueItem(p);
-            }
+                    @Override
+                    public MediaSession.QueueItem createFromParcel(Parcel p) {
+                        return new MediaSession.QueueItem(p);
+                    }
 
-            @Override
-            public MediaSession.QueueItem[] newArray(int size) {
-                return new MediaSession.QueueItem[size];
-            }
-        };
+                    @Override
+                    public MediaSession.QueueItem[] newArray(int size) {
+                        return new MediaSession.QueueItem[size];
+                    }
+                };
 
         @Override
         public String toString() {
-            return mImpl.toString();
+            return "MediaSession.QueueItem {" + "Description=" + mDescription + ", Id=" + mId
+                    + " }";
         }
 
         @Override
@@ -821,7 +1195,171 @@
                 return false;
             }
 
-            return mImpl.equals(((QueueItem) o).mImpl);
+            final QueueItem item = (QueueItem) o;
+            if (mId != item.mId) {
+                return false;
+            }
+
+            if (!Objects.equals(mDescription, item.mDescription)) {
+                return false;
+            }
+
+            return true;
+        }
+    }
+
+    private static final class Command {
+        public final String command;
+        public final Bundle extras;
+        public final ResultReceiver stub;
+
+        Command(String command, Bundle extras, ResultReceiver stub) {
+            this.command = command;
+            this.extras = extras;
+            this.stub = stub;
+        }
+    }
+
+    private class CallbackMessageHandler extends Handler {
+        private static final int MSG_COMMAND = 1;
+        private static final int MSG_MEDIA_BUTTON = 2;
+        private static final int MSG_PREPARE = 3;
+        private static final int MSG_PREPARE_MEDIA_ID = 4;
+        private static final int MSG_PREPARE_SEARCH = 5;
+        private static final int MSG_PREPARE_URI = 6;
+        private static final int MSG_PLAY = 7;
+        private static final int MSG_PLAY_MEDIA_ID = 8;
+        private static final int MSG_PLAY_SEARCH = 9;
+        private static final int MSG_PLAY_URI = 10;
+        private static final int MSG_SKIP_TO_ITEM = 11;
+        private static final int MSG_PAUSE = 12;
+        private static final int MSG_STOP = 13;
+        private static final int MSG_NEXT = 14;
+        private static final int MSG_PREVIOUS = 15;
+        private static final int MSG_FAST_FORWARD = 16;
+        private static final int MSG_REWIND = 17;
+        private static final int MSG_SEEK_TO = 18;
+        private static final int MSG_RATE = 19;
+        private static final int MSG_SET_PLAYBACK_SPEED = 20;
+        private static final int MSG_CUSTOM_ACTION = 21;
+        private static final int MSG_ADJUST_VOLUME = 22;
+        private static final int MSG_SET_VOLUME = 23;
+        private static final int MSG_PLAY_PAUSE_KEY_DOUBLE_TAP_TIMEOUT = 24;
+
+        private MediaSession.Callback mCallback;
+        private RemoteUserInfo mCurrentControllerInfo;
+
+        CallbackMessageHandler(Looper looper, MediaSession.Callback callback) {
+            super(looper);
+            mCallback = callback;
+            mCallback.mHandler = this;
+        }
+
+        void post(RemoteUserInfo caller, int what, Object obj, Bundle data, long delayMs) {
+            Pair<RemoteUserInfo, Object> objWithCaller = Pair.create(caller, obj);
+            Message msg = obtainMessage(what, objWithCaller);
+            msg.setAsynchronous(true);
+            msg.setData(data);
+            if (delayMs > 0) {
+                sendMessageDelayed(msg, delayMs);
+            } else {
+                sendMessage(msg);
+            }
+        }
+
+        @Override
+        public void handleMessage(Message msg) {
+            mCurrentControllerInfo = ((Pair<RemoteUserInfo, Object>) msg.obj).first;
+
+            VolumeProvider vp;
+            Object obj = ((Pair<RemoteUserInfo, Object>) msg.obj).second;
+
+            switch (msg.what) {
+                case MSG_COMMAND:
+                    Command cmd = (Command) obj;
+                    mCallback.onCommand(cmd.command, cmd.extras, cmd.stub);
+                    break;
+                case MSG_MEDIA_BUTTON:
+                    mCallback.onMediaButtonEvent((Intent) obj);
+                    break;
+                case MSG_PREPARE:
+                    mCallback.onPrepare();
+                    break;
+                case MSG_PREPARE_MEDIA_ID:
+                    mCallback.onPrepareFromMediaId((String) obj, msg.getData());
+                    break;
+                case MSG_PREPARE_SEARCH:
+                    mCallback.onPrepareFromSearch((String) obj, msg.getData());
+                    break;
+                case MSG_PREPARE_URI:
+                    mCallback.onPrepareFromUri((Uri) obj, msg.getData());
+                    break;
+                case MSG_PLAY:
+                    mCallback.onPlay();
+                    break;
+                case MSG_PLAY_MEDIA_ID:
+                    mCallback.onPlayFromMediaId((String) obj, msg.getData());
+                    break;
+                case MSG_PLAY_SEARCH:
+                    mCallback.onPlayFromSearch((String) obj, msg.getData());
+                    break;
+                case MSG_PLAY_URI:
+                    mCallback.onPlayFromUri((Uri) obj, msg.getData());
+                    break;
+                case MSG_SKIP_TO_ITEM:
+                    mCallback.onSkipToQueueItem((Long) obj);
+                    break;
+                case MSG_PAUSE:
+                    mCallback.onPause();
+                    break;
+                case MSG_STOP:
+                    mCallback.onStop();
+                    break;
+                case MSG_NEXT:
+                    mCallback.onSkipToNext();
+                    break;
+                case MSG_PREVIOUS:
+                    mCallback.onSkipToPrevious();
+                    break;
+                case MSG_FAST_FORWARD:
+                    mCallback.onFastForward();
+                    break;
+                case MSG_REWIND:
+                    mCallback.onRewind();
+                    break;
+                case MSG_SEEK_TO:
+                    mCallback.onSeekTo((Long) obj);
+                    break;
+                case MSG_RATE:
+                    mCallback.onSetRating((Rating) obj);
+                    break;
+                case MSG_SET_PLAYBACK_SPEED:
+                    mCallback.onSetPlaybackSpeed((Float) obj);
+                    break;
+                case MSG_CUSTOM_ACTION:
+                    mCallback.onCustomAction((String) obj, msg.getData());
+                    break;
+                case MSG_ADJUST_VOLUME:
+                    synchronized (mLock) {
+                        vp = mVolumeProvider;
+                    }
+                    if (vp != null) {
+                        vp.onAdjustVolume((int) obj);
+                    }
+                    break;
+                case MSG_SET_VOLUME:
+                    synchronized (mLock) {
+                        vp = mVolumeProvider;
+                    }
+                    if (vp != null) {
+                        vp.onSetVolumeTo((int) obj);
+                    }
+                    break;
+                case MSG_PLAY_PAUSE_KEY_DOUBLE_TAP_TIMEOUT:
+                    mCallback.handleMediaPlayPauseKeySingleTapIfPending();
+                    break;
+            }
+            mCurrentControllerInfo = null;
         }
     }
 }
diff --git a/media/java/android/media/session/MediaSessionEngine.java b/media/java/android/media/session/MediaSessionEngine.java
deleted file mode 100644
index 7c5243a..0000000
--- a/media/java/android/media/session/MediaSessionEngine.java
+++ /dev/null
@@ -1,1236 +0,0 @@
-/*
- * Copyright 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.media.session;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.app.Activity;
-import android.app.PendingIntent;
-import android.content.Context;
-import android.content.Intent;
-import android.media.AudioAttributes;
-import android.media.MediaDescription;
-import android.media.MediaMetadata;
-import android.media.MediaParceledListSlice;
-import android.media.Rating;
-import android.media.VolumeProvider;
-import android.media.session.MediaSessionManager.RemoteUserInfo;
-import android.net.Uri;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Looper;
-import android.os.Message;
-import android.os.Parcel;
-import android.os.RemoteException;
-import android.os.ResultReceiver;
-import android.service.media.MediaBrowserService;
-import android.text.TextUtils;
-import android.util.Log;
-import android.util.Pair;
-import android.view.KeyEvent;
-import android.view.ViewConfiguration;
-
-import java.util.List;
-import java.util.Objects;
-
-/**
- * @hide
- */
-public final class MediaSessionEngine implements AutoCloseable {
-    private static final String TAG = "MediaSession";
-
-    private final Object mLock = new Object();
-
-    private final MediaSession.Token mSessionToken;
-    private final MediaController mController;
-    private final ISession mBinder;
-
-    private CallbackMessageHandler mCallbackHandler;
-    private VolumeProvider mVolumeProvider;
-    private PlaybackState mPlaybackState;
-
-    private boolean mActive = false;
-
-    /**
-     * Creates a new session. The session will automatically be registered with
-     * the system but will not be published until {@link #setActive(boolean)
-     * setActive(true)} is called. You must call {@link #close()} when
-     * finished with the session.
-     *
-     * @param context The context to use to create the session.
-     * @param binder A session binder
-     */
-    public MediaSessionEngine(@NonNull Context context, @NonNull ISession binder,
-            @NonNull SessionCallbackLink cbLink) throws RemoteException {
-        mBinder = binder;
-
-        cbLink.setSessionEngine(this);
-        mSessionToken = new MediaSession.Token(mBinder.getController());
-        mController = new MediaController(context, mSessionToken);
-    }
-
-    /**
-     * Set the callback to receive updates for the MediaSession. This includes
-     * media button events and transport controls. The caller's thread will be
-     * used to post updates.
-     * <p>
-     * Set the callback to null to stop receiving updates.
-     *
-     * @param callback The callback object
-     */
-    public void setCallback(@Nullable MediaSession.Callback callback) {
-        setCallback(callback, new Handler());
-    }
-
-    /**
-     * Set the callback to receive updates for the MediaSession. This includes
-     * media button events and transport controls.
-     * <p>
-     * Set the callback to null to stop receiving updates.
-     *
-     * @param callback The callback to receive updates on.
-     * @param handler The handler that events should be posted on.
-     */
-    public void setCallback(@Nullable MediaSession.Callback callback, @NonNull Handler handler) {
-        setCallbackInternal(callback == null ? null : new CallbackWrapper(callback), handler);
-    }
-
-    private void setCallbackInternal(CallbackWrapper callback, Handler handler) {
-        synchronized (mLock) {
-            if (mCallbackHandler != null) {
-                // We're updating the callback, clear the session from the old one.
-                mCallbackHandler.mCallbackWrapper.mSessionImpl = null;
-                mCallbackHandler.removeCallbacksAndMessages(null);
-            }
-            if (callback == null) {
-                mCallbackHandler = null;
-                return;
-            }
-            callback.mSessionImpl = this;
-            CallbackMessageHandler msgHandler = new CallbackMessageHandler(handler.getLooper(),
-                    callback);
-            mCallbackHandler = msgHandler;
-        }
-    }
-
-    /**
-     * Set an intent for launching UI for this Session. This can be used as a
-     * quick link to an ongoing media screen. The intent should be for an
-     * activity that may be started using {@link Activity#startActivity(Intent)}.
-     *
-     * @param pi The intent to launch to show UI for this Session.
-     */
-    public void setSessionActivity(@Nullable PendingIntent pi) {
-        try {
-            mBinder.setLaunchPendingIntent(pi);
-        } catch (RemoteException e) {
-            Log.wtf(TAG, "Failure in setLaunchPendingIntent.", e);
-        }
-    }
-
-    /**
-     * Set a pending intent for your media button receiver to allow restarting
-     * playback after the session has been stopped. If your app is started in
-     * this way an {@link Intent#ACTION_MEDIA_BUTTON} intent will be sent via
-     * the pending intent.
-     *
-     * @param mbr The {@link PendingIntent} to send the media button event to.
-     */
-    public void setMediaButtonReceiver(@Nullable PendingIntent mbr) {
-        try {
-            mBinder.setMediaButtonReceiver(mbr);
-        } catch (RemoteException e) {
-            Log.wtf(TAG, "Failure in setMediaButtonReceiver.", e);
-        }
-    }
-
-    /**
-     * Set any flags for the session.
-     *
-     * @param flags The flags to set for this session.
-     */
-    public void setFlags(int flags) {
-        try {
-            mBinder.setFlags(flags);
-        } catch (RemoteException e) {
-            Log.wtf(TAG, "Failure in setFlags.", e);
-        }
-    }
-
-    /**
-     * Set the attributes for this session's audio. This will affect the
-     * system's volume handling for this session. If
-     * {@link #setPlaybackToRemote} was previously called it will stop receiving
-     * volume commands and the system will begin sending volume changes to the
-     * appropriate stream.
-     * <p>
-     * By default sessions use attributes for media.
-     *
-     * @param attributes The {@link AudioAttributes} for this session's audio.
-     */
-    public void setPlaybackToLocal(AudioAttributes attributes) {
-        if (attributes == null) {
-            throw new IllegalArgumentException("Attributes cannot be null for local playback.");
-        }
-        try {
-            mBinder.setPlaybackToLocal(attributes);
-        } catch (RemoteException e) {
-            Log.wtf(TAG, "Failure in setPlaybackToLocal.", e);
-        }
-    }
-
-    /**
-     * Configure this session to use remote volume handling. This must be called
-     * to receive volume button events, otherwise the system will adjust the
-     * appropriate stream volume for this session. If
-     * {@link #setPlaybackToLocal} was previously called the system will stop
-     * handling volume changes for this session and pass them to the volume
-     * provider instead.
-     *
-     * @param volumeProvider The provider that will handle volume changes. May
-     *            not be null.
-     */
-    public void setPlaybackToRemote(@NonNull VolumeProvider volumeProvider) {
-        if (volumeProvider == null) {
-            throw new IllegalArgumentException("volumeProvider may not be null!");
-        }
-        synchronized (mLock) {
-            mVolumeProvider = volumeProvider;
-        }
-        volumeProvider.setCallback(new VolumeProvider.Callback() {
-            @Override
-            public void onVolumeChanged(VolumeProvider volumeProvider) {
-                notifyRemoteVolumeChanged(volumeProvider);
-            }
-        });
-
-        try {
-            mBinder.setPlaybackToRemote(volumeProvider.getVolumeControl(),
-                    volumeProvider.getMaxVolume());
-            mBinder.setCurrentVolume(volumeProvider.getCurrentVolume());
-        } catch (RemoteException e) {
-            Log.wtf(TAG, "Failure in setPlaybackToRemote.", e);
-        }
-    }
-
-    /**
-     * Set if this session is currently active and ready to receive commands. If
-     * set to false your session's controller may not be discoverable. You must
-     * set the session to active before it can start receiving media button
-     * events or transport commands.
-     *
-     * @param active Whether this session is active or not.
-     */
-    public void setActive(boolean active) {
-        if (mActive == active) {
-            return;
-        }
-        try {
-            mBinder.setActive(active);
-            mActive = active;
-        } catch (RemoteException e) {
-            Log.wtf(TAG, "Failure in setActive.", e);
-        }
-    }
-
-    /**
-     * Get the current active state of this session.
-     *
-     * @return True if the session is active, false otherwise.
-     */
-    public boolean isActive() {
-        return mActive;
-    }
-
-    /**
-     * Send a proprietary event to all MediaControllers listening to this
-     * Session. It's up to the Controller/Session owner to determine the meaning
-     * of any events.
-     *
-     * @param event The name of the event to send
-     * @param extras Any extras included with the event
-     */
-    public void sendSessionEvent(@NonNull String event, @Nullable Bundle extras) {
-        if (TextUtils.isEmpty(event)) {
-            throw new IllegalArgumentException("event cannot be null or empty");
-        }
-        try {
-            mBinder.sendEvent(event, extras);
-        } catch (RemoteException e) {
-            Log.wtf(TAG, "Error sending event", e);
-        }
-    }
-
-    /**
-     * This must be called when an app has finished performing playback. If
-     * playback is expected to start again shortly the session can be left open,
-     * but it must be released if your activity or service is being destroyed.
-     */
-    public void close() {
-        try {
-            mBinder.destroySession();
-        } catch (RemoteException e) {
-            Log.wtf(TAG, "Error releasing session: ", e);
-        }
-    }
-
-    /**
-     * Retrieve a token object that can be used by apps to create a
-     * {@link MediaController} for interacting with this session. The owner of
-     * the session is responsible for deciding how to distribute these tokens.
-     *
-     * @return A token that can be used to create a MediaController for this
-     *         session
-     */
-    public @NonNull MediaSession.Token getSessionToken() {
-        return mSessionToken;
-    }
-
-    /**
-     * Get a controller for this session. This is a convenience method to avoid
-     * having to cache your own controller in process.
-     *
-     * @return A controller for this session.
-     */
-    public @NonNull MediaController getController() {
-        return mController;
-    }
-
-    /**
-     * Update the current playback state.
-     *
-     * @param state The current state of playback
-     */
-    public void setPlaybackState(@Nullable PlaybackState state) {
-        mPlaybackState = state;
-        try {
-            mBinder.setPlaybackState(state);
-        } catch (RemoteException e) {
-            Log.wtf(TAG, "Dead object in setPlaybackState.", e);
-        }
-    }
-
-    /**
-     * Update the current metadata. New metadata can be created using
-     * {@link android.media.MediaMetadata.Builder}. This operation may take time proportional to
-     * the size of the bitmap to replace large bitmaps with a scaled down copy.
-     *
-     * @param metadata The new metadata
-     * @see android.media.MediaMetadata.Builder#putBitmap
-     */
-    public void setMetadata(@Nullable MediaMetadata metadata) {
-        long duration = -1;
-        int fields = 0;
-        MediaDescription description = null;
-        if (metadata != null) {
-            if (metadata.containsKey(MediaMetadata.METADATA_KEY_DURATION)) {
-                duration = metadata.getLong(MediaMetadata.METADATA_KEY_DURATION);
-            }
-            fields = metadata.size();
-            description = metadata.getDescription();
-        }
-        String metadataDescription = "size=" + fields + ", description=" + description;
-
-        try {
-            mBinder.setMetadata(metadata, duration, metadataDescription);
-        } catch (RemoteException e) {
-            Log.wtf(TAG, "Dead object in setPlaybackState.", e);
-        }
-    }
-
-    /**
-     * Update the list of items in the play queue. It is an ordered list and
-     * should contain the current item, and previous or upcoming items if they
-     * exist. Specify null if there is no current play queue.
-     * <p>
-     * The queue should be of reasonable size. If the play queue is unbounded
-     * within your app, it is better to send a reasonable amount in a sliding
-     * window instead.
-     *
-     * @param queue A list of items in the play queue.
-     */
-    public void setQueue(@Nullable List<MediaSession.QueueItem> queue) {
-        try {
-            mBinder.setQueue(queue == null ? null : new MediaParceledListSlice(queue));
-        } catch (RemoteException e) {
-            Log.wtf("Dead object in setQueue.", e);
-        }
-    }
-
-    /**
-     * Set the title of the play queue. The UI should display this title along
-     * with the play queue itself.
-     * e.g. "Play Queue", "Now Playing", or an album name.
-     *
-     * @param title The title of the play queue.
-     */
-    public void setQueueTitle(@Nullable CharSequence title) {
-        try {
-            mBinder.setQueueTitle(title);
-        } catch (RemoteException e) {
-            Log.wtf("Dead object in setQueueTitle.", e);
-        }
-    }
-
-    /**
-     * Set the style of rating used by this session. Apps trying to set the
-     * rating should use this style. Must be one of the following:
-     * <ul>
-     * <li>{@link Rating#RATING_NONE}</li>
-     * <li>{@link Rating#RATING_3_STARS}</li>
-     * <li>{@link Rating#RATING_4_STARS}</li>
-     * <li>{@link Rating#RATING_5_STARS}</li>
-     * <li>{@link Rating#RATING_HEART}</li>
-     * <li>{@link Rating#RATING_PERCENTAGE}</li>
-     * <li>{@link Rating#RATING_THUMB_UP_DOWN}</li>
-     * </ul>
-     */
-    public void setRatingType(int type) {
-        try {
-            mBinder.setRatingType(type);
-        } catch (RemoteException e) {
-            Log.e(TAG, "Error in setRatingType.", e);
-        }
-    }
-
-    /**
-     * Set some extras that can be associated with the {@link MediaSession}. No assumptions should
-     * be made as to how a {@link MediaController} will handle these extras.
-     * Keys should be fully qualified (e.g. com.example.MY_EXTRA) to avoid conflicts.
-     *
-     * @param extras The extras associated with the {@link MediaSession}.
-     */
-    public void setExtras(@Nullable Bundle extras) {
-        try {
-            mBinder.setExtras(extras);
-        } catch (RemoteException e) {
-            Log.wtf("Dead object in setExtras.", e);
-        }
-    }
-
-    /**
-     * Gets the controller information who sent the current request.
-     * <p>
-     * Note: This is only valid while in a request callback, such as
-     * {@link MediaSession.Callback#onPlay}.
-     *
-     * @throws IllegalStateException If this method is called outside of
-     * {@link MediaSession.Callback} methods.
-     * @see MediaSessionManager#isTrustedForMediaControl(RemoteUserInfo)
-     */
-    public @NonNull RemoteUserInfo getCurrentControllerInfo() {
-        if (mCallbackHandler == null || mCallbackHandler.mCurrentControllerInfo == null) {
-            throw new IllegalStateException(
-                    "This should be called inside of MediaSession.Callback methods");
-        }
-        return mCallbackHandler.mCurrentControllerInfo;
-    }
-
-    /**
-     * Returns the name of the package that sent the last media button, transport control, or
-     * command from controllers and the system. This is only valid while in a request callback, such
-     * as {@link MediaSession.Callback#onPlay}.
-     */
-    public String getCallingPackage() {
-        if (mCallbackHandler != null && mCallbackHandler.mCurrentControllerInfo != null) {
-            return mCallbackHandler.mCurrentControllerInfo.getPackageName();
-        }
-        return null;
-    }
-
-
-    /**
-     * Notify the system that the remote volume changed.
-     *
-     * @param provider The provider that is handling volume changes.
-     */
-    private void notifyRemoteVolumeChanged(VolumeProvider provider) {
-        synchronized (mLock) {
-            if (provider == null || provider != mVolumeProvider) {
-                Log.w(TAG, "Received update from stale volume provider");
-                return;
-            }
-        }
-        try {
-            mBinder.setCurrentVolume(provider.getCurrentVolume());
-        } catch (RemoteException e) {
-            Log.e(TAG, "Error in notifyVolumeChanged", e);
-        }
-    }
-
-    void dispatchPrepare(RemoteUserInfo caller) {
-        postToCallback(caller, CallbackMessageHandler.MSG_PREPARE, null, null);
-    }
-
-    void dispatchPrepareFromMediaId(RemoteUserInfo caller, String mediaId, Bundle extras) {
-        postToCallback(caller, CallbackMessageHandler.MSG_PREPARE_MEDIA_ID, mediaId, extras);
-    }
-
-    void dispatchPrepareFromSearch(RemoteUserInfo caller, String query, Bundle extras) {
-        postToCallback(caller, CallbackMessageHandler.MSG_PREPARE_SEARCH, query, extras);
-    }
-
-    void dispatchPrepareFromUri(RemoteUserInfo caller, Uri uri, Bundle extras) {
-        postToCallback(caller, CallbackMessageHandler.MSG_PREPARE_URI, uri, extras);
-    }
-
-    void dispatchPlay(RemoteUserInfo caller) {
-        postToCallback(caller, CallbackMessageHandler.MSG_PLAY, null, null);
-    }
-
-    void dispatchPlayFromMediaId(RemoteUserInfo caller, String mediaId, Bundle extras) {
-        postToCallback(caller, CallbackMessageHandler.MSG_PLAY_MEDIA_ID, mediaId, extras);
-    }
-
-    void dispatchPlayFromSearch(RemoteUserInfo caller, String query, Bundle extras) {
-        postToCallback(caller, CallbackMessageHandler.MSG_PLAY_SEARCH, query, extras);
-    }
-
-    void dispatchPlayFromUri(RemoteUserInfo caller, Uri uri, Bundle extras) {
-        postToCallback(caller, CallbackMessageHandler.MSG_PLAY_URI, uri, extras);
-    }
-
-    void dispatchSkipToItem(RemoteUserInfo caller, long id) {
-        postToCallback(caller, CallbackMessageHandler.MSG_SKIP_TO_ITEM, id, null);
-    }
-
-    void dispatchPause(RemoteUserInfo caller) {
-        postToCallback(caller, CallbackMessageHandler.MSG_PAUSE, null, null);
-    }
-
-    void dispatchStop(RemoteUserInfo caller) {
-        postToCallback(caller, CallbackMessageHandler.MSG_STOP, null, null);
-    }
-
-    void dispatchNext(RemoteUserInfo caller) {
-        postToCallback(caller, CallbackMessageHandler.MSG_NEXT, null, null);
-    }
-
-    void dispatchPrevious(RemoteUserInfo caller) {
-        postToCallback(caller, CallbackMessageHandler.MSG_PREVIOUS, null, null);
-    }
-
-    void dispatchFastForward(RemoteUserInfo caller) {
-        postToCallback(caller, CallbackMessageHandler.MSG_FAST_FORWARD, null, null);
-    }
-
-    void dispatchRewind(RemoteUserInfo caller) {
-        postToCallback(caller, CallbackMessageHandler.MSG_REWIND, null, null);
-    }
-
-    void dispatchSeekTo(RemoteUserInfo caller, long pos) {
-        postToCallback(caller, CallbackMessageHandler.MSG_SEEK_TO, pos, null);
-    }
-
-    void dispatchRate(RemoteUserInfo caller, Rating rating) {
-        postToCallback(caller, CallbackMessageHandler.MSG_RATE, rating, null);
-    }
-
-    void dispatchSetPlaybackSpeed(RemoteUserInfo caller, float speed) {
-        postToCallback(caller, CallbackMessageHandler.MSG_SET_PLAYBACK_SPEED, speed, null);
-    }
-
-    void dispatchCustomAction(RemoteUserInfo caller, String action, Bundle args) {
-        postToCallback(caller, CallbackMessageHandler.MSG_CUSTOM_ACTION, action, args);
-    }
-
-    void dispatchMediaButton(RemoteUserInfo caller, Intent mediaButtonIntent) {
-        postToCallback(caller, CallbackMessageHandler.MSG_MEDIA_BUTTON, mediaButtonIntent, null);
-    }
-
-    void dispatchMediaButtonDelayed(RemoteUserInfo info, Intent mediaButtonIntent,
-            long delay) {
-        postToCallbackDelayed(info, CallbackMessageHandler.MSG_PLAY_PAUSE_KEY_DOUBLE_TAP_TIMEOUT,
-                mediaButtonIntent, null, delay);
-    }
-
-    void dispatchAdjustVolume(RemoteUserInfo caller, int direction) {
-        postToCallback(caller, CallbackMessageHandler.MSG_ADJUST_VOLUME, direction, null);
-    }
-
-    void dispatchSetVolumeTo(RemoteUserInfo caller, int volume) {
-        postToCallback(caller, CallbackMessageHandler.MSG_SET_VOLUME, volume, null);
-    }
-
-    void dispatchCommand(RemoteUserInfo caller, String command, Bundle args,
-            ResultReceiver resultCb) {
-        Command cmd = new Command(command, args, resultCb);
-        postToCallback(caller, CallbackMessageHandler.MSG_COMMAND, cmd, null);
-    }
-
-    private void postToCallback(RemoteUserInfo caller, int what, Object obj, Bundle data) {
-        postToCallbackDelayed(caller, what, obj, data, 0);
-    }
-
-    private void postToCallbackDelayed(RemoteUserInfo caller, int what, Object obj, Bundle data,
-            long delay) {
-        synchronized (mLock) {
-            if (mCallbackHandler != null) {
-                mCallbackHandler.post(caller, what, obj, data, delay);
-            }
-        }
-    }
-
-    /**
-     * Return true if this is considered an active playback state.
-     */
-    public static boolean isActiveState(int state) {
-        switch (state) {
-            case PlaybackState.STATE_FAST_FORWARDING:
-            case PlaybackState.STATE_REWINDING:
-            case PlaybackState.STATE_SKIPPING_TO_PREVIOUS:
-            case PlaybackState.STATE_SKIPPING_TO_NEXT:
-            case PlaybackState.STATE_BUFFERING:
-            case PlaybackState.STATE_CONNECTING:
-            case PlaybackState.STATE_PLAYING:
-                return true;
-        }
-        return false;
-    }
-
-    /**
-     * Interface for handling MediaButtoneEvent
-     */
-    public interface MediaButtonEventDelegate {
-        /**
-         * Called when a media button is pressed and this session has the
-         * highest priority or a controller sends a media button event to the
-         * session.
-         *
-         * @param mediaButtonIntent an intent containing the KeyEvent as an extra
-         * @return True if the event was handled, false otherwise.
-         */
-        boolean onMediaButtonIntent(Intent mediaButtonIntent);
-    }
-
-    /**
-     * Receives media buttons, transport controls, and commands from controllers
-     * and the system. A callback may be set using {@link #setCallback}.
-     * @hide
-     */
-    public static class CallbackWrapper implements MediaButtonEventDelegate {
-
-        private final MediaSession.Callback mCallback;
-
-        @SuppressWarnings("WeakerAccess") /* synthetic access */
-                MediaSessionEngine mSessionImpl;
-        @SuppressWarnings("WeakerAccess") /* synthetic access */
-        CallbackMessageHandler mHandler;
-        private boolean mMediaPlayPauseKeyPending;
-
-        public CallbackWrapper(MediaSession.Callback callback) {
-            mCallback = callback;
-            if (mCallback != null) {
-                mCallback.onSetMediaButtonEventDelegate(this);
-            }
-        }
-
-        /**
-         * Called when a controller has sent a command to this session.
-         * The owner of the session may handle custom commands but is not
-         * required to.
-         *
-         * @param command The command name.
-         * @param args Optional parameters for the command, may be null.
-         * @param cb A result receiver to which a result may be sent by the command, may be null.
-         */
-        public void onCommand(@NonNull String command, @Nullable Bundle args,
-                @Nullable ResultReceiver cb) {
-            if (mCallback != null) {
-                mCallback.onCommand(command, args, cb);
-            }
-        }
-
-        /**
-         * Called when a media button is pressed and this session has the
-         * highest priority or a controller sends a media button event to the
-         * session. The default behavior will call the relevant method if the
-         * action for it was set.
-         * <p>
-         * The intent will be of type {@link Intent#ACTION_MEDIA_BUTTON} with a
-         * KeyEvent in {@link Intent#EXTRA_KEY_EVENT}
-         *
-         * @param mediaButtonIntent an intent containing the KeyEvent as an
-         *            extra
-         * @return True if the event was handled, false otherwise.
-         */
-        public boolean onMediaButtonEvent(@NonNull Intent mediaButtonIntent) {
-            return mCallback == null ? false : mCallback.onMediaButtonEvent(mediaButtonIntent);
-        }
-
-        private void handleMediaPlayPauseKeySingleTapIfPending() {
-            if (!mMediaPlayPauseKeyPending) {
-                return;
-            }
-            mMediaPlayPauseKeyPending = false;
-            mHandler.removeMessages(CallbackMessageHandler.MSG_PLAY_PAUSE_KEY_DOUBLE_TAP_TIMEOUT);
-            PlaybackState state = mSessionImpl.mPlaybackState;
-            long validActions = state == null ? 0 : state.getActions();
-            boolean isPlaying = state != null
-                    && state.getState() == PlaybackState.STATE_PLAYING;
-            boolean canPlay = (validActions & (PlaybackState.ACTION_PLAY_PAUSE
-                    | PlaybackState.ACTION_PLAY)) != 0;
-            boolean canPause = (validActions & (PlaybackState.ACTION_PLAY_PAUSE
-                    | PlaybackState.ACTION_PAUSE)) != 0;
-            if (isPlaying && canPause) {
-                onPause();
-            } else if (!isPlaying && canPlay) {
-                onPlay();
-            }
-        }
-
-        /**
-         * Override to handle requests to prepare playback. During the preparation, a session should
-         * not hold audio focus in order to allow other sessions play seamlessly. The state of
-         * playback should be updated to {@link PlaybackState#STATE_PAUSED} after the preparation is
-         * done.
-         */
-        public void onPrepare() {
-            if (mCallback != null) {
-                mCallback.onPrepare();
-            }
-        }
-
-        /**
-         * Override to handle requests to prepare for playing a specific mediaId that was provided
-         * by your app's {@link MediaBrowserService}. During the preparation, a session should not
-         * hold audio focus in order to allow other sessions play seamlessly. The state of playback
-         * should be updated to {@link PlaybackState#STATE_PAUSED} after the preparation is done.
-         * The playback of the prepared content should start in the implementation of
-         * {@link #onPlay}. Override {@link #onPlayFromMediaId} to handle requests for starting
-         * playback without preparation.
-         */
-        public void onPrepareFromMediaId(String mediaId, Bundle extras) {
-            if (mCallback != null) {
-                mCallback.onPrepareFromMediaId(mediaId, extras);
-            }
-        }
-
-        /**
-         * Override to handle requests to prepare playback from a search query. An empty query
-         * indicates that the app may prepare any music. The implementation should attempt to make a
-         * smart choice about what to play. During the preparation, a session should not hold audio
-         * focus in order to allow other sessions play seamlessly. The state of playback should be
-         * updated to {@link PlaybackState#STATE_PAUSED} after the preparation is done. The playback
-         * of the prepared content should start in the implementation of {@link #onPlay}. Override
-         * {@link #onPlayFromSearch} to handle requests for starting playback without preparation.
-         */
-        public void onPrepareFromSearch(String query, Bundle extras) {
-            if (mCallback != null) {
-                mCallback.onPrepareFromSearch(query, extras);
-            }
-        }
-
-        /**
-         * Override to handle requests to prepare a specific media item represented by a URI.
-         * During the preparation, a session should not hold audio focus in order to allow
-         * other sessions play seamlessly. The state of playback should be updated to
-         * {@link PlaybackState#STATE_PAUSED} after the preparation is done.
-         * The playback of the prepared content should start in the implementation of
-         * {@link #onPlay}. Override {@link #onPlayFromUri} to handle requests
-         * for starting playback without preparation.
-         */
-        public void onPrepareFromUri(Uri uri, Bundle extras) {
-            if (mCallback != null) {
-                mCallback.onPrepareFromUri(uri, extras);
-            }
-        }
-
-        /**
-         * Override to handle requests to begin playback.
-         */
-        public void onPlay() {
-            if (mCallback != null) {
-                mCallback.onPlay();
-            }
-        }
-
-        /**
-         * Override to handle requests to begin playback from a search query. An
-         * empty query indicates that the app may play any music. The
-         * implementation should attempt to make a smart choice about what to
-         * play.
-         */
-        public void onPlayFromSearch(String query, Bundle extras) {
-            if (mCallback != null) {
-                mCallback.onPlayFromSearch(query, extras);
-            }
-        }
-
-        /**
-         * Override to handle requests to play a specific mediaId that was
-         * provided by your app's {@link MediaBrowserService}.
-         */
-        public void onPlayFromMediaId(String mediaId, Bundle extras) {
-            if (mCallback != null) {
-                mCallback.onPlayFromMediaId(mediaId, extras);
-            }
-        }
-
-        /**
-         * Override to handle requests to play a specific media item represented by a URI.
-         */
-        public void onPlayFromUri(Uri uri, Bundle extras) {
-            if (mCallback != null) {
-                mCallback.onPlayFromUri(uri, extras);
-            }
-        }
-
-        /**
-         * Override to handle requests to play an item with a given id from the
-         * play queue.
-         */
-        public void onSkipToQueueItem(long id) {
-            if (mCallback != null) {
-                mCallback.onSkipToQueueItem(id);
-            }
-        }
-
-        /**
-         * Override to handle requests to pause playback.
-         */
-        public void onPause() {
-            if (mCallback != null) {
-                mCallback.onPause();
-            }
-        }
-
-        /**
-         * Override to handle requests to skip to the next media item.
-         */
-        public void onSkipToNext() {
-            if (mCallback != null) {
-                mCallback.onSkipToNext();
-            }
-        }
-
-        /**
-         * Override to handle requests to skip to the previous media item.
-         */
-        public void onSkipToPrevious() {
-            if (mCallback != null) {
-                mCallback.onSkipToPrevious();
-            }
-        }
-
-        /**
-         * Override to handle requests to fast forward.
-         */
-        public void onFastForward() {
-            if (mCallback != null) {
-                mCallback.onFastForward();
-            }
-        }
-
-        /**
-         * Override to handle requests to rewind.
-         */
-        public void onRewind() {
-            if (mCallback != null) {
-                mCallback.onRewind();
-            }
-        }
-
-        /**
-         * Override to handle requests to stop playback.
-         */
-        public void onStop() {
-            if (mCallback != null) {
-                mCallback.onStop();
-            }
-        }
-
-        /**
-         * Override to handle requests to seek to a specific position in ms.
-         *
-         * @param pos New position to move to, in milliseconds.
-         */
-        public void onSeekTo(long pos) {
-            if (mCallback != null) {
-                mCallback.onSeekTo(pos);
-            }
-        }
-
-        /**
-         * Override to handle the item being rated.
-         *
-         * @param rating
-         */
-        public void onSetRating(@NonNull Rating rating) {
-            if (mCallback != null) {
-                mCallback.onSetRating(rating);
-            }
-        }
-
-        /**
-         * Override to handle the playback speed change.
-         *
-         * @param speed the playback speed
-         */
-        public void onSetPlaybackSpeed(float speed) {
-            if (mCallback != null) {
-                mCallback.onSetPlaybackSpeed(speed);
-            }
-        }
-
-        /**
-         * Called when a {@link MediaController} wants a {@link PlaybackState.CustomAction} to be
-         * performed.
-         *
-         * @param action The action that was originally sent in the
-         *               {@link PlaybackState.CustomAction}.
-         * @param extras Optional extras specified by the {@link MediaController}.
-         */
-        public void onCustomAction(@NonNull String action, @Nullable Bundle extras) {
-            if (mCallback != null) {
-                mCallback.onCustomAction(action, extras);
-            }
-        }
-
-        @Override
-        public boolean onMediaButtonIntent(Intent mediaButtonIntent) {
-            if (mSessionImpl != null && mHandler != null
-                    && Intent.ACTION_MEDIA_BUTTON.equals(mediaButtonIntent.getAction())) {
-                KeyEvent ke = mediaButtonIntent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
-                if (ke != null && ke.getAction() == KeyEvent.ACTION_DOWN) {
-                    PlaybackState state = mSessionImpl.mPlaybackState;
-                    long validActions = state == null ? 0 : state.getActions();
-                    switch (ke.getKeyCode()) {
-                        case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
-                        case KeyEvent.KEYCODE_HEADSETHOOK:
-                            if (ke.getRepeatCount() > 0) {
-                                // Consider long-press as a single tap.
-                                handleMediaPlayPauseKeySingleTapIfPending();
-                            } else if (mMediaPlayPauseKeyPending) {
-                                // Consider double tap as the next.
-                                mHandler.removeMessages(CallbackMessageHandler
-                                        .MSG_PLAY_PAUSE_KEY_DOUBLE_TAP_TIMEOUT);
-                                mMediaPlayPauseKeyPending = false;
-                                if ((validActions & PlaybackState.ACTION_SKIP_TO_NEXT) != 0) {
-                                    onSkipToNext();
-                                }
-                            } else {
-                                mMediaPlayPauseKeyPending = true;
-                                mSessionImpl.dispatchMediaButtonDelayed(
-                                        mSessionImpl.getCurrentControllerInfo(),
-                                        mediaButtonIntent, ViewConfiguration.getDoubleTapTimeout());
-                            }
-                            return true;
-                        default:
-                            // If another key is pressed within double tap timeout, consider the
-                            // pending play/pause as a single tap to handle media keys in order.
-                            handleMediaPlayPauseKeySingleTapIfPending();
-                            break;
-                    }
-
-                    switch (ke.getKeyCode()) {
-                        case KeyEvent.KEYCODE_MEDIA_PLAY:
-                            if ((validActions & PlaybackState.ACTION_PLAY) != 0) {
-                                onPlay();
-                                return true;
-                            }
-                            break;
-                        case KeyEvent.KEYCODE_MEDIA_PAUSE:
-                            if ((validActions & PlaybackState.ACTION_PAUSE) != 0) {
-                                onPause();
-                                return true;
-                            }
-                            break;
-                        case KeyEvent.KEYCODE_MEDIA_NEXT:
-                            if ((validActions & PlaybackState.ACTION_SKIP_TO_NEXT) != 0) {
-                                onSkipToNext();
-                                return true;
-                            }
-                            break;
-                        case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
-                            if ((validActions & PlaybackState.ACTION_SKIP_TO_PREVIOUS) != 0) {
-                                onSkipToPrevious();
-                                return true;
-                            }
-                            break;
-                        case KeyEvent.KEYCODE_MEDIA_STOP:
-                            if ((validActions & PlaybackState.ACTION_STOP) != 0) {
-                                onStop();
-                                return true;
-                            }
-                            break;
-                        case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
-                            if ((validActions & PlaybackState.ACTION_FAST_FORWARD) != 0) {
-                                onFastForward();
-                                return true;
-                            }
-                            break;
-                        case KeyEvent.KEYCODE_MEDIA_REWIND:
-                            if ((validActions & PlaybackState.ACTION_REWIND) != 0) {
-                                onRewind();
-                                return true;
-                            }
-                            break;
-                    }
-                }
-            }
-            return false;
-        }
-    }
-
-     /**
-     * A single item that is part of the play queue. It contains a description
-     * of the item and its id in the queue.
-     */
-    public static final class QueueItem {
-        /**
-         * This id is reserved. No items can be explicitly assigned this id.
-         */
-        public static final int UNKNOWN_ID = -1;
-
-        private final MediaDescription mDescription;
-        private final long mId;
-
-        /**
-         * Create a new {@link MediaSession.QueueItem}.
-         *
-         * @param description The {@link MediaDescription} for this item.
-         * @param id An identifier for this item. It must be unique within the
-         *            play queue and cannot be {@link #UNKNOWN_ID}.
-         */
-        public QueueItem(MediaDescription description, long id) {
-            if (description == null) {
-                throw new IllegalArgumentException("Description cannot be null.");
-            }
-            if (id == UNKNOWN_ID) {
-                throw new IllegalArgumentException("Id cannot be QueueItem.UNKNOWN_ID");
-            }
-            mDescription = description;
-            mId = id;
-        }
-
-        public QueueItem(Parcel in) {
-            mDescription = MediaDescription.CREATOR.createFromParcel(in);
-            mId = in.readLong();
-        }
-
-        /**
-         * Get the description for this item.
-         */
-        public MediaDescription getDescription() {
-            return mDescription;
-        }
-
-        /**
-         * Get the queue id for this item.
-         */
-        public long getQueueId() {
-            return mId;
-        }
-
-        /**
-         * Flatten this object in to a Parcel.
-         *
-         * @param dest The Parcel in which the object should be written.
-         * @param flags Additional flags about how the object should be written.
-         */
-        public void writeToParcel(Parcel dest, int flags) {
-            mDescription.writeToParcel(dest, flags);
-            dest.writeLong(mId);
-        }
-
-        @Override
-        public String toString() {
-            return "MediaSession.QueueItem {" + "Description=" + mDescription + ", Id=" + mId
-                    + " }";
-        }
-
-        @Override
-        public boolean equals(Object o) {
-            if (o == null) {
-                return false;
-            }
-
-            if (!(o instanceof QueueItem)) {
-                return false;
-            }
-
-            final QueueItem item = (QueueItem) o;
-            if (mId != item.mId) {
-                return false;
-            }
-
-            if (!Objects.equals(mDescription, item.mDescription)) {
-                return false;
-            }
-
-            return true;
-        }
-    }
-
-    private static final class Command {
-        public final String command;
-        public final Bundle extras;
-        public final ResultReceiver stub;
-
-        Command(String command, Bundle extras, ResultReceiver stub) {
-            this.command = command;
-            this.extras = extras;
-            this.stub = stub;
-        }
-    }
-
-    private class CallbackMessageHandler extends Handler {
-        private static final int MSG_COMMAND = 1;
-        private static final int MSG_MEDIA_BUTTON = 2;
-        private static final int MSG_PREPARE = 3;
-        private static final int MSG_PREPARE_MEDIA_ID = 4;
-        private static final int MSG_PREPARE_SEARCH = 5;
-        private static final int MSG_PREPARE_URI = 6;
-        private static final int MSG_PLAY = 7;
-        private static final int MSG_PLAY_MEDIA_ID = 8;
-        private static final int MSG_PLAY_SEARCH = 9;
-        private static final int MSG_PLAY_URI = 10;
-        private static final int MSG_SKIP_TO_ITEM = 11;
-        private static final int MSG_PAUSE = 12;
-        private static final int MSG_STOP = 13;
-        private static final int MSG_NEXT = 14;
-        private static final int MSG_PREVIOUS = 15;
-        private static final int MSG_FAST_FORWARD = 16;
-        private static final int MSG_REWIND = 17;
-        private static final int MSG_SEEK_TO = 18;
-        private static final int MSG_RATE = 19;
-        private static final int MSG_SET_PLAYBACK_SPEED = 20;
-        private static final int MSG_CUSTOM_ACTION = 21;
-        private static final int MSG_ADJUST_VOLUME = 22;
-        private static final int MSG_SET_VOLUME = 23;
-        private static final int MSG_PLAY_PAUSE_KEY_DOUBLE_TAP_TIMEOUT = 24;
-
-        @SuppressWarnings("WeakerAccess") /* synthetic access */
-        CallbackWrapper mCallbackWrapper;
-        @SuppressWarnings("WeakerAccess") /* synthetic access */
-        RemoteUserInfo mCurrentControllerInfo;
-
-        CallbackMessageHandler(Looper looper, CallbackWrapper callbackWrapper) {
-            super(looper);
-            mCallbackWrapper = callbackWrapper;
-            mCallbackWrapper.mHandler = this;
-        }
-
-        void post(RemoteUserInfo caller, int what, Object obj, Bundle data, long delayMs) {
-            Pair<RemoteUserInfo, Object> objWithCaller = Pair.create(caller, obj);
-            Message msg = obtainMessage(what, objWithCaller);
-            msg.setAsynchronous(true);
-            msg.setData(data);
-            if (delayMs > 0) {
-                sendMessageDelayed(msg, delayMs);
-            } else {
-                sendMessage(msg);
-            }
-        }
-
-        @Override
-        public void handleMessage(Message msg) {
-            mCurrentControllerInfo = ((Pair<RemoteUserInfo, Object>) msg.obj).first;
-
-            VolumeProvider vp;
-            Object obj = ((Pair<RemoteUserInfo, Object>) msg.obj).second;
-
-            switch (msg.what) {
-                case MSG_COMMAND:
-                    Command cmd = (Command) obj;
-                    mCallbackWrapper.onCommand(cmd.command, cmd.extras, cmd.stub);
-                    break;
-                case MSG_MEDIA_BUTTON:
-                    mCallbackWrapper.onMediaButtonEvent((Intent) obj);
-                    break;
-                case MSG_PREPARE:
-                    mCallbackWrapper.onPrepare();
-                    break;
-                case MSG_PREPARE_MEDIA_ID:
-                    mCallbackWrapper.onPrepareFromMediaId((String) obj, msg.getData());
-                    break;
-                case MSG_PREPARE_SEARCH:
-                    mCallbackWrapper.onPrepareFromSearch((String) obj, msg.getData());
-                    break;
-                case MSG_PREPARE_URI:
-                    mCallbackWrapper.onPrepareFromUri((Uri) obj, msg.getData());
-                    break;
-                case MSG_PLAY:
-                    mCallbackWrapper.onPlay();
-                    break;
-                case MSG_PLAY_MEDIA_ID:
-                    mCallbackWrapper.onPlayFromMediaId((String) obj, msg.getData());
-                    break;
-                case MSG_PLAY_SEARCH:
-                    mCallbackWrapper.onPlayFromSearch((String) obj, msg.getData());
-                    break;
-                case MSG_PLAY_URI:
-                    mCallbackWrapper.onPlayFromUri((Uri) obj, msg.getData());
-                    break;
-                case MSG_SKIP_TO_ITEM:
-                    mCallbackWrapper.onSkipToQueueItem((Long) obj);
-                    break;
-                case MSG_PAUSE:
-                    mCallbackWrapper.onPause();
-                    break;
-                case MSG_STOP:
-                    mCallbackWrapper.onStop();
-                    break;
-                case MSG_NEXT:
-                    mCallbackWrapper.onSkipToNext();
-                    break;
-                case MSG_PREVIOUS:
-                    mCallbackWrapper.onSkipToPrevious();
-                    break;
-                case MSG_FAST_FORWARD:
-                    mCallbackWrapper.onFastForward();
-                    break;
-                case MSG_REWIND:
-                    mCallbackWrapper.onRewind();
-                    break;
-                case MSG_SEEK_TO:
-                    mCallbackWrapper.onSeekTo((Long) obj);
-                    break;
-                case MSG_RATE:
-                    mCallbackWrapper.onSetRating((Rating) obj);
-                    break;
-                case MSG_SET_PLAYBACK_SPEED:
-                    mCallbackWrapper.onSetPlaybackSpeed((Float) obj);
-                    break;
-                case MSG_CUSTOM_ACTION:
-                    mCallbackWrapper.onCustomAction((String) obj, msg.getData());
-                    break;
-                case MSG_ADJUST_VOLUME:
-                    synchronized (mLock) {
-                        vp = mVolumeProvider;
-                    }
-                    if (vp != null) {
-                        vp.onAdjustVolume((int) obj);
-                    }
-                    break;
-                case MSG_SET_VOLUME:
-                    synchronized (mLock) {
-                        vp = mVolumeProvider;
-                    }
-                    if (vp != null) {
-                        vp.onSetVolumeTo((int) obj);
-                    }
-                    break;
-                case MSG_PLAY_PAUSE_KEY_DOUBLE_TAP_TIMEOUT:
-                    mCallbackWrapper.handleMediaPlayPauseKeySingleTapIfPending();
-                    break;
-            }
-            mCurrentControllerInfo = null;
-        }
-    }
-}
diff --git a/media/java/android/media/session/SessionCallbackLink.java b/media/java/android/media/session/SessionCallbackLink.java
index 6ffdc2b..c858a60 100644
--- a/media/java/android/media/session/SessionCallbackLink.java
+++ b/media/java/android/media/session/SessionCallbackLink.java
@@ -49,9 +49,9 @@
      * Constructor for stub (Callee)
      * @hide
      */
-    public SessionCallbackLink(@NonNull Context context) {
+    public SessionCallbackLink(@NonNull Context context, MediaSession session) {
         mContext = context;
-        mISessionCallback = new CallbackStub();
+        mISessionCallback = new CallbackStub(session);
     }
 
     /**
@@ -63,15 +63,6 @@
     }
 
     /**
-     * Set {@link MediaSessionEngine} which will be used by {@link CallbackStub}.
-     */
-    void setSessionEngine(@Nullable MediaSessionEngine sessionImpl) {
-        if (mISessionCallback instanceof CallbackStub) {
-            ((CallbackStub) mISessionCallback).mSessionImpl = new WeakReference<>(sessionImpl);
-        }
-    }
-
-    /**
      * Notify session that a controller sends a command.
      *
      * @param packageName the package name of the controller
@@ -568,7 +559,11 @@
             };
 
     private class CallbackStub extends ISessionCallback.Stub {
-        private WeakReference<MediaSessionEngine> mSessionImpl;
+        private WeakReference<MediaSession> mMediaSession;
+
+        private CallbackStub(MediaSession session) {
+            mMediaSession = new WeakReference<>(session);
+        }
 
         private RemoteUserInfo createRemoteUserInfo(String packageName, int pid, int uid) {
             return new RemoteUserInfo(packageName, pid, uid);
@@ -580,9 +575,9 @@
             ensureMediaControlPermission();
             final long token = Binder.clearCallingIdentity();
             try {
-                MediaSessionEngine sessionImpl = mSessionImpl.get();
-                if (sessionImpl != null) {
-                    sessionImpl.dispatchCommand(createRemoteUserInfo(packageName, pid, uid),
+                MediaSession session = mMediaSession.get();
+                if (session != null) {
+                    session.dispatchCommand(createRemoteUserInfo(packageName, pid, uid),
                             command, args, cb);
                 }
             } finally {
@@ -596,9 +591,9 @@
             ensureMediaControlPermission();
             final long token = Binder.clearCallingIdentity();
             try {
-                MediaSessionEngine sessionImpl = mSessionImpl.get();
-                if (sessionImpl != null) {
-                    sessionImpl.dispatchMediaButton(
+                MediaSession session = mMediaSession.get();
+                if (session != null) {
+                    session.dispatchMediaButton(
                             createRemoteUserInfo(packageName, pid, uid), mediaButtonIntent);
                 }
             } finally {
@@ -615,9 +610,9 @@
             ensureMediaControlPermission();
             final long token = Binder.clearCallingIdentity();
             try {
-                MediaSessionEngine sessionImpl = mSessionImpl.get();
-                if (sessionImpl != null) {
-                    sessionImpl.dispatchMediaButton(createRemoteUserInfo(packageName, pid, uid),
+                MediaSession session = mMediaSession.get();
+                if (session != null) {
+                    session.dispatchMediaButton(createRemoteUserInfo(packageName, pid, uid),
                             mediaButtonIntent);
                 }
             } finally {
@@ -631,9 +626,9 @@
             ensureMediaControlPermission();
             final long token = Binder.clearCallingIdentity();
             try {
-                MediaSessionEngine sessionImpl = mSessionImpl.get();
-                if (sessionImpl != null) {
-                    sessionImpl.dispatchPrepare(createRemoteUserInfo(packageName, pid, uid));
+                MediaSession session = mMediaSession.get();
+                if (session != null) {
+                    session.dispatchPrepare(createRemoteUserInfo(packageName, pid, uid));
                 }
             } finally {
                 Binder.restoreCallingIdentity(token);
@@ -646,9 +641,9 @@
             ensureMediaControlPermission();
             final long token = Binder.clearCallingIdentity();
             try {
-                MediaSessionEngine sessionImpl = mSessionImpl.get();
-                if (sessionImpl != null) {
-                    sessionImpl.dispatchPrepareFromMediaId(
+                MediaSession session = mMediaSession.get();
+                if (session != null) {
+                    session.dispatchPrepareFromMediaId(
                             createRemoteUserInfo(packageName, pid, uid), mediaId, extras);
                 }
             } finally {
@@ -662,9 +657,9 @@
             ensureMediaControlPermission();
             final long token = Binder.clearCallingIdentity();
             try {
-                MediaSessionEngine sessionImpl = mSessionImpl.get();
-                if (sessionImpl != null) {
-                    sessionImpl.dispatchPrepareFromSearch(
+                MediaSession session = mMediaSession.get();
+                if (session != null) {
+                    session.dispatchPrepareFromSearch(
                             createRemoteUserInfo(packageName, pid, uid), query, extras);
                 }
             } finally {
@@ -678,9 +673,9 @@
             ensureMediaControlPermission();
             final long token = Binder.clearCallingIdentity();
             try {
-                MediaSessionEngine sessionImpl = mSessionImpl.get();
-                if (sessionImpl != null) {
-                    sessionImpl.dispatchPrepareFromUri(
+                MediaSession session = mMediaSession.get();
+                if (session != null) {
+                    session.dispatchPrepareFromUri(
                             createRemoteUserInfo(packageName, pid, uid), uri, extras);
                 }
             } finally {
@@ -694,9 +689,9 @@
             ensureMediaControlPermission();
             final long token = Binder.clearCallingIdentity();
             try {
-                MediaSessionEngine sessionImpl = mSessionImpl.get();
-                if (sessionImpl != null) {
-                    sessionImpl.dispatchPlay(createRemoteUserInfo(packageName, pid, uid));
+                MediaSession session = mMediaSession.get();
+                if (session != null) {
+                    session.dispatchPlay(createRemoteUserInfo(packageName, pid, uid));
                 }
             } finally {
                 Binder.restoreCallingIdentity(token);
@@ -709,9 +704,9 @@
             ensureMediaControlPermission();
             final long token = Binder.clearCallingIdentity();
             try {
-                MediaSessionEngine sessionImpl = mSessionImpl.get();
-                if (sessionImpl != null) {
-                    sessionImpl.dispatchPlayFromMediaId(
+                MediaSession session = mMediaSession.get();
+                if (session != null) {
+                    session.dispatchPlayFromMediaId(
                             createRemoteUserInfo(packageName, pid, uid), mediaId, extras);
                 }
             } finally {
@@ -725,9 +720,9 @@
             ensureMediaControlPermission();
             final long token = Binder.clearCallingIdentity();
             try {
-                MediaSessionEngine sessionImpl = mSessionImpl.get();
-                if (sessionImpl != null) {
-                    sessionImpl.dispatchPlayFromSearch(
+                MediaSession session = mMediaSession.get();
+                if (session != null) {
+                    session.dispatchPlayFromSearch(
                             createRemoteUserInfo(packageName, pid, uid), query, extras);
                 }
             } finally {
@@ -741,9 +736,9 @@
             ensureMediaControlPermission();
             final long token = Binder.clearCallingIdentity();
             try {
-                MediaSessionEngine sessionImpl = mSessionImpl.get();
-                if (sessionImpl != null) {
-                    sessionImpl.dispatchPlayFromUri(
+                MediaSession session = mMediaSession.get();
+                if (session != null) {
+                    session.dispatchPlayFromUri(
                             createRemoteUserInfo(packageName, pid, uid), uri, extras);
                 }
             } finally {
@@ -757,9 +752,9 @@
             ensureMediaControlPermission();
             final long token = Binder.clearCallingIdentity();
             try {
-                MediaSessionEngine sessionImpl = mSessionImpl.get();
-                if (sessionImpl != null) {
-                    sessionImpl.dispatchSkipToItem(
+                MediaSession session = mMediaSession.get();
+                if (session != null) {
+                    session.dispatchSkipToItem(
                             createRemoteUserInfo(packageName, pid, uid), id);
                 }
             } finally {
@@ -773,9 +768,9 @@
             ensureMediaControlPermission();
             final long token = Binder.clearCallingIdentity();
             try {
-                MediaSessionEngine sessionImpl = mSessionImpl.get();
-                if (sessionImpl != null) {
-                    sessionImpl.dispatchPause(createRemoteUserInfo(packageName, pid, uid));
+                MediaSession session = mMediaSession.get();
+                if (session != null) {
+                    session.dispatchPause(createRemoteUserInfo(packageName, pid, uid));
                 }
             } finally {
                 Binder.restoreCallingIdentity(token);
@@ -788,9 +783,9 @@
             ensureMediaControlPermission();
             final long token = Binder.clearCallingIdentity();
             try {
-                MediaSessionEngine sessionImpl = mSessionImpl.get();
-                if (sessionImpl != null) {
-                    sessionImpl.dispatchStop(createRemoteUserInfo(packageName, pid, uid));
+                MediaSession session = mMediaSession.get();
+                if (session != null) {
+                    session.dispatchStop(createRemoteUserInfo(packageName, pid, uid));
                 }
             } finally {
                 Binder.restoreCallingIdentity(token);
@@ -803,9 +798,9 @@
             ensureMediaControlPermission();
             final long token = Binder.clearCallingIdentity();
             try {
-                MediaSessionEngine sessionImpl = mSessionImpl.get();
-                if (sessionImpl != null) {
-                    sessionImpl.dispatchNext(createRemoteUserInfo(packageName, pid, uid));
+                MediaSession session = mMediaSession.get();
+                if (session != null) {
+                    session.dispatchNext(createRemoteUserInfo(packageName, pid, uid));
                 }
             } finally {
                 Binder.restoreCallingIdentity(token);
@@ -818,9 +813,9 @@
             ensureMediaControlPermission();
             final long token = Binder.clearCallingIdentity();
             try {
-                MediaSessionEngine sessionImpl = mSessionImpl.get();
-                if (sessionImpl != null) {
-                    sessionImpl.dispatchPrevious(createRemoteUserInfo(packageName, pid, uid));
+                MediaSession session = mMediaSession.get();
+                if (session != null) {
+                    session.dispatchPrevious(createRemoteUserInfo(packageName, pid, uid));
                 }
             } finally {
                 Binder.restoreCallingIdentity(token);
@@ -833,9 +828,9 @@
             ensureMediaControlPermission();
             final long token = Binder.clearCallingIdentity();
             try {
-                MediaSessionEngine sessionImpl = mSessionImpl.get();
-                if (sessionImpl != null) {
-                    sessionImpl.dispatchFastForward(
+                MediaSession session = mMediaSession.get();
+                if (session != null) {
+                    session.dispatchFastForward(
                             createRemoteUserInfo(packageName, pid, uid));
                 }
             } finally {
@@ -849,9 +844,9 @@
             ensureMediaControlPermission();
             final long token = Binder.clearCallingIdentity();
             try {
-                MediaSessionEngine sessionImpl = mSessionImpl.get();
-                if (sessionImpl != null) {
-                    sessionImpl.dispatchRewind(createRemoteUserInfo(packageName, pid, uid));
+                MediaSession session = mMediaSession.get();
+                if (session != null) {
+                    session.dispatchRewind(createRemoteUserInfo(packageName, pid, uid));
                 }
             } finally {
                 Binder.restoreCallingIdentity(token);
@@ -864,9 +859,9 @@
             ensureMediaControlPermission();
             final long token = Binder.clearCallingIdentity();
             try {
-                MediaSessionEngine sessionImpl = mSessionImpl.get();
-                if (sessionImpl != null) {
-                    sessionImpl.dispatchSeekTo(
+                MediaSession session = mMediaSession.get();
+                if (session != null) {
+                    session.dispatchSeekTo(
                             createRemoteUserInfo(packageName, pid, uid), pos);
                 }
             } finally {
@@ -880,9 +875,9 @@
             ensureMediaControlPermission();
             final long token = Binder.clearCallingIdentity();
             try {
-                MediaSessionEngine sessionImpl = mSessionImpl.get();
-                if (sessionImpl != null) {
-                    sessionImpl.dispatchRate(
+                MediaSession session = mMediaSession.get();
+                if (session != null) {
+                    session.dispatchRate(
                             createRemoteUserInfo(packageName, pid, uid), rating);
                 }
             } finally {
@@ -896,9 +891,9 @@
             ensureMediaControlPermission();
             final long token = Binder.clearCallingIdentity();
             try {
-                MediaSessionEngine sessionImpl = mSessionImpl.get();
-                if (sessionImpl != null) {
-                    sessionImpl.dispatchSetPlaybackSpeed(
+                MediaSession session = mMediaSession.get();
+                if (session != null) {
+                    session.dispatchSetPlaybackSpeed(
                             createRemoteUserInfo(packageName, pid, uid), speed);
                 }
             } finally {
@@ -912,9 +907,9 @@
             ensureMediaControlPermission();
             final long token = Binder.clearCallingIdentity();
             try {
-                MediaSessionEngine sessionImpl = mSessionImpl.get();
-                if (sessionImpl != null) {
-                    sessionImpl.dispatchCustomAction(
+                MediaSession session = mMediaSession.get();
+                if (session != null) {
+                    session.dispatchCustomAction(
                             createRemoteUserInfo(packageName, pid, uid), action, args);
                 }
             } finally {
@@ -928,9 +923,9 @@
             ensureMediaControlPermission();
             final long token = Binder.clearCallingIdentity();
             try {
-                MediaSessionEngine sessionImpl = mSessionImpl.get();
-                if (sessionImpl != null) {
-                    sessionImpl.dispatchAdjustVolume(
+                MediaSession session = mMediaSession.get();
+                if (session != null) {
+                    session.dispatchAdjustVolume(
                             createRemoteUserInfo(packageName, pid, uid), direction);
                 }
             } finally {
@@ -944,9 +939,9 @@
             ensureMediaControlPermission();
             final long token = Binder.clearCallingIdentity();
             try {
-                MediaSessionEngine sessionImpl = mSessionImpl.get();
-                if (sessionImpl != null) {
-                    sessionImpl.dispatchSetVolumeTo(
+                MediaSession session = mMediaSession.get();
+                if (session != null) {
+                    session.dispatchSetVolumeTo(
                             createRemoteUserInfo(packageName, pid, uid), value);
                 }
             } finally {
diff --git a/media/jni/android_media_MediaRecorder.cpp b/media/jni/android_media_MediaRecorder.cpp
index 3ec0903..24fff06 100644
--- a/media/jni/android_media_MediaRecorder.cpp
+++ b/media/jni/android_media_MediaRecorder.cpp
@@ -760,9 +760,9 @@
     return jStatus;
 }
 
-static jint android_media_MediaRecord_setMicrophoneDirection(
+static jint android_media_MediaRecord_setPreferredMicrophoneDirection(
         JNIEnv *env, jobject thiz, jint direction) {
-    ALOGV("setMicrophoneDirection(%d)", direction);
+    ALOGV("setPreferredMicrophoneDirection(%d)", direction);
     sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
     if (mr == NULL) {
         jniThrowException(env, "java/lang/IllegalStateException", NULL);
@@ -771,7 +771,7 @@
 
     jint jStatus = AUDIO_JAVA_SUCCESS;
     status_t status =
-        mr->setMicrophoneDirection(static_cast<audio_microphone_direction_t>(direction));
+        mr->setPreferredMicrophoneDirection(static_cast<audio_microphone_direction_t>(direction));
     if (status != NO_ERROR) {
         jStatus = nativeToJavaStatus(status);
     }
@@ -779,9 +779,9 @@
     return jStatus;
 }
 
-static jint  android_media_MediaRecord_setMicrophoneFieldDimension(
+static jint  android_media_MediaRecord_setPreferredMicrophoneFieldDimension(
         JNIEnv *env, jobject thiz, jfloat zoom) {
-    ALOGV("setMicrophoneFieldDimension(%f)", zoom);
+    ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
     sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
     if (mr == NULL) {
         jniThrowException(env, "java/lang/IllegalStateException", NULL);
@@ -789,7 +789,7 @@
     }
 
     jint jStatus = AUDIO_JAVA_SUCCESS;
-    status_t status = mr->setMicrophoneFieldDimension(zoom);
+    status_t status = mr->setPreferredMicrophoneFieldDimension(zoom);
     if (status != NO_ERROR) {
         jStatus = nativeToJavaStatus(status);
     }
@@ -850,8 +850,10 @@
 
     {"native_getActiveMicrophones", "(Ljava/util/ArrayList;)I", (void *)android_media_MediaRecord_getActiveMicrophones},
     {"native_getPortId", "()I", (void *)android_media_MediaRecord_getPortId},
-    {"native_setMicrophoneDirection", "(I)I", (void *)android_media_MediaRecord_setMicrophoneDirection},
-    {"native_setMicrophoneFieldDimension", "(F)I", (void *)android_media_MediaRecord_setMicrophoneFieldDimension},
+    {"native_setPreferredMicrophoneDirection", "(I)I",
+            (void *)android_media_MediaRecord_setPreferredMicrophoneDirection},
+    {"native_setPreferredMicrophoneFieldDimension", "(F)I",
+            (void *)android_media_MediaRecord_setPreferredMicrophoneFieldDimension},
 };
 
 // This function only registers the native methods, and is called from
diff --git a/native/android/libandroid.map.txt b/native/android/libandroid.map.txt
index e1dc406..1f2480b 100644
--- a/native/android/libandroid.map.txt
+++ b/native/android/libandroid.map.txt
@@ -148,6 +148,7 @@
     AHardwareBuffer_getNativeHandle; # introduced=26
     AHardwareBuffer_isSupported; # introduced=29
     AHardwareBuffer_lock; # introduced=26
+    AHardwareBuffer_lockAndGetInfo; # introduced=29
     AHardwareBuffer_lockPlanes; # introduced=29
     AHardwareBuffer_recvHandleFromUnixSocket; # introduced=26
     AHardwareBuffer_release; # introduced=26
diff --git a/packages/NetworkStack/Android.bp b/packages/NetworkStack/Android.bp
index 8872147..01cd00a 100644
--- a/packages/NetworkStack/Android.bp
+++ b/packages/NetworkStack/Android.bp
@@ -29,6 +29,7 @@
         "netd_aidl_interface-java",
         "networkstack-aidl-interfaces-java",
         "datastallprotosnano",
+        "networkstackprotosnano",
     ],
     manifest: "AndroidManifestBase.xml",
 }
diff --git a/packages/NetworkStack/AndroidManifest.xml b/packages/NetworkStack/AndroidManifest.xml
index a90db11..b0a7923 100644
--- a/packages/NetworkStack/AndroidManifest.xml
+++ b/packages/NetworkStack/AndroidManifest.xml
@@ -19,6 +19,7 @@
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
           package="com.android.networkstack"
           android:sharedUserId="android.uid.networkstack">
+    <uses-sdk android:minSdkVersion="28" android:targetSdkVersion="28" />
     <!-- Signature permission defined in NetworkStackStub -->
     <uses-permission android:name="android.permission.MAINLINE_NETWORK_STACK" />
     <application>
@@ -28,4 +29,4 @@
             </intent-filter>
         </service>
     </application>
-</manifest>
\ No newline at end of file
+</manifest>
diff --git a/packages/NetworkStack/AndroidManifestBase.xml b/packages/NetworkStack/AndroidManifestBase.xml
index 621d30c..f69e4b2 100644
--- a/packages/NetworkStack/AndroidManifestBase.xml
+++ b/packages/NetworkStack/AndroidManifestBase.xml
@@ -20,7 +20,6 @@
           package="com.android.networkstack"
           android:versionCode="11"
           android:versionName="Q-initial">
-    <uses-sdk android:minSdkVersion="28" android:targetSdkVersion="28" />
     <uses-permission android:name="android.permission.INTERNET" />
     <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
diff --git a/packages/NetworkStack/AndroidManifest_InProcess.xml b/packages/NetworkStack/AndroidManifest_InProcess.xml
index 48fcecd..275cd02 100644
--- a/packages/NetworkStack/AndroidManifest_InProcess.xml
+++ b/packages/NetworkStack/AndroidManifest_InProcess.xml
@@ -20,6 +20,7 @@
           package="com.android.networkstack.inprocess"
           android:sharedUserId="android.uid.system"
           android:process="system">
+    <uses-sdk android:minSdkVersion="28" android:targetSdkVersion="28" />
     <application>
         <service android:name="com.android.server.NetworkStackService" android:process="system">
             <intent-filter>
@@ -27,4 +28,4 @@
             </intent-filter>
         </service>
     </application>
-</manifest>
\ No newline at end of file
+</manifest>
diff --git a/packages/NetworkStack/src/android/net/ip/IpClient.java b/packages/NetworkStack/src/android/net/ip/IpClient.java
index 61dc966..346ac68 100644
--- a/packages/NetworkStack/src/android/net/ip/IpClient.java
+++ b/packages/NetworkStack/src/android/net/ip/IpClient.java
@@ -897,7 +897,7 @@
         // accompanying code in IpReachabilityMonitor) is unreachable.
         final boolean ignoreIPv6ProvisioningLoss =
                 mConfiguration != null && mConfiguration.mUsingMultinetworkPolicyTracker
-                && mCm.getAvoidBadWifi();
+                && mCm.shouldAvoidBadWifi();
 
         // Additionally:
         //
diff --git a/packages/NetworkStack/src/android/net/ip/IpReachabilityMonitor.java b/packages/NetworkStack/src/android/net/ip/IpReachabilityMonitor.java
index e73cba6..3aa6933 100644
--- a/packages/NetworkStack/src/android/net/ip/IpReachabilityMonitor.java
+++ b/packages/NetworkStack/src/android/net/ip/IpReachabilityMonitor.java
@@ -332,7 +332,7 @@
     }
 
     private boolean avoidingBadLinks() {
-        return !mUsingMultinetworkPolicyTracker || mCm.getAvoidBadWifi();
+        return !mUsingMultinetworkPolicyTracker || mCm.shouldAvoidBadWifi();
     }
 
     public void probeAll() {
diff --git a/packages/Shell/src/com/android/shell/BugreportProgressService.java b/packages/Shell/src/com/android/shell/BugreportProgressService.java
index a9ff21f..1060c7b 100644
--- a/packages/Shell/src/com/android/shell/BugreportProgressService.java
+++ b/packages/Shell/src/com/android/shell/BugreportProgressService.java
@@ -1095,6 +1095,7 @@
         new AsyncTask<Void, Void, Void>() {
             @Override
             protected Void doInBackground(Void... params) {
+                Looper.prepare();
                 zipBugreport(info);
                 sendBugreportNotification(info, takingScreenshot);
                 return null;
diff --git a/packages/SystemUI/AndroidManifest.xml b/packages/SystemUI/AndroidManifest.xml
index 6df6c73..d654f5a 100644
--- a/packages/SystemUI/AndroidManifest.xml
+++ b/packages/SystemUI/AndroidManifest.xml
@@ -438,7 +438,7 @@
         <activity
             android:name=".media.MediaProjectionPermissionActivity"
             android:exported="true"
-            android:theme="@style/Theme.AlertDialogHost"
+            android:theme="@style/Theme.MediaProjectionAlertDialog"
             android:finishOnCloseSystemDialogs="true"
             android:launchMode="singleTop"
             android:excludeFromRecents="true"
diff --git a/packages/SystemUI/docs/physics-animation-layout-control-methods.png b/packages/SystemUI/docs/physics-animation-layout-control-methods.png
deleted file mode 100644
index e77c676..0000000
--- a/packages/SystemUI/docs/physics-animation-layout-control-methods.png
+++ /dev/null
Binary files differ
diff --git a/packages/SystemUI/docs/physics-animation-layout.md b/packages/SystemUI/docs/physics-animation-layout.md
index 300f63a..488c465 100644
--- a/packages/SystemUI/docs/physics-animation-layout.md
+++ b/packages/SystemUI/docs/physics-animation-layout.md
@@ -25,22 +25,74 @@
 Returns a SpringForce instance to use for animations of the given property. This allows the controller to configure stiffness and bounciness values. Since the physics animations internally use SpringForce instances to hold inflight animation values, this method needs to return a new SpringForce instance each time - no constants allowed.
 
 ### Animation Control Methods
-![Diagram of how calls to animateValueForChildAtIndex dispatch to DynamicAnimations.](physics-animation-layout-control-methods.png)
 Once the layout has used the controller’s configuration properties to build the animations, the controller can use them to actually run animations. This is done for two reasons - reacting to a view being added or removed, or responding to another class (such as a touch handler or broadcast receiver) requesting an animation. ```onChildAdded```, ```onChildRemoved```, and ```setChildVisibility``` are called automatically by the layout, giving the controller the opportunity to animate the child in/out/visible/gone. Custom methods are called by anyone with access to the controller instance to do things like expand, collapse, or move the child views.
 
-In either case, the controller has access to the layout’s protected ```animateValueForChildAtIndex(ViewProperty property, int index, float value)``` method. This method is used to actually run an animation.
+In either case, the controller can use `super.animationForChild` to retrieve a `PhysicsPropertyAnimator` instance. This object behaves similarly to the `ViewPropertyAnimator` object you would receive from `View.animate()`. 
 
-For example, moving the first child view to *(100, 200)*:
+#### PhysicsPropertyAnimator
+
+Like `ViewPropertyAnimator`, `PhysicsPropertyAnimator` provides the following methods for animating properties:
+- `alpha(float)`
+- `translationX/Y/Z(float)`
+- `scaleX/Y(float)`
+
+It also provides the following configuration methods:
+- `withStartDelay(int)`, for starting the animation after a given delay.
+- `withStartVelocity(float)`, for starting the animation with the given start velocity.
+- `withPositionStartVelocities(float, float)`, for setting specific start velocities for TRANSLATION_X and TRANSLATION_Y, since these typically differ.
+- `start(Runnable)`, to start the animation, with an optional end action to call when the animations for every property (including chained animations) have completed.
+
+For example, moving the first child view:
 
 ```
-animateValueForChildAtIndex(TRANSLATION_X, 0, 100);
-animateValueForChildAtIndex(TRANSLATION_Y, 0, 200);
+animationForChild(getChildAt(0))
+    .translationX(100)
+    .translationY(200)
+    .setStartDelay(500)
+    .start();
 ```
 
-This would use the physics animations constructed by the layout to spring the view to *(100, 200)*.
+This would use the physics animations constructed by the layout to spring the view to *(100, 200)* after 500ms.
 
 If the controller’s ```getNextAnimationInChain``` method set up the first child’s TRANSLATION_X/Y animations to be chained to the second child’s, this would result in the second child also springing towards (100, 200), plus any offset returned by ```getOffsetForChainedPropertyAnimation```.
 
+##### Advanced Usage
+The animator has additional functionality to reduce the amount of boilerplate required for typical physics animation use cases.
+
+- Often, animations will set starting values for properties before the animation begins. Property methods like `translationX` have an overloaded variant: `translationX(from, to)`. When `start()` is called, the animation will set the view's translationX property to `from` before beginning the animation to `to`.
+- We may want to use different end actions for each property. For example, if we're animating a view to the bottom of the screen, and also fading it out, we might want to perform an action as soon as the fade out is complete. We can use `alpha(to, endAction)`, which will call endAction as soon as the alpha animation is finished. A special case is `position(x, y, endAction)`, where the endAction is called when both translationX and translationY animations have completed.
+
+`PhysicsAnimationController` also provides `animationsForChildrenFromIndex(int, ChildAnimationConfigurator)`. This is a convenience method for starting animations on multiple child views, starting at the given index. The `ChildAnimationConfigurator` is called with a `PhysicsPropertyAnimator` for each child, where calls to methods like `translationX` and `withStartVelocity` can be made. `animationsForChildrenFromIndex` returns a `MultiAnimationStarter` with a single method, `startAll(endAction)`, which starts all of the animations and calls the end action when they have all completed.
+
+##### Examples
+Spring the stack of bubbles (whose animations are chained) to the bottom of the screen, shrinking them to 50% size. Once the first bubble is done shrinking, begin fading them out, and then remove them all from the parent once all bubbles have faded out:
+
+```
+animationForChild(leadBubble)
+    .position(screenCenter, screenBottom)
+    .scaleX(0.5f)
+    .scaleY(0.5f, () -> animationForChild(leadBubble).alpha(0).start(removeAllFromParent))
+    .start();
+```
+
+'Drop in' a child view that was just added to the layout:
+
+```
+animationForChild(newView)
+    .scaleX(1.15f /* from */, 1f /* to */)
+    .scaleY(1.15f /* from */, 1f /* to */)
+    .alpha(0f /* from */, 1f /* to */)
+    .position(posX, posY)
+    .start();
+```
+
+Move every view except for the first to x = (index - 1) * 50, then remove the first view.
+
+```
+animationsForChildrenFromIndex(1, (index, anim) -> anim.translationX((index - 1) * 50))
+    .startAll(removeFirstView);
+```
+
 ## PhysicsAnimationLayout
 The layout itself is a FrameLayout descendant with a few extra methods:
 
diff --git a/packages/SystemUI/res/layout/biometric_dialog.xml b/packages/SystemUI/res/layout/biometric_dialog.xml
index 83557f2..8f7a45f 100644
--- a/packages/SystemUI/res/layout/biometric_dialog.xml
+++ b/packages/SystemUI/res/layout/biometric_dialog.xml
@@ -128,7 +128,6 @@
                             android:textSize="12sp"
                             android:gravity="center_horizontal"
                             android:accessibilityLiveRegion="polite"
-                            android:contentDescription="@string/accessibility_biometric_dialog_help_area"
                             android:textColor="?android:attr/textColorSecondary"/>
 
                         <LinearLayout
diff --git a/packages/SystemUI/res/layout/bubble_permission_view.xml b/packages/SystemUI/res/layout/bubble_permission_view.xml
index c9d8a91..df5264c 100644
--- a/packages/SystemUI/res/layout/bubble_permission_view.xml
+++ b/packages/SystemUI/res/layout/bubble_permission_view.xml
@@ -58,7 +58,7 @@
         android:layout_height="wrap_content"
         android:layout_marginTop="8dp"
         android:text="@string/bubbles_prompt"
-        style="@*android:style/TextAppearance.Material.Body1" />
+        style="@*android:style/TextAppearance.DeviceDefault.Notification.Title"/>
 
     <!-- Buttons -->
     <LinearLayout
diff --git a/packages/SystemUI/res/layout/media_projection_dialog_title.xml b/packages/SystemUI/res/layout/media_projection_dialog_title.xml
new file mode 100644
index 0000000..c4d784b
--- /dev/null
+++ b/packages/SystemUI/res/layout/media_projection_dialog_title.xml
@@ -0,0 +1,39 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+    Copyright 2019, The Android Open Source Project
+
+    Licensed under the Apache License, Version 2.0 (the "License");
+    you may not use this file except in compliance with the License.
+    You may obtain a copy of the License at
+
+        http://www.apache.org/licenses/LICENSE-2.0
+
+    Unless required by applicable law or agreed to in writing, software
+    distributed under the License is distributed on an "AS IS" BASIS,
+    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+    See the License for the specific language governing permissions and
+    limitations under the License.
+-->
+
+<RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"
+        xmlns:android="http://schemas.android.com/apk/res/android"
+        android:theme="@style/Theme.MediaProjectionAlertDialog"
+        android:paddingStart="?android:attr/dialogPreferredPadding"
+        android:paddingEnd="?android:attr/dialogPreferredPadding"
+        android:paddingTop="?android:attr/dialogPreferredPadding">
+    <ImageView
+        android:id="@+id/dialog_icon"
+        android:src="@drawable/ic_media_projection_permission"
+        android:layout_height="wrap_content"
+        android:layout_width="match_parent"
+        android:layout_marginBottom="20dp"
+        android:layout_centerInParent="true"/>
+    <TextView
+        android:id="@+id/dialog_title"
+        android:gravity="center"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_below="@id/dialog_icon"
+        android:textColor="?android:attr/colorPrimary"
+        android:textAppearance="@*android:style/TextAppearance.DeviceDefault.Title" />
+</RelativeLayout>
diff --git a/packages/SystemUI/res/layout/qs_footer_impl.xml b/packages/SystemUI/res/layout/qs_footer_impl.xml
index 669d53b..6c8110b 100644
--- a/packages/SystemUI/res/layout/qs_footer_impl.xml
+++ b/packages/SystemUI/res/layout/qs_footer_impl.xml
@@ -30,13 +30,6 @@
     android:clipChildren="false"
     android:clipToPadding="false">
 
-    <View
-        android:id="@+id/qs_footer_divider"
-        android:layout_width="match_parent"
-        android:layout_height="1dp"
-        android:layout_gravity="top"
-        android:background="?android:attr/dividerHorizontal"/>
-
     <LinearLayout
         android:layout_width="match_parent"
         android:layout_height="match_parent"
diff --git a/packages/SystemUI/res/layout/quick_qs_status_icons.xml b/packages/SystemUI/res/layout/quick_qs_status_icons.xml
index fa74536..dc31b70 100644
--- a/packages/SystemUI/res/layout/quick_qs_status_icons.xml
+++ b/packages/SystemUI/res/layout/quick_qs_status_icons.xml
@@ -19,7 +19,7 @@
     android:id="@+id/quick_qs_status_icons"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
-    android:layout_marginTop="8dp"
+    android:layout_marginTop="@dimen/qs_header_top_margin"
     android:layout_marginBottom="14dp"
     android:layout_marginStart="@dimen/status_bar_padding_start"
     android:layout_marginEnd="@dimen/status_bar_padding_end"
diff --git a/packages/SystemUI/res/layout/quick_settings_header_info.xml b/packages/SystemUI/res/layout/quick_settings_header_info.xml
index 075f51d..da640fd 100644
--- a/packages/SystemUI/res/layout/quick_settings_header_info.xml
+++ b/packages/SystemUI/res/layout/quick_settings_header_info.xml
@@ -19,7 +19,9 @@
     android:layout_width="match_parent"
     android:layout_height="@dimen/qs_header_tooltip_height"
     android:layout_below="@id/quick_status_bar_system_icons"
-    android:layout_marginTop="12dp">
+    android:layout_marginTop="@dimen/qs_header_top_margin"
+    android:paddingStart="@dimen/status_bar_padding_start"
+    android:paddingEnd="@dimen/status_bar_padding_end">
 
     <TextView
         android:id="@+id/long_press_tooltip"
diff --git a/packages/SystemUI/res/values-land/dimens.xml b/packages/SystemUI/res/values-land/dimens.xml
index 77e79c9..e768939 100644
--- a/packages/SystemUI/res/values-land/dimens.xml
+++ b/packages/SystemUI/res/values-land/dimens.xml
@@ -33,7 +33,6 @@
     <integer name="quick_settings_num_columns">4</integer>
     <bool name="quick_settings_wide">true</bool>
     <dimen name="qs_detail_margin_top">0dp</dimen>
-    <dimen name="qs_paged_tile_layout_padding_bottom">0dp</dimen>
 
     <dimen name="volume_tool_tip_right_margin">136dp</dimen>
     <dimen name="volume_tool_tip_top_margin">12dp</dimen>
diff --git a/packages/SystemUI/res/values/dimens.xml b/packages/SystemUI/res/values/dimens.xml
index 27cebcc..1da1405 100644
--- a/packages/SystemUI/res/values/dimens.xml
+++ b/packages/SystemUI/res/values/dimens.xml
@@ -206,10 +206,10 @@
     <dimen name="status_bar_icon_padding">0dp</dimen>
 
     <!-- the padding on the start of the statusbar -->
-    <dimen name="status_bar_padding_start">6dp</dimen>
+    <dimen name="status_bar_padding_start">8dp</dimen>
 
     <!-- the padding on the end of the statusbar -->
-    <dimen name="status_bar_padding_end">6dp</dimen>
+    <dimen name="status_bar_padding_end">8dp</dimen>
 
     <!-- the radius of the overflow dot in the status bar -->
     <dimen name="overflow_dot_radius">2dp</dimen>
@@ -433,7 +433,7 @@
     <dimen name="qs_detail_item_icon_marginEnd">20dp</dimen>
     <dimen name="qs_header_tooltip_height">18dp</dimen>
     <dimen name="qs_header_alarm_icon_size">18dp</dimen>
-    <dimen name="qs_header_mobile_icon_size">18dp</dimen>
+    <dimen name="qs_header_mobile_icon_size">@dimen/status_bar_icon_drawing_size</dimen>
     <dimen name="qs_header_alarm_text_margin_start">6dp</dimen>
     <dimen name="qs_header_separator_width">8dp</dimen>
     <dimen name="qs_header_carrier_separator_width">6dp</dimen>
@@ -442,7 +442,8 @@
     <dimen name="qs_footer_padding_start">16dp</dimen>
     <dimen name="qs_footer_padding_end">16dp</dimen>
     <dimen name="qs_footer_icon_size">16dp</dimen>
-    <dimen name="qs_paged_tile_layout_padding_bottom">16dp</dimen>
+    <dimen name="qs_paged_tile_layout_padding_bottom">0dp</dimen>
+    <dimen name="qs_header_top_margin">12dp</dimen>
 
     <dimen name="qs_notif_collapsed_space">64dp</dimen>
 
diff --git a/packages/SystemUI/res/values/ids.xml b/packages/SystemUI/res/values/ids.xml
index 05cf040..501b1b5 100644
--- a/packages/SystemUI/res/values/ids.xml
+++ b/packages/SystemUI/res/values/ids.xml
@@ -111,13 +111,14 @@
     <!-- Optional cancel button on Keyguard -->
     <item type="id" name="cancel_button"/>
 
-    <!-- For saving DynamicAnimation physics animations as view tags. -->
+    <!-- For saving PhysicsAnimationLayout animations/animators as view tags. -->
     <item type="id" name="translation_x_dynamicanimation_tag"/>
     <item type="id" name="translation_y_dynamicanimation_tag"/>
     <item type="id" name="translation_z_dynamicanimation_tag"/>
     <item type="id" name="alpha_dynamicanimation_tag"/>
     <item type="id" name="scale_x_dynamicanimation_tag"/>
     <item type="id" name="scale_y_dynamicanimation_tag"/>
+    <item type="id" name="physics_animator_tag"/>
 
     <!-- Global Actions Menu -->
     <item type="id" name="global_actions_view" />
diff --git a/packages/SystemUI/res/values/strings.xml b/packages/SystemUI/res/values/strings.xml
index f8bec4a..265c620 100644
--- a/packages/SystemUI/res/values/strings.xml
+++ b/packages/SystemUI/res/values/strings.xml
@@ -279,8 +279,6 @@
     <!-- Button name for "Cancel". [CHAR LIMIT=NONE] -->
     <string name="cancel">Cancel</string>
 
-    <!-- Content description for the error/help message are when the system-provided fingerprint dialog is showing, for accessibility (not shown on the screen). [CHAR LIMIT=NONE] -->
-    <string name="accessibility_biometric_dialog_help_area">Help message area</string>
     <!-- Message shown when a biometric is authenticated, asking the user to confirm authentication [CHAR LIMIT=30] -->
     <string name="biometric_dialog_confirm">Confirm</string>
     <!-- Button name on BiometricPrompt shown when a biometric is detected but not authenticated. Tapping the button resumes authentication [CHAR_LIMIT=30] -->
diff --git a/packages/SystemUI/res/values/styles.xml b/packages/SystemUI/res/values/styles.xml
index 1c13750..a6a6e6b 100644
--- a/packages/SystemUI/res/values/styles.xml
+++ b/packages/SystemUI/res/values/styles.xml
@@ -353,13 +353,13 @@
     <style name="AutoSizingList">
         <item name="enableAutoSizing">true</item>
     </style>
-    <style name="Theme.AlertDialogHost" parent="android:Theme.DeviceDefault">
+    <style name="Theme.MediaProjectionAlertDialog" parent="android:Theme.DeviceDefault">
         <item name="android:windowIsTranslucent">true</item>
         <item name="android:windowBackground">@android:color/transparent</item>
         <item name="android:windowContentOverlay">@null</item>
         <item name="android:windowNoTitle">true</item>
         <item name="android:windowIsFloating">true</item>
-        <item name="android:backgroundDimEnabled">false</item>
+        <item name="android:backgroundDimEnabled">true</item>
         <item name="android:alertDialogTheme">@style/Theme.SystemUI.Dialog.Alert</item>
     </style>
 
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitch.java b/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitch.java
index ce65b5a..6ae2b45 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitch.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitch.java
@@ -271,14 +271,11 @@
         return mClockView.getTextSize();
     }
 
+    /**
+     * Refresh the time of the clock, due to either time tick broadcast or doze time tick alarm.
+     */
     public void refresh() {
         mClockView.refresh();
-    }
-
-    /**
-     * Notifies that time tick alarm from doze service fired.
-     */
-    public void dozeTimeTick() {
         if (mClockPlugin != null) {
             mClockPlugin.onTimeTick();
         }
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardStatusView.java b/packages/SystemUI/src/com/android/keyguard/KeyguardStatusView.java
index 808e264..0369e4c 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardStatusView.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardStatusView.java
@@ -214,7 +214,6 @@
     public void dozeTimeTick() {
         refreshTime();
         mKeyguardSlice.refresh();
-        mClockView.dozeTimeTick();
     }
 
     private void refreshTime() {
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/animation/ExpandedAnimationController.java b/packages/SystemUI/src/com/android/systemui/bubbles/animation/ExpandedAnimationController.java
index 40e08be..d601e63 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/animation/ExpandedAnimationController.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/animation/ExpandedAnimationController.java
@@ -104,16 +104,23 @@
      * @return The y-value to which the bubbles were expanded, in case that's useful.
      */
     public float expandFromStack(PointF collapseTo, Runnable after) {
+        animationsForChildrenFromIndex(
+                0, /* startIndex */
+                new ChildAnimationConfigurator() {
+                    // How much to translate the next bubble, so that it is not overlapping the
+                    // previous one.
+                    float mTranslateNextBubbleXBy = mBubblePaddingPx;
+
+                    @Override
+                    public void configureAnimationForChildAtIndex(
+                            int index, PhysicsAnimationLayout.PhysicsPropertyAnimator animation) {
+                        animation.position(mTranslateNextBubbleXBy, getExpandedY());
+                        mTranslateNextBubbleXBy += mBubbleSizePx + mBubblePaddingPx;
+                    }
+            })
+            .startAll(after);
+
         mCollapseToPoint = collapseTo;
-
-        // How much to translate the next bubble, so that it is not overlapping the previous one.
-        float translateNextBubbleXBy = mBubblePaddingPx;
-        for (int i = 0; i < mLayout.getChildCount(); i++) {
-            mLayout.animatePositionForChildAtIndex(i, translateNextBubbleXBy, getExpandedY());
-            translateNextBubbleXBy += mBubbleSizePx + mBubblePaddingPx;
-        }
-
-        runAfterTranslationsEnd(after);
         return getExpandedY();
     }
 
@@ -121,13 +128,14 @@
     public void collapseBackToStack(Runnable after) {
         // Stack to the left if we're going to the left, or right if not.
         final float sideMultiplier = mLayout.isFirstChildXLeftOfCenter(mCollapseToPoint.x) ? -1 : 1;
-        for (int i = 0; i < mLayout.getChildCount(); i++) {
-            mLayout.animatePositionForChildAtIndex(
-                    i,
-                    mCollapseToPoint.x + (sideMultiplier * i * mStackOffsetPx), mCollapseToPoint.y);
-        }
 
-        runAfterTranslationsEnd(after);
+        animationsForChildrenFromIndex(
+                0, /* startIndex */
+                (index, animation) ->
+                    animation.position(
+                            mCollapseToPoint.x + (sideMultiplier * index * mStackOffsetPx),
+                            mCollapseToPoint.y))
+            .startAll(after /* endAction */);
     }
 
     /** Prepares the given bubble to be dragged out. */
@@ -164,20 +172,10 @@
     public void snapBubbleBack(View bubbleView, float velX, float velY) {
         final int index = mLayout.indexOfChild(bubbleView);
 
-        // Snap the bubble back, respecting its current velocity.
-        mLayout.animateValueForChildAtIndex(
-                DynamicAnimation.TRANSLATION_X, index, getXForChildAtIndex(index), velX);
-        mLayout.animateValueForChildAtIndex(
-                DynamicAnimation.TRANSLATION_Y, index, getExpandedY(), velY);
-        mLayout.setEndListenerForProperties(
-                mLayout.new OneTimeMultiplePropertyEndListener() {
-                    @Override
-                    void onAllAnimationsForPropertiesEnd() {
-                        // Reset Z translation once the bubble is done snapping back.
-                        bubbleView.setTranslationZ(0f);
-                    }
-                },
-                DynamicAnimation.TRANSLATION_X, DynamicAnimation.TRANSLATION_Y);
+        animationForChildAtIndex(index)
+                .position(getXForChildAtIndex(index), getExpandedY())
+                .withPositionStartVelocities(velX, velY)
+                .start(() -> bubbleView.setTranslationZ(0f) /* after */);
 
         animateStackByBubbleWidthsStartingFrom(
                 /* numBubbleWidths */ 0, /* startIndex */ index + 1);
@@ -202,12 +200,8 @@
      */
     public void updateYPosition(Runnable after) {
         if (mLayout == null) return;
-
-        for (int i = 0; i < mLayout.getChildCount(); i++) {
-            boolean isLast = i == mLayout.getChildCount() - 1;
-            mLayout.animateValueForChildAtIndex(DynamicAnimation.TRANSLATION_Y, i,
-                    getExpandedY(), isLast ? after : null);
-        }
+        animationsForChildrenFromIndex(
+                0, (i, anim) -> anim.translationY(getExpandedY())).startAll(after);
     }
 
     /**
@@ -216,12 +210,11 @@
      * positions.
      */
     private void animateStackByBubbleWidthsStartingFrom(int numBubbleWidths, int startIndex) {
-        for (int i = startIndex; i < mLayout.getChildCount(); i++) {
-            mLayout.animateValueForChildAtIndex(
-                    DynamicAnimation.TRANSLATION_X,
-                    i,
-                    getXForChildAtIndex(i + numBubbleWidths));
-        }
+        animationsForChildrenFromIndex(
+                startIndex,
+                (index, animation) ->
+                        animation.translationX(getXForChildAtIndex(index + numBubbleWidths)))
+            .startAll();
     }
 
     /** The Y value of the row of expanded bubbles. */
@@ -248,21 +241,6 @@
         }
     }
 
-    /** Runs the given Runnable after all translation-related animations have ended. */
-    private void runAfterTranslationsEnd(Runnable after) {
-        DynamicAnimation.OnAnimationEndListener allEndedListener =
-                (animation, canceled, value, velocity) -> {
-                    if (!mLayout.arePropertiesAnimating(
-                            DynamicAnimation.TRANSLATION_X,
-                            DynamicAnimation.TRANSLATION_Y)) {
-                        after.run();
-                    }
-                };
-
-        mLayout.setEndListenerForProperty(allEndedListener, DynamicAnimation.TRANSLATION_X);
-        mLayout.setEndListenerForProperty(allEndedListener, DynamicAnimation.TRANSLATION_Y);
-    }
-
     @Override
     Set<DynamicAnimation.ViewProperty> getAnimatedProperties() {
         return Sets.newHashSet(
@@ -295,8 +273,12 @@
         // Pop in from the top.
         // TODO: Reverse this when bubbles are at the bottom.
         child.setTranslationX(getXForChildAtIndex(index));
-        child.setTranslationY(getExpandedY() - mBubbleSizePx * ANIMATE_TRANSLATION_FACTOR);
-        mLayout.animateValueForChild(DynamicAnimation.TRANSLATION_Y, child, getExpandedY());
+
+        animationForChild(child)
+                .translationY(
+                        getExpandedY() - mBubbleSizePx * ANIMATE_TRANSLATION_FACTOR, /* from */
+                        getExpandedY() /* to */)
+                .start();
         animateBubblesAfterIndexToCorrectX(index);
     }
 
@@ -304,36 +286,26 @@
     void onChildRemoved(View child, int index, Runnable finishRemoval) {
         // Bubble pops out to the top.
         // TODO: Reverse this when bubbles are at the bottom.
-        mLayout.animateValueForChild(
-                DynamicAnimation.ALPHA, child, 0f, finishRemoval);
+
+        final PhysicsAnimationLayout.PhysicsPropertyAnimator animator = animationForChild(child);
+        animator.alpha(0f, finishRemoval /* endAction */);
 
         // If we're removing the dragged-out bubble, that means it got dismissed.
         if (child.equals(mBubbleDraggingOut)) {
-            // Throw it to the bottom of the screen, towards the center horizontally.
-            mLayout.animateValueForChild(
-                    DynamicAnimation.TRANSLATION_X,
-                    child,
-                    mLayout.getWidth() / 2f - mBubbleSizePx / 2f,
-                    mBubbleDraggingOutVelX);
-            mLayout.animateValueForChild(
-                    DynamicAnimation.TRANSLATION_Y,
-                    child,
-                    mLayout.getHeight() + mBubbleSizePx,
-                    mBubbleDraggingOutVelY);
-
-            // Scale it down a bit so it looks like it's disappearing.
-            mLayout.animateValueForChild(DynamicAnimation.SCALE_X, child, ANIMATE_SCALE_PERCENT);
-            mLayout.animateValueForChild(DynamicAnimation.SCALE_Y, child, ANIMATE_SCALE_PERCENT);
+            animator.position(
+                            mLayout.getWidth() / 2f - mBubbleSizePx / 2f,
+                            mLayout.getHeight() + mBubbleSizePx)
+                    .withPositionStartVelocities(mBubbleDraggingOutVelX, mBubbleDraggingOutVelY)
+                    .scaleX(ANIMATE_SCALE_PERCENT)
+                    .scaleY(ANIMATE_SCALE_PERCENT);
 
             mBubbleDraggingOut = null;
         } else {
-            // If we're removing some random bubble just throw it off the top.
-            mLayout.animateValueForChild(
-                    DynamicAnimation.TRANSLATION_Y,
-                    child,
-                    getExpandedY() - mBubbleSizePx * ANIMATE_TRANSLATION_FACTOR);
+            animator.translationY(getExpandedY() - mBubbleSizePx * ANIMATE_TRANSLATION_FACTOR);
         }
 
+        animator.start();
+
         // Animate all the other bubbles to their new positions sans this bubble.
         animateBubblesAfterIndexToCorrectX(index);
     }
@@ -346,12 +318,9 @@
             child.setVisibility(View.VISIBLE);
         }
 
-        // Fade in.
-        mLayout.animateValueForChild(
-                DynamicAnimation.ALPHA,
-                child,
-                /* value */ visibility == View.GONE ? 0f : 1f,
-                () -> super.setChildVisibility(child, index, visibility));
+        animationForChild(child)
+                .alpha(visibility == View.GONE ? 0f : 1f)
+                .start(() -> super.setChildVisibility(child, index, visibility) /* after */);
     }
 
     /**
@@ -365,8 +334,9 @@
             // Don't animate the dragging out bubble, or it'll jump around while being dragged. It
             // will be snapped to the correct X value after the drag (if it's not dismissed).
             if (!bubble.equals(mBubbleDraggingOut)) {
-                mLayout.animateValueForChild(
-                        DynamicAnimation.TRANSLATION_X, bubble, getXForChildAtIndex(i));
+                animationForChild(bubble)
+                        .translationX(getXForChildAtIndex(i))
+                        .start();
             }
         }
     }
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/animation/PhysicsAnimationLayout.java b/packages/SystemUI/src/com/android/systemui/bubbles/animation/PhysicsAnimationLayout.java
index dfdcfc9..2fa87d8 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/animation/PhysicsAnimationLayout.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/animation/PhysicsAnimationLayout.java
@@ -27,8 +27,11 @@
 
 import com.android.systemui.R;
 
+import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
 import java.util.Set;
 
 /**
@@ -46,6 +49,35 @@
      */
     abstract static class PhysicsAnimationController {
 
+        /** Configures a given {@link PhysicsPropertyAnimator} for a view at the given index. */
+        interface ChildAnimationConfigurator {
+
+            /**
+             * Called to configure the animator for the view at the given index.
+             *
+             * This method should make use of methods such as
+             * {@link PhysicsPropertyAnimator#translationX} and
+             * {@link PhysicsPropertyAnimator#withStartDelay} to configure the animation.
+             *
+             * Implementations should not call {@link PhysicsPropertyAnimator#start}, this will
+             * happen elsewhere after configuration is complete.
+             */
+            void configureAnimationForChildAtIndex(int index, PhysicsPropertyAnimator animation);
+        }
+
+        /**
+         * Returned by {@link #animationsForChildrenFromIndex} to allow starting multiple animations
+         * on multiple child views at the same time.
+         */
+        interface MultiAnimationStarter {
+
+            /**
+             * Start all animations and call the given end actions once all animations have
+             * completed.
+             */
+            void startAll(Runnable... endActions);
+        }
+
         /**
          * Constant to return from {@link #getNextAnimationInChain} if the animation should not be
          * chained at all.
@@ -98,7 +130,7 @@
          * by getChildAt() and getChildCount().
          *
          * The controller can perform animations on the child (either manually, or by using
-         * {@link #animateValueForChild}), and then call finishRemoval when complete.
+         * {@link #animationForChild(View)}), and then call finishRemoval when complete.
          *
          * finishRemoval must be called by implementations of this method, or transient views will
          * never be removed.
@@ -125,14 +157,74 @@
         protected void setChildVisibility(View child, int index, int visibility) {
             child.setVisibility(visibility);
         }
+
+        /**
+         * Returns a {@link PhysicsPropertyAnimator} instance for the given child view.
+         */
+        protected PhysicsPropertyAnimator animationForChild(View child) {
+            PhysicsPropertyAnimator animator =
+                    (PhysicsPropertyAnimator) child.getTag(R.id.physics_animator_tag);
+
+            if (animator == null) {
+                animator = mLayout.new PhysicsPropertyAnimator(child);
+                child.setTag(R.id.physics_animator_tag, animator);
+            }
+
+            return animator;
+        }
+
+        /** Returns a {@link PhysicsPropertyAnimator} instance for child at the given index. */
+        protected PhysicsPropertyAnimator animationForChildAtIndex(int index) {
+            return animationForChild(mLayout.getChildAt(index));
+        }
+
+        /**
+         * Returns a {@link MultiAnimationStarter} whose startAll method will start the physics
+         * animations for all children from startIndex onward. The provided configurator will be
+         * called with each child's {@link PhysicsPropertyAnimator}, where it can set up each
+         * animation appropriately.
+         */
+        protected MultiAnimationStarter animationsForChildrenFromIndex(
+                int startIndex, ChildAnimationConfigurator configurator) {
+            final Set<DynamicAnimation.ViewProperty> allAnimatedProperties = new HashSet<>();
+            final List<PhysicsPropertyAnimator> allChildAnims = new ArrayList<>();
+
+            // Retrieve the animator for each child, ask the configurator to configure it, then save
+            // it and the properties it chose to animate.
+            for (int i = startIndex; i < mLayout.getChildCount(); i++) {
+                final PhysicsPropertyAnimator anim = animationForChildAtIndex(i);
+                configurator.configureAnimationForChildAtIndex(i, anim);
+                allAnimatedProperties.addAll(anim.getAnimatedProperties());
+                allChildAnims.add(anim);
+            }
+
+            // Return a MultiAnimationStarter that will start all of the child animations, and also
+            // add a multiple property end listener to the layout that will call the end action
+            // provided to startAll() once all animations on the animated properties complete.
+            return (endActions) -> {
+                if (endActions != null) {
+                    mLayout.setEndActionForMultipleProperties(
+                            () -> {
+                                for (Runnable action : endActions) {
+                                    action.run();
+                                }
+                            },
+                            allAnimatedProperties.toArray(
+                                    new DynamicAnimation.ViewProperty[0]));
+                }
+
+                for (PhysicsPropertyAnimator childAnim : allChildAnims) {
+                    childAnim.start();
+                }
+            };
+        }
     }
 
     /**
-     * End listeners that are called when every child's animation of the given property has
-     * finished.
+     * End actions that are called when every child's animation of the given property has finished.
      */
-    protected final HashMap<DynamicAnimation.ViewProperty, DynamicAnimation.OnAnimationEndListener>
-            mEndListenerForProperty = new HashMap<>();
+    protected final HashMap<DynamicAnimation.ViewProperty, Runnable> mEndActionForProperty =
+            new HashMap<>();
 
     /** Set of currently rendered transient views. */
     private final Set<View> mTransientViews = new HashSet<>();
@@ -165,7 +257,7 @@
      */
     public void setController(PhysicsAnimationController controller) {
         cancelAllAnimations();
-        mEndListenerForProperty.clear();
+        mEndActionForProperty.clear();
 
         this.mController = controller;
         mController.setLayout(this);
@@ -177,26 +269,27 @@
     }
 
     /**
-     * Sets an end listener that will be called when all child animations for a given property have
+     * Sets an end action that will be run when all child animations for a given property have
      * stopped running.
      */
-    public void setEndListenerForProperty(
-            DynamicAnimation.OnAnimationEndListener listener,
-            DynamicAnimation.ViewProperty property) {
-        mEndListenerForProperty.put(property, listener);
+    public void setEndActionForProperty(Runnable action, DynamicAnimation.ViewProperty property) {
+        mEndActionForProperty.put(property, action);
     }
 
     /**
-     * Sets an end listener that will be called whenever any of the given properties' animations
-     * end. For example, setting a listener for TRANSLATION_X and TRANSLATION_Y will result in that
-     * listener being called twice - once when all TRANSLATION_X animations end, and again when all
-     * TRANSLATION_Y animations end.
+     * Sets an end action that will be run when all child animations for all of the given properties
+     * have stopped running.
      */
-    public void setEndListenerForProperties(
-            DynamicAnimation.OnAnimationEndListener endListener,
-            DynamicAnimation.ViewProperty... properties) {
+    public void setEndActionForMultipleProperties(
+            Runnable action, DynamicAnimation.ViewProperty... properties) {
+        final Runnable checkIfAllFinished = () -> {
+            if (!arePropertiesAnimating(properties)) {
+                action.run();
+            }
+        };
+
         for (DynamicAnimation.ViewProperty property : properties) {
-            setEndListenerForProperty(endListener, property);
+            setEndActionForProperty(checkIfAllFinished, property);
         }
     }
 
@@ -204,8 +297,8 @@
      * Removes the end listener that would have been called when all child animations for a given
      * property stopped running.
      */
-    public void removeEndListenerForProperty(DynamicAnimation.ViewProperty property) {
-        mEndListenerForProperty.remove(property);
+    public void removeEndActionForProperty(DynamicAnimation.ViewProperty property) {
+        mEndActionForProperty.remove(property);
     }
 
     @Override
@@ -231,6 +324,11 @@
     }
 
     @Override
+    public void removeViewAt(int index) {
+        removeView(getChildAt(index));
+    }
+
+    @Override
     public void addTransientView(View view, int index) {
         super.addTransientView(view, index);
         mTransientViews.add(view);
@@ -304,7 +402,10 @@
 
         for (int i = 0; i < getChildCount(); i++) {
             for (DynamicAnimation.ViewProperty property : mController.getAnimatedProperties()) {
-                getAnimationAtIndex(property, i).cancel();
+                final DynamicAnimation anim = getAnimationAtIndex(property, i);
+                if (anim != null) {
+                    anim.cancel();
+                }
             }
         }
     }
@@ -316,107 +417,6 @@
         }
     }
 
-    /**
-     * Animates the property of the given child view, then runs the callback provided when the
-     * animation ends.
-     */
-    protected void animateValueForChild(
-            DynamicAnimation.ViewProperty property,
-            View view,
-            float value,
-            float startVel,
-            Runnable after) {
-        if (view != null) {
-            final SpringAnimation animation =
-                    (SpringAnimation) view.getTag(getTagIdForProperty(property));
-            if (after != null) {
-                animation.addEndListener(new OneTimeEndListener() {
-                    @Override
-                    public void onAnimationEnd(DynamicAnimation animation, boolean canceled,
-                            float value, float velocity) {
-                        super.onAnimationEnd(animation, canceled, value, velocity);
-                        after.run();
-                    }
-                });
-            }
-
-            // Set the start velocity if it's something other than the not-set value.
-            if (startVel != Float.MAX_VALUE) {
-                animation.setStartVelocity(startVel);
-            }
-
-            animation.animateToFinalPosition(value);
-        }
-    }
-
-    protected void animateValueForChild(
-            DynamicAnimation.ViewProperty property,
-            View view,
-            float value,
-            Runnable after) {
-        animateValueForChild(property, view, value, Float.MAX_VALUE, after);
-    }
-
-    protected void animateValueForChild(
-            DynamicAnimation.ViewProperty property,
-            View view,
-            float value) {
-        animateValueForChild(property, view, value, Float.MAX_VALUE, /* after */ null);
-    }
-
-    protected void animateValueForChild(
-            DynamicAnimation.ViewProperty property,
-            View view,
-            float value,
-            float startVel) {
-        animateValueForChild(property, view, value, startVel, /* after */ null);
-    }
-
-    /**
-     * Animates the property of the child at the given index to the given value, then runs the
-     * callback provided when the animation ends.
-     */
-    protected void animateValueForChildAtIndex(
-            DynamicAnimation.ViewProperty property,
-            int index,
-            float value,
-            float startVel,
-            Runnable after) {
-        animateValueForChild(property, getChildAt(index), value, startVel, after);
-    }
-
-    /** Shortcut to animate a value with a callback, but no start velocity. */
-    protected void animateValueForChildAtIndex(
-            DynamicAnimation.ViewProperty property,
-            int index,
-            float value,
-            Runnable after) {
-        animateValueForChildAtIndex(property, index, value, Float.MAX_VALUE, after);
-    }
-
-    /** Shortcut to animate a value with a start velocity, but no callback. */
-    protected void animateValueForChildAtIndex(
-            DynamicAnimation.ViewProperty property,
-            int index,
-            float value,
-            float startVel) {
-        animateValueForChildAtIndex(property, index, value, startVel, /* callback */ null);
-    }
-
-    /** Shortcut to animate a value without changing the velocity or providing a callback. */
-    protected void animateValueForChildAtIndex(
-            DynamicAnimation.ViewProperty property,
-            int index,
-            float value) {
-        animateValueForChildAtIndex(property, index, value, Float.MAX_VALUE, /* callback */ null);
-    }
-
-    /** Shortcut to animate a child view's TRANSLATION_X and TRANSLATION_Y values. */
-    protected void animatePositionForChildAtIndex(int index, float x, float y) {
-        animateValueForChildAtIndex(DynamicAnimation.TRANSLATION_X, index, x);
-        animateValueForChildAtIndex(DynamicAnimation.TRANSLATION_Y, index, y);
-    }
-
     /** Whether the first child would be left of center if translated to the given x value. */
     protected boolean isFirstChildXLeftOfCenter(float x) {
         if (getChildCount() > 0) {
@@ -562,40 +562,256 @@
         public void onAnimationEnd(
                 DynamicAnimation anim, boolean canceled, float value, float velocity) {
             if (!arePropertiesAnimating(mProperty)) {
-                if (mEndListenerForProperty.containsKey(mProperty)) {
-                    mEndListenerForProperty.get(mProperty).onAnimationEnd(anim, canceled, value,
-                            velocity);
+                if (mEndActionForProperty.containsKey(mProperty)) {
+                    mEndActionForProperty.get(mProperty).run();
                 }
             }
         }
     }
 
     /**
-     * One time end listener that waits for every animation on every given property to finish. At
-     * that point, it calls {@link #onAllAnimationsForPropertiesEnd} and then removes itself as an
-     * end listener from each property.
+     * Animator class returned by {@link PhysicsAnimationController#animationForChild}, to allow
+     * controllers to animate child views using physics animations.
+     *
+     * See docs/physics-animation-layout.md for documentation and examples.
      */
-    public abstract class OneTimeMultiplePropertyEndListener
-            implements DynamicAnimation.OnAnimationEndListener {
-        final DynamicAnimation.ViewProperty[] mViewProperties;
+    protected class PhysicsPropertyAnimator {
+        /** The view whose properties this animator animates. */
+        private View mView;
 
-        OneTimeMultiplePropertyEndListener(DynamicAnimation.ViewProperty... properties) {
-            mViewProperties = properties;
+        /** Start velocity to use for all property animations. */
+        private float mDefaultStartVelocity = 0f;
+
+        /** Start delay to use when start is called. */
+        private long mStartDelay = 0;
+
+        /** End actions to call when animations for the given property complete. */
+        private Map<DynamicAnimation.ViewProperty, Runnable[]> mEndActionsForProperty =
+                new HashMap<>();
+
+        /**
+         * Start velocities to use for TRANSLATION_X and TRANSLATION_Y, since these are often
+         * provided by VelocityTrackers and differ from each other.
+         */
+        private Map<DynamicAnimation.ViewProperty, Float> mPositionStartVelocities =
+                new HashMap<>();
+
+        /**
+         * End actions to call when both TRANSLATION_X and TRANSLATION_Y animations have completed,
+         * if {@link #position} was used to animate TRANSLATION_X and TRANSLATION_Y simultaneously.
+         */
+        private Runnable[] mPositionEndActions;
+
+        /**
+         * All of the properties that have been set and will animate when {@link #start} is called.
+         */
+        private Map<DynamicAnimation.ViewProperty, Float> mAnimatedProperties = new HashMap<>();
+
+        protected PhysicsPropertyAnimator(View view) {
+            this.mView = view;
         }
 
-        @Override
-        public void onAnimationEnd(DynamicAnimation animation, boolean canceled, float value,
-                float velocity) {
-            if (!arePropertiesAnimating(mViewProperties)) {
-                onAllAnimationsForPropertiesEnd();
+        /** Animate a property to the given value, then call the optional end actions. */
+        public PhysicsPropertyAnimator property(
+                DynamicAnimation.ViewProperty property, float value, Runnable... endActions) {
+            mAnimatedProperties.put(property, value);
+            mEndActionsForProperty.put(property, endActions);
+            return this;
+        }
 
-                for (DynamicAnimation.ViewProperty property : mViewProperties) {
-                    removeEndListenerForProperty(property);
+        /** Animate the view's alpha value to the provided value. */
+        public PhysicsPropertyAnimator alpha(float alpha, Runnable... endActions) {
+            return property(DynamicAnimation.ALPHA, alpha, endActions);
+        }
+
+        /** Set the view's alpha value to 'from', then animate it to the given value. */
+        public PhysicsPropertyAnimator alpha(float from, float to, Runnable... endActions) {
+            mView.setAlpha(from);
+            return alpha(to, endActions);
+        }
+
+        /** Animate the view's translationX value to the provided value. */
+        public PhysicsPropertyAnimator translationX(float translationX, Runnable... endActions) {
+            return property(DynamicAnimation.TRANSLATION_X, translationX, endActions);
+        }
+
+        /** Set the view's translationX value to 'from', then animate it to the given value. */
+        public PhysicsPropertyAnimator translationX(
+                float from, float to, Runnable... endActions) {
+            mView.setTranslationX(from);
+            return translationX(to, endActions);
+        }
+
+        /** Animate the view's translationY value to the provided value. */
+        public PhysicsPropertyAnimator translationY(float translationY, Runnable... endActions) {
+            return property(DynamicAnimation.TRANSLATION_Y, translationY, endActions);
+        }
+
+        /** Set the view's translationY value to 'from', then animate it to the given value. */
+        public PhysicsPropertyAnimator translationY(
+                float from, float to, Runnable... endActions) {
+            mView.setTranslationY(from);
+            return translationY(to, endActions);
+        }
+
+        /**
+         * Animate the view's translationX and translationY values, and call the end actions only
+         * once both TRANSLATION_X and TRANSLATION_Y animations have completed.
+         */
+        public PhysicsPropertyAnimator position(
+                float translationX, float translationY, Runnable... endActions) {
+            mPositionEndActions = endActions;
+            translationX(translationX);
+            return translationY(translationY);
+        }
+
+        /** Animate the view's scaleX value to the provided value. */
+        public PhysicsPropertyAnimator scaleX(float scaleX, Runnable... endActions) {
+            return property(DynamicAnimation.SCALE_X, scaleX, endActions);
+        }
+
+        /** Set the view's scaleX value to 'from', then animate it to the given value. */
+        public PhysicsPropertyAnimator scaleX(float from, float to, Runnable... endActions) {
+            mView.setScaleX(from);
+            return scaleX(to, endActions);
+        }
+
+        /** Animate the view's scaleY value to the provided value. */
+        public PhysicsPropertyAnimator scaleY(float scaleY, Runnable... endActions) {
+            return property(DynamicAnimation.SCALE_Y, scaleY, endActions);
+        }
+
+        /** Set the view's scaleY value to 'from', then animate it to the given value. */
+        public PhysicsPropertyAnimator scaleY(float from, float to, Runnable... endActions) {
+            mView.setScaleY(from);
+            return scaleY(to, endActions);
+        }
+
+        /** Set the start velocity to use for all property animations. */
+        public PhysicsPropertyAnimator withStartVelocity(float startVel) {
+            mDefaultStartVelocity = startVel;
+            return this;
+        }
+
+        /**
+         * Set the start velocities to use for TRANSLATION_X and TRANSLATION_Y animations. This
+         * overrides any value set via {@link #withStartVelocity(float)} for those properties.
+         */
+        public PhysicsPropertyAnimator withPositionStartVelocities(float velX, float velY) {
+            mPositionStartVelocities.put(DynamicAnimation.TRANSLATION_X, velX);
+            mPositionStartVelocities.put(DynamicAnimation.TRANSLATION_Y, velY);
+            return this;
+        }
+
+        /** Set a delay, in milliseconds, before kicking off the animations. */
+        public PhysicsPropertyAnimator withStartDelay(long startDelay) {
+            mStartDelay = startDelay;
+            return this;
+        }
+
+        /**
+         * Start the animations, and call the optional end actions once all animations for every
+         * animated property on every child (including chained animations) have ended.
+         */
+        public void start(Runnable... after) {
+            final Set<DynamicAnimation.ViewProperty> properties = getAnimatedProperties();
+
+            // If there are end actions, set an end listener on the layout for all the properties
+            // we're about to animate.
+            if (after != null) {
+                final DynamicAnimation.ViewProperty[] propertiesArray =
+                        properties.toArray(new DynamicAnimation.ViewProperty[0]);
+                for (Runnable callback : after) {
+                    setEndActionForMultipleProperties(callback, propertiesArray);
+                }
+            }
+
+            // If we used position-specific end actions, we'll need to listen for both TRANSLATION_X
+            // and TRANSLATION_Y animations ending, and call them once both have finished.
+            if (mPositionEndActions != null) {
+                final SpringAnimation translationXAnim =
+                        getAnimationFromView(DynamicAnimation.TRANSLATION_X, mView);
+                final SpringAnimation translationYAnim =
+                        getAnimationFromView(DynamicAnimation.TRANSLATION_Y, mView);
+                final Runnable waitForBothXAndY = () -> {
+                    if (!translationXAnim.isRunning() && !translationYAnim.isRunning()) {
+                        if (mPositionEndActions != null) {
+                            for (Runnable callback : mPositionEndActions) {
+                                callback.run();
+                            }
+                        }
+
+                        mPositionEndActions = null;
+                    }
+                };
+
+                mEndActionsForProperty.put(DynamicAnimation.TRANSLATION_X,
+                        new Runnable[]{waitForBothXAndY});
+                mEndActionsForProperty.put(DynamicAnimation.TRANSLATION_Y,
+                        new Runnable[]{waitForBothXAndY});
+            }
+
+            // Actually start the animations.
+            for (DynamicAnimation.ViewProperty property : properties) {
+                animateValueForChild(
+                        property,
+                        mView,
+                        mAnimatedProperties.get(property),
+                        mPositionStartVelocities.getOrDefault(property, mDefaultStartVelocity),
+                        mStartDelay,
+                        mEndActionsForProperty.get(property));
+            }
+
+            // Clear out the animator.
+            mAnimatedProperties.clear();
+            mPositionStartVelocities.clear();
+            mDefaultStartVelocity = 0;
+            mStartDelay = 0;
+            mEndActionsForProperty.clear();
+        }
+
+        /** Returns the set of properties that will animate once {@link #start} is called. */
+        protected Set<DynamicAnimation.ViewProperty> getAnimatedProperties() {
+            return mAnimatedProperties.keySet();
+        }
+
+        /**
+         * Animates the property of the given child view, then runs the callback provided when the
+         * animation ends.
+         */
+        protected void animateValueForChild(
+                DynamicAnimation.ViewProperty property,
+                View view,
+                float value,
+                float startVel,
+                long startDelay,
+                Runnable[] afterCallbacks) {
+            if (view != null) {
+                final SpringAnimation animation =
+                        (SpringAnimation) view.getTag(getTagIdForProperty(property));
+                if (afterCallbacks != null) {
+                    animation.addEndListener(new OneTimeEndListener() {
+                        @Override
+                        public void onAnimationEnd(DynamicAnimation animation, boolean canceled,
+                                float value, float velocity) {
+                            super.onAnimationEnd(animation, canceled, value, velocity);
+                            for (Runnable runnable : afterCallbacks) {
+                                runnable.run();
+                            }
+                        }
+                    });
+                }
+
+                if (startVel > 0) {
+                    animation.setStartVelocity(startVel);
+                }
+
+                if (startDelay > 0) {
+                    postDelayed(() -> animation.animateToFinalPosition(value), startDelay);
+                } else {
+                    animation.animateToFinalPosition(value);
                 }
             }
         }
-
-        /** Called when every animation for every property has finished. */
-        abstract void onAllAnimationsForPropertiesEnd();
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/animation/StackAnimationController.java b/packages/SystemUI/src/com/android/systemui/bubbles/animation/StackAnimationController.java
index 3c4bc72..c395031 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/animation/StackAnimationController.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/animation/StackAnimationController.java
@@ -206,12 +206,12 @@
                         .setDampingRatio(SPRING_DAMPING_RATIO),
                 /* destination */ null);
 
-        mLayout.setEndListenerForProperties(
-                (animation, canceled, value, velocity) -> {
+        mLayout.setEndActionForMultipleProperties(
+                () -> {
                     mRestingStackPosition = new PointF();
                     mRestingStackPosition.set(mStackPosition);
-                    mLayout.removeEndListenerForProperty(DynamicAnimation.TRANSLATION_X);
-                    mLayout.removeEndListenerForProperty(DynamicAnimation.TRANSLATION_Y);
+                    mLayout.removeEndActionForProperty(DynamicAnimation.TRANSLATION_X);
+                    mLayout.removeEndActionForProperty(DynamicAnimation.TRANSLATION_Y);
                 },
                 DynamicAnimation.TRANSLATION_X, DynamicAnimation.TRANSLATION_Y);
     }
@@ -292,8 +292,8 @@
         cancelStackPositionAnimation(DynamicAnimation.TRANSLATION_X);
         cancelStackPositionAnimation(DynamicAnimation.TRANSLATION_Y);
 
-        mLayout.removeEndListenerForProperty(DynamicAnimation.TRANSLATION_X);
-        mLayout.removeEndListenerForProperty(DynamicAnimation.TRANSLATION_Y);
+        mLayout.removeEndActionForProperty(DynamicAnimation.TRANSLATION_X);
+        mLayout.removeEndActionForProperty(DynamicAnimation.TRANSLATION_Y);
     }
 
     /**
@@ -441,19 +441,18 @@
 
     @Override
     void onChildRemoved(View child, int index, Runnable finishRemoval) {
-        // Animate the child out, actually removing it once its alpha is zero.
-        mLayout.animateValueForChild(DynamicAnimation.ALPHA, child, 0f, finishRemoval);
-        mLayout.animateValueForChild(DynamicAnimation.SCALE_X, child, ANIMATE_IN_STARTING_SCALE);
-        mLayout.animateValueForChild(DynamicAnimation.SCALE_Y, child, ANIMATE_IN_STARTING_SCALE);
-
         // Animate the removing view in the opposite direction of the stack.
         final float xOffset = getOffsetForChainedPropertyAnimation(DynamicAnimation.TRANSLATION_X);
-        mLayout.animateValueForChild(DynamicAnimation.TRANSLATION_X, child,
-                mStackPosition.x - (-xOffset * ANIMATE_TRANSLATION_FACTOR));
+        animationForChild(child)
+                .alpha(0f, finishRemoval /* after */)
+                .scaleX(ANIMATE_IN_STARTING_SCALE)
+                .scaleY(ANIMATE_IN_STARTING_SCALE)
+                .translationX(mStackPosition.x - (-xOffset * ANIMATE_TRANSLATION_FACTOR))
+                .start();
 
-        // Pull the top of the stack to the correct position, the chained animations will instruct
-        // any children that are out of place to animate to the correct position.
-        mLayout.animateValueForChildAtIndex(DynamicAnimation.TRANSLATION_X, 0, mStackPosition.x);
+        if (mLayout.getChildCount() > 0) {
+            animationForChildAtIndex(0).translationX(mStackPosition.x).start();
+        }
     }
 
     /** Moves the stack, without any animation, to the starting position. */
@@ -486,10 +485,12 @@
 
         if (mLayout.getChildCount() > 0) {
             property.setValue(mLayout.getChildAt(0), value);
-            mLayout.animateValueForChildAtIndex(
-                    property,
-                    /* index */ 1,
-                    value + getOffsetForChainedPropertyAnimation(property));
+
+            if (mLayout.getChildCount() > 1) {
+                animationForChildAtIndex(1)
+                        .property(property, value + getOffsetForChainedPropertyAnimation(property))
+                        .start();
+            }
         }
     }
 
@@ -520,23 +521,15 @@
     private void animateInBubble(View child) {
         child.setTranslationY(mStackPosition.y);
 
-        // Pop in the new bubble.
-        child.setScaleX(ANIMATE_IN_STARTING_SCALE);
-        child.setScaleY(ANIMATE_IN_STARTING_SCALE);
-        mLayout.animateValueForChildAtIndex(DynamicAnimation.SCALE_X, 0, 1f);
-        mLayout.animateValueForChildAtIndex(DynamicAnimation.SCALE_Y, 0, 1f);
-
-        // Fade in the new bubble.
-        child.setAlpha(0);
-        mLayout.animateValueForChildAtIndex(DynamicAnimation.ALPHA, 0, 1f);
-
-        // Start the new bubble 4x the normal offset distance in the opposite direction. We'll
-        // animate in from this position. Since the animations are chained, when the new bubble
-        // flies in from the side, it will push the other ones out of the way.
         float xOffset = getOffsetForChainedPropertyAnimation(DynamicAnimation.TRANSLATION_X);
-        child.setTranslationX(mStackPosition.x - ANIMATE_TRANSLATION_FACTOR * xOffset);
-        mLayout.animateValueForChildAtIndex(
-                DynamicAnimation.TRANSLATION_X, 0, mStackPosition.x);
+        animationForChild(child)
+                .scaleX(ANIMATE_IN_STARTING_SCALE /* from */, 1f /* to */)
+                .scaleY(ANIMATE_IN_STARTING_SCALE /* from */, 1f /* to */)
+                .alpha(0f /* from */, 1f /* to */)
+                .translationX(
+                        mStackPosition.x - ANIMATE_TRANSLATION_FACTOR * xOffset /* from */,
+                        mStackPosition.x /* to */)
+                .start();
     }
 
     /**
diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeMachine.java b/packages/SystemUI/src/com/android/systemui/doze/DozeMachine.java
index 6c4be06..c243899 100644
--- a/packages/SystemUI/src/com/android/systemui/doze/DozeMachine.java
+++ b/packages/SystemUI/src/com/android/systemui/doze/DozeMachine.java
@@ -211,7 +211,7 @@
         mDozeService.requestWakeUp();
     }
 
-    private boolean isExecutingTransition() {
+    public boolean isExecutingTransition() {
         return !mQueuedRequests.isEmpty();
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeTriggers.java b/packages/SystemUI/src/com/android/systemui/doze/DozeTriggers.java
index 031f562..7189a48 100644
--- a/packages/SystemUI/src/com/android/systemui/doze/DozeTriggers.java
+++ b/packages/SystemUI/src/com/android/systemui/doze/DozeTriggers.java
@@ -198,6 +198,14 @@
     }
 
     private void onProximityFar(boolean far) {
+        // Proximity checks are asynchronous and the user might have interacted with the phone
+        // when a new event is arriving. This means that a state transition might have happened
+        // and the proximity check is now obsolete.
+        if (mMachine.isExecutingTransition()) {
+            Log.w(TAG, "onProximityFar called during transition. Ignoring sensor response.");
+            return;
+        }
+
         final boolean near = !far;
         final DozeMachine.State state = mMachine.getState();
         final boolean paused = (state == DozeMachine.State.DOZE_AOD_PAUSED);
diff --git a/packages/SystemUI/src/com/android/systemui/media/MediaProjectionPermissionActivity.java b/packages/SystemUI/src/com/android/systemui/media/MediaProjectionPermissionActivity.java
index 9f0f53e..3a0534d2 100644
--- a/packages/SystemUI/src/com/android/systemui/media/MediaProjectionPermissionActivity.java
+++ b/packages/SystemUI/src/com/android/systemui/media/MediaProjectionPermissionActivity.java
@@ -38,8 +38,10 @@
 import android.text.TextUtils;
 import android.text.style.StyleSpan;
 import android.util.Log;
+import android.view.View;
 import android.view.Window;
 import android.view.WindowManager;
+import android.widget.TextView;
 
 import com.android.systemui.R;
 
@@ -133,9 +135,12 @@
 
         String dialogTitle = getString(R.string.media_projection_dialog_title, appName);
 
+        View dialogTitleView = View.inflate(this, R.layout.media_projection_dialog_title, null);
+        TextView titleText = (TextView) dialogTitleView.findViewById(R.id.dialog_title);
+        titleText.setText(dialogTitle);
+
         mDialog = new AlertDialog.Builder(this)
-                .setTitle(dialogTitle)
-                .setIcon(R.drawable.ic_media_projection_permission)
+                .setCustomTitle(dialogTitleView)
                 .setMessage(message)
                 .setPositiveButton(R.string.media_projection_action_text, this)
                 .setNegativeButton(android.R.string.cancel, this)
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSFooterImpl.java b/packages/SystemUI/src/com/android/systemui/qs/QSFooterImpl.java
index 0ae8f6c..10eacba 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QSFooterImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QSFooterImpl.java
@@ -87,7 +87,6 @@
 
     private boolean mListening;
 
-    private View mDivider;
     protected MultiUserSwitch mMultiUserSwitch;
     private ImageView mMultiUserAvatar;
 
@@ -133,7 +132,6 @@
     @Override
     protected void onFinishInflate() {
         super.onFinishInflate();
-        mDivider = findViewById(R.id.qs_footer_divider);
         mEdit = findViewById(android.R.id.edit);
         mEdit.setOnClickListener(view ->
                 mActivityStarter.postQSRunnableDismissingKeyguard(() ->
@@ -218,7 +216,6 @@
     @Nullable
     private TouchAnimator createFooterAnimator() {
         return new TouchAnimator.Builder()
-                .addFloat(mDivider, "alpha", 0, 1)
                 .addFloat(mActionsContainer, "alpha", 0, 1)
                 .addFloat(mEditContainer, "alpha", 0, 1)
                 .addFloat(mDragHandle, "alpha", 1, 0, 0)
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QuickStatusBarHeader.java b/packages/SystemUI/src/com/android/systemui/qs/QuickStatusBarHeader.java
index c897b9c..d789821 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QuickStatusBarHeader.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QuickStatusBarHeader.java
@@ -395,14 +395,13 @@
 
     private void updateStatusIconAlphaAnimator() {
         mStatusIconsAlphaAnimator = new TouchAnimator.Builder()
-                .addFloat(mQuickQsStatusIcons, "alpha", 1, 0)
+                .addFloat(mQuickQsStatusIcons, "alpha", 1, 0, 0)
                 .build();
     }
 
     private void updateHeaderTextContainerAlphaAnimator() {
         mHeaderTextContainerAlphaAnimator = new TouchAnimator.Builder()
-                .addFloat(mHeaderTextContainerView, "alpha", 0, 1)
-                .setStartDelay(.5f)
+                .addFloat(mHeaderTextContainerView, "alpha", 0, 0, 1)
                 .build();
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardStatusBarView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardStatusBarView.java
index c8ce392..4c50d07 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardStatusBarView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardStatusBarView.java
@@ -468,6 +468,11 @@
     }
 
     @Override
+    public void onDensityOrFontScaleChanged() {
+        loadDimens();
+    }
+
+    @Override
     public void onOverlayChanged() {
         mCarrierLabel.setTextAppearance(
                 Utils.getThemeAttr(mContext, com.android.internal.R.attr.textAppearanceSmall));
@@ -514,6 +519,8 @@
             return;
         }
         mDozing = dozing;
+        setClipChildren(!dozing);
+        setClipToPadding(!dozing);
         updateVisibilities();
     }
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/ExpandedAnimationControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/ExpandedAnimationControllerTest.java
index b8add89..cd84805 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/ExpandedAnimationControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/ExpandedAnimationControllerTest.java
@@ -43,7 +43,6 @@
     @Spy
     private ExpandedAnimationController mExpandedController =
             new ExpandedAnimationController(new Point(500, 1000) /* displaySize */);
-
     private int mStackOffset;
     private float mBubblePadding;
     private float mBubbleSize;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/PhysicsAnimationLayoutTest.java b/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/PhysicsAnimationLayoutTest.java
index a50919b..38a90f7 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/PhysicsAnimationLayoutTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/PhysicsAnimationLayoutTest.java
@@ -20,12 +20,11 @@
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
 import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyBoolean;
-import static org.mockito.ArgumentMatchers.anyFloat;
 import static org.mockito.ArgumentMatchers.anyInt;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.inOrder;
 import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
 
 import android.os.SystemClock;
 import android.testing.AndroidTestingRunner;
@@ -68,7 +67,8 @@
         // offset, and don't actually remove views immediately (since most implementations will wait
         // to animate child views out before actually removing them).
         mTestableController.setAnimatedProperties(Sets.newHashSet(
-                DynamicAnimation.TRANSLATION_X, DynamicAnimation.TRANSLATION_Y));
+                DynamicAnimation.TRANSLATION_X,
+                DynamicAnimation.TRANSLATION_Y));
         mTestableController.setChainedProperties(Sets.newHashSet(DynamicAnimation.TRANSLATION_X));
         mTestableController.setOffsetForProperty(
                 DynamicAnimation.TRANSLATION_X, TEST_TRANSLATION_X_OFFSET);
@@ -126,11 +126,11 @@
 
         // Animate the first child's translation X.
         final CountDownLatch animLatch = new CountDownLatch(1);
-        mLayout.animateValueForChildAtIndex(
-                DynamicAnimation.TRANSLATION_X,
-                0,
-                100,
-                animLatch::countDown);
+
+        mTestableController
+                .animationForChildAtIndex(0)
+                .translationX(100)
+                .start(animLatch::countDown);
         animLatch.await(1, TimeUnit.SECONDS);
 
         // Ensure that the first view has been translated, but not the second one.
@@ -140,60 +140,50 @@
 
     @Test
     public void testUpdateValueXChained() throws InterruptedException {
-        mLayout.setController(mTestableController);
-        addOneMoreThanRenderLimitBubbles();
         testChainedTranslationAnimations();
     }
 
     @Test
-    public void testSetEndListeners() throws InterruptedException {
+    public void testSetEndActions() throws InterruptedException {
         mLayout.setController(mTestableController);
         addOneMoreThanRenderLimitBubbles();
         mTestableController.setChainedProperties(Sets.newHashSet());
 
         final CountDownLatch xLatch = new CountDownLatch(1);
-        OneTimeEndListener xEndListener = Mockito.spy(new OneTimeEndListener() {
+        Runnable xEndAction = Mockito.spy(new Runnable() {
+
             @Override
-            public void onAnimationEnd(DynamicAnimation animation, boolean canceled, float value,
-                    float velocity) {
-                super.onAnimationEnd(animation, canceled, value, velocity);
+            public void run() {
                 xLatch.countDown();
             }
         });
 
         final CountDownLatch yLatch = new CountDownLatch(1);
-        final OneTimeEndListener yEndListener = Mockito.spy(new OneTimeEndListener() {
+        Runnable yEndAction = Mockito.spy(new Runnable() {
+
             @Override
-            public void onAnimationEnd(DynamicAnimation animation, boolean canceled, float value,
-                    float velocity) {
-                super.onAnimationEnd(animation, canceled, value, velocity);
+            public void run() {
                 yLatch.countDown();
             }
         });
 
         // Set end listeners for both x and y.
-        mLayout.setEndListenerForProperty(xEndListener, DynamicAnimation.TRANSLATION_X);
-        mLayout.setEndListenerForProperty(yEndListener, DynamicAnimation.TRANSLATION_Y);
+        mLayout.setEndActionForProperty(xEndAction, DynamicAnimation.TRANSLATION_X);
+        mLayout.setEndActionForProperty(yEndAction, DynamicAnimation.TRANSLATION_Y);
 
         // Animate x, and wait for it to finish.
-        mLayout.animateValueForChildAtIndex(
-                DynamicAnimation.TRANSLATION_X,
-                0,
-                100);
+        mTestableController.animationForChildAtIndex(0)
+                .translationX(100)
+                .start();
+
         xLatch.await();
         yLatch.await(1, TimeUnit.SECONDS);
 
         // Make sure the x end listener was called only one time, and the y listener was never
         // called since we didn't animate y. Wait 1 second after the original animation end trigger
         // to make sure it doesn't get called again.
-        Mockito.verify(xEndListener, Mockito.after(1000).times(1))
-                .onAnimationEnd(
-                        any(),
-                        eq(false),
-                        eq(100f),
-                        anyFloat());
-        Mockito.verify(yEndListener, Mockito.after(1000).never())
-                .onAnimationEnd(any(), anyBoolean(), anyFloat(), anyFloat());
+        Mockito.verify(xEndAction, Mockito.after(1000).times(1)).run();
+        Mockito.verify(yEndAction, Mockito.after(1000).never()).run();
     }
 
     @Test
@@ -203,39 +193,31 @@
         mTestableController.setChainedProperties(Sets.newHashSet());
 
         final CountDownLatch xLatch = new CountDownLatch(1);
-        OneTimeEndListener xEndListener = Mockito.spy(new OneTimeEndListener() {
+        Runnable xEndListener = Mockito.spy(new Runnable() {
+
             @Override
-            public void onAnimationEnd(DynamicAnimation animation, boolean canceled, float value,
-                    float velocity) {
-                super.onAnimationEnd(animation, canceled, value, velocity);
+            public void run() {
                 xLatch.countDown();
             }
         });
 
         // Set the end listener.
-        mLayout.setEndListenerForProperty(xEndListener, DynamicAnimation.TRANSLATION_X);
+        mLayout.setEndActionForProperty(xEndListener, DynamicAnimation.TRANSLATION_X);
 
         // Animate x, and wait for it to finish.
-        mLayout.animateValueForChildAtIndex(
-                DynamicAnimation.TRANSLATION_X,
-                0,
-                100);
+        mTestableController.animationForChildAtIndex(0)
+                .translationX(100)
+                .start();
         xLatch.await();
 
         InOrder endListenerCalls = inOrder(xEndListener);
-        endListenerCalls.verify(xEndListener, Mockito.times(1))
-                .onAnimationEnd(
-                        any(),
-                        eq(false),
-                        eq(100f),
-                        anyFloat());
+        endListenerCalls.verify(xEndListener, Mockito.times(1)).run();
 
         // Animate X again, remove the end listener.
-        mLayout.animateValueForChildAtIndex(
-                DynamicAnimation.TRANSLATION_X,
-                0,
-                1000);
-        mLayout.removeEndListenerForProperty(DynamicAnimation.TRANSLATION_X);
+        mTestableController.animationForChildAtIndex(0)
+                .translationX(1000)
+                .start();
+        mLayout.removeEndActionForProperty(DynamicAnimation.TRANSLATION_X);
         xLatch.await(1, TimeUnit.SECONDS);
 
         // Make sure the end listener was not called.
@@ -261,10 +243,9 @@
         secondController.setRemoveImmediately(true);
 
         mLayout.setController(secondController);
-        mLayout.animateValueForChildAtIndex(
-                DynamicAnimation.SCALE_X,
-                0,
-                1.5f);
+        mTestableController.animationForChildAtIndex(0)
+                .scaleX(1.5f)
+                .start();
 
         waitForPropertyAnimations(DynamicAnimation.SCALE_X);
 
@@ -285,10 +266,9 @@
                 .getOffsetForChainedPropertyAnimation(eq(DynamicAnimation.SCALE_X));
 
         mLayout.setController(mTestableController);
-        mLayout.animateValueForChildAtIndex(
-                DynamicAnimation.TRANSLATION_X,
-                0,
-                100f);
+        mTestableController.animationForChildAtIndex(0)
+                .translationX(100f)
+                .start();
 
         waitForPropertyAnimations(DynamicAnimation.TRANSLATION_X);
 
@@ -308,10 +288,9 @@
         assertFalse(mLayout.arePropertiesAnimating(
                 DynamicAnimation.TRANSLATION_X, DynamicAnimation.TRANSLATION_Y));
 
-        mLayout.animateValueForChildAtIndex(
-                DynamicAnimation.TRANSLATION_X,
-                0,
-                100);
+        mTestableController.animationForChildAtIndex(0)
+                .translationX(100f)
+                .start();
 
         // Wait for the animations to get underway.
         SystemClock.sleep(50);
@@ -330,14 +309,9 @@
         mLayout.setController(mTestableController);
         addOneMoreThanRenderLimitBubbles();
 
-        mLayout.animateValueForChildAtIndex(
-                DynamicAnimation.TRANSLATION_X,
-                0,
-                1000);
-        mLayout.animateValueForChildAtIndex(
-                DynamicAnimation.TRANSLATION_Y,
-                0,
-                1000);
+        mTestableController.animationForChildAtIndex(0)
+                .position(1000, 1000)
+                .start();
 
         mLayout.cancelAllAnimations();
 
@@ -367,13 +341,15 @@
 
     /** Standard test of chained translation animations. */
     private void testChainedTranslationAnimations() throws InterruptedException {
+        mLayout.setController(mTestableController);
+        addOneMoreThanRenderLimitBubbles();
+
         assertEquals(0, mLayout.getChildAt(0).getTranslationX(), .1f);
         assertEquals(0, mLayout.getChildAt(1).getTranslationX(), .1f);
 
-        mLayout.animateValueForChildAtIndex(
-                DynamicAnimation.TRANSLATION_X,
-                0,
-                100);
+        mTestableController.animationForChildAtIndex(0)
+                .translationX(100f)
+                .start();
 
         waitForPropertyAnimations(DynamicAnimation.TRANSLATION_X);
 
@@ -392,10 +368,9 @@
         assertEquals(0, mLayout.getChildAt(1).getTranslationY(), .1f);
 
         // Animate the first child's Y translation.
-        mLayout.animateValueForChildAtIndex(
-                DynamicAnimation.TRANSLATION_Y,
-                0,
-                100);
+        mTestableController.animationForChildAtIndex(0)
+                .translationY(100f)
+                .start();
 
         waitForPropertyAnimations(DynamicAnimation.TRANSLATION_Y);
 
@@ -405,6 +380,75 @@
         assertEquals(0, mLayout.getChildAt(1).getTranslationY(), .1f);
     }
 
+    @Test
+    public void testPhysicsAnimator() throws InterruptedException {
+        mLayout.setController(mTestableController);
+        addOneMoreThanRenderLimitBubbles();
+
+        Runnable afterAll = Mockito.mock(Runnable.class);
+        Runnable after = Mockito.spy(new Runnable() {
+            int mCallCount = 0;
+
+            @Override
+            public void run() {
+                // Make sure that if only one of the animations has finished, we didn't already call
+                // afterAll.
+                if (mCallCount == 1) {
+                    Mockito.verifyNoMoreInteractions(afterAll);
+                }
+            }
+        });
+
+        // Animate from x = 7 to x = 100, and from y = 100 to 7 = 200, calling 'after' after each
+        // property's animation completes, then call afterAll when they're all complete.
+        mTestableController.animationForChildAtIndex(0)
+                .translationX(7, 100, after)
+                .translationY(100, 200, after)
+                .start(afterAll);
+
+        // We should have immediately set the 'from' values.
+        assertEquals(7, mViews.get(0).getTranslationX(), .01f);
+        assertEquals(100, mViews.get(0).getTranslationY(), .01f);
+
+        waitForPropertyAnimations(
+                DynamicAnimation.TRANSLATION_X,
+                DynamicAnimation.TRANSLATION_Y);
+
+        // We should have called the after callback twice, and afterAll once. We verify in the
+        // mocked callback that afterAll isn't called before both finish.
+        Mockito.verify(after, times(2)).run();
+        Mockito.verify(afterAll).run();
+
+        // Make sure we actually animated the views.
+        assertEquals(100, mViews.get(0).getTranslationX(), .01f);
+        assertEquals(200, mViews.get(0).getTranslationY(), .01f);
+    }
+
+    @Test
+    public void testAnimationsForChildrenFromIndex() throws InterruptedException {
+        // Don't chain since we're going to invoke each animation independently.
+        mTestableController.setChainedProperties(new HashSet<>());
+
+        mLayout.setController(mTestableController);
+
+        addOneMoreThanRenderLimitBubbles();
+
+        Runnable allEnd = Mockito.mock(Runnable.class);
+
+        mTestableController.animationsForChildrenFromIndex(
+                1, (index, animation) -> animation.translationX((index - 1) * 50))
+            .startAll(allEnd);
+
+        waitForPropertyAnimations(DynamicAnimation.TRANSLATION_X);
+
+        assertEquals(0, mViews.get(0).getTranslationX(), .1f);
+        assertEquals(0, mViews.get(1).getTranslationX(), .1f);
+        assertEquals(50, mViews.get(2).getTranslationX(), .1f);
+        assertEquals(100, mViews.get(3).getTranslationX(), .1f);
+
+        Mockito.verify(allEnd, times(1)).run();
+    }
+
     /**
      * Animation controller with configuration methods whose return values can be set by individual
      * tests.
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/PhysicsAnimationLayoutTestCase.java b/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/PhysicsAnimationLayoutTestCase.java
index d94b669..9fce092 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/PhysicsAnimationLayoutTestCase.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/PhysicsAnimationLayoutTestCase.java
@@ -28,6 +28,7 @@
 import android.widget.FrameLayout;
 
 import androidx.dynamicanimation.animation.DynamicAnimation;
+import androidx.dynamicanimation.animation.SpringForce;
 
 import com.android.systemui.R;
 import com.android.systemui.SysuiTestCase;
@@ -38,6 +39,7 @@
 
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Set;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 
@@ -113,25 +115,17 @@
             throws InterruptedException {
         final CountDownLatch animLatch = new CountDownLatch(properties.length);
         for (DynamicAnimation.ViewProperty property : properties) {
-            mLayout.setTestEndListenerForProperty(new OneTimeEndListener() {
-                @Override
-                public void onAnimationEnd(DynamicAnimation animation, boolean canceled,
-                        float value,
-                        float velocity) {
-                    super.onAnimationEnd(animation, canceled, value, velocity);
-                    animLatch.countDown();
-                }
-            }, property);
+            mLayout.setTestEndActionForProperty(animLatch::countDown, property);
         }
-        animLatch.await(1, TimeUnit.SECONDS);
+
+        animLatch.await(2, TimeUnit.SECONDS);
     }
 
-    /** Uses a latch to wait for the message queue to finish. */
+    /** Uses a latch to wait for the main thread message queue to finish. */
     void waitForLayoutMessageQueue() throws InterruptedException {
-        // Wait for layout, then the view should be actually removed.
         CountDownLatch layoutLatch = new CountDownLatch(1);
         mMainThreadHandler.post(layoutLatch::countDown);
-        layoutLatch.await(1, TimeUnit.SECONDS);
+        layoutLatch.await(2, TimeUnit.SECONDS);
     }
 
     /**
@@ -145,8 +139,9 @@
 
         @Override
         public void setController(PhysicsAnimationController controller) {
-            mMainThreadHandler.post(() -> super.setController(controller));
-            waitForMessageQueueAndIgnoreIfInterrupted();
+            runOnMainThreadAndBlock(
+                    () -> super.setController(
+                            new MainThreadAnimationControllerWrapper(controller)));
         }
 
         @Override
@@ -160,59 +155,139 @@
         }
 
         @Override
-        protected void animateValueForChildAtIndex(DynamicAnimation.ViewProperty property,
-                int index, float value, float startVel, Runnable after) {
-            mMainThreadHandler.post(() ->
-                    super.animateValueForChildAtIndex(property, index, value, startVel, after));
-        }
-
-        @Override
         public WindowInsets getRootWindowInsets() {
             return mWindowInsets;
         }
 
         @Override
-        public void removeView(View view) {
-            mMainThreadHandler.post(() ->
-                    super.removeView(view));
-            waitForMessageQueueAndIgnoreIfInterrupted();
+        public void addView(View child, int index) {
+            child.setTag(R.id.physics_animator_tag, new TestablePhysicsPropertyAnimator(child));
+            super.addView(child, index);
         }
 
         @Override
         public void addView(View child, int index, ViewGroup.LayoutParams params) {
-            mMainThreadHandler.post(() ->
-                    super.addView(child, index, params));
-            waitForMessageQueueAndIgnoreIfInterrupted();
+            child.setTag(R.id.physics_animator_tag, new TestablePhysicsPropertyAnimator(child));
+            super.addView(child, index, params);
         }
 
         /**
-         * Wait for the queue but just catch and print the exception if interrupted, since we can't
-         * just add the exception to the overridden methods' signatures.
+         * Sets an end action that will be called after the 'real' end action that was already set.
          */
-        private void waitForMessageQueueAndIgnoreIfInterrupted() {
-            try {
-                waitForLayoutMessageQueue();
-            } catch (InterruptedException e) {
-                e.printStackTrace();
+        private void setTestEndActionForProperty(
+                Runnable action, DynamicAnimation.ViewProperty property) {
+            final Runnable realEndAction = mEndActionForProperty.get(property);
+
+            setEndActionForProperty(() -> {
+                if (realEndAction != null) {
+                    realEndAction.run();
+                }
+
+                action.run();
+            }, property);
+        }
+
+        /** PhysicsPropertyAnimator that posts its animations to the main thread. */
+        protected class TestablePhysicsPropertyAnimator extends PhysicsPropertyAnimator {
+            public TestablePhysicsPropertyAnimator(View view) {
+                super(view);
+            }
+
+            @Override
+            protected void animateValueForChild(DynamicAnimation.ViewProperty property, View view,
+                    float value, float startVel, long startDelay, Runnable[] afterCallbacks) {
+                mMainThreadHandler.post(() -> super.animateValueForChild(
+                        property, view, value, startVel, startDelay, afterCallbacks));
             }
         }
 
         /**
-         * Sets an end listener that will be called after the 'real' end listener that was already
-         * set.
+         * Wrapper around an animation controller that dispatches methods that could start
+         * animations to the main thread.
          */
-        private void setTestEndListenerForProperty(DynamicAnimation.OnAnimationEndListener listener,
-                DynamicAnimation.ViewProperty property) {
-            final DynamicAnimation.OnAnimationEndListener realEndListener =
-                    mEndListenerForProperty.get(property);
+        protected class MainThreadAnimationControllerWrapper extends PhysicsAnimationController {
 
-            setEndListenerForProperty((animation, canceled, value, velocity) -> {
-                if (realEndListener != null) {
-                    realEndListener.onAnimationEnd(animation, canceled, value, velocity);
+            private final PhysicsAnimationController mWrappedController;
+
+            protected MainThreadAnimationControllerWrapper(PhysicsAnimationController controller) {
+                mWrappedController = controller;
+            }
+
+            @Override
+            protected void setLayout(PhysicsAnimationLayout layout) {
+                mWrappedController.setLayout(layout);
+            }
+
+            @Override
+            protected PhysicsAnimationLayout getLayout() {
+                return mWrappedController.getLayout();
+            }
+
+            @Override
+            Set<DynamicAnimation.ViewProperty> getAnimatedProperties() {
+                return mWrappedController.getAnimatedProperties();
+            }
+
+            @Override
+            int getNextAnimationInChain(DynamicAnimation.ViewProperty property, int index) {
+                return mWrappedController.getNextAnimationInChain(property, index);
+            }
+
+            @Override
+            float getOffsetForChainedPropertyAnimation(DynamicAnimation.ViewProperty property) {
+                return mWrappedController.getOffsetForChainedPropertyAnimation(property);
+            }
+
+            @Override
+            SpringForce getSpringForce(DynamicAnimation.ViewProperty property, View view) {
+                return mWrappedController.getSpringForce(property, view);
+            }
+
+            @Override
+            void onChildAdded(View child, int index) {
+                runOnMainThreadAndBlock(() -> mWrappedController.onChildAdded(child, index));
+            }
+
+            @Override
+            void onChildRemoved(View child, int index, Runnable finishRemoval) {
+                runOnMainThreadAndBlock(
+                        () -> mWrappedController.onChildRemoved(child, index, finishRemoval));
+            }
+
+            @Override
+            protected void setChildVisibility(View child, int index, int visibility) {
+                mWrappedController.setChildVisibility(child, index, visibility);
+            }
+
+            @Override
+            protected PhysicsPropertyAnimator animationForChild(View child) {
+                PhysicsPropertyAnimator animator =
+                        (PhysicsPropertyAnimator) child.getTag(R.id.physics_animator_tag);
+
+                if (!(animator instanceof TestablePhysicsPropertyAnimator)) {
+                    animator = new TestablePhysicsPropertyAnimator(child);
+                    child.setTag(R.id.physics_animator_tag, animator);
                 }
 
-                listener.onAnimationEnd(animation, canceled, value, velocity);
-            }, property);
+                return animator;
+            }
+        }
+    }
+
+    /**
+     * Posts the given Runnable on the main thread, and blocks the calling thread until it's run.
+     */
+    private void runOnMainThreadAndBlock(Runnable action) {
+        final CountDownLatch latch = new CountDownLatch(1);
+        mMainThreadHandler.post(() -> {
+            action.run();
+            latch.countDown();
+        });
+
+        try {
+            latch.await(5, TimeUnit.SECONDS);
+        } catch (InterruptedException e) {
+            e.printStackTrace();
         }
     }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/StackAnimationControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/StackAnimationControllerTest.java
index 2ee73f3..096f205 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/StackAnimationControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/StackAnimationControllerTest.java
@@ -209,6 +209,9 @@
         final PointF prevStackPos = mStackController.getStackPosition();
 
         mLayout.removeAllViews();
+
+        waitForLayoutMessageQueue();
+
         mLayout.addView(new FrameLayout(getContext()));
 
         waitForLayoutMessageQueue();
diff --git a/services/appprediction/java/com/android/server/appprediction/AppPredictionManagerService.java b/services/appprediction/java/com/android/server/appprediction/AppPredictionManagerService.java
index 833eaa0..6bb5370 100644
--- a/services/appprediction/java/com/android/server/appprediction/AppPredictionManagerService.java
+++ b/services/appprediction/java/com/android/server/appprediction/AppPredictionManagerService.java
@@ -94,10 +94,10 @@
         }
 
         @Override
-        public void notifyLocationShown(@NonNull AppPredictionSessionId sessionId,
+        public void notifyLaunchLocationShown(@NonNull AppPredictionSessionId sessionId,
                 @NonNull String launchLocation, @NonNull ParceledListSlice targetIds) {
             runForUserLocked((service) ->
-                    service.notifyLocationShownLocked(sessionId, launchLocation, targetIds));
+                    service.notifyLaunchLocationShownLocked(sessionId, launchLocation, targetIds));
         }
 
         @Override
diff --git a/services/appprediction/java/com/android/server/appprediction/AppPredictionPerUserService.java b/services/appprediction/java/com/android/server/appprediction/AppPredictionPerUserService.java
index 24d592c..430abf5 100644
--- a/services/appprediction/java/com/android/server/appprediction/AppPredictionPerUserService.java
+++ b/services/appprediction/java/com/android/server/appprediction/AppPredictionPerUserService.java
@@ -111,11 +111,11 @@
      * Records when a launch location is shown.
      */
     @GuardedBy("mLock")
-    public void notifyLocationShownLocked(@NonNull AppPredictionSessionId sessionId,
+    public void notifyLaunchLocationShownLocked(@NonNull AppPredictionSessionId sessionId,
             @NonNull String launchLocation, @NonNull ParceledListSlice targetIds) {
         final RemoteAppPredictionService service = getRemoteServiceLocked();
         if (service != null) {
-            service.notifyLocationShown(sessionId, launchLocation, targetIds);
+            service.notifyLaunchLocationShown(sessionId, launchLocation, targetIds);
         }
     }
 
diff --git a/services/appprediction/java/com/android/server/appprediction/RemoteAppPredictionService.java b/services/appprediction/java/com/android/server/appprediction/RemoteAppPredictionService.java
index 922b327..21088e4 100644
--- a/services/appprediction/java/com/android/server/appprediction/RemoteAppPredictionService.java
+++ b/services/appprediction/java/com/android/server/appprediction/RemoteAppPredictionService.java
@@ -85,9 +85,10 @@
     /**
      * Records when a launch location is shown.
      */
-    public void notifyLocationShown(@NonNull AppPredictionSessionId sessionId,
+    public void notifyLaunchLocationShown(@NonNull AppPredictionSessionId sessionId,
             @NonNull String launchLocation, @NonNull ParceledListSlice targetIds) {
-        scheduleAsyncRequest((s) -> s.notifyLocationShown(sessionId, launchLocation, targetIds));
+        scheduleAsyncRequest((s)
+                -> s.notifyLaunchLocationShown(sessionId, launchLocation, targetIds));
     }
 
     /**
diff --git a/services/core/java/com/android/server/ConnectivityService.java b/services/core/java/com/android/server/ConnectivityService.java
index ec5987e..21c1e12 100644
--- a/services/core/java/com/android/server/ConnectivityService.java
+++ b/services/core/java/com/android/server/ConnectivityService.java
@@ -2564,7 +2564,12 @@
                                     || (nai.networkMisc.acceptPartialConnectivity
                                             && nai.partialConnectivity);
                     // Once a network is determined to have partial connectivity, it cannot
-                    // go back to full connectivity without a disconnect.
+                    // go back to full connectivity without a disconnect. This is because
+                    // NetworkMonitor can only communicate either PARTIAL_CONNECTIVITY or VALID,
+                    // but not both.
+                    // TODO: Provide multi-testResult to improve the communication between
+                    // ConnectivityService and NetworkMonitor, so that ConnectivityService could
+                    // know the real status of network.
                     final boolean partialConnectivityChanged =
                             (partialConnectivity && !nai.partialConnectivity);
 
@@ -3470,8 +3475,12 @@
         return mMultinetworkPolicyTracker.getAvoidBadWifi();
     }
 
-    @Override
-    public boolean getAvoidBadWifi() {
+    /**
+     * Return whether the device should maintain continuous, working connectivity by switching away
+     * from WiFi networks having no connectivity.
+     * @see MultinetworkPolicyTracker#getAvoidBadWifi()
+     */
+    public boolean shouldAvoidBadWifi() {
         if (!checkNetworkStackPermission()) {
             throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
         }
@@ -3581,9 +3590,7 @@
         // NetworkMonitor detects the network is partial connectivity. Need to change the design to
         // popup the notification immediately when the network is partial connectivity.
         if (nai.partialConnectivity) {
-            // Treat PARTIAL_CONNECTIVITY as NO_INTERNET temporary until Settings has been updated.
-            // TODO: Need to change back to PARTIAL_CONNECTIVITY when Settings part is merged.
-            showNetworkNotification(nai, NotificationType.NO_INTERNET);
+            showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
         } else {
             showNetworkNotification(nai, NotificationType.NO_INTERNET);
         }
diff --git a/services/core/java/com/android/server/StorageManagerService.java b/services/core/java/com/android/server/StorageManagerService.java
index 5bd0b89..05214824 100644
--- a/services/core/java/com/android/server/StorageManagerService.java
+++ b/services/core/java/com/android/server/StorageManagerService.java
@@ -3862,6 +3862,14 @@
                         case "jp.naver.line.android": // b/124767356
                         case "com.mxtech.videoplayer.ad": // b/124531483
                         case "com.whatsapp": // b/124766614
+                        case "com.maxmpz.audioplayer": // b/127886230
+                        case "com.estrongs.android.pop": // b/127926473
+                        case "com.roidapp.photogrid": // b/128269119
+                        case "com.cleanmaster.mguard": // b/128384413
+                        case "com.skype.raider": // b/128487044
+                        case "org.telegram.messenger": // b/128652960
+                        case "com.jrtstudio.AnotherMusicPlayer": // b/129084562
+                        case "ak.alizandro.smartaudiobookplayer": // b/129084042
                             return Zygote.MOUNT_EXTERNAL_LEGACY;
                     }
                 }
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index 97cc756..a1f2ac6 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -5121,6 +5121,7 @@
                                 String data, Bundle extras, boolean ordered,
                                 boolean sticky, int sendingUser) {
                             synchronized (ActivityManagerService.this) {
+                                mOomAdjuster.mAppCompact.compactAllSystem();
                                 requestPssAllProcsLocked(SystemClock.uptimeMillis(), true, false);
                             }
                         }
@@ -8614,6 +8615,10 @@
         synchronized (this) {
             final long now = SystemClock.uptimeMillis();
             final long timeSinceLastIdle = now - mLastIdleTime;
+
+            // Compact all non-zygote processes to freshen up the page cache.
+            mOomAdjuster.mAppCompact.compactAllSystem();
+
             final long lowRamSinceLastIdle = getLowRamTimeSinceIdle(now);
             mLastIdleTime = now;
             mLowRamTimeSinceLastIdle = 0;
diff --git a/services/core/java/com/android/server/am/AppCompactor.java b/services/core/java/com/android/server/am/AppCompactor.java
index 9216343..f58fb95 100644
--- a/services/core/java/com/android/server/am/AppCompactor.java
+++ b/services/core/java/com/android/server/am/AppCompactor.java
@@ -51,6 +51,8 @@
     @VisibleForTesting static final String KEY_COMPACT_THROTTLE_2 = "compact_throttle_2";
     @VisibleForTesting static final String KEY_COMPACT_THROTTLE_3 = "compact_throttle_3";
     @VisibleForTesting static final String KEY_COMPACT_THROTTLE_4 = "compact_throttle_4";
+    @VisibleForTesting static final String KEY_COMPACT_THROTTLE_5 = "compact_throttle_5";
+    @VisibleForTesting static final String KEY_COMPACT_THROTTLE_6 = "compact_throttle_6";
     @VisibleForTesting static final String KEY_COMPACT_STATSD_SAMPLE_RATE =
             "compact_statsd_sample_rate";
 
@@ -73,6 +75,8 @@
     @VisibleForTesting static final long DEFAULT_COMPACT_THROTTLE_2 = 10_000;
     @VisibleForTesting static final long DEFAULT_COMPACT_THROTTLE_3 = 500;
     @VisibleForTesting static final long DEFAULT_COMPACT_THROTTLE_4 = 10_000;
+    @VisibleForTesting static final long DEFAULT_COMPACT_THROTTLE_5 = 10 * 60 * 1000;
+    @VisibleForTesting static final long DEFAULT_COMPACT_THROTTLE_6 = 10 * 60 * 1000;
     // The sampling rate to push app compaction events into statsd for upload.
     @VisibleForTesting static final float DEFAULT_STATSD_SAMPLE_RATE = 0.1f;
 
@@ -85,7 +89,10 @@
     // Handler constants.
     static final int COMPACT_PROCESS_SOME = 1;
     static final int COMPACT_PROCESS_FULL = 2;
+    static final int COMPACT_PROCESS_PERSISTENT = 3;
+    static final int COMPACT_PROCESS_BFGS = 4;
     static final int COMPACT_PROCESS_MSG = 1;
+    static final int COMPACT_SYSTEM_MSG = 2;
 
     /**
      * This thread must be moved to the system background cpuset.
@@ -142,6 +149,10 @@
     @GuardedBy("mPhenotypeFlagLock")
     @VisibleForTesting volatile long mCompactThrottleFullFull = DEFAULT_COMPACT_THROTTLE_4;
     @GuardedBy("mPhenotypeFlagLock")
+    @VisibleForTesting volatile long mCompactThrottleBFGS = DEFAULT_COMPACT_THROTTLE_5;
+    @GuardedBy("mPhenotypeFlagLock")
+    @VisibleForTesting volatile long mCompactThrottlePersistent = DEFAULT_COMPACT_THROTTLE_6;
+    @GuardedBy("mPhenotypeFlagLock")
     private volatile boolean mUseCompaction = DEFAULT_USE_COMPACTION;
 
     private final Random mRandom = new Random();
@@ -224,6 +235,46 @@
 
     }
 
+    @GuardedBy("mAm")
+    void compactAppPersistent(ProcessRecord app) {
+        app.reqCompactAction = COMPACT_PROCESS_PERSISTENT;
+        mPendingCompactionProcesses.add(app);
+        mCompactionHandler.sendMessage(
+                mCompactionHandler.obtainMessage(
+                    COMPACT_PROCESS_MSG, app.curAdj, app.setProcState));
+    }
+
+    @GuardedBy("mAm")
+    boolean shouldCompactPersistent(ProcessRecord app, long now) {
+        return (app.lastCompactTime == 0
+                || (now - app.lastCompactTime) > mCompactThrottlePersistent);
+    }
+
+    @GuardedBy("mAm")
+    void compactAppBfgs(ProcessRecord app) {
+        app.reqCompactAction = COMPACT_PROCESS_BFGS;
+        mPendingCompactionProcesses.add(app);
+        mCompactionHandler.sendMessage(
+                mCompactionHandler.obtainMessage(
+                    COMPACT_PROCESS_MSG, app.curAdj, app.setProcState));
+    }
+
+    @GuardedBy("mAm")
+    boolean shouldCompactBFGS(ProcessRecord app, long now) {
+        return (app.lastCompactTime == 0
+                || (now - app.lastCompactTime) > mCompactThrottleBFGS);
+    }
+
+    @GuardedBy("mAm")
+    void compactAllSystem() {
+        if (mUseCompaction) {
+            mCompactionHandler.sendMessage(mCompactionHandler.obtainMessage(
+                                              COMPACT_SYSTEM_MSG));
+        }
+    }
+
+    private native void compactSystem();
+
     /**
      * Reads the flag value from DeviceConfig to determine whether app compaction
      * should be enabled, and starts/stops the compaction thread as needed.
@@ -265,10 +316,18 @@
         String throttleFullFullFlag =
                 DeviceConfig.getProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
                     KEY_COMPACT_THROTTLE_4);
+        String throttleBFGSFlag =
+                DeviceConfig.getProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+                    KEY_COMPACT_THROTTLE_5);
+        String throttlePersistentFlag =
+                DeviceConfig.getProperty(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+                    KEY_COMPACT_THROTTLE_6);
 
         if (TextUtils.isEmpty(throttleSomeSomeFlag) || TextUtils.isEmpty(throttleSomeFullFlag)
                 || TextUtils.isEmpty(throttleFullSomeFlag)
-                || TextUtils.isEmpty(throttleFullFullFlag)) {
+                || TextUtils.isEmpty(throttleFullFullFlag)
+                || TextUtils.isEmpty(throttleBFGSFlag)
+                || TextUtils.isEmpty(throttlePersistentFlag)) {
             // Set defaults for all if any are not set.
             useThrottleDefaults = true;
         } else {
@@ -277,6 +336,8 @@
                 mCompactThrottleSomeFull = Integer.parseInt(throttleSomeFullFlag);
                 mCompactThrottleFullSome = Integer.parseInt(throttleFullSomeFlag);
                 mCompactThrottleFullFull = Integer.parseInt(throttleFullFullFlag);
+                mCompactThrottleBFGS = Integer.parseInt(throttleBFGSFlag);
+                mCompactThrottlePersistent = Integer.parseInt(throttlePersistentFlag);
             } catch (NumberFormatException e) {
                 useThrottleDefaults = true;
             }
@@ -287,6 +348,8 @@
             mCompactThrottleSomeFull = DEFAULT_COMPACT_THROTTLE_2;
             mCompactThrottleFullSome = DEFAULT_COMPACT_THROTTLE_3;
             mCompactThrottleFullFull = DEFAULT_COMPACT_THROTTLE_4;
+            mCompactThrottleBFGS = DEFAULT_COMPACT_THROTTLE_5;
+            mCompactThrottlePersistent = DEFAULT_COMPACT_THROTTLE_6;
         }
     }
 
@@ -332,14 +395,19 @@
                     synchronized (mAm) {
                         proc = mPendingCompactionProcesses.remove(0);
 
+                        pendingAction = proc.reqCompactAction;
+
                         // don't compact if the process has returned to perceptible
-                        if (proc.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
+                        // and this is only a cached/home/prev compaction
+                        if ((pendingAction == COMPACT_PROCESS_SOME
+                                || pendingAction == COMPACT_PROCESS_FULL)
+                                && (proc.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ)) {
                             return;
                         }
 
                         pid = proc.pid;
                         name = proc.processName;
-                        pendingAction = proc.reqCompactAction;
+
                         lastCompactAction = proc.lastCompactAction;
                         lastCompactTime = proc.lastCompactTime;
                     }
@@ -356,31 +424,49 @@
                     // Note that we explicitly don't take mPhenotypeFlagLock here as the flags
                     // should very seldom change, and taking the risk of using the wrong action is
                     // preferable to taking the lock for every single compaction action.
-                    if (pendingAction == COMPACT_PROCESS_SOME) {
-                        if ((lastCompactAction == COMPACT_PROCESS_SOME
-                                  && (start - lastCompactTime < mCompactThrottleSomeSome))
-                                  || (lastCompactAction == COMPACT_PROCESS_FULL
-                                      && (start - lastCompactTime
-                                          < mCompactThrottleSomeFull))) {
-                            return;
-                        }
-                    } else {
-                        if ((lastCompactAction == COMPACT_PROCESS_SOME
-                                  && (start - lastCompactTime < mCompactThrottleFullSome))
-                                  || (lastCompactAction == COMPACT_PROCESS_FULL
-                                      && (start - lastCompactTime
-                                          < mCompactThrottleFullFull))) {
-                            return;
+                    if (lastCompactTime != 0) {
+                        if (pendingAction == COMPACT_PROCESS_SOME) {
+                            if ((lastCompactAction == COMPACT_PROCESS_SOME
+                                    && (start - lastCompactTime < mCompactThrottleSomeSome))
+                                    || (lastCompactAction == COMPACT_PROCESS_FULL
+                                        && (start - lastCompactTime
+                                                < mCompactThrottleSomeFull))) {
+                                return;
+                            }
+                        } else if (pendingAction == COMPACT_PROCESS_FULL) {
+                            if ((lastCompactAction == COMPACT_PROCESS_SOME
+                                    && (start - lastCompactTime < mCompactThrottleFullSome))
+                                    || (lastCompactAction == COMPACT_PROCESS_FULL
+                                        && (start - lastCompactTime
+                                                < mCompactThrottleFullFull))) {
+                                return;
+                            }
+                        } else if (pendingAction == COMPACT_PROCESS_PERSISTENT) {
+                            if (start - lastCompactTime < mCompactThrottlePersistent) {
+                                return;
+                            }
+                        } else if (pendingAction == COMPACT_PROCESS_BFGS) {
+                            if (start - lastCompactTime < mCompactThrottleBFGS) {
+                                return;
+                            }
                         }
                     }
-
-                    if (pendingAction == COMPACT_PROCESS_SOME) {
-                        action = mCompactActionSome;
-                    } else {
-                        action = mCompactActionFull;
+                    switch (pendingAction) {
+                        case COMPACT_PROCESS_SOME:
+                            action = mCompactActionSome;
+                            break;
+                        // For the time being, treat these as equivalent.
+                        case COMPACT_PROCESS_FULL:
+                        case COMPACT_PROCESS_PERSISTENT:
+                        case COMPACT_PROCESS_BFGS:
+                            action = mCompactActionFull;
+                            break;
+                        default:
+                            action = COMPACT_ACTION_NONE;
+                            break;
                     }
 
-                    if (action.equals(COMPACT_ACTION_NONE)) {
+                    if (COMPACT_ACTION_NONE.equals(action)) {
                         return;
                     }
 
@@ -422,6 +508,13 @@
                         // nothing to do, presumably the process died
                         Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                     }
+                    break;
+                }
+                case COMPACT_SYSTEM_MSG: {
+                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "compactSystem");
+                    compactSystem();
+                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
+                    break;
                 }
             }
         }
diff --git a/services/core/java/com/android/server/am/BatteryStatsService.java b/services/core/java/com/android/server/am/BatteryStatsService.java
index 4d5cb8c..f86ba27 100644
--- a/services/core/java/com/android/server/am/BatteryStatsService.java
+++ b/services/core/java/com/android/server/am/BatteryStatsService.java
@@ -754,7 +754,7 @@
     }
 
     public void noteStartAudio(int uid) {
-        enforceCallingPermission();
+        enforceSelfOrCallingPermission(uid);
         synchronized (mStats) {
             mStats.noteAudioOnLocked(uid);
             StatsLog.write_non_chained(StatsLog.AUDIO_STATE_CHANGED, uid, null,
@@ -763,7 +763,7 @@
     }
 
     public void noteStopAudio(int uid) {
-        enforceCallingPermission();
+        enforceSelfOrCallingPermission(uid);
         synchronized (mStats) {
             mStats.noteAudioOffLocked(uid);
             StatsLog.write_non_chained(StatsLog.AUDIO_STATE_CHANGED, uid, null,
@@ -772,7 +772,7 @@
     }
 
     public void noteStartVideo(int uid) {
-        enforceCallingPermission();
+        enforceSelfOrCallingPermission(uid);
         synchronized (mStats) {
             mStats.noteVideoOnLocked(uid);
             StatsLog.write_non_chained(StatsLog.MEDIA_CODEC_STATE_CHANGED, uid, null,
@@ -781,7 +781,7 @@
     }
 
     public void noteStopVideo(int uid) {
-        enforceCallingPermission();
+        enforceSelfOrCallingPermission(uid);
         synchronized (mStats) {
             mStats.noteVideoOffLocked(uid);
             StatsLog.write_non_chained(StatsLog.MEDIA_CODEC_STATE_CHANGED, uid,
@@ -1182,6 +1182,13 @@
                 Binder.getCallingPid(), Binder.getCallingUid(), null);
     }
 
+    private void enforceSelfOrCallingPermission(int uid) {
+        if (Binder.getCallingUid() == uid) {
+            return;
+        }
+        enforceCallingPermission();
+    }
+
     final class WakeupReasonThread extends Thread {
         private static final int MAX_REASON_SIZE = 512;
         private CharsetDecoder mDecoder;
diff --git a/services/core/java/com/android/server/am/OomAdjuster.java b/services/core/java/com/android/server/am/OomAdjuster.java
index aa03de1..c1b9a20 100644
--- a/services/core/java/com/android/server/am/OomAdjuster.java
+++ b/services/core/java/com/android/server/am/OomAdjuster.java
@@ -1686,9 +1686,10 @@
 
         int changes = 0;
 
-        if (app.curAdj != app.setAdj) {
-            // don't compact during bootup
-            if (mAppCompact.useCompaction() && mService.mBooted) {
+        // don't compact during bootup
+        if (mAppCompact.useCompaction() && mService.mBooted) {
+            // Cached and prev/home compaction
+            if (app.curAdj != app.setAdj) {
                 // Perform a minor compaction when a perceptible app becomes the prev/home app
                 // Perform a major compaction when any app enters cached
                 // reminder: here, setAdj is previous state, curAdj is upcoming state
@@ -1702,7 +1703,23 @@
                         && app.curAdj <= ProcessList.CACHED_APP_MAX_ADJ) {
                     mAppCompact.compactAppFull(app);
                 }
+            } else if (mService.mWakefulness != PowerManagerInternal.WAKEFULNESS_AWAKE
+                    && app.setAdj < ProcessList.FOREGROUND_APP_ADJ
+                    // Because these can fire independent of oom_adj/procstate changes, we need
+                    // to throttle the actual dispatch of these requests in addition to the
+                    // processing of the requests. As a result, there is throttling both here
+                    // and in AppCompactor.
+                    && mAppCompact.shouldCompactPersistent(app, now)) {
+                mAppCompact.compactAppPersistent(app);
+            } else if (mService.mWakefulness != PowerManagerInternal.WAKEFULNESS_AWAKE
+                    && app.getCurProcState()
+                        == ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
+                    && mAppCompact.shouldCompactBFGS(app, now)) {
+                mAppCompact.compactAppBfgs(app);
             }
+        }
+
+        if (app.curAdj != app.setAdj) {
             ProcessList.setOomAdj(app.pid, app.uid, app.curAdj);
             if (DEBUG_SWITCH || DEBUG_OOM_ADJ || mService.mCurOomAdjUid == app.info.uid) {
                 String msg = "Set " + app.pid + " " + app.processName + " adj "
diff --git a/services/core/java/com/android/server/locksettings/LockSettingsService.java b/services/core/java/com/android/server/locksettings/LockSettingsService.java
index 0c5fb79..3e134b2 100644
--- a/services/core/java/com/android/server/locksettings/LockSettingsService.java
+++ b/services/core/java/com/android/server/locksettings/LockSettingsService.java
@@ -323,8 +323,8 @@
             }
             Arrays.fill(newPasswordChars, '\u0000');
             final int quality = DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC;
-            setLockCredentialInternal(newPassword, CREDENTIAL_TYPE_PASSWORD,
-                    managedUserPassword, quality, managedUserId);
+            setLockCredentialInternal(newPassword, CREDENTIAL_TYPE_PASSWORD, managedUserPassword,
+                    quality, managedUserId, false);
             // We store a private credential for the managed user that's unlocked by the primary
             // account holder's credential. As such, the user will never be prompted to enter this
             // password directly, so we always store a password.
@@ -1302,12 +1302,14 @@
                     if (profilePasswordMap != null && profilePasswordMap.containsKey(managedUserId)) {
                         setLockCredentialInternal(null, CREDENTIAL_TYPE_NONE,
                                 profilePasswordMap.get(managedUserId),
-                                DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, managedUserId);
+                                DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, managedUserId,
+                                false);
                     } else {
                         Slog.wtf(TAG, "clear tied profile challenges, but no password supplied.");
                         // Supplying null here would lead to untrusted credential change
                         setLockCredentialInternal(null, CREDENTIAL_TYPE_NONE, null,
-                                DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, managedUserId);
+                                DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, managedUserId,
+                                true);
                     }
                     mStorage.removeChildProfileLock(managedUserId);
                     removeKeystoreProfileKey(managedUserId);
@@ -1330,8 +1332,8 @@
     // should call setLockCredentialInternal.
     @Override
     public void setLockCredential(byte[] credential, int type,
-            byte[] savedCredential, int requestedQuality, int userId)
-            throws RemoteException {
+            byte[] savedCredential, int requestedQuality, int userId,
+            boolean allowUntrustedChange) throws RemoteException {
 
         if (!mLockPatternUtils.hasSecureLockScreen()) {
             throw new UnsupportedOperationException(
@@ -1339,7 +1341,8 @@
         }
         checkWritePermission(userId);
         synchronized (mSeparateChallengeLock) {
-            setLockCredentialInternal(credential, type, savedCredential, requestedQuality, userId);
+            setLockCredentialInternal(credential, type, savedCredential, requestedQuality, userId,
+                    allowUntrustedChange);
             setSeparateProfileChallengeEnabledLocked(userId, true, null);
             notifyPasswordChanged(userId);
         }
@@ -1347,7 +1350,8 @@
     }
 
     private void setLockCredentialInternal(byte[] credential, @CredentialType int credentialType,
-            byte[] savedCredential, int requestedQuality, int userId) throws RemoteException {
+            byte[] savedCredential, int requestedQuality, int userId,
+            boolean allowUntrustedChange) throws RemoteException {
         // Normalize savedCredential and credential such that empty string is always represented
         // as null.
         if (savedCredential == null || savedCredential.length == 0) {
@@ -1359,7 +1363,7 @@
         synchronized (mSpManager) {
             if (isSyntheticPasswordBasedCredentialLocked(userId)) {
                 spBasedSetLockCredentialInternalLocked(credential, credentialType, savedCredential,
-                        requestedQuality, userId);
+                        requestedQuality, userId, allowUntrustedChange);
                 return;
             }
         }
@@ -1410,7 +1414,7 @@
                 initializeSyntheticPasswordLocked(currentHandle.hash, savedCredential,
                         currentHandle.type, requestedQuality, userId);
                 spBasedSetLockCredentialInternalLocked(credential, credentialType, savedCredential,
-                        requestedQuality, userId);
+                        requestedQuality, userId, allowUntrustedChange);
                 return;
             }
         }
@@ -1705,7 +1709,7 @@
             mStrongAuth.reportSuccessfulStrongAuthUnlock(userId);
             if (shouldReEnrollBaseZero) {
                 setLockCredentialInternal(credential, storedHash.type, credentialToVerify,
-                        DevicePolicyManager.PASSWORD_QUALITY_SOMETHING, userId);
+                        DevicePolicyManager.PASSWORD_QUALITY_SOMETHING, userId, false);
             }
         }
 
@@ -1796,7 +1800,7 @@
                         storedHash.type == CREDENTIAL_TYPE_PATTERN
                                 ? DevicePolicyManager.PASSWORD_QUALITY_SOMETHING
                                 : DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC
-                                /* TODO(roosa): keep the same password quality */, userId);
+                                /* TODO(roosa): keep the same password quality */, userId, false);
                 if (!hasChallenge) {
                     notifyActivePasswordMetricsAvailable(storedHash.type, credential, userId);
                     // Use credentials to create recoverable keystore snapshot.
@@ -1841,7 +1845,7 @@
                     /* TODO(roosa): keep the same password quality */;
             if (shouldReEnroll) {
                 setLockCredentialInternal(credential, storedHash.type, credential,
-                        reEnrollQuality, userId);
+                        reEnrollQuality, userId, false);
             } else {
                 // Now that we've cleared of all required GK migration, let's do the final
                 // migration to synthetic password.
@@ -2544,7 +2548,8 @@
 
     @GuardedBy("mSpManager")
     private void spBasedSetLockCredentialInternalLocked(byte[] credential, int credentialType,
-            byte[] savedCredential, int requestedQuality, int userId) throws RemoteException {
+            byte[] savedCredential, int requestedQuality, int userId,
+            boolean allowUntrustedChange) throws RemoteException {
         if (DEBUG) Slog.d(TAG, "spBasedSetLockCredentialInternalLocked: user=" + userId);
         if (isManagedProfileWithUnifiedLock(userId)) {
             // get credential from keystore when managed profile has unified lock
@@ -2565,27 +2570,31 @@
         VerifyCredentialResponse response = authResult.gkResponse;
         AuthenticationToken auth = authResult.authToken;
 
-        // If existing credential is provided, then it must match.
+        // If existing credential is provided, the existing credential must match.
         if (savedCredential != null && auth == null) {
-            throw new RemoteException("Failed to enroll " +
-                    (credentialType == CREDENTIAL_TYPE_PASSWORD ? "password" : "pattern"));
+            throw new IllegalStateException("Failed to enroll "
+                    + (credentialType == CREDENTIAL_TYPE_PASSWORD
+                    ? "password" : "pattern"));
         }
-
         boolean untrustedReset = false;
         if (auth != null) {
             onAuthTokenKnownForUser(userId, auth);
-        } else if (response != null
-                && response.getResponseCode() == VerifyCredentialResponse.RESPONSE_ERROR) {
+        } else if (response == null) {
+            throw new IllegalStateException("Password change failed.");
+        } else if (response.getResponseCode() == VerifyCredentialResponse.RESPONSE_ERROR) {
             // We are performing an untrusted credential change, by DevicePolicyManager or other
             // internal callers that don't provide the existing credential
             Slog.w(TAG, "Untrusted credential change invoked");
             // Try to get a cached auth token, so we can keep SP unchanged.
             auth = mSpCache.get(userId);
+            if (!allowUntrustedChange) {
+                throw new IllegalStateException("Untrusted credential change was invoked but it was"
+                        + " not allowed. This is likely a bug. Auth token is null: "
+                        + Boolean.toString(auth == null));
+            }
             untrustedReset = true;
-        } else /* response == null || responseCode == VerifyCredentialResponse.RESPONSE_RETRY */ {
-            Slog.w(TAG, "spBasedSetLockCredentialInternalLocked: " +
-                    (response != null ? "rate limit exceeded" : "failed"));
-            return;
+        } else /* responseCode == VerifyCredentialResponse.RESPONSE_RETRY */ {
+            throw new IllegalStateException("Rate limit exceeded, so password was not changed.");
         }
 
         if (auth != null) {
diff --git a/services/core/java/com/android/server/media/projection/MediaProjectionManagerService.java b/services/core/java/com/android/server/media/projection/MediaProjectionManagerService.java
index 3872523..1f1ba20 100644
--- a/services/core/java/com/android/server/media/projection/MediaProjectionManagerService.java
+++ b/services/core/java/com/android/server/media/projection/MediaProjectionManagerService.java
@@ -63,6 +63,7 @@
  */
 public final class MediaProjectionManagerService extends SystemService
         implements Watchdog.Monitor {
+    private static final boolean REQUIRE_FG_SERVICE_FOR_PROJECTION = false;
     private static final String TAG = "MediaProjectionManagerService";
 
     private final Object mLock = new Object(); // Protects the list of media projections
@@ -100,21 +101,23 @@
                 false /*allowIsolated*/);
         mMediaRouter.addCallback(MediaRouter.ROUTE_TYPE_REMOTE_DISPLAY, mMediaRouterCallback,
                 MediaRouter.CALLBACK_FLAG_PASSIVE_DISCOVERY);
-        mActivityManagerInternal.registerProcessObserver(new IProcessObserver.Stub() {
-            @Override
-            public void onForegroundActivitiesChanged(int pid, int uid, boolean fg) {
-            }
+        if (REQUIRE_FG_SERVICE_FOR_PROJECTION) {
+            mActivityManagerInternal.registerProcessObserver(new IProcessObserver.Stub() {
+                @Override
+                public void onForegroundActivitiesChanged(int pid, int uid, boolean fg) {
+                }
 
-            @Override
-            public void onForegroundServicesChanged(int pid, int uid, int serviceTypes) {
-                MediaProjectionManagerService.this.handleForegroundServicesChanged(pid, uid,
-                        serviceTypes);
-            }
+                @Override
+                public void onForegroundServicesChanged(int pid, int uid, int serviceTypes) {
+                    MediaProjectionManagerService.this.handleForegroundServicesChanged(pid, uid,
+                            serviceTypes);
+                }
 
-            @Override
-            public void onProcessDied(int pid, int uid) {
-            }
-        });
+                @Override
+                public void onProcessDied(int pid, int uid) {
+                }
+            });
+        }
     }
 
     @Override
@@ -462,7 +465,8 @@
                     return;
                 }
 
-                if (targetSdkVersion >= Build.VERSION_CODES.Q
+                if (REQUIRE_FG_SERVICE_FOR_PROJECTION
+                        && targetSdkVersion >= Build.VERSION_CODES.Q
                         && !mActivityManagerInternal.hasRunningForegroundService(
                                 uid, ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION)) {
                     throw new SecurityException("Media projections require a foreground service"
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index ec2ff28..c17b6c8 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -4979,7 +4979,9 @@
                         PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
                         false  /* throwIfPermNotDeclared*/)
                 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
-                        == PERMISSION_GRANTED;
+                        == PERMISSION_GRANTED
+                || mContext.checkCallingOrSelfPermission(
+                        Manifest.permission.ACCESS_SHARED_LIBRARIES) == PERMISSION_GRANTED;
 
         synchronized (mPackages) {
             List<SharedLibraryInfo> result = null;
@@ -5029,6 +5031,76 @@
         }
     }
 
+    @Nullable
+    @Override
+    public ParceledListSlice<SharedLibraryInfo> getDeclaredSharedLibraries(
+            @NonNull String packageName, int flags, @NonNull int userId) {
+        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_SHARED_LIBRARIES,
+                "getDeclaredSharedLibraries");
+        int callingUid = Binder.getCallingUid();
+        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
+                true /* requireFullPermission */, false /* checkShell */,
+                "getDeclaredSharedLibraries");
+
+        Preconditions.checkNotNull(packageName, "packageName cannot be null");
+        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
+        if (!sUserManager.exists(userId)) {
+            return null;
+        }
+
+        if (getInstantAppPackageName(callingUid) != null) {
+            return null;
+        }
+
+        synchronized (mPackages) {
+            List<SharedLibraryInfo> result = null;
+
+            int libraryCount = mSharedLibraries.size();
+            for (int i = 0; i < libraryCount; i++) {
+                LongSparseArray<SharedLibraryInfo> versionedLibrary = mSharedLibraries.valueAt(i);
+                if (versionedLibrary == null) {
+                    continue;
+                }
+
+                int versionCount = versionedLibrary.size();
+                for (int j = 0; j < versionCount; j++) {
+                    SharedLibraryInfo libraryInfo = versionedLibrary.valueAt(j);
+
+                    VersionedPackage declaringPackage = libraryInfo.getDeclaringPackage();
+                    if (!Objects.equals(declaringPackage.getPackageName(), packageName)) {
+                        continue;
+                    }
+
+                    long identity = Binder.clearCallingIdentity();
+                    try {
+                        PackageInfo packageInfo = getPackageInfoVersioned(declaringPackage, flags
+                                | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
+                        if (packageInfo == null) {
+                            continue;
+                        }
+                    } finally {
+                        Binder.restoreCallingIdentity(identity);
+                    }
+
+                    SharedLibraryInfo resultLibraryInfo = new SharedLibraryInfo(
+                            libraryInfo.getPath(), libraryInfo.getPackageName(),
+                            libraryInfo.getAllCodePaths(), libraryInfo.getName(),
+                            libraryInfo.getLongVersion(), libraryInfo.getType(),
+                            libraryInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(
+                            libraryInfo, flags, userId), libraryInfo.getDependencies() == null
+                            ? null : new ArrayList<>(libraryInfo.getDependencies()));
+
+                    if (result == null) {
+                        result = new ArrayList<>();
+                    }
+                    result.add(resultLibraryInfo);
+                }
+            }
+
+            return result != null ? new ParceledListSlice<>(result) : null;
+        }
+    }
+
     @GuardedBy("mPackages")
     private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
             SharedLibraryInfo libInfo, int flags, int userId) {
diff --git a/services/core/java/com/android/server/policy/PhoneWindowManager.java b/services/core/java/com/android/server/policy/PhoneWindowManager.java
index 7b16043..55af357 100644
--- a/services/core/java/com/android/server/policy/PhoneWindowManager.java
+++ b/services/core/java/com/android/server/policy/PhoneWindowManager.java
@@ -5214,13 +5214,15 @@
     private VibrationEffect getVibrationEffect(int effectId) {
         long[] pattern;
         switch (effectId) {
-            case HapticFeedbackConstants.CLOCK_TICK:
             case HapticFeedbackConstants.CONTEXT_CLICK:
                 return VibrationEffect.get(VibrationEffect.EFFECT_TICK);
             case HapticFeedbackConstants.TEXT_HANDLE_MOVE:
                 if (!mHapticTextHandleEnabled) {
                     return null;
                 }
+                // fallthrough
+            case HapticFeedbackConstants.CLOCK_TICK:
+                return VibrationEffect.get(VibrationEffect.EFFECT_TEXTURE_TICK);
             case HapticFeedbackConstants.KEYBOARD_RELEASE:
             case HapticFeedbackConstants.VIRTUAL_KEY_RELEASE:
             case HapticFeedbackConstants.ENTRY_BUMP:
diff --git a/services/core/java/com/android/server/wm/KeyguardController.java b/services/core/java/com/android/server/wm/KeyguardController.java
index 72a1a2f..432d75e 100644
--- a/services/core/java/com/android/server/wm/KeyguardController.java
+++ b/services/core/java/com/android/server/wm/KeyguardController.java
@@ -95,13 +95,15 @@
     }
 
     /**
-     * @return {@code true} if 1) Keyguard is showing, not going away, and not being occluded on the
-     *         given display, or 2) AOD is showing, {@code false} otherwise.
+     * @return {@code true} for default display when AOD is showing. Otherwise, same as
+     *         {@link #isKeyguardOrAodShowing(int)}
      * TODO(b/125198167): Replace isKeyguardOrAodShowing() by this logic.
      */
     boolean isKeyguardUnoccludedOrAodShowing(int displayId) {
-        return (mKeyguardShowing && !mKeyguardGoingAway && !isDisplayOccluded(displayId))
-                || mAodShowing;
+        if (displayId == DEFAULT_DISPLAY && mAodShowing) {
+            return true;
+        }
+        return isKeyguardOrAodShowing(displayId);
     }
 
     /**
diff --git a/services/core/java/com/android/server/wm/RecentsAnimationController.java b/services/core/java/com/android/server/wm/RecentsAnimationController.java
index 26df832..3813669 100644
--- a/services/core/java/com/android/server/wm/RecentsAnimationController.java
+++ b/services/core/java/com/android/server/wm/RecentsAnimationController.java
@@ -208,7 +208,10 @@
             try {
                 synchronized (mService.getWindowManagerLock()) {
                     for (int i = mPendingAnimations.size() - 1; i >= 0; i--) {
-                        mPendingAnimations.get(i).mTask.setCanAffectSystemUiFlags(behindSystemBars);
+                        final Task task = mPendingAnimations.get(i).mTask;
+                        if (task.getActivityType() != mTargetActivityType) {
+                            task.setCanAffectSystemUiFlags(behindSystemBars);
+                        }
                     }
                     mService.mWindowPlacerLocked.requestTraversal();
                 }
diff --git a/services/core/jni/Android.bp b/services/core/jni/Android.bp
index 00b815a..a7423ea 100644
--- a/services/core/jni/Android.bp
+++ b/services/core/jni/Android.bp
@@ -50,6 +50,7 @@
         "com_android_server_VibratorService.cpp",
         "com_android_server_PersistentDataBlockService.cpp",
         "com_android_server_GraphicsStatsService.cpp",
+        "com_android_server_am_AppCompactor.cpp",
         "onload.cpp",
     ],
 
diff --git a/services/core/jni/com_android_server_VibratorService.cpp b/services/core/jni/com_android_server_VibratorService.cpp
index 63dca62..d5fbd2b 100644
--- a/services/core/jni/com_android_server_VibratorService.cpp
+++ b/services/core/jni/com_android_server_VibratorService.cpp
@@ -96,7 +96,7 @@
     }
     R val = static_cast<R>(effect);
     auto iter = hardware::hidl_enum_range<R>();
-    return val >= *iter.begin() && val < *std::prev(iter.end());
+    return val >= *iter.begin() && val <= *std::prev(iter.end());
 }
 
 static void vibratorInit(JNIEnv /* env */, jobject /* clazz */)
@@ -170,6 +170,9 @@
     } else if (isValidEffect<V1_2::Effect>(effect)) {
         ret = halCall(&V1_2::IVibrator::perform_1_2, static_cast<V1_2::Effect>(effect),
                            effectStrength, callback);
+    } else if (isValidEffect<V1_3::Effect>(effect)) {
+        ret = halCall(&V1_3::IVibrator::perform_1_3, static_cast<V1_3::Effect>(effect),
+                           effectStrength, callback);
     } else {
         ALOGW("Unable to perform haptic effect, invalid effect ID (%" PRId32 ")",
                 static_cast<int32_t>(effect));
diff --git a/services/core/jni/com_android_server_am_AppCompactor.cpp b/services/core/jni/com_android_server_am_AppCompactor.cpp
new file mode 100644
index 0000000..de6aa8b
--- /dev/null
+++ b/services/core/jni/com_android_server_am_AppCompactor.cpp
@@ -0,0 +1,88 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "AppCompactor"
+//#define LOG_NDEBUG 0
+
+#include <dirent.h>
+#include <stddef.h>
+#include <stdio.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <android-base/stringprintf.h>
+#include <android-base/file.h>
+
+#include <nativehelper/JNIHelp.h>
+#include <android_runtime/AndroidRuntime.h>
+#include <jni.h>
+
+using android::base::StringPrintf;
+using android::base::WriteStringToFile;
+
+namespace android {
+
+// This performs per-process reclaim on all processes belonging to non-app UIDs.
+// For the most part, these are non-zygote processes like Treble HALs, but it
+// also includes zygote-derived processes that run in system UIDs, like bluetooth
+// or potentially some mainline modules. The only process that should definitely
+// not be compacted is system_server, since compacting system_server around the
+// time of BOOT_COMPLETE could result in perceptible issues.
+static void com_android_server_am_AppCompactor_compactSystem(JNIEnv *, jobject) {
+    std::unique_ptr<DIR, decltype(&closedir)> proc(opendir("/proc"), closedir);
+    struct dirent* current;
+    while ((current = readdir(proc.get()))) {
+        if (current->d_type != DT_DIR) {
+            continue;
+        }
+
+        // don't compact system_server, rely on persistent compaction during screen off
+        // in order to avoid mmap_sem-related stalls
+        if (atoi(current->d_name) == getpid()) {
+            continue;
+        }
+
+        std::string status_name = StringPrintf("/proc/%s/status", current->d_name);
+        struct stat status_info;
+
+        if (stat(status_name.c_str(), &status_info) != 0) {
+            // must be some other directory that isn't a pid
+            continue;
+        }
+
+        // android.os.Process.FIRST_APPLICATION_UID
+        if (status_info.st_uid >= 10000) {
+            continue;
+        }
+
+        std::string reclaim_path = StringPrintf("/proc/%s/reclaim", current->d_name);
+        WriteStringToFile(std::string("all"), reclaim_path);
+    }
+}
+
+static const JNINativeMethod sMethods[] = {
+    /* name, signature, funcPtr */
+    {"compactSystem", "()V", (void*)com_android_server_am_AppCompactor_compactSystem},
+};
+
+int register_android_server_am_AppCompactor(JNIEnv* env)
+{
+    return jniRegisterNativeMethods(env, "com/android/server/am/AppCompactor",
+                                    sMethods, NELEM(sMethods));
+}
+
+}
diff --git a/services/core/jni/onload.cpp b/services/core/jni/onload.cpp
index 5ffed03..2cfaebf 100644
--- a/services/core/jni/onload.cpp
+++ b/services/core/jni/onload.cpp
@@ -54,6 +54,7 @@
 int register_android_hardware_display_DisplayViewport(JNIEnv* env);
 int register_android_server_net_NetworkStatsService(JNIEnv* env);
 int register_android_server_security_VerityUtils(JNIEnv* env);
+int register_android_server_am_AppCompactor(JNIEnv* env);
 };
 
 using namespace android;
@@ -101,5 +102,6 @@
     register_android_hardware_display_DisplayViewport(env);
     register_android_server_net_NetworkStatsService(env);
     register_android_server_security_VerityUtils(env);
+    register_android_server_am_AppCompactor(env);
     return JNI_VERSION_1_4;
 }
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
index 2d01471..4ff5d61 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
@@ -5133,11 +5133,14 @@
         final boolean result;
         try {
             if (token == null) {
+                // This is the legacy reset password for DPM. Here we want to be able to override
+                // the old device password without necessarily knowing it.
                 if (!TextUtils.isEmpty(password)) {
                     mLockPatternUtils.saveLockPassword(password.getBytes(), null, quality,
-                            userHandle);
+                            userHandle, /*allowUntrustedChange */true);
                 } else {
-                    mLockPatternUtils.clearLock(null, userHandle);
+                    mLockPatternUtils.clearLock(null, userHandle,
+                            /*allowUntrustedChange */ true);
                 }
                 result = true;
             } else {
diff --git a/services/net/Android.bp b/services/net/Android.bp
index 486d15d..9e1d44b 100644
--- a/services/net/Android.bp
+++ b/services/net/Android.bp
@@ -1,3 +1,61 @@
+// AIDL interfaces between the core system and the networking mainline module.
+aidl_interface {
+    name: "ipmemorystore-aidl-interfaces",
+    local_include_dir: "java",
+    srcs: [
+        // TODO: Define and use a filegroup for these files, since they're also used in
+        // networkstack-aidl-interfaces. This does not appear to work at the moment.
+        "java/android/net/IIpMemoryStore.aidl",
+        "java/android/net/IIpMemoryStoreCallbacks.aidl",
+        "java/android/net/ipmemorystore/**/*.aidl",
+    ],
+    backend: {
+        ndk: {
+            enabled: false,
+        },
+        cpp: {
+            enabled: false,
+        },
+    },
+    api_dir: "aidl/networkstack",
+}
+
+aidl_interface {
+    name: "networkstack-aidl-interfaces",
+    local_include_dir: "java",
+    include_dirs: ["frameworks/base/core/java"],  // For framework parcelables.
+    srcs: [
+        "java/android/net/ApfCapabilitiesParcelable.aidl",
+        "java/android/net/DhcpResultsParcelable.aidl",
+        "java/android/net/IIpMemoryStore.aidl",
+        "java/android/net/IIpMemoryStoreCallbacks.aidl",
+        "java/android/net/INetworkMonitor.aidl",
+        "java/android/net/INetworkMonitorCallbacks.aidl",
+        "java/android/net/INetworkStackConnector.aidl",
+        "java/android/net/INetworkStackStatusCallback.aidl",
+        "java/android/net/InitialConfigurationParcelable.aidl",
+        "java/android/net/PrivateDnsConfigParcel.aidl",
+        "java/android/net/ProvisioningConfigurationParcelable.aidl",
+        "java/android/net/StaticIpConfigurationParcelable.aidl",
+        "java/android/net/TcpKeepalivePacketDataParcelable.aidl",
+        "java/android/net/dhcp/DhcpServingParamsParcel.aidl",
+        "java/android/net/dhcp/IDhcpServer.aidl",
+        "java/android/net/dhcp/IDhcpServerCallbacks.aidl",
+        "java/android/net/ip/IIpClient.aidl",
+        "java/android/net/ip/IIpClientCallbacks.aidl",
+        "java/android/net/ipmemorystore/**/*.aidl",
+    ],
+    backend: {
+        ndk: {
+            enabled: false,
+        },
+        cpp: {
+            enabled: false,
+        },
+    },
+    api_dir: "aidl/networkstack",
+}
+
 java_library_static {
     name: "services.net",
     srcs: ["java/**/*.java"],
diff --git a/core/java/android/net/ApfCapabilitiesParcelable.aidl b/services/net/java/android/net/ApfCapabilitiesParcelable.aidl
similarity index 100%
rename from core/java/android/net/ApfCapabilitiesParcelable.aidl
rename to services/net/java/android/net/ApfCapabilitiesParcelable.aidl
diff --git a/core/java/android/net/DhcpResultsParcelable.aidl b/services/net/java/android/net/DhcpResultsParcelable.aidl
similarity index 100%
rename from core/java/android/net/DhcpResultsParcelable.aidl
rename to services/net/java/android/net/DhcpResultsParcelable.aidl
diff --git a/core/java/android/net/IIpMemoryStore.aidl b/services/net/java/android/net/IIpMemoryStore.aidl
similarity index 100%
rename from core/java/android/net/IIpMemoryStore.aidl
rename to services/net/java/android/net/IIpMemoryStore.aidl
diff --git a/core/java/android/net/IIpMemoryStoreCallbacks.aidl b/services/net/java/android/net/IIpMemoryStoreCallbacks.aidl
similarity index 100%
rename from core/java/android/net/IIpMemoryStoreCallbacks.aidl
rename to services/net/java/android/net/IIpMemoryStoreCallbacks.aidl
diff --git a/core/java/android/net/INetworkMonitor.aidl b/services/net/java/android/net/INetworkMonitor.aidl
similarity index 100%
rename from core/java/android/net/INetworkMonitor.aidl
rename to services/net/java/android/net/INetworkMonitor.aidl
diff --git a/core/java/android/net/INetworkMonitorCallbacks.aidl b/services/net/java/android/net/INetworkMonitorCallbacks.aidl
similarity index 100%
rename from core/java/android/net/INetworkMonitorCallbacks.aidl
rename to services/net/java/android/net/INetworkMonitorCallbacks.aidl
diff --git a/core/java/android/net/INetworkStackConnector.aidl b/services/net/java/android/net/INetworkStackConnector.aidl
similarity index 100%
rename from core/java/android/net/INetworkStackConnector.aidl
rename to services/net/java/android/net/INetworkStackConnector.aidl
diff --git a/core/java/android/net/INetworkStackStatusCallback.aidl b/services/net/java/android/net/INetworkStackStatusCallback.aidl
similarity index 100%
rename from core/java/android/net/INetworkStackStatusCallback.aidl
rename to services/net/java/android/net/INetworkStackStatusCallback.aidl
diff --git a/core/java/android/net/InitialConfigurationParcelable.aidl b/services/net/java/android/net/InitialConfigurationParcelable.aidl
similarity index 100%
rename from core/java/android/net/InitialConfigurationParcelable.aidl
rename to services/net/java/android/net/InitialConfigurationParcelable.aidl
diff --git a/core/java/android/net/PrivateDnsConfigParcel.aidl b/services/net/java/android/net/PrivateDnsConfigParcel.aidl
similarity index 100%
rename from core/java/android/net/PrivateDnsConfigParcel.aidl
rename to services/net/java/android/net/PrivateDnsConfigParcel.aidl
diff --git a/core/java/android/net/ProvisioningConfigurationParcelable.aidl b/services/net/java/android/net/ProvisioningConfigurationParcelable.aidl
similarity index 100%
rename from core/java/android/net/ProvisioningConfigurationParcelable.aidl
rename to services/net/java/android/net/ProvisioningConfigurationParcelable.aidl
diff --git a/core/java/android/net/StaticIpConfigurationParcelable.aidl b/services/net/java/android/net/StaticIpConfigurationParcelable.aidl
similarity index 100%
rename from core/java/android/net/StaticIpConfigurationParcelable.aidl
rename to services/net/java/android/net/StaticIpConfigurationParcelable.aidl
diff --git a/core/java/android/net/TcpKeepalivePacketDataParcelable.aidl b/services/net/java/android/net/TcpKeepalivePacketDataParcelable.aidl
similarity index 100%
rename from core/java/android/net/TcpKeepalivePacketDataParcelable.aidl
rename to services/net/java/android/net/TcpKeepalivePacketDataParcelable.aidl
diff --git a/core/java/android/net/dhcp/DhcpServingParamsParcel.aidl b/services/net/java/android/net/dhcp/DhcpServingParamsParcel.aidl
similarity index 100%
rename from core/java/android/net/dhcp/DhcpServingParamsParcel.aidl
rename to services/net/java/android/net/dhcp/DhcpServingParamsParcel.aidl
diff --git a/core/java/android/net/dhcp/IDhcpServer.aidl b/services/net/java/android/net/dhcp/IDhcpServer.aidl
similarity index 100%
rename from core/java/android/net/dhcp/IDhcpServer.aidl
rename to services/net/java/android/net/dhcp/IDhcpServer.aidl
diff --git a/core/java/android/net/dhcp/IDhcpServerCallbacks.aidl b/services/net/java/android/net/dhcp/IDhcpServerCallbacks.aidl
similarity index 100%
rename from core/java/android/net/dhcp/IDhcpServerCallbacks.aidl
rename to services/net/java/android/net/dhcp/IDhcpServerCallbacks.aidl
diff --git a/core/java/android/net/ip/IIpClient.aidl b/services/net/java/android/net/ip/IIpClient.aidl
similarity index 100%
rename from core/java/android/net/ip/IIpClient.aidl
rename to services/net/java/android/net/ip/IIpClient.aidl
diff --git a/core/java/android/net/ip/IIpClientCallbacks.aidl b/services/net/java/android/net/ip/IIpClientCallbacks.aidl
similarity index 100%
rename from core/java/android/net/ip/IIpClientCallbacks.aidl
rename to services/net/java/android/net/ip/IIpClientCallbacks.aidl
diff --git a/core/java/android/net/ipmemorystore/Blob.aidl b/services/net/java/android/net/ipmemorystore/Blob.aidl
similarity index 100%
rename from core/java/android/net/ipmemorystore/Blob.aidl
rename to services/net/java/android/net/ipmemorystore/Blob.aidl
diff --git a/core/java/android/net/ipmemorystore/IOnBlobRetrievedListener.aidl b/services/net/java/android/net/ipmemorystore/IOnBlobRetrievedListener.aidl
similarity index 100%
rename from core/java/android/net/ipmemorystore/IOnBlobRetrievedListener.aidl
rename to services/net/java/android/net/ipmemorystore/IOnBlobRetrievedListener.aidl
diff --git a/core/java/android/net/ipmemorystore/IOnL2KeyResponseListener.aidl b/services/net/java/android/net/ipmemorystore/IOnL2KeyResponseListener.aidl
similarity index 100%
rename from core/java/android/net/ipmemorystore/IOnL2KeyResponseListener.aidl
rename to services/net/java/android/net/ipmemorystore/IOnL2KeyResponseListener.aidl
diff --git a/core/java/android/net/ipmemorystore/IOnNetworkAttributesRetrieved.aidl b/services/net/java/android/net/ipmemorystore/IOnNetworkAttributesRetrieved.aidl
similarity index 100%
rename from core/java/android/net/ipmemorystore/IOnNetworkAttributesRetrieved.aidl
rename to services/net/java/android/net/ipmemorystore/IOnNetworkAttributesRetrieved.aidl
diff --git a/core/java/android/net/ipmemorystore/IOnSameNetworkResponseListener.aidl b/services/net/java/android/net/ipmemorystore/IOnSameNetworkResponseListener.aidl
similarity index 100%
rename from core/java/android/net/ipmemorystore/IOnSameNetworkResponseListener.aidl
rename to services/net/java/android/net/ipmemorystore/IOnSameNetworkResponseListener.aidl
diff --git a/core/java/android/net/ipmemorystore/IOnStatusListener.aidl b/services/net/java/android/net/ipmemorystore/IOnStatusListener.aidl
similarity index 100%
rename from core/java/android/net/ipmemorystore/IOnStatusListener.aidl
rename to services/net/java/android/net/ipmemorystore/IOnStatusListener.aidl
diff --git a/core/java/android/net/ipmemorystore/NetworkAttributesParcelable.aidl b/services/net/java/android/net/ipmemorystore/NetworkAttributesParcelable.aidl
similarity index 100%
rename from core/java/android/net/ipmemorystore/NetworkAttributesParcelable.aidl
rename to services/net/java/android/net/ipmemorystore/NetworkAttributesParcelable.aidl
diff --git a/core/java/android/net/ipmemorystore/SameL3NetworkResponseParcelable.aidl b/services/net/java/android/net/ipmemorystore/SameL3NetworkResponseParcelable.aidl
similarity index 100%
rename from core/java/android/net/ipmemorystore/SameL3NetworkResponseParcelable.aidl
rename to services/net/java/android/net/ipmemorystore/SameL3NetworkResponseParcelable.aidl
diff --git a/core/java/android/net/ipmemorystore/StatusParcelable.aidl b/services/net/java/android/net/ipmemorystore/StatusParcelable.aidl
similarity index 100%
rename from core/java/android/net/ipmemorystore/StatusParcelable.aidl
rename to services/net/java/android/net/ipmemorystore/StatusParcelable.aidl
diff --git a/services/tests/servicestests/src/com/android/server/backup/testutils/IPackageManagerStub.java b/services/tests/servicestests/src/com/android/server/backup/testutils/IPackageManagerStub.java
index caf6c9c..4b3d9cf 100644
--- a/services/tests/servicestests/src/com/android/server/backup/testutils/IPackageManagerStub.java
+++ b/services/tests/servicestests/src/com/android/server/backup/testutils/IPackageManagerStub.java
@@ -1068,6 +1068,12 @@
     }
 
     @Override
+    public ParceledListSlice getDeclaredSharedLibraries(String packageName, int flags, int userId)
+            throws RemoteException {
+        return null;
+    }
+
+    @Override
     public boolean canRequestPackageInstalls(String packageName, int userId)
         throws RemoteException {
         return false;
diff --git a/services/tests/servicestests/src/com/android/server/locksettings/CachedSyntheticPasswordTests.java b/services/tests/servicestests/src/com/android/server/locksettings/CachedSyntheticPasswordTests.java
index 94d21dd..ca4330f 100644
--- a/services/tests/servicestests/src/com/android/server/locksettings/CachedSyntheticPasswordTests.java
+++ b/services/tests/servicestests/src/com/android/server/locksettings/CachedSyntheticPasswordTests.java
@@ -61,12 +61,12 @@
         long sid = mGateKeeperService.getSecureUserId(PRIMARY_USER_ID);
         // clear password
         mService.setLockCredential(null, LockPatternUtils.CREDENTIAL_TYPE_NONE, null,
-                PASSWORD_QUALITY_UNSPECIFIED, PRIMARY_USER_ID);
+                PASSWORD_QUALITY_UNSPECIFIED, PRIMARY_USER_ID, true);
         assertEquals(0, mGateKeeperService.getSecureUserId(PRIMARY_USER_ID));
 
         // set a new password
         mService.setLockCredential(newPassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
-                PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
+                PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID, false);
         assertEquals(VerifyCredentialResponse.RESPONSE_OK, mService.verifyCredential(newPassword,
                 LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID)
                         .getResponseCode());
@@ -81,7 +81,7 @@
         long sid = mGateKeeperService.getSecureUserId(PRIMARY_USER_ID);
         // Untrusted change password
         mService.setLockCredential(newPassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
-                PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
+                PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID, true);
         assertNotEquals(0, mGateKeeperService.getSecureUserId(PRIMARY_USER_ID));
         assertNotEquals(sid, mGateKeeperService.getSecureUserId(PRIMARY_USER_ID));
 
@@ -99,7 +99,7 @@
         initializeCredentialUnderSP(password, PRIMARY_USER_ID);
         // Untrusted change password
         mService.setLockCredential(newPassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
-                PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
+                PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID, true);
 
         // Verify the password
         assertEquals(VerifyCredentialResponse.RESPONSE_OK, mService.verifyCredential(newPassword,
@@ -124,10 +124,12 @@
         initializeCredentialUnderSP(password, PRIMARY_USER_ID);
         long sid = mGateKeeperService.getSecureUserId(PRIMARY_USER_ID);
         // Untrusted change password
-        assertExpectException(IllegalStateException.class, /* messageRegex= */ null,
+        assertExpectException(
+                IllegalStateException.class,
+                /* messageRegex= */ "Untrusted credential reset not possible without cached SP",
                 () -> mService.setLockCredential(newPassword,
                         LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
-                        PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID));
+                        PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID, true));
         assertEquals(sid, mGateKeeperService.getSecureUserId(PRIMARY_USER_ID));
 
         // Verify the new password doesn't work but the old one still does
diff --git a/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTests.java b/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTests.java
index 6e0ba3c..255e694b 100644
--- a/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTests.java
+++ b/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTests.java
@@ -85,9 +85,9 @@
 
         try {
             mService.setLockCredential("newpwd".getBytes(), CREDENTIAL_TYPE_PASSWORD,
-                    "badpwd".getBytes(), PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
+                    "badpwd".getBytes(), PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID, false);
             fail("Did not fail when enrolling using incorrect credential");
-        } catch (RemoteException expected) {
+        } catch (IllegalStateException expected) {
             assertTrue(expected.getMessage().equals(FAILED_MESSAGE));
         }
         assertVerifyCredentials(PRIMARY_USER_ID, "password", CREDENTIAL_TYPE_PASSWORD, sid);
@@ -97,7 +97,7 @@
         final String PASSWORD = "password";
         initializeStorageWithCredential(PRIMARY_USER_ID, PASSWORD, CREDENTIAL_TYPE_PASSWORD, 1234);
         mService.setLockCredential(null, CREDENTIAL_TYPE_NONE, PASSWORD.getBytes(),
-                PASSWORD_QUALITY_UNSPECIFIED, PRIMARY_USER_ID);
+                PASSWORD_QUALITY_UNSPECIFIED, PRIMARY_USER_ID, false);
         assertFalse(mService.havePassword(PRIMARY_USER_ID));
         assertFalse(mService.havePattern(PRIMARY_USER_ID));
         assertEquals(0, mGateKeeperService.getSecureUserId(PRIMARY_USER_ID));
@@ -108,7 +108,7 @@
         final String secondUnifiedPassword = "testManagedProfileUnifiedChallenge-pwd-2";
         mService.setLockCredential(firstUnifiedPassword.getBytes(),
                 LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
-                null, PASSWORD_QUALITY_COMPLEX, PRIMARY_USER_ID);
+                null, PASSWORD_QUALITY_COMPLEX, PRIMARY_USER_ID, false);
         mService.setSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID, false, null);
         final long primarySid = mGateKeeperService.getSecureUserId(PRIMARY_USER_ID);
         final long profileSid = mGateKeeperService.getSecureUserId(MANAGED_PROFILE_USER_ID);
@@ -143,15 +143,16 @@
         mStorageManager.setIgnoreBadUnlock(true);
         // Change primary password and verify that profile SID remains
         mService.setLockCredential(secondUnifiedPassword.getBytes(),
-                LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
-                firstUnifiedPassword.getBytes(), PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
+                LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, firstUnifiedPassword.getBytes(),
+                PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID, false);
         mStorageManager.setIgnoreBadUnlock(false);
         assertEquals(profileSid, mGateKeeperService.getSecureUserId(MANAGED_PROFILE_USER_ID));
         assertNull(mGateKeeperService.getAuthToken(TURNED_OFF_PROFILE_USER_ID));
 
         // Clear unified challenge
         mService.setLockCredential(null, LockPatternUtils.CREDENTIAL_TYPE_NONE,
-                secondUnifiedPassword.getBytes(), PASSWORD_QUALITY_UNSPECIFIED, PRIMARY_USER_ID);
+                secondUnifiedPassword.getBytes(), PASSWORD_QUALITY_UNSPECIFIED, PRIMARY_USER_ID,
+                false);
         assertEquals(0, mGateKeeperService.getSecureUserId(PRIMARY_USER_ID));
         assertEquals(0, mGateKeeperService.getSecureUserId(MANAGED_PROFILE_USER_ID));
         assertEquals(0, mGateKeeperService.getSecureUserId(TURNED_OFF_PROFILE_USER_ID));
@@ -162,7 +163,7 @@
         final String profilePassword = "testManagedProfileSeparateChallenge-profile";
         mService.setLockCredential(primaryPassword.getBytes(),
                 LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
-                PASSWORD_QUALITY_COMPLEX, PRIMARY_USER_ID);
+                PASSWORD_QUALITY_COMPLEX, PRIMARY_USER_ID, false);
         /* Currently in LockSettingsService.setLockCredential, unlockUser() is called with the new
          * credential as part of verifyCredential() before the new credential is committed in
          * StorageManager. So we relax the check in our mock StorageManager to allow that.
@@ -170,7 +171,7 @@
         mStorageManager.setIgnoreBadUnlock(true);
         mService.setLockCredential(profilePassword.getBytes(),
                 LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
-                PASSWORD_QUALITY_COMPLEX, MANAGED_PROFILE_USER_ID);
+                PASSWORD_QUALITY_COMPLEX, MANAGED_PROFILE_USER_ID, false);
         mStorageManager.setIgnoreBadUnlock(false);
 
         final long primarySid = mGateKeeperService.getSecureUserId(PRIMARY_USER_ID);
@@ -197,7 +198,7 @@
         // Change primary credential and make sure we don't affect profile
         mStorageManager.setIgnoreBadUnlock(true);
         mService.setLockCredential("pwd".getBytes(), LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
-                primaryPassword.getBytes(), PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
+                primaryPassword.getBytes(), PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID, false);
         mStorageManager.setIgnoreBadUnlock(false);
         assertEquals(VerifyCredentialResponse.RESPONSE_OK, mService.verifyCredential(
                 profilePassword.getBytes(), LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0,
@@ -208,7 +209,7 @@
     private void testCreateCredential(int userId, String credential, int type, int quality)
             throws RemoteException {
         mService.setLockCredential(credential.getBytes(), type, null, quality,
-                userId);
+                userId, false);
         assertVerifyCredentials(userId, credential, type, -1);
     }
 
@@ -218,7 +219,7 @@
 
         try {
             mService.setLockCredential(credential.getBytes(), type, null, quality,
-                    userId);
+                    userId, false);
             fail("An exception should have been thrown.");
         } catch (UnsupportedOperationException e) {
             // Success - the exception was expected.
@@ -233,7 +234,7 @@
         final long sid = 1234;
         initializeStorageWithCredential(userId, oldCredential, oldType, sid);
         mService.setLockCredential(newCredential.getBytes(), newType, oldCredential.getBytes(),
-                quality, userId);
+                quality, userId, false);
         assertVerifyCredentials(userId, newCredential, newType, sid);
     }
 
diff --git a/services/tests/servicestests/src/com/android/server/locksettings/SyntheticPasswordTests.java b/services/tests/servicestests/src/com/android/server/locksettings/SyntheticPasswordTests.java
index 6a07a45..58055e5 100644
--- a/services/tests/servicestests/src/com/android/server/locksettings/SyntheticPasswordTests.java
+++ b/services/tests/servicestests/src/com/android/server/locksettings/SyntheticPasswordTests.java
@@ -102,7 +102,7 @@
 
         disableSyntheticPassword();
         mService.setLockCredential(password, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
-                PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
+                PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID, false);
         long sid = mGateKeeperService.getSecureUserId(PRIMARY_USER_ID);
         final byte[] primaryStorageKey = mStorageManager.getUserUnlockToken(PRIMARY_USER_ID);
         enableSyntheticPassword();
@@ -127,7 +127,7 @@
                 : PASSWORD_QUALITY_UNSPECIFIED;
         int type = password != null ? LockPatternUtils.CREDENTIAL_TYPE_PASSWORD
                 : LockPatternUtils.CREDENTIAL_TYPE_NONE;
-        mService.setLockCredential(password, type, null, quality, userId);
+        mService.setLockCredential(password, type, null, quality, userId, false);
     }
 
     public void testSyntheticPasswordChangeCredential() throws RemoteException {
@@ -137,7 +137,7 @@
         initializeCredentialUnderSP(password, PRIMARY_USER_ID);
         long sid = mGateKeeperService.getSecureUserId(PRIMARY_USER_ID);
         mService.setLockCredential(newPassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, password,
-                PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
+                PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID, false);
         assertEquals(VerifyCredentialResponse.RESPONSE_OK, mService.verifyCredential(
                 newPassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID)
                         .getResponseCode());
@@ -166,12 +166,12 @@
         long sid = mGateKeeperService.getSecureUserId(PRIMARY_USER_ID);
         // clear password
         mService.setLockCredential(null, LockPatternUtils.CREDENTIAL_TYPE_NONE, password,
-                PASSWORD_QUALITY_UNSPECIFIED, PRIMARY_USER_ID);
+                PASSWORD_QUALITY_UNSPECIFIED, PRIMARY_USER_ID, false);
         assertEquals(0 ,mGateKeeperService.getSecureUserId(PRIMARY_USER_ID));
 
         // set a new password
         mService.setLockCredential(badPassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
-                PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
+                PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID, false);
         assertEquals(VerifyCredentialResponse.RESPONSE_OK, mService.verifyCredential(
                 badPassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID)
                         .getResponseCode());
@@ -186,7 +186,7 @@
 
         initializeCredentialUnderSP(password, PRIMARY_USER_ID);
         mService.setLockCredential(badPassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, password,
-                PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
+                PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID, false);
         assertEquals(VerifyCredentialResponse.RESPONSE_OK, mService.verifyCredential(
                 badPassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 0, PRIMARY_USER_ID)
                         .getResponseCode());
@@ -245,7 +245,7 @@
         final byte[] password = "getASyntheticPassword".getBytes();
         initializeCredentialUnderSP(password, PRIMARY_USER_ID);
         mService.setLockCredential(null, LockPatternUtils.CREDENTIAL_TYPE_NONE, password,
-                PASSWORD_QUALITY_UNSPECIFIED, PRIMARY_USER_ID);
+                PASSWORD_QUALITY_UNSPECIFIED, PRIMARY_USER_ID, false);
 
         reset(mAuthSecretService);
         mService.onUnlockUser(PRIMARY_USER_ID);
@@ -257,7 +257,7 @@
         final byte[] UnifiedPassword = "testManagedProfileUnifiedChallengeMigration-pwd".getBytes();
         disableSyntheticPassword();
         mService.setLockCredential(UnifiedPassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
-                PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
+                PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID, false);
         mService.setSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID, false, null);
         final long primarySid = mGateKeeperService.getSecureUserId(PRIMARY_USER_ID);
         final long profileSid = mGateKeeperService.getSecureUserId(MANAGED_PROFILE_USER_ID);
@@ -294,9 +294,9 @@
                 "testManagedProfileSeparateChallengeMigration-profile".getBytes();
         disableSyntheticPassword();
         mService.setLockCredential(primaryPassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
-                PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
+                PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID, false);
         mService.setLockCredential(profilePassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
-                PASSWORD_QUALITY_ALPHABETIC, MANAGED_PROFILE_USER_ID);
+                PASSWORD_QUALITY_ALPHABETIC, MANAGED_PROFILE_USER_ID, false);
         final long primarySid = mGateKeeperService.getSecureUserId(PRIMARY_USER_ID);
         final long profileSid = mGateKeeperService.getSecureUserId(MANAGED_PROFILE_USER_ID);
         final byte[] primaryStorageKey = mStorageManager.getUserUnlockToken(PRIMARY_USER_ID);
@@ -404,7 +404,7 @@
         assertTrue(mLocalService.isEscrowTokenActive(handle, PRIMARY_USER_ID));
 
         mService.setLockCredential(pattern, LockPatternUtils.CREDENTIAL_TYPE_PATTERN, password,
-                PASSWORD_QUALITY_SOMETHING, PRIMARY_USER_ID);
+                PASSWORD_QUALITY_SOMETHING, PRIMARY_USER_ID, false);
 
         mLocalService.setLockCredentialWithToken(newPassword,
                 LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, handle, token,
@@ -443,7 +443,7 @@
         // Set up pre-SP user password
         disableSyntheticPassword();
         mService.setLockCredential(password, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
-                PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
+                PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID, false);
         enableSyntheticPassword();
 
         long handle = mLocalService.addEscrowToken(token, PRIMARY_USER_ID, null);
@@ -491,12 +491,12 @@
     public void testgetHashFactorPrimaryUser() throws RemoteException {
         final byte[] password = "password".getBytes();
         mService.setLockCredential(password, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
-                PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
+                PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID, false);
         final byte[] hashFactor = mService.getHashFactor(password, PRIMARY_USER_ID);
         assertNotNull(hashFactor);
 
         mService.setLockCredential(null, LockPatternUtils.CREDENTIAL_TYPE_NONE,
-                password, PASSWORD_QUALITY_UNSPECIFIED, PRIMARY_USER_ID);
+                password, PASSWORD_QUALITY_UNSPECIFIED, PRIMARY_USER_ID, false);
         final byte[] newHashFactor = mService.getHashFactor(null, PRIMARY_USER_ID);
         assertNotNull(newHashFactor);
         // Hash factor should never change after password change/removal
@@ -506,7 +506,7 @@
     public void testgetHashFactorManagedProfileUnifiedChallenge() throws RemoteException {
         final byte[] pattern = "1236".getBytes();
         mService.setLockCredential(pattern, LockPatternUtils.CREDENTIAL_TYPE_PATTERN,
-                null, PASSWORD_QUALITY_SOMETHING, PRIMARY_USER_ID);
+                null, PASSWORD_QUALITY_SOMETHING, PRIMARY_USER_ID, false);
         mService.setSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID, false, null);
         assertNotNull(mService.getHashFactor(null, MANAGED_PROFILE_USER_ID));
     }
@@ -515,9 +515,9 @@
         final byte[] primaryPassword = "primary".getBytes();
         final byte[] profilePassword = "profile".getBytes();
         mService.setLockCredential(primaryPassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
-                PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID);
+                PASSWORD_QUALITY_ALPHABETIC, PRIMARY_USER_ID, false);
         mService.setLockCredential(profilePassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, null,
-                PASSWORD_QUALITY_ALPHABETIC, MANAGED_PROFILE_USER_ID);
+                PASSWORD_QUALITY_ALPHABETIC, MANAGED_PROFILE_USER_ID, false);
         assertNotNull(mService.getHashFactor(profilePassword, MANAGED_PROFILE_USER_ID));
     }
 
diff --git a/telephony/java/android/telephony/SubscriptionInfo.java b/telephony/java/android/telephony/SubscriptionInfo.java
index ac11940..ee28ca2 100644
--- a/telephony/java/android/telephony/SubscriptionInfo.java
+++ b/telephony/java/android/telephony/SubscriptionInfo.java
@@ -32,6 +32,7 @@
 import android.graphics.Typeface;
 import android.os.Build;
 import android.os.Parcel;
+import android.os.ParcelUuid;
 import android.os.Parcelable;
 import android.text.TextUtils;
 import android.util.DisplayMetrics;
@@ -154,11 +155,11 @@
     private boolean mIsOpportunistic;
 
     /**
-     * A UUID assigned to the subscription group. It returns
-     * null if not assigned.
+     * A UUID assigned to the subscription group. It returns null if not assigned.
+     * Check {@link SubscriptionManager#createSubscriptionGroup(List)} for more details.
      */
     @Nullable
-    private String mGroupUUID;
+    private ParcelUuid mGroupUUID;
 
     /**
      * Whether group of the subscription is disabled.
@@ -237,7 +238,7 @@
         this.mCardString = cardString;
         this.mCardId = cardId;
         this.mIsOpportunistic = isOpportunistic;
-        this.mGroupUUID = groupUUID;
+        this.mGroupUUID = groupUUID == null ? null : ParcelUuid.fromString(groupUUID);
         this.mIsGroupDisabled = isGroupDisabled;
         this.mCarrierId = carrierId;
         this.mProfileClass = profileClass;
@@ -461,7 +462,7 @@
      * @return group UUID a String of group UUID if it belongs to a group. Otherwise
      * it will return null.
      */
-    public @Nullable String getGroupUuid() {
+    public @Nullable ParcelUuid getGroupUuid() {
         return mGroupUUID;
     }
 
@@ -643,7 +644,7 @@
         dest.writeString(mCardString);
         dest.writeInt(mCardId);
         dest.writeBoolean(mIsOpportunistic);
-        dest.writeString(mGroupUUID);
+        dest.writeString(mGroupUUID == null ? null : mGroupUUID.toString());
         dest.writeBoolean(mIsGroupDisabled);
         dest.writeInt(mCarrierId);
         dest.writeInt(mProfileClass);
diff --git a/telephony/java/android/telephony/SubscriptionManager.java b/telephony/java/android/telephony/SubscriptionManager.java
index 2edef83..14eac87 100644
--- a/telephony/java/android/telephony/SubscriptionManager.java
+++ b/telephony/java/android/telephony/SubscriptionManager.java
@@ -50,11 +50,12 @@
 import android.os.Handler;
 import android.os.Looper;
 import android.os.Message;
+import android.os.ParcelUuid;
+import android.os.Process;
 import android.os.RemoteException;
 import android.os.ServiceManager;
 import android.telephony.euicc.EuiccManager;
 import android.telephony.ims.ImsMmTelManager;
-import android.text.TextUtils;
 import android.util.DisplayMetrics;
 import android.util.Log;
 
@@ -1752,6 +1753,10 @@
         Rlog.d(LOG_TAG, msg);
     }
 
+    private static void loge(String msg) {
+        Rlog.e(LOG_TAG, msg);
+    }
+
     /**
      * Returns the system's default subscription id.
      *
@@ -1991,24 +1996,6 @@
     }
 
     /**
-     * If a default is set to subscription which is not active, this will reset that default back to
-     * an invalid subscription id, i.e. < 0.
-     * @hide
-     */
-    @UnsupportedAppUsage
-    public void clearDefaultsForInactiveSubIds() {
-        if (VDBG) logd("clearDefaultsForInactiveSubIds");
-        try {
-            ISub iSub = ISub.Stub.asInterface(ServiceManager.getService("isub"));
-            if (iSub != null) {
-                iSub.clearDefaultsForInactiveSubIds();
-            }
-        } catch (RemoteException ex) {
-            // ignore it
-        }
-    }
-
-    /**
      * Check if the supplied subscription ID is valid.
      *
      * <p>A valid subscription ID is not necessarily an active subscription ID
@@ -2740,11 +2727,20 @@
 
     /**
      * Inform SubscriptionManager that subscriptions in the list are bundled
-     * as a group. Typically it's a primary subscription and an opportunistic
-     * subscription. It should only affect multi-SIM scenarios where primary
-     * and opportunistic subscriptions can be activated together.
-     * Being in the same group means they might be activated or deactivated
-     * together, some of them may be invisible to the users, etc.
+     * as a group. It can be multiple primary (non-opportunistic) subscriptions,
+     * or one or more primary plus one or more opportunistic subscriptions.
+     *
+     * This API will always create a new immutable group and assign group UUID to all the
+     * subscriptions, regardless whether they are in a group already or not.
+     *
+     * Grouped subscriptions will have below behaviors:
+     * 1) They will share the same user settings.
+     * 2) The opportunistic subscriptions in the group is considered invisible and will not
+     *    return from {@link #getActiveSubscriptionInfoList()}, unless caller has carrier
+     *    privilege permission of the subscriptions.
+     * 3) The opportunistic subscriptions in the group can't be active by itself. If all other
+     *    non-opportunistic ones are deactivated (unplugged or disabled in Settings),
+     *    the opportunistic ones will be deactivated automatically.
      *
      * Caller will either have {@link android.Manifest.permission#MODIFY_PHONE_STATE}
      * permission or had carrier privilege permission on the subscriptions:
@@ -2755,34 +2751,42 @@
      *             outlined above.
      *
      * @param subIdList list of subId that will be in the same group
-     * @return groupUUID a UUID assigned to the subscription group. It returns
-     * null if fails.
+     * @return groupUUID a UUID assigned to the subscription group.
      *
      */
     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
-    public @Nullable String setSubscriptionGroup(@NonNull int[] subIdList) {
+    public @NonNull ParcelUuid createSubscriptionGroup(@NonNull List<Integer> subIdList) {
+        Preconditions.checkNotNull(subIdList, "can't create group for null subId list");
         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
         if (VDBG) {
-            logd("[setSubscriptionGroup]+ subIdList:" + Arrays.toString(subIdList));
+            logd("[createSubscriptionGroup]");
         }
 
-        String groupUUID = null;
+        ParcelUuid groupUuid = null;
+        int[] subIdArray = subIdList.stream().mapToInt(i->i).toArray();
         try {
             ISub iSub = ISub.Stub.asInterface(ServiceManager.getService("isub"));
             if (iSub != null) {
-                groupUUID = iSub.setSubscriptionGroup(subIdList, pkgForDebug);
+                groupUuid = iSub.createSubscriptionGroup(subIdArray, pkgForDebug);
+            } else {
+                if (!isSystemProcess()) {
+                    throw new IllegalStateException("telephony service is null.");
+                }
             }
         } catch (RemoteException ex) {
-            // ignore it
+            loge("createSubscriptionGroup RemoteException " + ex);
+            if (!isSystemProcess()) {
+                ex.rethrowAsRuntimeException();
+            }
         }
 
-        return groupUUID;
+        return groupUuid;
     }
 
     /**
-     * Remove a list of subscriptions from their subscription group.
-     * See {@link #setSubscriptionGroup(int[])} for more details.
+     * Add a list of subscriptions into a group.
+     * See {@link #createSubscriptionGroup(List)} for more details.
      *
      * Caller will either have {@link android.Manifest.permission#MODIFY_PHONE_STATE}
      * permission or had carrier privilege permission on the subscriptions:
@@ -2791,34 +2795,97 @@
      *
      * @throws SecurityException if the caller doesn't meet the requirements
      *             outlined above.
+     * @throws IllegalArgumentException if the some subscriptions in the list doesn't exist,
+     *             or the groupUuid doesn't exist.
      *
-     * @param subIdList list of subId that need removing from their groups.
-     * @return whether the operation succeeds.
+     * @param subIdList list of subId that need adding into the group
+     * @param groupUuid the groupUuid the subscriptions are being added to.
      *
      */
     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
-    public boolean removeSubscriptionsFromGroup(@NonNull int[] subIdList) {
+    public void addSubscriptionsIntoGroup(@NonNull List<Integer> subIdList,
+            @NonNull ParcelUuid groupUuid) {
+        Preconditions.checkNotNull(subIdList, "subIdList can't be null.");
+        Preconditions.checkNotNull(groupUuid, "groupUuid can't be null.");
         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
         if (VDBG) {
-            logd("[removeSubscriptionsFromGroup]+ subIdList:" + Arrays.toString(subIdList));
+            logd("[addSubscriptionsIntoGroup]");
         }
 
+        int[] subIdArray = subIdList.stream().mapToInt(i->i).toArray();
+
         try {
             ISub iSub = ISub.Stub.asInterface(ServiceManager.getService("isub"));
             if (iSub != null) {
-                return iSub.removeSubscriptionsFromGroup(subIdList, pkgForDebug);
+                iSub.addSubscriptionsIntoGroup(subIdArray, groupUuid, pkgForDebug);
+            } else {
+                if (!isSystemProcess()) {
+                    throw new IllegalStateException("telephony service is null.");
+                }
             }
         } catch (RemoteException ex) {
-            // ignore it
+            loge("addSubscriptionsIntoGroup RemoteException " + ex);
+            if (!isSystemProcess()) {
+                ex.rethrowAsRuntimeException();
+            }
+        }
+    }
+
+    private boolean isSystemProcess() {
+        return Process.myUid() == Process.SYSTEM_UID;
+    }
+
+    /**
+     * Remove a list of subscriptions from their subscription group.
+     * See {@link #createSubscriptionGroup(List)} for more details.
+     *
+     * Caller will either have {@link android.Manifest.permission#MODIFY_PHONE_STATE}
+     * permission or had carrier privilege permission on the subscriptions:
+     * {@link TelephonyManager#hasCarrierPrivileges()} or
+     * {@link #canManageSubscription(SubscriptionInfo)}
+     *
+     * @throws SecurityException if the caller doesn't meet the requirements
+     *             outlined above.
+     * @throws IllegalArgumentException if the some subscriptions in the list doesn't belong
+     *             the specified group.
+     *
+     * @param subIdList list of subId that need removing from their groups.
+     *
+     */
+    @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
+    @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
+    public void removeSubscriptionsFromGroup(@NonNull List<Integer> subIdList,
+            @NonNull ParcelUuid groupUuid) {
+        Preconditions.checkNotNull(subIdList, "subIdList can't be null.");
+        Preconditions.checkNotNull(groupUuid, "groupUuid can't be null.");
+        String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
+        if (VDBG) {
+            logd("[removeSubscriptionsFromGroup]");
         }
 
-        return false;
+        int[] subIdArray = subIdList.stream().mapToInt(i->i).toArray();
+
+        try {
+            ISub iSub = ISub.Stub.asInterface(ServiceManager.getService("isub"));
+            if (iSub != null) {
+                iSub.removeSubscriptionsFromGroup(subIdArray, groupUuid, pkgForDebug);
+            } else {
+                if (!isSystemProcess()) {
+                    throw new IllegalStateException("telephony service is null.");
+                }
+            }
+        } catch (RemoteException ex) {
+            loge("removeSubscriptionsFromGroup RemoteException " + ex);
+            if (!isSystemProcess()) {
+                ex.rethrowAsRuntimeException();
+            }
+        }
     }
 
     /**
      * Get subscriptionInfo list of subscriptions that are in the same group of given subId.
-     * See {@link #setSubscriptionGroup(int[])} for more details.
+     * See {@link #createSubscriptionGroup(List)} for more details.
      *
      * Caller will either have {@link android.Manifest.permission#READ_PHONE_STATE}
      * permission or had carrier privilege permission on the subscription.
@@ -2827,28 +2894,35 @@
      * @throws SecurityException if the caller doesn't meet the requirements
      *             outlined above.
      *
-     * @param subId of which list of subInfo from the same group will be returned.
+     * @param groupUuid of which list of subInfo will be returned.
      * @return list of subscriptionInfo that belong to the same group, including the given
-     * subscription itself. It will return null if the subscription doesn't exist or it
-     * doesn't belong to any group.
+     * subscription itself. It will return an empty list if no subscription belongs to the group.
      *
      */
     @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
     @RequiresPermission(Manifest.permission.READ_PHONE_STATE)
-    public @Nullable List<SubscriptionInfo> getSubscriptionsInGroup(int subId) {
+    public @NonNull List<SubscriptionInfo> getSubscriptionsInGroup(@NonNull ParcelUuid groupUuid) {
+        Preconditions.checkNotNull(groupUuid, "groupUuid can't be null");
         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
         if (VDBG) {
-            logd("[getSubscriptionsInGroup]+ subId:" + subId);
+            logd("[getSubscriptionsInGroup]+ groupUuid:" + groupUuid);
         }
 
         List<SubscriptionInfo> result = null;
         try {
             ISub iSub = ISub.Stub.asInterface(ServiceManager.getService("isub"));
             if (iSub != null) {
-                result = iSub.getSubscriptionsInGroup(subId, pkgForDebug);
+                result = iSub.getSubscriptionsInGroup(groupUuid, pkgForDebug);
+            } else {
+                if (!isSystemProcess()) {
+                    throw new IllegalStateException("telephony service is null.");
+                }
             }
         } catch (RemoteException ex) {
-            // ignore it
+            loge("removeSubscriptionsFromGroup RemoteException " + ex);
+            if (!isSystemProcess()) {
+                ex.rethrowAsRuntimeException();
+            }
         }
 
         return result;
@@ -2868,7 +2942,7 @@
         if (info == null) return false;
 
         // If subscription is NOT grouped opportunistic subscription, it's visible.
-        if (TextUtils.isEmpty(info.getGroupUuid()) || !info.isOpportunistic()) return true;
+        if (info.getGroupUuid() == null || !info.isOpportunistic()) return true;
 
         // If the caller is the carrier app and owns the subscription, it should be visible
         // to the caller.
@@ -2898,14 +2972,14 @@
             // It should be the current active primary subscription if any, or any
             // primary subscription.
             List<SubscriptionInfo> selectableList = new ArrayList<>();
-            Map<String, SubscriptionInfo> groupMap = new HashMap<>();
+            Map<ParcelUuid, SubscriptionInfo> groupMap = new HashMap<>();
 
             for (SubscriptionInfo info : availableList) {
                 // Opportunistic subscriptions are considered invisible
                 // to users so they should never be returned.
                 if (!isSubscriptionVisible(info)) continue;
 
-                String groupUuid = info.getGroupUuid();
+                ParcelUuid groupUuid = info.getGroupUuid();
                 if (groupUuid == null) {
                     // Doesn't belong to any group. Add in the list.
                     selectableList.add(info);
diff --git a/telephony/java/android/telephony/TelephonyManager.java b/telephony/java/android/telephony/TelephonyManager.java
index d296b2f..0d4d654 100644
--- a/telephony/java/android/telephony/TelephonyManager.java
+++ b/telephony/java/android/telephony/TelephonyManager.java
@@ -1428,6 +1428,70 @@
     public static final String EXTRA_ANOMALY_DESCRIPTION =
             "android.telephony.extra.ANOMALY_DESCRIPTION";
 
+    /**
+     * Broadcast intent sent to indicate primary (non-opportunistic) subscription list has changed.
+     *
+     * @hide
+     */
+    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
+    public static final String ACTION_PRIMARY_SUBSCRIPTION_LIST_CHANGED =
+            "android.telephony.action.PRIMARY_SUBSCRIPTION_LIST_CHANGED";
+
+    /**
+     * Integer intent extra to be used with {@link #ACTION_PRIMARY_SUBSCRIPTION_LIST_CHANGED}
+     * to indicate whether a SIM selection is needed to choose default subscription.
+     *
+     * @hide
+     */
+    public static final String EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE =
+            "android.telephony.extra.DEFAULT_SUBSCRIPTION_SELECT_TYPE";
+
+    /**
+     * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
+     * to indicate there's no need to re-select any default subscription.
+     * @hide
+     */
+    public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_NONE = 0;
+
+    /**
+     * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
+     * to indicate there's a need to select default data subscription.
+     * @hide
+     */
+    public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_DATA = 1;
+
+    /**
+     * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
+     * to indicate there's a need to select default voice call subscription.
+     * @hide
+     */
+    public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_VOICE = 2;
+
+    /**
+     * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
+     * to indicate there's a need to select default sms subscription.
+     * @hide
+     */
+    public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_SMS = 3;
+
+    /**
+     * Used as an int value for {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE}
+     * to indicate user to decide whether current SIM should be preferred for all
+     * data / voice / sms.
+     * @hide
+     */
+    public static final int EXTRA_DEFAULT_SUBSCRIPTION_SELECT_FOR_ALL_TYPES = 4;
+
+    /**
+     * Integer intent extra to be used with
+     * {@link #EXTRA_DEFAULT_SUBSCRIPTION_SELECT_FOR_ALL_TYPES}
+     * to indicate which SIM is being selected.
+     *
+     * @hide
+     */
+    public static final String EXTRA_DEFAULT_SUBSCRIPTION_ID =
+            "android.telephony.extra.DEFAULT_SUBSCRIPTION_ID";
+
     //
     //
     // Device Info
diff --git a/telephony/java/android/telephony/ims/feature/ImsFeature.java b/telephony/java/android/telephony/ims/feature/ImsFeature.java
index d2b4133..5e3f398 100644
--- a/telephony/java/android/telephony/ims/feature/ImsFeature.java
+++ b/telephony/java/android/telephony/ims/feature/ImsFeature.java
@@ -210,7 +210,7 @@
     /**
      * Contains the capabilities defined and supported by an ImsFeature in the form of a bit mask.
      * @hide
-     * @deprecated
+     * @deprecated Use {@link MmTelFeature.MmTelCapabilities} instead.
      */
     @SystemApi  // SystemApi only because it was leaked through type usage in a previous release.
     public static class Capabilities {
diff --git a/telephony/java/com/android/internal/telephony/ISub.aidl b/telephony/java/com/android/internal/telephony/ISub.aidl
index 3bbf7a4..01fdae8 100755
--- a/telephony/java/com/android/internal/telephony/ISub.aidl
+++ b/telephony/java/com/android/internal/telephony/ISub.aidl
@@ -17,6 +17,7 @@
 package com.android.internal.telephony;
 
 import android.telephony.SubscriptionInfo;
+import android.os.ParcelUuid;
 import com.android.internal.telephony.ISetOpportunisticDataCallback;
 
 interface ISub {
@@ -202,7 +203,7 @@
      * null if fails.
      *
      */
-    String setSubscriptionGroup(in int[] subIdList, String callingPackage);
+    ParcelUuid createSubscriptionGroup(in int[] subIdList, String callingPackage);
 
     /**
      * Set which subscription is preferred for cellular data. It's
@@ -234,9 +235,13 @@
      */
     List<SubscriptionInfo> getOpportunisticSubscriptions(String callingPackage);
 
-    boolean removeSubscriptionsFromGroup(in int[] subIdList, String callingPackage);
+    void removeSubscriptionsFromGroup(in int[] subIdList, in ParcelUuid groupUuid,
+        String callingPackage);
 
-    List<SubscriptionInfo> getSubscriptionsInGroup(int subId, String callingPackage);
+    void addSubscriptionsIntoGroup(in int[] subIdList, in ParcelUuid groupUuid,
+        String callingPackage);
+
+    List<SubscriptionInfo> getSubscriptionsInGroup(in ParcelUuid groupUuid, String callingPackage);
 
     int getSlotIndex(int subId);
 
@@ -264,8 +269,6 @@
 
     void setDefaultSmsSubId(int subId);
 
-    void clearDefaultsForInactiveSubIds();
-
     int[] getActiveSubIdList(boolean visibleOnly);
 
     int setSubscriptionProperty(int subId, String propKey, String propValue);
diff --git a/wifi/java/android/net/wifi/WifiUsabilityStatsEntry.java b/wifi/java/android/net/wifi/WifiUsabilityStatsEntry.java
index 01176f2..e595164 100644
--- a/wifi/java/android/net/wifi/WifiUsabilityStatsEntry.java
+++ b/wifi/java/android/net/wifi/WifiUsabilityStatsEntry.java
@@ -345,7 +345,7 @@
     }
 
     /** Whether the primary registered cell of current entry is same as that of previous entry */
-    public boolean getIsSameRegisteredCell() {
+    public boolean isSameRegisteredCell() {
         return mIsSameRegisteredCell;
     }
 }
diff --git a/wifi/tests/src/android/net/wifi/WifiUsabilityStatsEntryTest.java b/wifi/tests/src/android/net/wifi/WifiUsabilityStatsEntryTest.java
index cd60f02..5184152 100644
--- a/wifi/tests/src/android/net/wifi/WifiUsabilityStatsEntryTest.java
+++ b/wifi/tests/src/android/net/wifi/WifiUsabilityStatsEntryTest.java
@@ -116,6 +116,6 @@
         assertEquals(expected.getCellularSignalStrengthDbm(),
                 actual.getCellularSignalStrengthDbm());
         assertEquals(expected.getCellularSignalStrengthDb(), actual.getCellularSignalStrengthDb());
-        assertEquals(expected.getIsSameRegisteredCell(), actual.getIsSameRegisteredCell());
+        assertEquals(expected.isSameRegisteredCell(), actual.isSameRegisteredCell());
     }
 }