Merge "Add handling for preferCodeIntegrity"
diff --git a/Android.bp b/Android.bp
index 7ce8b31..f97cf72 100644
--- a/Android.bp
+++ b/Android.bp
@@ -656,6 +656,7 @@
         ":vold_aidl",
         ":installd_aidl",
         ":dumpstate_aidl",
+        ":incidentcompanion_aidl",
 
         "lowpan/java/android/net/lowpan/ILowpanEnergyScanCallback.aidl",
         "lowpan/java/android/net/lowpan/ILowpanNetScanCallback.aidl",
@@ -706,6 +707,7 @@
             "system/update_engine/binder_bindings",
             "frameworks/native/aidl/binder",
             "frameworks/native/cmds/dumpstate/binder",
+            "frameworks/native/libs/incidentcompanion/binder",
             "frameworks/av/camera/aidl",
             "frameworks/av/media/libaudioclient/aidl",
             "frameworks/native/aidl/gui",
@@ -778,6 +780,7 @@
         "--multi-dex",
     ],
 
+    plugins: ["view-inspector-annotation-processor"],
 }
 
 filegroup {
diff --git a/api/current.txt b/api/current.txt
index d431e39..ac75dc8 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -6606,6 +6606,7 @@
     method @Nullable public String[] getAccountTypesWithManagementDisabled();
     method @Nullable public java.util.List<android.content.ComponentName> getActiveAdmins();
     method @NonNull public java.util.Set<java.lang.String> getAffiliationIds(@NonNull android.content.ComponentName);
+    method @Nullable public java.util.List<java.lang.String> getAlwaysOnVpnLockdownWhitelist(@NonNull android.content.ComponentName);
     method @Nullable public String getAlwaysOnVpnPackage(@NonNull android.content.ComponentName);
     method @WorkerThread @NonNull public android.os.Bundle getApplicationRestrictions(@Nullable android.content.ComponentName, String);
     method @Deprecated @Nullable public String getApplicationRestrictionsManagingPackage(@NonNull android.content.ComponentName);
@@ -6680,6 +6681,7 @@
     method public boolean isActivePasswordSufficient();
     method public boolean isAdminActive(@NonNull android.content.ComponentName);
     method public boolean isAffiliatedUser();
+    method public boolean isAlwaysOnVpnLockdownEnabled(@NonNull android.content.ComponentName);
     method public boolean isApplicationHidden(@NonNull android.content.ComponentName, String);
     method public boolean isBackupServiceEnabled(@NonNull android.content.ComponentName);
     method @Deprecated public boolean isCallerApplicationRestrictionsManagingPackage();
@@ -6716,7 +6718,8 @@
     method @Nullable public java.util.List<android.app.admin.SecurityLog.SecurityEvent> retrieveSecurityLogs(@NonNull android.content.ComponentName);
     method public void setAccountManagementDisabled(@NonNull android.content.ComponentName, String, boolean);
     method public void setAffiliationIds(@NonNull android.content.ComponentName, @NonNull java.util.Set<java.lang.String>);
-    method public void setAlwaysOnVpnPackage(@NonNull android.content.ComponentName, @Nullable String, boolean) throws android.content.pm.PackageManager.NameNotFoundException, java.lang.UnsupportedOperationException;
+    method public void setAlwaysOnVpnPackage(@NonNull android.content.ComponentName, @Nullable String, boolean) throws android.content.pm.PackageManager.NameNotFoundException;
+    method public void setAlwaysOnVpnPackage(@NonNull android.content.ComponentName, @Nullable String, boolean, @Nullable java.util.List<java.lang.String>) throws android.content.pm.PackageManager.NameNotFoundException;
     method public boolean setApplicationHidden(@NonNull android.content.ComponentName, String, boolean);
     method @WorkerThread public void setApplicationRestrictions(@Nullable android.content.ComponentName, String, android.os.Bundle);
     method @Deprecated public void setApplicationRestrictionsManagingPackage(@NonNull android.content.ComponentName, @Nullable String) throws android.content.pm.PackageManager.NameNotFoundException;
@@ -11648,8 +11651,7 @@
     field public static final String FEATURE_FAKETOUCH = "android.hardware.faketouch";
     field public static final String FEATURE_FAKETOUCH_MULTITOUCH_DISTINCT = "android.hardware.faketouch.multitouch.distinct";
     field public static final String FEATURE_FAKETOUCH_MULTITOUCH_JAZZHAND = "android.hardware.faketouch.multitouch.jazzhand";
-    field public static final String FEATURE_FINGERPRINT = "android.hardware.biometrics.fingerprint";
-    field public static final String FEATURE_FINGERPRINT_PRE_29 = "android.hardware.fingerprint";
+    field public static final String FEATURE_FINGERPRINT = "android.hardware.fingerprint";
     field public static final String FEATURE_FREEFORM_WINDOW_MANAGEMENT = "android.software.freeform_window_management";
     field public static final String FEATURE_GAMEPAD = "android.hardware.gamepad";
     field public static final String FEATURE_HIFI_SENSORS = "android.hardware.sensor.hifi_sensors";
@@ -16678,6 +16680,7 @@
   }
 
   public static final class CameraCharacteristics.Key<T> {
+    ctor public CameraCharacteristics.Key(String, Class<T>);
     method @NonNull public String getName();
   }
 
@@ -17049,6 +17052,7 @@
   }
 
   public static final class CaptureRequest.Key<T> {
+    ctor public CaptureRequest.Key(String, Class<T>);
     method @NonNull public String getName();
   }
 
@@ -17143,6 +17147,7 @@
   }
 
   public static final class CaptureResult.Key<T> {
+    ctor public CaptureResult.Key(String, Class<T>);
     method @NonNull public String getName();
   }
 
@@ -28949,6 +28954,7 @@
   }
 
   public abstract class NetworkSpecifier {
+    ctor public NetworkSpecifier();
   }
 
   public class ParseException extends java.lang.RuntimeException {
@@ -29972,24 +29978,25 @@
     method @Deprecated public abstract void onSucceeded();
   }
 
-  public class WifiNetworkConfigBuilder {
-    ctor public WifiNetworkConfigBuilder();
-    method public android.net.NetworkSpecifier buildNetworkSpecifier();
-    method public android.net.wifi.WifiNetworkSuggestion buildNetworkSuggestion();
-    method public android.net.wifi.WifiNetworkConfigBuilder setBssid(@NonNull android.net.MacAddress);
-    method public android.net.wifi.WifiNetworkConfigBuilder setBssidPattern(@NonNull android.net.MacAddress, @NonNull android.net.MacAddress);
-    method public android.net.wifi.WifiNetworkConfigBuilder setIsAppInteractionRequired();
-    method public android.net.wifi.WifiNetworkConfigBuilder setIsEnhancedOpen();
-    method public android.net.wifi.WifiNetworkConfigBuilder setIsHiddenSsid();
-    method public android.net.wifi.WifiNetworkConfigBuilder setIsMetered();
-    method public android.net.wifi.WifiNetworkConfigBuilder setIsUserInteractionRequired();
-    method public android.net.wifi.WifiNetworkConfigBuilder setPriority(int);
-    method public android.net.wifi.WifiNetworkConfigBuilder setSsid(@NonNull String);
-    method public android.net.wifi.WifiNetworkConfigBuilder setSsidPattern(@NonNull android.os.PatternMatcher);
-    method public android.net.wifi.WifiNetworkConfigBuilder setWpa2EnterpriseConfig(@NonNull android.net.wifi.WifiEnterpriseConfig);
-    method public android.net.wifi.WifiNetworkConfigBuilder setWpa2Passphrase(@NonNull String);
-    method public android.net.wifi.WifiNetworkConfigBuilder setWpa3EnterpriseConfig(@NonNull android.net.wifi.WifiEnterpriseConfig);
-    method public android.net.wifi.WifiNetworkConfigBuilder setWpa3Passphrase(@NonNull String);
+  public final class WifiNetworkSpecifier extends android.net.NetworkSpecifier implements android.os.Parcelable {
+    method public int describeContents();
+    method public void writeToParcel(android.os.Parcel, int);
+    field public static final android.os.Parcelable.Creator<android.net.wifi.WifiNetworkSpecifier> CREATOR;
+  }
+
+  public static class WifiNetworkSpecifier.Builder {
+    ctor public WifiNetworkSpecifier.Builder();
+    method public android.net.NetworkSpecifier build();
+    method public android.net.wifi.WifiNetworkSpecifier.Builder setBssid(@NonNull android.net.MacAddress);
+    method public android.net.wifi.WifiNetworkSpecifier.Builder setBssidPattern(@NonNull android.net.MacAddress, @NonNull android.net.MacAddress);
+    method public android.net.wifi.WifiNetworkSpecifier.Builder setIsEnhancedOpen();
+    method public android.net.wifi.WifiNetworkSpecifier.Builder setIsHiddenSsid();
+    method public android.net.wifi.WifiNetworkSpecifier.Builder setSsid(@NonNull String);
+    method public android.net.wifi.WifiNetworkSpecifier.Builder setSsidPattern(@NonNull android.os.PatternMatcher);
+    method public android.net.wifi.WifiNetworkSpecifier.Builder setWpa2EnterpriseConfig(@NonNull android.net.wifi.WifiEnterpriseConfig);
+    method public android.net.wifi.WifiNetworkSpecifier.Builder setWpa2Passphrase(@NonNull String);
+    method public android.net.wifi.WifiNetworkSpecifier.Builder setWpa3EnterpriseConfig(@NonNull android.net.wifi.WifiEnterpriseConfig);
+    method public android.net.wifi.WifiNetworkSpecifier.Builder setWpa3Passphrase(@NonNull String);
   }
 
   public final class WifiNetworkSuggestion implements android.os.Parcelable {
@@ -29998,6 +30005,23 @@
     field public static final android.os.Parcelable.Creator<android.net.wifi.WifiNetworkSuggestion> CREATOR;
   }
 
+  public static class WifiNetworkSuggestion.Builder {
+    ctor public WifiNetworkSuggestion.Builder();
+    method public android.net.wifi.WifiNetworkSuggestion build();
+    method public android.net.wifi.WifiNetworkSuggestion.Builder setBssid(@NonNull android.net.MacAddress);
+    method public android.net.wifi.WifiNetworkSuggestion.Builder setIsAppInteractionRequired();
+    method public android.net.wifi.WifiNetworkSuggestion.Builder setIsEnhancedOpen();
+    method public android.net.wifi.WifiNetworkSuggestion.Builder setIsHiddenSsid();
+    method public android.net.wifi.WifiNetworkSuggestion.Builder setIsMetered();
+    method public android.net.wifi.WifiNetworkSuggestion.Builder setIsUserInteractionRequired();
+    method public android.net.wifi.WifiNetworkSuggestion.Builder setPriority(int);
+    method public android.net.wifi.WifiNetworkSuggestion.Builder setSsid(@NonNull String);
+    method public android.net.wifi.WifiNetworkSuggestion.Builder setWpa2EnterpriseConfig(@NonNull android.net.wifi.WifiEnterpriseConfig);
+    method public android.net.wifi.WifiNetworkSuggestion.Builder setWpa2Passphrase(@NonNull String);
+    method public android.net.wifi.WifiNetworkSuggestion.Builder setWpa3EnterpriseConfig(@NonNull android.net.wifi.WifiEnterpriseConfig);
+    method public android.net.wifi.WifiNetworkSuggestion.Builder setWpa3Passphrase(@NonNull String);
+  }
+
   public class WpsInfo implements android.os.Parcelable {
     ctor public WpsInfo();
     ctor public WpsInfo(android.net.wifi.WpsInfo);
@@ -44151,6 +44175,9 @@
     field public static final String KEY_MONTHLY_DATA_CYCLE_DAY_INT = "monthly_data_cycle_day_int";
     field public static final String KEY_ONLY_SINGLE_DC_ALLOWED_INT_ARRAY = "only_single_dc_allowed_int_array";
     field public static final String KEY_OPERATOR_SELECTION_EXPAND_BOOL = "operator_selection_expand_bool";
+    field public static final String KEY_OPPORTUNISTIC_NETWORK_DATA_SWITCH_HYSTERESIS_TIME_LONG = "opportunistic_network_data_switch_hysteresis_time_long";
+    field public static final String KEY_OPPORTUNISTIC_NETWORK_ENTRY_OR_EXIT_HYSTERESIS_TIME_LONG = "opportunistic_network_entry_or_exit_hysteresis_time_long";
+    field public static final String KEY_OPPORTUNISTIC_NETWORK_ENTRY_THRESHOLD_BANDWIDTH_INT = "opportunistic_network_entry_threshold_bandwidth_int";
     field public static final String KEY_OPPORTUNISTIC_NETWORK_ENTRY_THRESHOLD_RSRP_INT = "opportunistic_network_entry_threshold_rsrp_int";
     field public static final String KEY_OPPORTUNISTIC_NETWORK_ENTRY_THRESHOLD_RSSNR_INT = "opportunistic_network_entry_threshold_rssnr_int";
     field public static final String KEY_OPPORTUNISTIC_NETWORK_EXIT_THRESHOLD_RSRP_INT = "opportunistic_network_exit_threshold_rsrp_int";
@@ -44819,6 +44846,7 @@
   public class SubscriptionInfo implements android.os.Parcelable {
     method public android.graphics.Bitmap createIconBitmap(android.content.Context);
     method public int describeContents();
+    method public int getCardId();
     method public int getCarrierId();
     method public CharSequence getCarrierName();
     method public String getCountryIso();
@@ -44935,6 +44963,7 @@
     method public android.telephony.TelephonyManager createForSubscriptionId(int);
     method @RequiresPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION) public java.util.List<android.telephony.CellInfo> getAllCellInfo();
     method public int getCallState();
+    method public int getCardIdForDefaultEuicc();
     method @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) @WorkerThread public android.os.PersistableBundle getCarrierConfig();
     method public int getCarrierIdFromSimMccMnc();
     method @Deprecated @RequiresPermission(anyOf={android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}) public android.telephony.CellLocation getCellLocation();
@@ -44982,6 +45011,7 @@
     method @RequiresPermission("android.permission.READ_PRIVILEGED_PHONE_STATE") public String getSubscriberId();
     method public String getTypeAllocationCode();
     method public String getTypeAllocationCode(int);
+    method @RequiresPermission("android.permission.READ_PRIVILEGED_PHONE_STATE") public java.util.List<android.telephony.UiccCardInfo> getUiccCardsInfo();
     method @Nullable @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public String getVisualVoicemailPackageName();
     method @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public String getVoiceMailAlphaTag();
     method @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public String getVoiceMailNumber();
@@ -45076,6 +45106,7 @@
     field public static final String EXTRA_STATE_RINGING;
     field public static final String EXTRA_SUBSCRIPTION_ID = "android.telephony.extra.SUBSCRIPTION_ID";
     field public static final String EXTRA_VOICEMAIL_NUMBER = "android.telephony.extra.VOICEMAIL_NUMBER";
+    field public static final int INVALID_CARD_ID = -1; // 0xffffffff
     field public static final String METADATA_HIDE_VOICEMAIL_SETTINGS_MENU = "android.telephony.HIDE_VOICEMAIL_SETTINGS_MENU";
     field public static final int NETWORK_TYPE_1xRTT = 7; // 0x7
     field public static final int NETWORK_TYPE_CDMA = 4; // 0x4
@@ -45143,6 +45174,18 @@
     method public void onResults(java.util.List<android.telephony.CellInfo>);
   }
 
+  public final class UiccCardInfo implements android.os.Parcelable {
+    ctor public UiccCardInfo(boolean, int, String, String, int);
+    method public int describeContents();
+    method public int getCardId();
+    method public String getEid();
+    method public String getIccId();
+    method public int getSlotIndex();
+    method public boolean isEuicc();
+    method public void writeToParcel(android.os.Parcel, int);
+    field public static final android.os.Parcelable.Creator<android.telephony.UiccCardInfo> CREATOR;
+  }
+
   public abstract class VisualVoicemailService extends android.app.Service {
     ctor public VisualVoicemailService();
     method public android.os.IBinder onBind(android.content.Intent);
diff --git a/api/system-current.txt b/api/system-current.txt
index f1918fd..b9c1362 100644
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -18,6 +18,7 @@
     field public static final String ALLOCATE_AGGRESSIVE = "android.permission.ALLOCATE_AGGRESSIVE";
     field public static final String ALLOW_ANY_CODEC_FOR_PLAYBACK = "android.permission.ALLOW_ANY_CODEC_FOR_PLAYBACK";
     field public static final String AMBIENT_WALLPAPER = "android.permission.AMBIENT_WALLPAPER";
+    field public static final String APPROVE_INCIDENT_REPORTS = "android.permission.APPROVE_INCIDENT_REPORTS";
     field public static final String BACKUP = "android.permission.BACKUP";
     field public static final String BIND_ATTENTION_SERVICE = "android.permission.BIND_ATTENTION_SERVICE";
     field public static final String BIND_AUGMENTED_AUTOFILL_SERVICE = "android.permission.BIND_AUGMENTED_AUTOFILL_SERVICE";
@@ -346,10 +347,11 @@
     field public static final String OPSTR_WRITE_ICC_SMS = "android:write_icc_sms";
     field public static final String OPSTR_WRITE_SMS = "android:write_sms";
     field public static final String OPSTR_WRITE_WALLPAPER = "android:write_wallpaper";
-    field public static final int UID_STATE_BACKGROUND = 4; // 0x4
-    field public static final int UID_STATE_CACHED = 5; // 0x5
-    field public static final int UID_STATE_FOREGROUND = 3; // 0x3
-    field public static final int UID_STATE_FOREGROUND_SERVICE = 2; // 0x2
+    field public static final int UID_STATE_BACKGROUND = 5; // 0x5
+    field public static final int UID_STATE_CACHED = 6; // 0x6
+    field public static final int UID_STATE_FOREGROUND = 4; // 0x4
+    field public static final int UID_STATE_FOREGROUND_SERVICE = 3; // 0x3
+    field public static final int UID_STATE_FOREGROUND_SERVICE_LOCATION = 2; // 0x2
     field public static final int UID_STATE_PERSISTENT = 0; // 0x0
     field public static final int UID_STATE_TOP = 1; // 0x1
   }
@@ -1306,6 +1308,7 @@
     field public static final String ACTION_MANAGE_PERMISSION_APPS = "android.intent.action.MANAGE_PERMISSION_APPS";
     field @RequiresPermission(android.Manifest.permission.MANAGE_ROLE_HOLDERS) public static final String ACTION_MANAGE_SPECIAL_APP_ACCESSES = "android.intent.action.MANAGE_SPECIAL_APP_ACCESSES";
     field public static final String ACTION_MASTER_CLEAR_NOTIFICATION = "android.intent.action.MASTER_CLEAR_NOTIFICATION";
+    field public static final String ACTION_PENDING_INCIDENT_REPORTS_CHANGED = "android.intent.action.PENDING_INCIDENT_REPORTS_CHANGED";
     field public static final String ACTION_PRE_BOOT_COMPLETED = "android.intent.action.PRE_BOOT_COMPLETED";
     field public static final String ACTION_QUERY_PACKAGE_RESTART = "android.intent.action.QUERY_PACKAGE_RESTART";
     field public static final String ACTION_RESOLVE_INSTANT_APP_PACKAGE = "android.intent.action.RESOLVE_INSTANT_APP_PACKAGE";
@@ -1489,6 +1492,7 @@
     method @NonNull public android.content.pm.dex.ArtManager getArtManager();
     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();
     method @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL) public abstract java.util.List<android.content.pm.PackageInfo> getInstalledPackagesAsUser(int, int);
     method @Nullable @RequiresPermission(android.Manifest.permission.ACCESS_INSTANT_APPS) public abstract android.graphics.drawable.Drawable getInstantAppIcon(String);
     method public abstract android.content.ComponentName getInstantAppInstallerComponent();
@@ -1610,6 +1614,7 @@
     field public static final int FLAG_REMOVED = 2; // 0x2
     field public static final int PROTECTION_FLAG_CONFIGURATOR = 524288; // 0x80000
     field public static final int PROTECTION_FLAG_DOCUMENTER = 262144; // 0x40000
+    field public static final int PROTECTION_FLAG_INCIDENT_REPORT_APPROVER = 1048576; // 0x100000
     field public static final int PROTECTION_FLAG_OEM = 16384; // 0x4000
     field public static final int PROTECTION_FLAG_SYSTEM_TEXT_CLASSIFIER = 65536; // 0x10000
     field public static final int PROTECTION_FLAG_WELLBEING = 131072; // 0x20000
@@ -5330,7 +5335,27 @@
   }
 
   public class IncidentManager {
+    method @RequiresPermission(android.Manifest.permission.APPROVE_INCIDENT_REPORTS) public void approveReport(android.net.Uri);
+    method @RequiresPermission("android.permission.REQUEST_INCIDENT_REPORT_APPROVAL") public void cancelAuthorization(android.os.IncidentManager.AuthListener);
+    method @RequiresPermission(android.Manifest.permission.APPROVE_INCIDENT_REPORTS) public void denyReport(android.net.Uri);
+    method @RequiresPermission(android.Manifest.permission.APPROVE_INCIDENT_REPORTS) public java.util.List<android.os.IncidentManager.PendingReport> getPendingReports();
     method @RequiresPermission(allOf={android.Manifest.permission.DUMP, android.Manifest.permission.PACKAGE_USAGE_STATS}) public void reportIncident(android.os.IncidentReportArgs);
+    method @RequiresPermission("android.permission.REQUEST_INCIDENT_REPORT_APPROVAL") public void requestAuthorization(int, String, int, android.os.IncidentManager.AuthListener);
+    field public static final int FLAG_CONFIRMATION_DIALOG = 1; // 0x1
+  }
+
+  public static class IncidentManager.AuthListener {
+    ctor public IncidentManager.AuthListener();
+    method public void onReportApproved();
+    method public void onReportDenied();
+  }
+
+  public static class IncidentManager.PendingReport {
+    ctor public IncidentManager.PendingReport(@NonNull android.net.Uri);
+    method public int getFlags();
+    method @NonNull public String getRequestingPackage();
+    method public long getTimestamp();
+    method @NonNull public android.net.Uri getUri();
   }
 
   public final class IncidentReportArgs implements android.os.Parcelable {
@@ -5759,7 +5784,6 @@
     field public static final String NAMESPACE_GAME_DRIVER = "game_driver";
     field public static final String NAMESPACE_INPUT_NATIVE_BOOT = "input_native_boot";
     field public static final String NAMESPACE_NETD_NATIVE = "netd_native";
-    field public static final String NAMESPACE_NOTIFICATION_ASSISTANT = "notification_assistant";
   }
 
   public static interface DeviceConfig.ActivityManager {
@@ -5780,6 +5804,10 @@
     field public static final String PROPERTY_SERVICE_ENABLED = "service_enabled";
   }
 
+  public static interface DeviceConfig.ContentCapture {
+    field public static final String NAMESPACE = "content_capture";
+  }
+
   public static interface DeviceConfig.FsiBoot {
     field public static final String NAMESPACE = "fsi_boot";
     field public static final String OOB_ENABLED = "oob_enabled";
@@ -5792,10 +5820,22 @@
     field public static final String PROPERTY_ATTENTION_SETTINGS = "attention_settings";
   }
 
+  public static interface DeviceConfig.NotificationAssistant {
+    field public static final String GENERATE_ACTIONS = "generate_actions";
+    field public static final String GENERATE_REPLIES = "generate_replies";
+    field public static final String NAMESPACE = "notification_assistant";
+  }
+
   public static interface DeviceConfig.OnPropertyChangedListener {
     method public void onPropertyChanged(String, String, String);
   }
 
+  public static interface DeviceConfig.Privacy {
+    field public static final String NAMESPACE = "privacy";
+    field public static final String PROPERTY_LOCATION_ACCESS_CHECK_ENABLED = "enable_location_access_check";
+    field public static final String PROPERTY_PERMISSIONS_HUB_ENABLED = "enable_permissions_hub";
+  }
+
   public static interface DeviceConfig.Storage {
     field public static final String ISOLATED_STORAGE_ENABLED = "isolated_storage_enabled";
     field public static final String NAMESPACE = "storage";
@@ -5988,6 +6028,7 @@
     field public static final String AUTOFILL_USER_DATA_MAX_VALUE_LENGTH = "autofill_user_data_max_value_length";
     field public static final String AUTOFILL_USER_DATA_MIN_VALUE_LENGTH = "autofill_user_data_min_value_length";
     field public static final String COMPLETED_CATEGORY_PREFIX = "suggested.completed_category.";
+    field public static final String CONTENT_CAPTURE_ENABLED = "content_capture_enabled";
     field public static final String DOZE_ALWAYS_ON = "doze_always_on";
     field public static final String HUSH_GESTURE_USED = "hush_gesture_used";
     field public static final String INSTANT_APPS_ENABLED = "instant_apps_enabled";
@@ -7569,6 +7610,7 @@
   public class PhoneStateListener {
     method public void onCallAttributesChanged(@NonNull android.telephony.CallAttributes);
     method public void onCallDisconnectCauseChanged(int, int);
+    method public void onImsCallDisconnectCauseChanged(@NonNull android.telephony.ims.ImsReasonInfo);
     method public void onPreciseCallStateChanged(android.telephony.PreciseCallState);
     method public void onPreciseDataConnectionStateChanged(android.telephony.PreciseDataConnectionState);
     method public void onRadioPowerStateChanged(int);
@@ -7576,6 +7618,7 @@
     method public void onVoiceActivationStateChanged(int);
     field public static final int LISTEN_CALL_ATTRIBUTES_CHANGED = 67108864; // 0x4000000
     field public static final int LISTEN_CALL_DISCONNECT_CAUSES = 33554432; // 0x2000000
+    field public static final int LISTEN_IMS_CALL_DISCONNECT_CAUSES = 134217728; // 0x8000000
     field public static final int LISTEN_PRECISE_CALL_STATE = 2048; // 0x800
     field public static final int LISTEN_PRECISE_DATA_CONNECTION_STATE = 4096; // 0x1000
     field public static final int LISTEN_RADIO_POWER_STATE_CHANGED = 8388608; // 0x800000
@@ -7746,7 +7789,6 @@
 
   public class SubscriptionInfo implements android.os.Parcelable {
     method @Nullable public java.util.List<android.telephony.UiccAccessRule> getAccessRules();
-    method public int getCardId();
     method public int getProfileClass();
   }
 
@@ -7809,7 +7851,6 @@
     method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void enableVideoCalling(boolean);
     method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public String getAidForAppType(int);
     method @Deprecated @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public java.util.List<android.service.carrier.CarrierIdentifier> getAllowedCarriers(int);
-    method @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public int getCardIdForDefaultEuicc();
     method public java.util.List<java.lang.String> getCarrierPackageNamesForIntent(android.content.Intent);
     method public java.util.List<java.lang.String> getCarrierPackageNamesForIntentAndPhone(android.content.Intent, int);
     method @Nullable @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public android.telephony.CarrierRestrictionRules getCarrierRestrictionRules();
@@ -7833,7 +7874,6 @@
     method @Nullable @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public String getSimLocale();
     method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public int getSupportedRadioAccessFamily();
     method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public java.util.List<android.telephony.TelephonyHistogram> getTelephonyHistograms();
-    method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public android.telephony.UiccCardInfo[] getUiccCardsInfo();
     method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public android.telephony.UiccSlotInfo[] getUiccSlotsInfo();
     method @Nullable public android.os.Bundle getVisualVoicemailSettings();
     method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public int getVoiceActivationState();
@@ -7882,7 +7922,6 @@
     field public static final String EXTRA_SIM_STATE = "android.telephony.extra.SIM_STATE";
     field public static final String EXTRA_VISUAL_VOICEMAIL_ENABLED_BY_USER_BOOL = "android.telephony.extra.VISUAL_VOICEMAIL_ENABLED_BY_USER_BOOL";
     field public static final String EXTRA_VOICEMAIL_SCRAMBLED_PIN_STRING = "android.telephony.extra.VOICEMAIL_SCRAMBLED_PIN_STRING";
-    field public static final int INVALID_CARD_ID = -1; // 0xffffffff
     field public static final long MAX_NUMBER_VERIFICATION_TIMEOUT_MILLIS = 60000L; // 0xea60L
     field public static final int NETWORK_TYPE_BITMASK_1xRTT = 128; // 0x80
     field public static final int NETWORK_TYPE_BITMASK_CDMA = 16; // 0x10
@@ -7934,18 +7973,6 @@
     field public static final android.os.Parcelable.Creator<android.telephony.UiccAccessRule> CREATOR;
   }
 
-  public class UiccCardInfo implements android.os.Parcelable {
-    ctor public UiccCardInfo(boolean, int, String, String, int);
-    method public int describeContents();
-    method public int getCardId();
-    method public String getEid();
-    method public String getIccId();
-    method public int getSlotIndex();
-    method public boolean isEuicc();
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.UiccCardInfo> CREATOR;
-  }
-
   public class UiccSlotInfo implements android.os.Parcelable {
     ctor public UiccSlotInfo(boolean, boolean, String, int, int, boolean);
     method public int describeContents();
@@ -9323,6 +9350,11 @@
     field public static final int TYPE_VIEW_TEXT_CHANGED = 3; // 0x3
   }
 
+  public final class ContentCaptureManager {
+    method public boolean isContentCaptureFeatureEnabled();
+    method public void setContentCaptureFeatureEnabled(boolean);
+  }
+
   public final class UserDataRemovalRequest implements android.os.Parcelable {
     method @NonNull public String getPackageName();
     method @NonNull public java.util.List<android.view.contentcapture.UserDataRemovalRequest.UriRequest> getUriRequests();
diff --git a/api/test-current.txt b/api/test-current.txt
index 9c27535..01faa23 100644
--- a/api/test-current.txt
+++ b/api/test-current.txt
@@ -4,6 +4,7 @@
   public static final class Manifest.permission {
     field public static final String ACCESS_NOTIFICATIONS = "android.permission.ACCESS_NOTIFICATIONS";
     field public static final String ACTIVITY_EMBEDDING = "android.permission.ACTIVITY_EMBEDDING";
+    field public static final String APPROVE_INCIDENT_REPORTS = "android.permission.APPROVE_INCIDENT_REPORTS";
     field public static final String BRIGHTNESS_SLIDER_USAGE = "android.permission.BRIGHTNESS_SLIDER_USAGE";
     field public static final String CHANGE_APP_IDLE_STATE = "android.permission.CHANGE_APP_IDLE_STATE";
     field public static final String CLEAR_APP_USER_DATA = "android.permission.CLEAR_APP_USER_DATA";
@@ -163,10 +164,11 @@
     field public static final int OP_COARSE_LOCATION = 0; // 0x0
     field public static final int OP_RECORD_AUDIO = 27; // 0x1b
     field public static final int OP_SYSTEM_ALERT_WINDOW = 24; // 0x18
-    field public static final int UID_STATE_BACKGROUND = 4; // 0x4
-    field public static final int UID_STATE_CACHED = 5; // 0x5
-    field public static final int UID_STATE_FOREGROUND = 3; // 0x3
-    field public static final int UID_STATE_FOREGROUND_SERVICE = 2; // 0x2
+    field public static final int UID_STATE_BACKGROUND = 5; // 0x5
+    field public static final int UID_STATE_CACHED = 6; // 0x6
+    field public static final int UID_STATE_FOREGROUND = 4; // 0x4
+    field public static final int UID_STATE_FOREGROUND_SERVICE = 3; // 0x3
+    field public static final int UID_STATE_FOREGROUND_SERVICE_LOCATION = 2; // 0x2
     field public static final int UID_STATE_PERSISTENT = 0; // 0x0
     field public static final int UID_STATE_TOP = 1; // 0x1
   }
@@ -413,6 +415,7 @@
   public abstract class PackageManager {
     method public abstract boolean arePermissionsIndividuallyControlled();
     method @RequiresPermission("android.permission.INTERACT_ACROSS_USERS_FULL") public abstract String getDefaultBrowserPackageNameAsUser(int);
+    method public String getIncidentReportApproverPackageName();
     method public abstract int getInstallReason(String, @NonNull android.os.UserHandle);
     method public abstract java.util.List<android.content.pm.ApplicationInfo> getInstalledApplicationsAsUser(int, int);
     method @RequiresPermission("android.permission.INTERACT_ACROSS_USERS_FULL") public abstract java.util.List<android.content.pm.PackageInfo> getInstalledPackagesAsUser(int, int);
@@ -434,6 +437,7 @@
   public class PermissionInfo extends android.content.pm.PackageItemInfo implements android.os.Parcelable {
     field public static final int PROTECTION_FLAG_CONFIGURATOR = 524288; // 0x80000
     field public static final int PROTECTION_FLAG_DOCUMENTER = 262144; // 0x40000
+    field public static final int PROTECTION_FLAG_INCIDENT_REPORT_APPROVER = 1048576; // 0x100000
     field public static final int PROTECTION_FLAG_OEM = 16384; // 0x4000
     field public static final int PROTECTION_FLAG_SYSTEM_TEXT_CLASSIFIER = 65536; // 0x10000
     field public static final int PROTECTION_FLAG_VENDOR_PRIVILEGED = 32768; // 0x8000
@@ -1279,7 +1283,27 @@
   }
 
   public class IncidentManager {
+    method @RequiresPermission(android.Manifest.permission.APPROVE_INCIDENT_REPORTS) public void approveReport(android.net.Uri);
+    method @RequiresPermission("android.permission.REQUEST_INCIDENT_REPORT_APPROVAL") public void cancelAuthorization(android.os.IncidentManager.AuthListener);
+    method @RequiresPermission(android.Manifest.permission.APPROVE_INCIDENT_REPORTS) public void denyReport(android.net.Uri);
+    method @RequiresPermission(android.Manifest.permission.APPROVE_INCIDENT_REPORTS) public java.util.List<android.os.IncidentManager.PendingReport> getPendingReports();
     method @RequiresPermission(allOf={android.Manifest.permission.DUMP, android.Manifest.permission.PACKAGE_USAGE_STATS}) public void reportIncident(android.os.IncidentReportArgs);
+    method @RequiresPermission("android.permission.REQUEST_INCIDENT_REPORT_APPROVAL") public void requestAuthorization(int, String, int, android.os.IncidentManager.AuthListener);
+    field public static final int FLAG_CONFIRMATION_DIALOG = 1; // 0x1
+  }
+
+  public static class IncidentManager.AuthListener {
+    ctor public IncidentManager.AuthListener();
+    method public void onReportApproved();
+    method public void onReportDenied();
+  }
+
+  public static class IncidentManager.PendingReport {
+    ctor public IncidentManager.PendingReport(@NonNull android.net.Uri);
+    method public int getFlags();
+    method @NonNull public String getRequestingPackage();
+    method public long getTimestamp();
+    method @NonNull public android.net.Uri getUri();
   }
 
   public final class IncidentReportArgs implements android.os.Parcelable {
@@ -1610,6 +1634,16 @@
     field public static final android.net.Uri CORP_CONTENT_URI;
   }
 
+  public final class DeviceConfig {
+    method @RequiresPermission("android.permission.WRITE_DEVICE_CONFIG") public static void resetToDefaults(int, @Nullable String);
+    method @RequiresPermission("android.permission.WRITE_DEVICE_CONFIG") public static boolean setProperty(String, String, String, boolean);
+  }
+
+  public static interface DeviceConfig.Privacy {
+    field public static final String NAMESPACE = "privacy";
+    field public static final String PROPERTY_LOCATION_ACCESS_CHECK_ENABLED = "enable_location_access_check";
+  }
+
   public final class MediaStore {
     method @RequiresPermission(android.Manifest.permission.CLEAR_APP_USER_DATA) public static void deleteContributedMedia(android.content.Context, String, android.os.UserHandle) throws java.io.IOException;
     method @RequiresPermission(android.Manifest.permission.CLEAR_APP_USER_DATA) public static long getContributedMediaSize(android.content.Context, String, android.os.UserHandle) throws java.io.IOException;
@@ -1621,6 +1655,7 @@
 
   public final class Settings {
     field public static final String ACTION_ENTERPRISE_PRIVACY_SETTINGS = "android.settings.ENTERPRISE_PRIVACY_SETTINGS";
+    field public static final int RESET_MODE_PACKAGE_DEFAULTS = 1; // 0x1
   }
 
   public static final class Settings.Global extends android.provider.Settings.NameValueTable {
@@ -1663,6 +1698,7 @@
     field public static final String AUTOFILL_USER_DATA_MAX_USER_DATA_SIZE = "autofill_user_data_max_user_data_size";
     field public static final String AUTOFILL_USER_DATA_MAX_VALUE_LENGTH = "autofill_user_data_max_value_length";
     field public static final String AUTOFILL_USER_DATA_MIN_VALUE_LENGTH = "autofill_user_data_min_value_length";
+    field public static final String CONTENT_CAPTURE_ENABLED = "content_capture_enabled";
     field public static final String DISABLED_PRINT_SERVICES = "disabled_print_services";
     field @Deprecated public static final String ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES = "enabled_notification_policy_access_packages";
     field public static final String LOCATION_ACCESS_CHECK_DELAY_MILLIS = "location_access_check_delay_millis";
diff --git a/core/java/android/app/ActivityManager.java b/core/java/android/app/ActivityManager.java
index 1045b7a..75ea7bb 100644
--- a/core/java/android/app/ActivityManager.java
+++ b/core/java/android/app/ActivityManager.java
@@ -505,71 +505,74 @@
     @UnsupportedAppUsage
     public static final int PROCESS_STATE_TOP = 2;
 
+    /** @hide Process is hosting a foreground service with location type. */
+    public static final int PROCESS_STATE_FOREGROUND_SERVICE_LOCATION = 3;
+
     /** @hide Process is hosting a foreground service. */
     @UnsupportedAppUsage
-    public static final int PROCESS_STATE_FOREGROUND_SERVICE = 3;
+    public static final int PROCESS_STATE_FOREGROUND_SERVICE = 4;
 
     /** @hide Process is hosting a foreground service due to a system binding. */
     @UnsupportedAppUsage
-    public static final int PROCESS_STATE_BOUND_FOREGROUND_SERVICE = 4;
+    public static final int PROCESS_STATE_BOUND_FOREGROUND_SERVICE = 5;
 
     /** @hide Process is important to the user, and something they are aware of. */
-    public static final int PROCESS_STATE_IMPORTANT_FOREGROUND = 5;
+    public static final int PROCESS_STATE_IMPORTANT_FOREGROUND = 6;
 
     /** @hide Process is important to the user, but not something they are aware of. */
     @UnsupportedAppUsage
-    public static final int PROCESS_STATE_IMPORTANT_BACKGROUND = 6;
+    public static final int PROCESS_STATE_IMPORTANT_BACKGROUND = 7;
 
     /** @hide Process is in the background transient so we will try to keep running. */
-    public static final int PROCESS_STATE_TRANSIENT_BACKGROUND = 7;
+    public static final int PROCESS_STATE_TRANSIENT_BACKGROUND = 8;
 
     /** @hide Process is in the background running a backup/restore operation. */
-    public static final int PROCESS_STATE_BACKUP = 8;
+    public static final int PROCESS_STATE_BACKUP = 9;
 
     /** @hide Process is in the background running a service.  Unlike oom_adj, this level
      * is used for both the normal running in background state and the executing
      * operations state. */
     @UnsupportedAppUsage
-    public static final int PROCESS_STATE_SERVICE = 9;
+    public static final int PROCESS_STATE_SERVICE = 10;
 
     /** @hide Process is in the background running a receiver.   Note that from the
      * perspective of oom_adj, receivers run at a higher foreground level, but for our
      * prioritization here that is not necessary and putting them below services means
      * many fewer changes in some process states as they receive broadcasts. */
     @UnsupportedAppUsage
-    public static final int PROCESS_STATE_RECEIVER = 10;
+    public static final int PROCESS_STATE_RECEIVER = 11;
 
     /** @hide Same as {@link #PROCESS_STATE_TOP} but while device is sleeping. */
-    public static final int PROCESS_STATE_TOP_SLEEPING = 11;
+    public static final int PROCESS_STATE_TOP_SLEEPING = 12;
 
     /** @hide Process is in the background, but it can't restore its state so we want
      * to try to avoid killing it. */
-    public static final int PROCESS_STATE_HEAVY_WEIGHT = 12;
+    public static final int PROCESS_STATE_HEAVY_WEIGHT = 13;
 
     /** @hide Process is in the background but hosts the home activity. */
     @UnsupportedAppUsage
-    public static final int PROCESS_STATE_HOME = 13;
+    public static final int PROCESS_STATE_HOME = 14;
 
     /** @hide Process is in the background but hosts the last shown activity. */
-    public static final int PROCESS_STATE_LAST_ACTIVITY = 14;
+    public static final int PROCESS_STATE_LAST_ACTIVITY = 15;
 
     /** @hide Process is being cached for later use and contains activities. */
     @UnsupportedAppUsage
-    public static final int PROCESS_STATE_CACHED_ACTIVITY = 15;
+    public static final int PROCESS_STATE_CACHED_ACTIVITY = 16;
 
     /** @hide Process is being cached for later use and is a client of another cached
      * process that contains activities. */
-    public static final int PROCESS_STATE_CACHED_ACTIVITY_CLIENT = 16;
+    public static final int PROCESS_STATE_CACHED_ACTIVITY_CLIENT = 17;
 
     /** @hide Process is being cached for later use and has an activity that corresponds
      * to an existing recent task. */
-    public static final int PROCESS_STATE_CACHED_RECENT = 17;
+    public static final int PROCESS_STATE_CACHED_RECENT = 18;
 
     /** @hide Process is being cached for later use and is empty. */
-    public static final int PROCESS_STATE_CACHED_EMPTY = 18;
+    public static final int PROCESS_STATE_CACHED_EMPTY = 19;
 
     /** @hide Process does not exist. */
-    public static final int PROCESS_STATE_NONEXISTENT = 19;
+    public static final int PROCESS_STATE_NONEXISTENT = 20;
 
     // NOTE: If PROCESS_STATEs are added, then new fields must be added
     // to frameworks/base/core/proto/android/app/enums.proto and the following method must
@@ -594,6 +597,7 @@
                 return AppProtoEnums.PROCESS_STATE_PERSISTENT_UI;
             case PROCESS_STATE_TOP:
                 return AppProtoEnums.PROCESS_STATE_TOP;
+            case PROCESS_STATE_FOREGROUND_SERVICE_LOCATION:
             case PROCESS_STATE_FOREGROUND_SERVICE:
                 return AppProtoEnums.PROCESS_STATE_FOREGROUND_SERVICE;
             case PROCESS_STATE_BOUND_FOREGROUND_SERVICE:
@@ -646,6 +650,12 @@
         return procState >= PROCESS_STATE_TRANSIENT_BACKGROUND;
     }
 
+    /** @hide Is this a foreground service type? */
+    public static boolean isForegroundService(int procState) {
+        return procState == PROCESS_STATE_FOREGROUND_SERVICE_LOCATION
+                || procState == PROCESS_STATE_FOREGROUND_SERVICE;
+    }
+
     /** @hide requestType for assist context: only basic information. */
     public static final int ASSIST_CONTEXT_BASIC = 0;
 
@@ -2874,7 +2884,7 @@
                 return IMPORTANCE_PERCEPTIBLE;
             } else if (procState >= PROCESS_STATE_IMPORTANT_FOREGROUND) {
                 return IMPORTANCE_VISIBLE;
-            } else if (procState >= PROCESS_STATE_FOREGROUND_SERVICE) {
+            } else if (procState >= PROCESS_STATE_FOREGROUND_SERVICE_LOCATION) {
                 return IMPORTANCE_FOREGROUND_SERVICE;
             } else {
                 return IMPORTANCE_FOREGROUND;
@@ -2936,6 +2946,7 @@
                 return PROCESS_STATE_IMPORTANT_FOREGROUND;
             } else if (importance >= IMPORTANCE_FOREGROUND_SERVICE) {
                 return PROCESS_STATE_FOREGROUND_SERVICE;
+                // TODO: Asymmetrical mapping for LOCATION service type. Ok?
             } else {
                 return PROCESS_STATE_TOP;
             }
diff --git a/core/java/android/app/AppOpsManager.java b/core/java/android/app/AppOpsManager.java
index d2630d5..9ee2f03 100644
--- a/core/java/android/app/AppOpsManager.java
+++ b/core/java/android/app/AppOpsManager.java
@@ -218,6 +218,7 @@
     @IntDef(flag = true, prefix = { "UID_STATE_" }, value = {
             UID_STATE_PERSISTENT,
             UID_STATE_TOP,
+            UID_STATE_FOREGROUND_SERVICE_LOCATION,
             UID_STATE_FOREGROUND_SERVICE,
             UID_STATE_FOREGROUND,
             UID_STATE_BACKGROUND,
@@ -248,18 +249,26 @@
     public static final int UID_STATE_TOP = 1;
 
     /**
+     * Metrics about an op when its uid is running a foreground service with location type.
+     * @hide
+     */
+    @TestApi
+    @SystemApi
+    public static final int UID_STATE_FOREGROUND_SERVICE_LOCATION = 2;
+
+    /**
      * Metrics about an op when its uid is running a foreground service.
      * @hide
      */
     @TestApi
     @SystemApi
-    public static final int UID_STATE_FOREGROUND_SERVICE = 2;
+    public static final int UID_STATE_FOREGROUND_SERVICE = 3;
 
     /**
      * Last UID state in which we don't restrict what an op can do.
      * @hide
      */
-    public static final int UID_STATE_LAST_NON_RESTRICTED = UID_STATE_FOREGROUND_SERVICE;
+    public static final int UID_STATE_LAST_NON_RESTRICTED = UID_STATE_FOREGROUND_SERVICE_LOCATION;
 
     /**
      * Metrics about an op when its uid is in the foreground for any other reasons.
@@ -267,7 +276,7 @@
      */
     @TestApi
     @SystemApi
-    public static final int UID_STATE_FOREGROUND = 3;
+    public static final int UID_STATE_FOREGROUND = 4;
 
     /**
      * Metrics about an op when its uid is in the background for any reason.
@@ -275,7 +284,7 @@
      */
     @TestApi
     @SystemApi
-    public static final int UID_STATE_BACKGROUND = 4;
+    public static final int UID_STATE_BACKGROUND = 5;
 
     /**
      * Metrics about an op when its uid is cached.
@@ -283,13 +292,13 @@
      */
     @TestApi
     @SystemApi
-    public static final int UID_STATE_CACHED = 5;
+    public static final int UID_STATE_CACHED = 6;
 
     /**
      * Number of uid states we track.
      * @hide
      */
-    public static final int _NUM_UID_STATE = 6;
+    public static final int _NUM_UID_STATE = 7;
 
     // when adding one of these:
     //  - increment _NUM_OP
@@ -3270,6 +3279,7 @@
          *
          * @param uidState The UID state for which to query. Could be one of
          * {@link #UID_STATE_PERSISTENT}, {@link #UID_STATE_TOP},
+         * {@link #UID_STATE_FOREGROUND_SERVICE_LOCATION},
          * {@link #UID_STATE_FOREGROUND_SERVICE}, {@link #UID_STATE_FOREGROUND},
          * {@link #UID_STATE_BACKGROUND}, {@link #UID_STATE_CACHED}.
          *
@@ -3320,6 +3330,7 @@
          *
          * @param uidState The UID state for which to query. Could be one of
          * {@link #UID_STATE_PERSISTENT}, {@link #UID_STATE_TOP},
+         * {@link #UID_STATE_FOREGROUND_SERVICE_LOCATION},
          * {@link #UID_STATE_FOREGROUND_SERVICE}, {@link #UID_STATE_FOREGROUND},
          * {@link #UID_STATE_BACKGROUND}, {@link #UID_STATE_CACHED}.
          *
@@ -3370,6 +3381,7 @@
          *
          * @param uidState The UID state for which to query. Could be one of
          * {@link #UID_STATE_PERSISTENT}, {@link #UID_STATE_TOP},
+         * {@link #UID_STATE_FOREGROUND_SERVICE_LOCATION},
          * {@link #UID_STATE_FOREGROUND_SERVICE}, {@link #UID_STATE_FOREGROUND},
          * {@link #UID_STATE_BACKGROUND}, {@link #UID_STATE_CACHED}.
          *
@@ -4787,6 +4799,9 @@
             case UID_STATE_TOP: {
                 return "UID_STATE_TOP";
             }
+            case UID_STATE_FOREGROUND_SERVICE_LOCATION: {
+                return "UID_STATE_FOREGROUND_SERVICE_LOCATION";
+            }
             case UID_STATE_FOREGROUND_SERVICE: {
                 return "UID_STATE_FOREGROUND_SERVICE";
             }
diff --git a/core/java/android/app/ApplicationPackageManager.java b/core/java/android/app/ApplicationPackageManager.java
index 4491b95..a937422 100644
--- a/core/java/android/app/ApplicationPackageManager.java
+++ b/core/java/android/app/ApplicationPackageManager.java
@@ -3026,6 +3026,15 @@
     }
 
     @Override
+    public String getIncidentReportApproverPackageName() {
+        try {
+            return mPM.getIncidentReportApproverPackageName();
+        } catch (RemoteException e) {
+            throw e.rethrowAsRuntimeException();
+        }
+    }
+
+    @Override
     public boolean isPackageStateProtected(String packageName, int userId) {
         try {
             return mPM.isPackageStateProtected(packageName, userId);
diff --git a/core/java/android/app/admin/DevicePolicyManager.java b/core/java/android/app/admin/DevicePolicyManager.java
index 2514eee..b8f4385 100644
--- a/core/java/android/app/admin/DevicePolicyManager.java
+++ b/core/java/android/app/admin/DevicePolicyManager.java
@@ -5059,11 +5059,16 @@
     }
 
     /**
+     * Service-specific error code used in implementation of {@code setAlwaysOnVpnPackage} methods.
+     * @hide
+     */
+    public static final int ERROR_VPN_PACKAGE_NOT_FOUND = 1;
+
+    /**
      * Called by a device or profile owner to configure an always-on VPN connection through a
      * specific application for the current user. This connection is automatically granted and
      * persisted after a reboot.
-     * <p>
-     * To support the always-on feature, an app must
+     * <p> To support the always-on feature, an app must
      * <ul>
      *     <li>declare a {@link android.net.VpnService} in its manifest, guarded by
      *         {@link android.Manifest.permission#BIND_VPN_SERVICE};</li>
@@ -5072,25 +5077,61 @@
      *         {@link android.net.VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}.</li>
      * </ul>
      * The call will fail if called with the package name of an unsupported VPN app.
+     * <p> Enabling lockdown via {@code lockdownEnabled} argument carries the risk that any failure
+     * of the VPN provider could break networking for all apps.
      *
      * @param vpnPackage The package name for an installed VPN app on the device, or {@code null} to
      *        remove an existing always-on VPN configuration.
      * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
-     *        {@code false} otherwise. This carries the risk that any failure of the VPN provider
-     *        could break networking for all apps. This has no effect when clearing.
+     *        {@code false} otherwise. This has no effect when clearing.
      * @throws SecurityException if {@code admin} is not a device or a profile owner.
      * @throws NameNotFoundException if {@code vpnPackage} is not installed.
      * @throws UnsupportedOperationException if {@code vpnPackage} exists but does not support being
      *         set as always-on, or if always-on VPN is not available.
+     * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean, List)
      */
     public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage,
-            boolean lockdownEnabled)
-            throws NameNotFoundException, UnsupportedOperationException {
+            boolean lockdownEnabled) throws NameNotFoundException {
+        setAlwaysOnVpnPackage(admin, vpnPackage, lockdownEnabled, Collections.emptyList());
+    }
+
+    /**
+     * A version of {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)} that allows the
+     * admin to specify a set of apps that should be able to access the network directly when VPN
+     * is not connected. When VPN connects these apps switch over to VPN if allowed to use that VPN.
+     * System apps can always bypass VPN.
+     * <p> Note that the system doesn't update the whitelist when packages are installed or
+     * uninstalled, the admin app must call this method to keep the list up to date.
+     *
+     * @param vpnPackage package name for an installed VPN app on the device, or {@code null}
+     *         to remove an existing always-on VPN configuration
+     * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
+     *         {@code false} otherwise. This has no effect when clearing.
+     * @param lockdownWhitelist Packages that will be able to access the network directly when VPN
+     *         is in lockdown mode but not connected. Has no effect when clearing.
+     * @throws SecurityException if {@code admin} is not a device or a profile
+     *         owner.
+     * @throws NameNotFoundException if {@code vpnPackage} or one of
+     *         {@code lockdownWhitelist} is not installed.
+     * @throws UnsupportedOperationException if {@code vpnPackage} exists but does
+     *         not support being set as always-on, or if always-on VPN is not
+     *         available.
+     */
+    public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage,
+            boolean lockdownEnabled, @Nullable List<String> lockdownWhitelist)
+            throws NameNotFoundException {
         throwIfParentInstance("setAlwaysOnVpnPackage");
         if (mService != null) {
             try {
-                if (!mService.setAlwaysOnVpnPackage(admin, vpnPackage, lockdownEnabled)) {
-                    throw new NameNotFoundException(vpnPackage);
+                mService.setAlwaysOnVpnPackage(
+                        admin, vpnPackage, lockdownEnabled, lockdownWhitelist);
+            } catch (ServiceSpecificException e) {
+                switch (e.errorCode) {
+                    case ERROR_VPN_PACKAGE_NOT_FOUND:
+                        throw new NameNotFoundException(e.getMessage());
+                    default:
+                        throw new RuntimeException(
+                                "Unknown error setting always-on VPN: " + e.errorCode, e);
                 }
             } catch (RemoteException e) {
                 throw e.rethrowFromSystemServer();
@@ -5099,6 +5140,51 @@
     }
 
     /**
+     * Called by device or profile owner to query whether current always-on VPN is configured in
+     * lockdown mode. Returns {@code false} when no always-on configuration is set.
+     *
+     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
+     *
+     * @throws SecurityException if {@code admin} is not a device or a profile owner.
+     *
+     * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean)
+     */
+    public boolean isAlwaysOnVpnLockdownEnabled(@NonNull ComponentName admin) {
+        throwIfParentInstance("isAlwaysOnVpnLockdownEnabled");
+        if (mService != null) {
+            try {
+                return mService.isAlwaysOnVpnLockdownEnabled(admin);
+            } catch (RemoteException e) {
+                throw e.rethrowFromSystemServer();
+            }
+        }
+        return false;
+    }
+
+    /**
+     * Called by device or profile owner to query the list of packages that are allowed to access
+     * the network directly when always-on VPN is in lockdown mode but not connected. Returns
+     * {@code null} when always-on VPN is not active or not in lockdown mode.
+     *
+     * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
+     *
+     * @throws SecurityException if {@code admin} is not a device or a profile owner.
+     *
+     * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean, List)
+     */
+    public @Nullable List<String> getAlwaysOnVpnLockdownWhitelist(@NonNull ComponentName admin) {
+        throwIfParentInstance("getAlwaysOnVpnLockdownWhitelist");
+        if (mService != null) {
+            try {
+                return mService.getAlwaysOnVpnLockdownWhitelist(admin);
+            } catch (RemoteException e) {
+                throw e.rethrowFromSystemServer();
+            }
+        }
+        return null;
+    }
+
+    /**
      * Called by a device or profile owner to read the name of the package administering an
      * always-on VPN connection for the current user. If there is no such package, or the always-on
      * VPN is provided by the system instead of by an application, {@code null} will be returned.
diff --git a/core/java/android/app/admin/IDevicePolicyManager.aidl b/core/java/android/app/admin/IDevicePolicyManager.aidl
index 1751a91c..5790fda 100644
--- a/core/java/android/app/admin/IDevicePolicyManager.aidl
+++ b/core/java/android/app/admin/IDevicePolicyManager.aidl
@@ -187,8 +187,10 @@
     void setCertInstallerPackage(in ComponentName who, String installerPackage);
     String getCertInstallerPackage(in ComponentName who);
 
-    boolean setAlwaysOnVpnPackage(in ComponentName who, String vpnPackage, boolean lockdown);
+    boolean setAlwaysOnVpnPackage(in ComponentName who, String vpnPackage, boolean lockdown, in List<String> lockdownWhitelist);
     String getAlwaysOnVpnPackage(in ComponentName who);
+    boolean isAlwaysOnVpnLockdownEnabled(in ComponentName who);
+    List<String> getAlwaysOnVpnLockdownWhitelist(in ComponentName who);
 
     void addPersistentPreferredActivity(in ComponentName admin, in IntentFilter filter, in ComponentName activity);
     void clearPackagePersistentPreferredActivities(in ComponentName admin, String packageName);
diff --git a/core/java/android/app/role/RoleManagerCallback.java b/core/java/android/app/role/RoleManagerCallback.java
index d9f0a6c..a92ef32 100644
--- a/core/java/android/app/role/RoleManagerCallback.java
+++ b/core/java/android/app/role/RoleManagerCallback.java
@@ -19,6 +19,8 @@
 import android.annotation.SystemApi;
 import android.annotation.TestApi;
 
+import java.util.concurrent.CompletableFuture;
+
 /**
  * Callback for a {@link RoleManager} request.
  *
@@ -37,4 +39,18 @@
      * Signals a failure.
      */
     void onFailure();
+
+    /** @hide */
+    class Future extends CompletableFuture<Void> implements RoleManagerCallback {
+
+        @Override
+        public void onSuccess() {
+            complete(null);
+        }
+
+        @Override
+        public void onFailure() {
+            completeExceptionally(new RuntimeException());
+        }
+    }
 }
diff --git a/core/java/android/content/ContentProvider.java b/core/java/android/content/ContentProvider.java
index f138d39..13d12c9 100644
--- a/core/java/android/content/ContentProvider.java
+++ b/core/java/android/content/ContentProvider.java
@@ -28,6 +28,7 @@
 import android.annotation.Nullable;
 import android.annotation.UnsupportedAppUsage;
 import android.app.AppOpsManager;
+import android.app.role.RoleManager;
 import android.content.pm.PathPermission;
 import android.content.pm.ProviderInfo;
 import android.content.res.AssetFileDescriptor;
@@ -225,6 +226,17 @@
         @Override
         public Cursor query(String callingPkg, Uri uri, @Nullable String[] projection,
                 @Nullable Bundle queryArgs, @Nullable ICancellationSignal cancellationSignal) {
+            if (uri.toString().startsWith("content://sms")) {
+                RoleManager rm = getContext().getSystemService(RoleManager.class);
+                if (!rm.isRoleHeld(RoleManager.ROLE_SMS)
+                        && !rm.isRoleHeld(RoleManager.ROLE_DIALER)
+                        && !rm.isRoleHeld(RoleManager.ROLE_ASSISTANT)) {
+                    // STOPSHIP: log it to westworld instead
+                    Log.wtf(TAG, "Sms access attempted by " + callingPkg
+                            + " despite not holding an appropriate role");
+                }
+            }
+
             uri = validateIncomingUri(uri);
             uri = maybeGetUriWithoutUserId(uri);
             if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
diff --git a/core/java/android/content/Context.java b/core/java/android/content/Context.java
index 87f9e46..d9d0ee9 100644
--- a/core/java/android/content/Context.java
+++ b/core/java/android/content/Context.java
@@ -3180,6 +3180,7 @@
             //@hide: CONTEXTHUB_SERVICE,
             SYSTEM_HEALTH_SERVICE,
             //@hide: INCIDENT_SERVICE,
+            //@hide: INCIDENT_COMPANION_SERVICE,
             //@hide: STATS_COMPANION_SERVICE,
             COMPANION_DEVICE_SERVICE,
             CROSS_PROFILE_APPS_SERVICE,
@@ -4466,6 +4467,13 @@
     public static final String INCIDENT_SERVICE = "incident";
 
     /**
+     * Service to assist incidentd and dumpstated in reporting status to the user
+     * and in confirming authorization to take an incident report or bugreport
+     * @hide
+     */
+    public static final String INCIDENT_COMPANION_SERVICE = "incidentcompanion";
+
+    /**
      * Service to assist statsd in obtaining general stats.
      * @hide
      */
diff --git a/core/java/android/content/Intent.java b/core/java/android/content/Intent.java
index 22f73db..8d14091 100644
--- a/core/java/android/content/Intent.java
+++ b/core/java/android/content/Intent.java
@@ -1475,6 +1475,18 @@
     public static final String ACTION_APP_ERROR = "android.intent.action.APP_ERROR";
 
     /**
+     * An incident or bug report has been taken, and a system app has requested it to be shared,
+     * so trigger the confirmation screen.
+     *
+     * This will be sent directly to the registered receiver with the
+     * android.permission.APPROVE_INCIDENT_REPORTS permission.
+     * @hide
+     */
+    @SystemApi
+    public static final String ACTION_PENDING_INCIDENT_REPORTS_CHANGED =
+            "android.intent.action.PENDING_INCIDENT_REPORTS_CHANGED";
+
+    /**
      * Activity Action: Show power usage information to the user.
      * <p>Input: Nothing.
      * <p>Output: Nothing.
diff --git a/core/java/android/content/pm/IPackageManager.aidl b/core/java/android/content/pm/IPackageManager.aidl
index 7bd8c4e..a6a6f01 100644
--- a/core/java/android/content/pm/IPackageManager.aidl
+++ b/core/java/android/content/pm/IPackageManager.aidl
@@ -688,6 +688,8 @@
 
     String getContentCaptureServicePackageName();
 
+    String getIncidentReportApproverPackageName();
+
     boolean isPackageStateProtected(String packageName, int userId);
 
     void sendDeviceCustomizationReadyBroadcast();
diff --git a/core/java/android/content/pm/LauncherApps.java b/core/java/android/content/pm/LauncherApps.java
index 36bb5d4..98dd9b3 100644
--- a/core/java/android/content/pm/LauncherApps.java
+++ b/core/java/android/content/pm/LauncherApps.java
@@ -781,6 +781,9 @@
     /**
      * Checks if the activity exists and it enabled for a profile.
      *
+     * <p>The activity may still not be exported, in which case {@link #startMainActivity} will
+     * throw a {@link SecurityException} unless the caller has the same UID as the target app's.
+     *
      * @param component The activity to check.
      * @param user The UserHandle of the profile.
      *
diff --git a/core/java/android/content/pm/PackageManager.java b/core/java/android/content/pm/PackageManager.java
index 0aa33c8..d88f36c 100644
--- a/core/java/android/content/pm/PackageManager.java
+++ b/core/java/android/content/pm/PackageManager.java
@@ -2346,14 +2346,7 @@
      * {@link #hasSystemFeature}: The device has biometric hardware to detect a fingerprint.
      */
     @SdkConstant(SdkConstantType.FEATURE)
-    public static final String FEATURE_FINGERPRINT_PRE_29 = "android.hardware.fingerprint";
-
-    /**
-     * Feature for {@link #getSystemAvailableFeatures} and
-     * {@link #hasSystemFeature}: The device has biometric hardware to detect a fingerprint.
-     */
-    @SdkConstant(SdkConstantType.FEATURE)
-    public static final String FEATURE_FINGERPRINT = "android.hardware.biometrics.fingerprint";
+    public static final String FEATURE_FINGERPRINT = "android.hardware.fingerprint";
 
     /**
      * Feature for {@link #getSystemAvailableFeatures} and
@@ -6744,6 +6737,19 @@
     }
 
     /**
+     * @return the incident report approver app package name, or null if it's not defined
+     * by the OEM.
+     *
+     * @hide
+     */
+    @SystemApi
+    @TestApi
+    public String getIncidentReportApproverPackageName() {
+        throw new UnsupportedOperationException(
+                "getIncidentReportApproverPackageName not implemented in subclass");
+    }
+
+    /**
      * @return whether a given package's state is protected, e.g. package cannot be disabled,
      *         suspended, hidden or force stopped.
      *
diff --git a/core/java/android/content/pm/PackageManagerInternal.java b/core/java/android/content/pm/PackageManagerInternal.java
index c9a4c82..738730e 100644
--- a/core/java/android/content/pm/PackageManagerInternal.java
+++ b/core/java/android/content/pm/PackageManagerInternal.java
@@ -56,6 +56,7 @@
     public static final int PACKAGE_WELLBEING = 7;
     public static final int PACKAGE_DOCUMENTER = 8;
     public static final int PACKAGE_CONFIGURATOR = 9;
+    public static final int PACKAGE_INCIDENT_REPORT_APPROVER = 10;
     @IntDef(value = {
         PACKAGE_SYSTEM,
         PACKAGE_SETUP_WIZARD,
@@ -67,6 +68,7 @@
         PACKAGE_WELLBEING,
         PACKAGE_DOCUMENTER,
         PACKAGE_CONFIGURATOR,
+        PACKAGE_INCIDENT_REPORT_APPROVER,
     })
     @Retention(RetentionPolicy.SOURCE)
     public @interface KnownPackage {}
diff --git a/core/java/android/content/pm/PermissionInfo.java b/core/java/android/content/pm/PermissionInfo.java
index 5d2cf0a..e776984 100644
--- a/core/java/android/content/pm/PermissionInfo.java
+++ b/core/java/android/content/pm/PermissionInfo.java
@@ -213,6 +213,16 @@
     @TestApi
     public static final int PROTECTION_FLAG_CONFIGURATOR = 0x80000;
 
+    /**
+     * Additional flag for {${link #protectionLevel}, corresponding
+     * to the <code>incident_report_approver</code> value of
+     * {@link android.R.attr#protectionLevel}.
+     *
+     * @hide
+     */
+    @SystemApi
+    @TestApi
+    public static final int PROTECTION_FLAG_INCIDENT_REPORT_APPROVER = 0x100000;
 
     /** @hide */
     @IntDef(flag = true, prefix = { "PROTECTION_FLAG_" }, value = {
@@ -233,6 +243,7 @@
             PROTECTION_FLAG_WELLBEING,
             PROTECTION_FLAG_DOCUMENTER,
             PROTECTION_FLAG_CONFIGURATOR,
+            PROTECTION_FLAG_INCIDENT_REPORT_APPROVER,
     })
     @Retention(RetentionPolicy.SOURCE)
     public @interface ProtectionFlags {}
@@ -431,6 +442,9 @@
         if ((level & PROTECTION_FLAG_CONFIGURATOR) != 0) {
             protLevel += "|configurator";
         }
+        if ((level & PermissionInfo.PROTECTION_FLAG_INCIDENT_REPORT_APPROVER) != 0) {
+            protLevel += "|incidentReportApprover";
+        }
         return protLevel;
     }
 
diff --git a/core/java/android/content/pm/RegisteredServicesCache.java b/core/java/android/content/pm/RegisteredServicesCache.java
index a8c3b88..63f01cc 100644
--- a/core/java/android/content/pm/RegisteredServicesCache.java
+++ b/core/java/android/content/pm/RegisteredServicesCache.java
@@ -289,9 +289,11 @@
         }
 
         final RegisteredServicesCacheListener<V> listener2 = listener;
-        handler.post(new Runnable() {
-            public void run() {
+        handler.post(() -> {
+            try {
                 listener2.onServiceChanged(type, userId, removed);
+            } catch (Throwable th) {
+                Slog.wtf(TAG, "Exception from onServiceChanged", th);
             }
         });
     }
diff --git a/core/java/android/hardware/camera2/CameraCharacteristics.java b/core/java/android/hardware/camera2/CameraCharacteristics.java
index 425b956..4bc2702 100644
--- a/core/java/android/hardware/camera2/CameraCharacteristics.java
+++ b/core/java/android/hardware/camera2/CameraCharacteristics.java
@@ -24,8 +24,6 @@
 import android.hardware.camera2.impl.SyntheticKey;
 import android.hardware.camera2.params.RecommendedStreamConfigurationMap;
 import android.hardware.camera2.params.SessionConfiguration;
-import android.hardware.camera2.params.MandatoryStreamCombination;
-import android.hardware.camera2.params.MandatoryStreamCombination.MandatoryStreamInformation;
 import android.hardware.camera2.utils.ArrayUtils;
 import android.hardware.camera2.utils.TypeReference;
 import android.util.Rational;
@@ -92,11 +90,13 @@
         }
 
         /**
-         * Visible for testing and vendor extensions only.
+         * Construct a new Key with a given name and type.
          *
-         * @hide
+         * <p>Normally, applications should use the existing Key definitions in
+         * {@link CameraCharacteristics}, and not need to construct their own Key objects. However,
+         * they may be useful for testing purposes and for defining custom camera
+         * characteristics.</p>
          */
-        @UnsupportedAppUsage
         public Key(String name, Class<T> type) {
             mKey = new CameraMetadataNative.Key<T>(name,  type);
         }
diff --git a/core/java/android/hardware/camera2/CaptureRequest.java b/core/java/android/hardware/camera2/CaptureRequest.java
index 5f05cfb..3d3a916 100644
--- a/core/java/android/hardware/camera2/CaptureRequest.java
+++ b/core/java/android/hardware/camera2/CaptureRequest.java
@@ -114,11 +114,12 @@
         }
 
         /**
-         * Visible for testing and vendor extensions only.
+         * Construct a new Key with a given name and type.
          *
-         * @hide
+         * <p>Normally, applications should use the existing Key definitions in
+         * {@link CaptureRequest}, and not need to construct their own Key objects. However, they
+         * may be useful for testing purposes and for defining custom capture request fields.</p>
          */
-        @UnsupportedAppUsage
         public Key(String name, Class<T> type) {
             mKey = new CameraMetadataNative.Key<T>(name, type);
         }
diff --git a/core/java/android/hardware/camera2/CaptureResult.java b/core/java/android/hardware/camera2/CaptureResult.java
index 585c597..8982b40 100644
--- a/core/java/android/hardware/camera2/CaptureResult.java
+++ b/core/java/android/hardware/camera2/CaptureResult.java
@@ -94,11 +94,12 @@
         }
 
        /**
-         * Visible for testing and vendor extensions only.
+         * Construct a new Key with a given name and type.
          *
-         * @hide
+         * <p>Normally, applications should use the existing Key definitions in
+         * {@link CaptureResult}, and not need to construct their own Key objects. However, they may
+         * be useful for testing purposes and for defining custom capture result fields.</p>
          */
-        @UnsupportedAppUsage
         public Key(String name, Class<T> type) {
             mKey = new CameraMetadataNative.Key<T>(name, type);
         }
diff --git a/core/java/android/net/NetworkSpecifier.java b/core/java/android/net/NetworkSpecifier.java
index fcfb720..2bc3eb5 100644
--- a/core/java/android/net/NetworkSpecifier.java
+++ b/core/java/android/net/NetworkSpecifier.java
@@ -23,7 +23,6 @@
  * subclasses of this class via other APIs.
  */
 public abstract class NetworkSpecifier {
-    /** @hide */
     public NetworkSpecifier() {}
 
     /**
diff --git a/core/java/android/os/BatteryStats.java b/core/java/android/os/BatteryStats.java
index 1919fcc..ab6dd7c 100644
--- a/core/java/android/os/BatteryStats.java
+++ b/core/java/android/os/BatteryStats.java
@@ -16,6 +16,8 @@
 
 package android.os;
 
+import static android.app.ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE_LOCATION;
+
 import android.app.ActivityManager;
 import android.app.job.JobParameters;
 import android.content.Context;
@@ -578,7 +580,7 @@
             return ActivityManager.PROCESS_STATE_NONEXISTENT;
         } else if (procState == ActivityManager.PROCESS_STATE_TOP) {
             return Uid.PROCESS_STATE_TOP;
-        } else if (procState == ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) {
+        } else if (ActivityManager.isForegroundService(procState)) {
             // State when app has put itself in the foreground.
             return Uid.PROCESS_STATE_FOREGROUND_SERVICE;
         } else if (procState <= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND) {
@@ -818,7 +820,9 @@
          * is not attributed to any non-critical process states.
          */
         public static final int[] CRITICAL_PROC_STATES = {
-            PROCESS_STATE_TOP, PROCESS_STATE_FOREGROUND_SERVICE, PROCESS_STATE_FOREGROUND
+                PROCESS_STATE_TOP,
+                PROCESS_STATE_FOREGROUND_SERVICE_LOCATION, PROCESS_STATE_FOREGROUND_SERVICE,
+                PROCESS_STATE_FOREGROUND
         };
 
         public abstract long getProcessStateTime(int state, long elapsedRealtimeUs, int which);
diff --git a/core/java/android/os/IncidentManager.java b/core/java/android/os/IncidentManager.java
index 0e6652d..88a578a 100644
--- a/core/java/android/os/IncidentManager.java
+++ b/core/java/android/os/IncidentManager.java
@@ -16,13 +16,18 @@
 
 package android.os;
 
+import android.annotation.NonNull;
 import android.annotation.RequiresPermission;
 import android.annotation.SystemApi;
 import android.annotation.SystemService;
 import android.annotation.TestApi;
 import android.content.Context;
+import android.net.Uri;
 import android.util.Slog;
 
+import java.util.ArrayList;
+import java.util.List;
+
 /**
  * Class to take an incident report.
  *
@@ -34,9 +39,200 @@
 public class IncidentManager {
     private static final String TAG = "IncidentManager";
 
+    /**
+     * Authority for pending report id urls.
+     *
+     * @hide
+     */
+    public static final String URI_SCHEME = "content";
+
+    /**
+     * Authority for pending report id urls.
+     *
+     * @hide
+     */
+    public static final String URI_AUTHORITY = "android.os.IncidentManager";
+
+    /**
+     * Authority for pending report id urls.
+     *
+     * @hide
+     */
+    public static final String URI_PATH = "/pending";
+
+    /**
+     * Query parameter for the uris for the pending report id.
+     *
+     * @hide
+     */
+    public static final String URI_PARAM_ID = "id";
+
+    /**
+     * Query parameter for the uris for the pending report id.
+     *
+     * @hide
+     */
+    public static final String URI_PARAM_CALLING_PACKAGE = "pkg";
+
+    /**
+     * Query parameter for the uris for the pending report id, in wall clock
+     * ({@link System.currentTimeMillis()}) timebase.
+     *
+     * @hide
+     */
+    public static final String URI_PARAM_TIMESTAMP = "t";
+
+    /**
+     * Query parameter for the uris for the pending report id.
+     *
+     * @hide
+     */
+    public static final String URI_PARAM_FLAGS = "flags";
+
+    /**
+     * Do the confirmation with a dialog instead of the default, which is a notification.
+     * It is possible for the dialog to be downgraded to a notification in some cases.
+     */
+    public static final int FLAG_CONFIRMATION_DIALOG = 0x1;
+
     private final Context mContext;
 
-    private IIncidentManager mService;
+    private Object mLock = new Object();
+    private IIncidentManager mIncidentService;
+    private IIncidentCompanion mCompanionService;
+
+    /**
+     * Record for a report that has been taken and is pending user authorization
+     * to share it.
+     * @hide
+     */
+    @SystemApi
+    @TestApi
+    public static class PendingReport {
+        /**
+         * Encoded data.
+         */
+        private final Uri mUri;
+
+        /**
+         * URI_PARAM_FLAGS from the uri
+         */
+        private final int mFlags;
+
+        /**
+         * URI_PARAM_CALLING_PACKAGE from the uri
+         */
+        private final String mRequestingPackage;
+
+        /**
+         * URI_PARAM_TIMESTAMP from the uri
+         */
+        private final long mTimestamp;
+
+        /**
+         * Constructor.
+         */
+        public PendingReport(@NonNull Uri uri) {
+            int flags = 0;
+            try {
+                flags = Integer.parseInt(uri.getQueryParameter(URI_PARAM_FLAGS));
+            } catch (NumberFormatException ex) {
+                throw new RuntimeException("Invalid URI: No " + URI_PARAM_FLAGS
+                        + " parameter. " + uri);
+            }
+            mFlags = flags;
+
+            String requestingPackage = uri.getQueryParameter(URI_PARAM_CALLING_PACKAGE);
+            if (requestingPackage == null) {
+                throw new RuntimeException("Invalid URI: No " + URI_PARAM_CALLING_PACKAGE
+                        + " parameter. " + uri);
+            }
+            mRequestingPackage = requestingPackage;
+
+            long timestamp = -1;
+            try {
+                timestamp = Long.parseLong(uri.getQueryParameter(URI_PARAM_TIMESTAMP));
+            } catch (NumberFormatException ex) {
+                throw new RuntimeException("Invalid URI: No " + URI_PARAM_TIMESTAMP
+                        + " parameter. " + uri);
+            }
+            mTimestamp = timestamp;
+
+            mUri = uri;
+        }
+
+        /**
+         * Get the package with which this report will be shared.
+         */
+        public @NonNull String getRequestingPackage() {
+            return mRequestingPackage;
+        }
+
+        /**
+         * Get the flags requested for this pending report.
+         *
+         * @see #FLAG_CONFIRMATION_DIALOG
+         */
+        public int getFlags() {
+            return mFlags;
+        }
+
+        /**
+         * Get the time this pending report was posted.
+         */
+        public long getTimestamp() {
+            return mTimestamp;
+        }
+
+        /**
+         * Get the URI associated with this PendingReport.  It can be used to
+         * re-retrieve it from {@link IncidentManager} or set as the data field of
+         * an Intent.
+         */
+        public @NonNull Uri getUri() {
+            return mUri;
+        }
+
+        /**
+         * String representation of this PendingReport.
+         */
+        @Override
+        public @NonNull String toString() {
+            return "PendingReport(" + getUri().toString() + ")";
+        }
+    }
+
+    /**
+     * Listener for the status of an incident report being authroized or denied.
+     *
+     * @see #requestAuthorization
+     * @see #cancelAuthorization
+     */
+    public static class AuthListener {
+        IIncidentAuthListener.Stub mBinder = new IIncidentAuthListener.Stub() {
+            @Override
+            public void onReportApproved() {
+                AuthListener.this.onReportApproved();
+            }
+
+            @Override
+            public void onReportDenied() {
+                AuthListener.this.onReportDenied();
+            }
+        };
+
+        /**
+         * Called when a report is approved.
+         */
+        public void onReportApproved() {
+        }
+
+        /**
+         * Called when a report is denied.
+         */
+        public void onReportDenied() {
+        }
+    }
 
     /**
      * @hide
@@ -56,12 +252,76 @@
         reportIncidentInternal(args);
     }
 
-    private class IncidentdDeathRecipient implements IBinder.DeathRecipient {
-        @Override
-        public void binderDied() {
-            synchronized (this) {
-                mService = null;
-            }
+    /**
+     * Request authorization of an incident report.
+     */
+    @RequiresPermission(android.Manifest.permission.REQUEST_INCIDENT_REPORT_APPROVAL)
+    public void requestAuthorization(int callingUid, String callingPackage, int flags,
+            AuthListener listener) {
+        try {
+            getCompanionServiceLocked().authorizeReport(callingUid, callingPackage, flags,
+                    listener.mBinder);
+        } catch (RemoteException ex) {
+            // System process going down
+            throw new RuntimeException(ex);
+        }
+    }
+
+    /**
+     * Cancel a previous request for incident report authorization.
+     */
+    @RequiresPermission(android.Manifest.permission.REQUEST_INCIDENT_REPORT_APPROVAL)
+    public void cancelAuthorization(AuthListener listener) {
+        try {
+            getCompanionServiceLocked().cancelAuthorization(listener.mBinder);
+        } catch (RemoteException ex) {
+            // System process going down
+            throw new RuntimeException(ex);
+        }
+    }
+
+    /**
+     * Get incident (and bug) reports that are pending approval to share.
+     */
+    @RequiresPermission(android.Manifest.permission.APPROVE_INCIDENT_REPORTS)
+    public List<PendingReport> getPendingReports() {
+        List<String> strings;
+        try {
+            strings = getCompanionServiceLocked().getPendingReports();
+        } catch (RemoteException ex) {
+            throw new RuntimeException(ex);
+        }
+        final int size = strings.size();
+        ArrayList<PendingReport> result = new ArrayList(size);
+        for (int i = 0; i < size; i++) {
+            result.add(new PendingReport(Uri.parse(strings.get(i))));
+        }
+        return result;
+    }
+
+    /**
+     * Allow this report to be shared with the given app.
+     */
+    @RequiresPermission(android.Manifest.permission.APPROVE_INCIDENT_REPORTS)
+    public void approveReport(Uri uri) {
+        try {
+            getCompanionServiceLocked().approveReport(uri.toString());
+        } catch (RemoteException ex) {
+            // System process going down
+            throw new RuntimeException(ex);
+        }
+    }
+
+    /**
+     * Do not allow this report to be shared with the given app.
+     */
+    @RequiresPermission(android.Manifest.permission.APPROVE_INCIDENT_REPORTS)
+    public void denyReport(Uri uri) {
+        try {
+            getCompanionServiceLocked().denyReport(uri.toString());
+        } catch (RemoteException ex) {
+            // System process going down
+            throw new RuntimeException(ex);
         }
     }
 
@@ -79,22 +339,47 @@
     }
 
     private IIncidentManager getIIncidentManagerLocked() throws RemoteException {
-        if (mService != null) {
-            return mService;
+        if (mIncidentService != null) {
+            return mIncidentService;
         }
 
-        synchronized (this) {
-            if (mService != null) {
-                return mService;
+        synchronized (mLock) {
+            if (mIncidentService != null) {
+                return mIncidentService;
             }
-            mService = IIncidentManager.Stub.asInterface(
+            mIncidentService = IIncidentManager.Stub.asInterface(
                 ServiceManager.getService(Context.INCIDENT_SERVICE));
-            if (mService != null) {
-                mService.asBinder().linkToDeath(new IncidentdDeathRecipient(), 0);
+            if (mIncidentService != null) {
+                mIncidentService.asBinder().linkToDeath(() -> {
+                    synchronized (mLock) {
+                        mIncidentService = null;
+                    }
+                }, 0);
             }
-            return mService;
+            return mIncidentService;
         }
     }
 
+    private IIncidentCompanion getCompanionServiceLocked() throws RemoteException {
+        if (mCompanionService != null) {
+            return mCompanionService;
+        }
+
+        synchronized (this) {
+            if (mCompanionService != null) {
+                return mCompanionService;
+            }
+            mCompanionService = IIncidentCompanion.Stub.asInterface(
+                ServiceManager.getService(Context.INCIDENT_COMPANION_SERVICE));
+            if (mCompanionService != null) {
+                mCompanionService.asBinder().linkToDeath(() -> {
+                    synchronized (mLock) {
+                        mCompanionService = null;
+                    }
+                }, 0);
+            }
+            return mCompanionService;
+        }
+    }
 }
 
diff --git a/core/java/android/provider/DeviceConfig.java b/core/java/android/provider/DeviceConfig.java
index d58e00a..264f975 100644
--- a/core/java/android/provider/DeviceConfig.java
+++ b/core/java/android/provider/DeviceConfig.java
@@ -24,6 +24,7 @@
 import android.annotation.Nullable;
 import android.annotation.RequiresPermission;
 import android.annotation.SystemApi;
+import android.annotation.TestApi;
 import android.app.ActivityThread;
 import android.content.ContentResolver;
 import android.database.ContentObserver;
@@ -44,6 +45,7 @@
  * @hide
  */
 @SystemApi
+@TestApi
 public final class DeviceConfig {
     /**
      * The content:// style URL for the config table.
@@ -70,6 +72,39 @@
     public static final String NAMESPACE_AUTOFILL = "autofill";
 
     /**
+     * ContentCapture-related properties definitions.
+     *
+     * @hide
+     */
+    @SystemApi
+    public interface ContentCapture {
+        String NAMESPACE = "content_capture";
+
+        /**
+         * Property used by {@code com.android.server.SystemServer} on start to decide whether
+         * the Content Capture service should be created or not.
+         *
+         * <p>Possible values are:
+         *
+         * <ul>
+         *   <li>If set to {@code default}, it will only be set if the OEM provides and defines the
+         *   service name by overlaying {@code config_defaultContentCaptureService} (this is the
+         *   "default" mode)
+         *   <li>If set to {@code always}, it will always be enabled, even when the resource is not
+         *   overlaid (this is useful during development and to run the CTS tests on AOSP builds).
+         *   <li>Otherwise, it's explicitly disabled (this could work as a "kill switch" so OEMs
+         *   can disable it remotely in case of emergency by setting to something else (like
+         *   {@code "false"}); notice that it's also disabled if the OEM doesn't explicitly set one
+         *   of the values above).
+         * </ul>
+         *
+         * @hide
+         */
+        // TODO(b/121153631): revert back to SERVICE_EXPLICITLY_ENABLED approach
+        String PROPERTY_CONTENTCAPTURE_ENABLED = "enable_contentcapture";
+    }
+
+    /**
      * Namespace for content capture feature used by on-device machine intelligence
      * to provide suggestions in a privacy-safe manner.
      *
@@ -102,7 +137,17 @@
      * @hide
      */
     @SystemApi
-    public static final String NAMESPACE_NOTIFICATION_ASSISTANT = "notification_assistant";
+    public interface NotificationAssistant {
+        String NAMESPACE = "notification_assistant";
+        /**
+         * Whether the Notification Assistant should generate replies for notifications.
+         */
+        String GENERATE_REPLIES = "generate_replies";
+        /**
+         * Whether the Notification Assistant should generate contextual actions for notifications.
+         */
+        String GENERATE_ACTIONS = "generate_actions";
+    }
 
     /**
      * Namespace for attention-based features provided by on-device machine intelligence.
@@ -121,6 +166,30 @@
     }
 
     /**
+     * Privacy related properties definitions.
+     *
+     * @hide
+     */
+    @SystemApi
+    @TestApi
+    public interface Privacy {
+        String NAMESPACE = "privacy";
+
+        /**
+         * Whether to show the Permissions Hub.
+         *
+         * @hide
+         */
+        @SystemApi
+        String PROPERTY_PERMISSIONS_HUB_ENABLED = "enable_permissions_hub";
+
+        /**
+         * Whether to show location access check notifications.
+         */
+        String PROPERTY_LOCATION_ACCESS_CHECK_ENABLED = "enable_location_access_check";
+    }
+
+    /**
      * Telephony related properties definitions.
      *
      * @hide
@@ -259,6 +328,7 @@
      * @see #resetToDefaults(int, String).
      */
     @SystemApi
+    @TestApi
     @RequiresPermission(WRITE_DEVICE_CONFIG)
     public static boolean setProperty(
             String namespace, String name, String value, boolean makeDefault) {
@@ -279,6 +349,7 @@
      * @see #setProperty(String, String, String, boolean)
      */
     @SystemApi
+    @TestApi
     @RequiresPermission(WRITE_DEVICE_CONFIG)
     public static void resetToDefaults(@ResetMode int resetMode, @Nullable String namespace) {
         ContentResolver contentResolver = ActivityThread.currentApplication().getContentResolver();
@@ -425,7 +496,10 @@
      * Interface for monitoring to properties.
      * <p>
      * Override {@link #onPropertyChanged(String, String, String)} to handle callbacks for changes.
+     *
+     * @hide
      */
+    @SystemApi
     public interface OnPropertyChangedListener {
         /**
          * Called when a property has changed.
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index a7af5d1..794c2f1 100644
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -1861,6 +1861,7 @@
      * This is the only type of reset available to non-system clients.
      * @hide
      */
+    @TestApi
     public static final int RESET_MODE_PACKAGE_DEFAULTS = 1;
 
     /**
@@ -5687,6 +5688,14 @@
                 "autofill_user_data_min_value_length";
 
         /**
+         * Defines whether Content Capture is enabled  for the user.
+         * @hide
+         */
+        @SystemApi
+        @TestApi
+        public static final String CONTENT_CAPTURE_ENABLED = "content_capture_enabled";
+
+        /**
          * @deprecated Use {@link android.provider.Settings.Global#DEVICE_PROVISIONED} instead
          */
         @Deprecated
@@ -11765,6 +11774,7 @@
          * entity_list_not_editable                 (String[])
          * entity_list_editable                     (String[])
          * lang_id_threshold_override               (float)
+         * template_intent_factory_enabled          (boolean)
          * </pre>
          *
          * <p>
@@ -13271,29 +13281,6 @@
         public static final String MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY =
                 "max_sound_trigger_detection_service_ops_per_day";
 
-        /**
-         * Property used by {@code com.android.server.SystemServer} on start to decide whether
-         * the Content Capture service should be created or not.
-         *
-         * <p>Possible values are:
-         *
-         * <ul>
-         *   <li>If set to {@code default}, it will only be set if the OEM provides and defines the
-         *   service name by overlaying {@code config_defaultContentCaptureService} (this is the
-         *   "default" mode)
-         *   <li>If set to {@code always}, it will always be enabled, even when the resource is not
-         *   overlaid (this is useful during development and to run the CTS tests on AOSP builds).
-         *   <li>Otherwise, it's explicitly disabled (this could work as a "kill switch" so OEMs
-         *   can disable it remotely in case of emergency by setting to something else (like
-         *   {@code "false"}); notice that it's also disabled if the OEM doesn't explicitly set one
-         *   of the values above).
-         * </ul>
-         *
-         * @hide
-         */
-        public static final String CONTENT_CAPTURE_SERVICE_EXPLICITLY_ENABLED =
-                "content_capture_service_explicitly_enabled";
-
         /** {@hide} */
         public static final String ISOLATED_STORAGE_LOCAL = "isolated_storage_local";
         /** {@hide} */
@@ -14130,6 +14117,7 @@
          * edit_choices_before_sending       (boolean)
          * show_in_heads_up                  (boolean)
          * min_num_system_generated_replies  (int)
+         * max_num_actions                   (int)
          * </pre>
          * @see com.android.systemui.statusbar.policy.SmartReplyConstants
          * @hide
diff --git a/core/java/android/util/KeyValueListParser.java b/core/java/android/util/KeyValueListParser.java
index d051ed8..fbc66e6 100644
--- a/core/java/android/util/KeyValueListParser.java
+++ b/core/java/android/util/KeyValueListParser.java
@@ -373,4 +373,57 @@
             proto.write(tag, mValue);
         }
     }
+
+    /** Represents an float config value. */
+    public static class FloatValue {
+        private final String mKey;
+        private final float mDefaultValue;
+        private float mValue;
+
+        /** Constructor, initialize with a config key and a default value. */
+        public FloatValue(String key, float defaultValue) {
+            mKey = key;
+            mDefaultValue = defaultValue;
+            mValue = mDefaultValue;
+        }
+
+        /** Read a value from {@link KeyValueListParser} */
+        public void parse(KeyValueListParser parser) {
+            mValue = parser.getFloat(mKey, mDefaultValue);
+        }
+
+        /** Return the config key. */
+        public String getKey() {
+            return mKey;
+        }
+
+        /** Return the default value. */
+        public float getDefaultValue() {
+            return mDefaultValue;
+        }
+
+        /** Return the actual config value. */
+        public float getValue() {
+            return mValue;
+        }
+
+        /** Overwrites with a value. */
+        public void setValue(float value) {
+            mValue = value;
+        }
+
+        /** Used for dumpsys */
+        public void dump(PrintWriter pw, String prefix) {
+            pw.print(prefix);
+            pw.print(mKey);
+            pw.print("=");
+            pw.print(mValue);
+            pw.println();
+        }
+
+        /** Used for proto dumpsys */
+        public void dumpProto(ProtoOutputStream proto, long tag) {
+            proto.write(tag, mValue);
+        }
+    }
 }
diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java
index cd3decf..a17a188 100644
--- a/core/java/android/view/View.java
+++ b/core/java/android/view/View.java
@@ -11396,7 +11396,6 @@
      * @see #setAssistBlocked(boolean)
      * @attr ref android.R.styleable#View_assistBlocked
      */
-    @InspectableProperty
     public boolean isAssistBlocked() {
         return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0;
     }
@@ -18272,7 +18271,7 @@
      *
      * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
      */
-    @InspectableProperty
+    @InspectableProperty(name = "scrollbarDefaultDelayBeforeFade")
     public int getScrollBarDefaultDelayBeforeFade() {
         return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
                 mScrollCache.scrollBarDefaultDelayBeforeFade;
@@ -18297,7 +18296,7 @@
      *
      * @attr ref android.R.styleable#View_scrollbarFadeDuration
      */
-    @InspectableProperty
+    @InspectableProperty(name = "scrollbarFadeDuration")
     public int getScrollBarFadeDuration() {
         return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
                 mScrollCache.scrollBarFadeDuration;
@@ -18322,7 +18321,7 @@
      *
      * @attr ref android.R.styleable#View_scrollbarSize
      */
-    @InspectableProperty
+    @InspectableProperty(name = "scrollbarSize")
     public int getScrollBarSize() {
         return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
                 mScrollCache.scrollBarSize;
@@ -18382,7 +18381,7 @@
             @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
             @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
     })
-    @InspectableProperty(enumMapping = {
+    @InspectableProperty(name = "scrollbarStyle", enumMapping = {
             @EnumMap(value = SCROLLBARS_INSIDE_OVERLAY, name = "insideOverlay"),
             @EnumMap(value = SCROLLBARS_INSIDE_INSET, name = "insideInset"),
             @EnumMap(value = SCROLLBARS_OUTSIDE_OVERLAY, name = "outsideOverlay"),
diff --git a/core/java/android/view/contentcapture/ContentCaptureManager.java b/core/java/android/view/contentcapture/ContentCaptureManager.java
index d7f1b9f..fde0ced 100644
--- a/core/java/android/view/contentcapture/ContentCaptureManager.java
+++ b/core/java/android/view/contentcapture/ContentCaptureManager.java
@@ -15,12 +15,12 @@
  */
 package android.view.contentcapture;
 
+import static android.view.contentcapture.ContentCaptureHelper.DEBUG;
 import static android.view.contentcapture.ContentCaptureHelper.VERBOSE;
 
-import static com.android.internal.util.function.pooled.PooledLambda.obtainMessage;
-
 import android.annotation.NonNull;
 import android.annotation.Nullable;
+import android.annotation.SystemApi;
 import android.annotation.SystemService;
 import android.annotation.UiThread;
 import android.content.ComponentName;
@@ -33,7 +33,6 @@
 import android.view.contentcapture.ContentCaptureSession.FlushReason;
 
 import com.android.internal.annotations.GuardedBy;
-import com.android.internal.os.IResultReceiver;
 import com.android.internal.util.Preconditions;
 import com.android.internal.util.SyncResultReceiver;
 
@@ -54,6 +53,13 @@
 
     private static final String TAG = ContentCaptureManager.class.getSimpleName();
 
+    /** @hide */
+    public static final int RESULT_CODE_TRUE = 1;
+    /** @hide */
+    public static final int RESULT_CODE_FALSE = 2;
+    /** @hide */
+    public static final int RESULT_CODE_NOT_SERVICE = -1;
+
     /**
      * Timeout for calls to system_server.
      */
@@ -111,9 +117,7 @@
             if (mMainSession == null) {
                 mMainSession = new MainContentCaptureSession(mContext, mHandler, mService,
                         mDisabled);
-                if (VERBOSE) {
-                    Log.v(TAG, "getDefaultContentCaptureSession(): created " + mMainSession);
-                }
+                if (VERBOSE) Log.v(TAG, "getMainContentCaptureSession(): created " + mMainSession);
             }
             return mMainSession;
         }
@@ -150,24 +154,30 @@
      */
     @Nullable
     public ComponentName getServiceComponentName() {
-        if (!isContentCaptureEnabled()) {
-            return null;
-        }
-        // Wait for system server to return the component name.
-        final SyncResultReceiver resultReceiver = new SyncResultReceiver(SYNC_CALLS_TIMEOUT_MS);
-        mHandler.sendMessage(obtainMessage(
-                ContentCaptureManager::handleGetComponentName, this, resultReceiver));
+        if (!isContentCaptureEnabled()) return null;
 
+        final SyncResultReceiver resultReceiver = new SyncResultReceiver(SYNC_CALLS_TIMEOUT_MS);
         try {
+            mService.getServiceComponentName(resultReceiver);
             return resultReceiver.getParcelableResult();
         } catch (RemoteException e) {
-            // Unable to retrieve component name in a reasonable amount of time.
             throw e.rethrowFromSystemServer();
         }
     }
 
     /**
      * Checks whether content capture is enabled for this activity.
+     *
+     * <p>There are many reasons it could be disabled, such as:
+     * <ul>
+     *   <li>App itself disabled content capture through {@link #setContentCaptureEnabled(boolean)}.
+     *   <li>Service disabled content capture for this specific activity.
+     *   <li>Service disabled content capture for all activities of this package.
+     *   <li>Service disabled content capture globally.
+     *   <li>User disabled content capture globally (through Settings).
+     *   <li>OEM disabled content capture globally.
+     *   <li>Transient errors.
+     * </ul>
      */
     public boolean isContentCaptureEnabled() {
         synchronized (mLock) {
@@ -182,12 +192,82 @@
      * it on {@link android.app.Activity#onCreate(android.os.Bundle, android.os.PersistableBundle)}.
      */
     public void setContentCaptureEnabled(boolean enabled) {
+        if (DEBUG) {
+            Log.d(TAG, "setContentCaptureEnabled(): setting to " + enabled + " for " + mContext);
+        }
+
         synchronized (mLock) {
             mFlags |= enabled ? 0 : ContentCaptureContext.FLAG_DISABLED_BY_APP;
         }
     }
 
     /**
+     * Gets whether Content Capture is enabled for the given user.
+     *
+     * <p>This method is typically used by the Content Capture Service settings page, so it can
+     * provide a toggle to enable / disable it.
+     *
+     * @throws SecurityException if caller is not the app that owns the Content Capture service
+     * associated with the user.
+     *
+     * @hide
+     */
+    @SystemApi
+    public boolean isContentCaptureFeatureEnabled() {
+        if (mService == null) return false;
+
+        final SyncResultReceiver resultReceiver = new SyncResultReceiver(SYNC_CALLS_TIMEOUT_MS);
+        final int resultCode;
+        try {
+            mService.isContentCaptureFeatureEnabled(resultReceiver);
+            resultCode = resultReceiver.getIntResult();
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+        switch (resultCode) {
+            case RESULT_CODE_TRUE:
+                return true;
+            case RESULT_CODE_FALSE:
+                return false;
+            case RESULT_CODE_NOT_SERVICE:
+                throw new SecurityException("caller is not user's ContentCapture service");
+            default:
+                throw new IllegalStateException("received invalid result: " + resultCode);
+        }
+    }
+
+    /**
+     * Sets whether Content Capture is enabled for the given user.
+     *
+     * @throws SecurityException if caller is not the app that owns the Content Capture service
+     * associated with the user.
+     *
+     * @hide
+     */
+    @SystemApi
+    public void setContentCaptureFeatureEnabled(boolean enabled) {
+        if (DEBUG) Log.d(TAG, "setContentCaptureFeatureEnabled(): setting to " + enabled);
+
+        final SyncResultReceiver resultReceiver = new SyncResultReceiver(SYNC_CALLS_TIMEOUT_MS);
+        final int resultCode;
+        try {
+            mService.setContentCaptureFeatureEnabled(enabled, resultReceiver);
+            resultCode = resultReceiver.getIntResult();
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+        switch (resultCode) {
+            case RESULT_CODE_TRUE:
+                // Our work is done here, in our void existance...
+                return;
+            case RESULT_CODE_NOT_SERVICE:
+                throw new SecurityException("caller is not user's ContentCapture service");
+            default:
+                throw new IllegalStateException("received invalid result: " + resultCode);
+        }
+    }
+
+    /**
      * Called by the app to request the Content Capture service to remove user-data associated with
      * some context.
      *
@@ -223,14 +303,4 @@
             }
         }
     }
-
-
-    /** Retrieves the component name of the target content capture service through system_server. */
-    private void handleGetComponentName(@NonNull IResultReceiver resultReceiver) {
-        try {
-            mService.getServiceComponentName(resultReceiver);
-        } catch (RemoteException e) {
-            Log.w(TAG, "Unable to retrieve service component name: " + e);
-        }
-    }
 }
diff --git a/core/java/android/view/contentcapture/ContentCaptureSession.java b/core/java/android/view/contentcapture/ContentCaptureSession.java
index c425e7b..e6ee6ed 100644
--- a/core/java/android/view/contentcapture/ContentCaptureSession.java
+++ b/core/java/android/view/contentcapture/ContentCaptureSession.java
@@ -99,7 +99,8 @@
     public static final int STATE_FLAG_SECURE = 0x20;
 
     /**
-     * Session is disabled manually by the specific app.
+     * Session is disabled manually by the specific app
+     * (through {@link ContentCaptureManager#setContentCaptureEnabled(boolean)}).
      *
      * @hide
      */
diff --git a/core/java/android/view/contentcapture/IContentCaptureManager.aidl b/core/java/android/view/contentcapture/IContentCaptureManager.aidl
index 56ed8bf..26cf34c 100644
--- a/core/java/android/view/contentcapture/IContentCaptureManager.aidl
+++ b/core/java/android/view/contentcapture/IContentCaptureManager.aidl
@@ -62,4 +62,14 @@
      * Requests the removal of user data for the calling user.
      */
     void removeUserData(in UserDataRemovalRequest request);
+
+    /**
+     * Returns whether the content capture feature is enabled for the calling user.
+     */
+    void isContentCaptureFeatureEnabled(in IResultReceiver result);
+
+    /**
+     * Sets whether the content capture feature is enabled for the given user.
+     */
+    void setContentCaptureFeatureEnabled(boolean enabled, in IResultReceiver result);
 }
diff --git a/core/java/android/view/contentcapture/MainContentCaptureSession.java b/core/java/android/view/contentcapture/MainContentCaptureSession.java
index 83dbf2d..72aefb2 100644
--- a/core/java/android/view/contentcapture/MainContentCaptureSession.java
+++ b/core/java/android/view/contentcapture/MainContentCaptureSession.java
@@ -402,7 +402,7 @@
     }
 
     private void handleFlushIfNeeded(@FlushReason int reason) {
-        if (mEvents.isEmpty()) {
+        if (mEvents == null || mEvents.isEmpty()) {
             if (VERBOSE) Log.v(TAG, "Nothing to flush");
             return;
         }
diff --git a/core/java/android/view/textclassifier/IntentFactory.java b/core/java/android/view/textclassifier/IntentFactory.java
new file mode 100644
index 0000000..d9c03c8
--- /dev/null
+++ b/core/java/android/view/textclassifier/IntentFactory.java
@@ -0,0 +1,56 @@
+/*
+ * 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.
+ */
+package android.view.textclassifier;
+
+import android.annotation.Nullable;
+import android.content.Context;
+import android.content.Intent;
+
+import com.google.android.textclassifier.AnnotatorModel;
+
+import java.time.Instant;
+import java.util.List;
+
+/**
+ * @hide
+ */
+public interface IntentFactory {
+
+    /**
+     * Return a list of LabeledIntent from the classification result.
+     */
+    List<TextClassifierImpl.LabeledIntent> create(
+            Context context,
+            String text,
+            boolean foreignText,
+            @Nullable Instant referenceTime,
+            @Nullable AnnotatorModel.ClassificationResult classification);
+
+    /**
+     * Inserts translate action to the list if it is a foreign text.
+     */
+    static void insertTranslateAction(
+            List<TextClassifierImpl.LabeledIntent> actions, Context context, String text) {
+        actions.add(new TextClassifierImpl.LabeledIntent(
+                context.getString(com.android.internal.R.string.translate),
+                context.getString(com.android.internal.R.string.translate_desc),
+                new Intent(Intent.ACTION_TRANSLATE)
+                        // TODO: Probably better to introduce a "translate" scheme instead of
+                        // using EXTRA_TEXT.
+                        .putExtra(Intent.EXTRA_TEXT, text),
+                text.hashCode()));
+    }
+}
diff --git a/core/java/android/view/textclassifier/LegacyIntentFactory.java b/core/java/android/view/textclassifier/LegacyIntentFactory.java
new file mode 100644
index 0000000..b6e5b3e2
--- /dev/null
+++ b/core/java/android/view/textclassifier/LegacyIntentFactory.java
@@ -0,0 +1,260 @@
+/*
+ * 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.
+ */
+package android.view.textclassifier;
+
+import static java.time.temporal.ChronoUnit.MILLIS;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.app.SearchManager;
+import android.content.ContentUris;
+import android.content.Context;
+import android.content.Intent;
+import android.net.Uri;
+import android.os.Bundle;
+import android.os.UserManager;
+import android.provider.Browser;
+import android.provider.CalendarContract;
+import android.provider.ContactsContract;
+import android.view.textclassifier.TextClassifierImpl.LabeledIntent;
+
+import com.google.android.textclassifier.AnnotatorModel;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Creates intents based on the classification type.
+ * @hide
+ */
+public final class LegacyIntentFactory implements IntentFactory {
+
+    private static final String TAG = "LegacyIntentFactory";
+    private static final long MIN_EVENT_FUTURE_MILLIS = TimeUnit.MINUTES.toMillis(5);
+    private static final long DEFAULT_EVENT_DURATION = TimeUnit.HOURS.toMillis(1);
+
+    public LegacyIntentFactory() {}
+
+    @NonNull
+    @Override
+    public List<LabeledIntent> create(Context context, String text, boolean foreignText,
+            @Nullable Instant referenceTime,
+            AnnotatorModel.ClassificationResult classification) {
+        final String type = classification != null
+                ? classification.getCollection().trim().toLowerCase(Locale.ENGLISH)
+                : "";
+        text = text.trim();
+        final List<LabeledIntent> actions;
+        switch (type) {
+            case TextClassifier.TYPE_EMAIL:
+                actions = createForEmail(context, text);
+                break;
+            case TextClassifier.TYPE_PHONE:
+                actions = createForPhone(context, text);
+                break;
+            case TextClassifier.TYPE_ADDRESS:
+                actions = createForAddress(context, text);
+                break;
+            case TextClassifier.TYPE_URL:
+                actions = createForUrl(context, text);
+                break;
+            case TextClassifier.TYPE_DATE:  // fall through
+            case TextClassifier.TYPE_DATE_TIME:
+                if (classification.getDatetimeResult() != null) {
+                    final Instant parsedTime = Instant.ofEpochMilli(
+                            classification.getDatetimeResult().getTimeMsUtc());
+                    actions = createForDatetime(context, type, referenceTime, parsedTime);
+                } else {
+                    actions = new ArrayList<>();
+                }
+                break;
+            case TextClassifier.TYPE_FLIGHT_NUMBER:
+                actions = createForFlight(context, text);
+                break;
+            case TextClassifier.TYPE_DICTIONARY:
+                actions = createForDictionary(context, text);
+                break;
+            default:
+                actions = new ArrayList<>();
+                break;
+        }
+        if (foreignText) {
+            IntentFactory.insertTranslateAction(actions, context, text);
+        }
+        actions.forEach(
+                action -> action.getIntent()
+                        .putExtra(TextClassifier.EXTRA_FROM_TEXT_CLASSIFIER, true));
+        return actions;
+    }
+
+    @NonNull
+    private static List<LabeledIntent> createForEmail(Context context, String text) {
+        final List<LabeledIntent> actions = new ArrayList<>();
+        actions.add(new LabeledIntent(
+                context.getString(com.android.internal.R.string.email),
+                context.getString(com.android.internal.R.string.email_desc),
+                new Intent(Intent.ACTION_SENDTO)
+                        .setData(Uri.parse(String.format("mailto:%s", text))),
+                LabeledIntent.DEFAULT_REQUEST_CODE));
+        actions.add(new LabeledIntent(
+                context.getString(com.android.internal.R.string.add_contact),
+                context.getString(com.android.internal.R.string.add_contact_desc),
+                new Intent(Intent.ACTION_INSERT_OR_EDIT)
+                        .setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE)
+                        .putExtra(ContactsContract.Intents.Insert.EMAIL, text),
+                text.hashCode()));
+        return actions;
+    }
+
+    @NonNull
+    private static List<LabeledIntent> createForPhone(Context context, String text) {
+        final List<LabeledIntent> actions = new ArrayList<>();
+        final UserManager userManager = context.getSystemService(UserManager.class);
+        final Bundle userRestrictions = userManager != null
+                ? userManager.getUserRestrictions() : new Bundle();
+        if (!userRestrictions.getBoolean(UserManager.DISALLOW_OUTGOING_CALLS, false)) {
+            actions.add(new LabeledIntent(
+                    context.getString(com.android.internal.R.string.dial),
+                    context.getString(com.android.internal.R.string.dial_desc),
+                    new Intent(Intent.ACTION_DIAL).setData(
+                            Uri.parse(String.format("tel:%s", text))),
+                    LabeledIntent.DEFAULT_REQUEST_CODE));
+        }
+        actions.add(new LabeledIntent(
+                context.getString(com.android.internal.R.string.add_contact),
+                context.getString(com.android.internal.R.string.add_contact_desc),
+                new Intent(Intent.ACTION_INSERT_OR_EDIT)
+                        .setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE)
+                        .putExtra(ContactsContract.Intents.Insert.PHONE, text),
+                text.hashCode()));
+        if (!userRestrictions.getBoolean(UserManager.DISALLOW_SMS, false)) {
+            actions.add(new LabeledIntent(
+                    context.getString(com.android.internal.R.string.sms),
+                    context.getString(com.android.internal.R.string.sms_desc),
+                    new Intent(Intent.ACTION_SENDTO)
+                            .setData(Uri.parse(String.format("smsto:%s", text))),
+                    LabeledIntent.DEFAULT_REQUEST_CODE));
+        }
+        return actions;
+    }
+
+    @NonNull
+    private static List<LabeledIntent> createForAddress(Context context, String text) {
+        final List<LabeledIntent> actions = new ArrayList<>();
+        try {
+            final String encText = URLEncoder.encode(text, "UTF-8");
+            actions.add(new LabeledIntent(
+                    context.getString(com.android.internal.R.string.map),
+                    context.getString(com.android.internal.R.string.map_desc),
+                    new Intent(Intent.ACTION_VIEW)
+                            .setData(Uri.parse(String.format("geo:0,0?q=%s", encText))),
+                    LabeledIntent.DEFAULT_REQUEST_CODE));
+        } catch (UnsupportedEncodingException e) {
+            Log.e(TAG, "Could not encode address", e);
+        }
+        return actions;
+    }
+
+    @NonNull
+    private static List<LabeledIntent> createForUrl(Context context, String text) {
+        if (Uri.parse(text).getScheme() == null) {
+            text = "http://" + text;
+        }
+        final List<LabeledIntent> actions = new ArrayList<>();
+        actions.add(new LabeledIntent(
+                context.getString(com.android.internal.R.string.browse),
+                context.getString(com.android.internal.R.string.browse_desc),
+                new Intent(Intent.ACTION_VIEW, Uri.parse(text))
+                        .putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName()),
+                LabeledIntent.DEFAULT_REQUEST_CODE));
+        return actions;
+    }
+
+    @NonNull
+    private static List<LabeledIntent> createForDatetime(
+            Context context, String type, @Nullable Instant referenceTime,
+            Instant parsedTime) {
+        if (referenceTime == null) {
+            // If no reference time was given, use now.
+            referenceTime = Instant.now();
+        }
+        List<LabeledIntent> actions = new ArrayList<>();
+        actions.add(createCalendarViewIntent(context, parsedTime));
+        final long millisUntilEvent = referenceTime.until(parsedTime, MILLIS);
+        if (millisUntilEvent > MIN_EVENT_FUTURE_MILLIS) {
+            actions.add(createCalendarCreateEventIntent(context, parsedTime, type));
+        }
+        return actions;
+    }
+
+    @NonNull
+    private static List<LabeledIntent> createForFlight(Context context, String text) {
+        final List<LabeledIntent> actions = new ArrayList<>();
+        actions.add(new LabeledIntent(
+                context.getString(com.android.internal.R.string.view_flight),
+                context.getString(com.android.internal.R.string.view_flight_desc),
+                new Intent(Intent.ACTION_WEB_SEARCH)
+                        .putExtra(SearchManager.QUERY, text),
+                text.hashCode()));
+        return actions;
+    }
+
+    @NonNull
+    private static LabeledIntent createCalendarViewIntent(Context context, Instant parsedTime) {
+        Uri.Builder builder = CalendarContract.CONTENT_URI.buildUpon();
+        builder.appendPath("time");
+        ContentUris.appendId(builder, parsedTime.toEpochMilli());
+        return new LabeledIntent(
+                context.getString(com.android.internal.R.string.view_calendar),
+                context.getString(com.android.internal.R.string.view_calendar_desc),
+                new Intent(Intent.ACTION_VIEW).setData(builder.build()),
+                LabeledIntent.DEFAULT_REQUEST_CODE);
+    }
+
+    @NonNull
+    private static LabeledIntent createCalendarCreateEventIntent(
+            Context context, Instant parsedTime, @TextClassifier.EntityType String type) {
+        final boolean isAllDay = TextClassifier.TYPE_DATE.equals(type);
+        return new LabeledIntent(
+                context.getString(com.android.internal.R.string.add_calendar_event),
+                context.getString(com.android.internal.R.string.add_calendar_event_desc),
+                new Intent(Intent.ACTION_INSERT)
+                        .setData(CalendarContract.Events.CONTENT_URI)
+                        .putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, isAllDay)
+                        .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME,
+                                parsedTime.toEpochMilli())
+                        .putExtra(CalendarContract.EXTRA_EVENT_END_TIME,
+                                parsedTime.toEpochMilli() + DEFAULT_EVENT_DURATION),
+                parsedTime.hashCode());
+    }
+
+    @NonNull
+    private static List<LabeledIntent> createForDictionary(Context context, String text) {
+        final List<LabeledIntent> actions = new ArrayList<>();
+        actions.add(new LabeledIntent(
+                context.getString(com.android.internal.R.string.define),
+                context.getString(com.android.internal.R.string.define_desc),
+                new Intent(Intent.ACTION_DEFINE)
+                        .putExtra(Intent.EXTRA_TEXT, text),
+                text.hashCode()));
+        return actions;
+    }
+}
diff --git a/core/java/android/view/textclassifier/TemplateIntentFactory.java b/core/java/android/view/textclassifier/TemplateIntentFactory.java
new file mode 100644
index 0000000..97e11bb
--- /dev/null
+++ b/core/java/android/view/textclassifier/TemplateIntentFactory.java
@@ -0,0 +1,167 @@
+/*
+ * 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.
+ */
+package android.view.textclassifier;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.content.Context;
+import android.content.Intent;
+import android.net.Uri;
+import android.os.Bundle;
+import android.text.TextUtils;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.util.ArrayUtils;
+import com.android.internal.util.Preconditions;
+
+import com.google.android.textclassifier.AnnotatorModel;
+import com.google.android.textclassifier.NamedVariant;
+import com.google.android.textclassifier.RemoteActionTemplate;
+
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * Creates intents based on {@link RemoteActionTemplate} objects.
+ * @hide
+ */
+@VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
+public final class TemplateIntentFactory implements IntentFactory {
+    private static final String TAG = TextClassifier.DEFAULT_LOG_TAG;
+    private final IntentFactory mFallback;
+
+    public TemplateIntentFactory(IntentFactory fallback) {
+        mFallback = Preconditions.checkNotNull(fallback);
+    }
+
+    /**
+     * Returns a list of {@link android.view.textclassifier.TextClassifierImpl.LabeledIntent}
+     * that are constructed from the classification result.
+     */
+    @NonNull
+    @Override
+    public List<TextClassifierImpl.LabeledIntent> create(
+            Context context,
+            String text,
+            boolean foreignText,
+            @Nullable Instant referenceTime,
+            @Nullable AnnotatorModel.ClassificationResult classification) {
+        if (classification == null) {
+            return Collections.emptyList();
+        }
+        RemoteActionTemplate[] remoteActionTemplates = classification.getRemoteActionTemplates();
+        if (ArrayUtils.isEmpty(remoteActionTemplates)) {
+            // RemoteActionTemplate is missing, fallback.
+            Log.w(TAG, "RemoteActionTemplate is missing, fallback to LegacyIntentFactory.");
+            return mFallback.create(context, text, foreignText, referenceTime, classification);
+        }
+        final List<TextClassifierImpl.LabeledIntent> labeledIntents =
+                new ArrayList<>(createFromRemoteActionTemplates(remoteActionTemplates));
+        if (foreignText) {
+            IntentFactory.insertTranslateAction(labeledIntents, context, text.trim());
+        }
+        labeledIntents.forEach(
+                action -> action.getIntent()
+                        .putExtra(TextClassifier.EXTRA_FROM_TEXT_CLASSIFIER, true));
+        return labeledIntents;
+    }
+
+    private static List<TextClassifierImpl.LabeledIntent> createFromRemoteActionTemplates(
+            RemoteActionTemplate[] remoteActionTemplates) {
+        final List<TextClassifierImpl.LabeledIntent> labeledIntents = new ArrayList<>();
+        for (RemoteActionTemplate remoteActionTemplate : remoteActionTemplates) {
+            Intent intent = createIntent(remoteActionTemplate);
+            if (intent == null) {
+                continue;
+            }
+            TextClassifierImpl.LabeledIntent
+                    labeledIntent = new TextClassifierImpl.LabeledIntent(
+                    remoteActionTemplate.title,
+                    remoteActionTemplate.description,
+                    intent,
+                    remoteActionTemplate.requestCode == null
+                            ? TextClassifierImpl.LabeledIntent.DEFAULT_REQUEST_CODE
+                            : remoteActionTemplate.requestCode
+            );
+            labeledIntents.add(labeledIntent);
+        }
+        return labeledIntents;
+    }
+
+    @Nullable
+    private static Intent createIntent(RemoteActionTemplate remoteActionTemplate) {
+        Intent intent = new Intent();
+        if (!TextUtils.isEmpty(remoteActionTemplate.packageName)) {
+            Log.w(TAG, "A RemoteActionTemplate is skipped as package name is set.");
+            return null;
+        }
+        if (!TextUtils.isEmpty(remoteActionTemplate.action)) {
+            intent.setAction(remoteActionTemplate.action);
+        }
+        Uri data = null;
+        if (!TextUtils.isEmpty(remoteActionTemplate.data)) {
+            data = Uri.parse(remoteActionTemplate.data);
+        }
+        if (data != null || !TextUtils.isEmpty(remoteActionTemplate.type)) {
+            intent.setDataAndType(data, remoteActionTemplate.type);
+        }
+        if (remoteActionTemplate.flags != null) {
+            intent.setFlags(remoteActionTemplate.flags);
+        }
+        if (remoteActionTemplate.category != null) {
+            for (String category : remoteActionTemplate.category) {
+                intent.addCategory(category);
+            }
+        }
+        intent.putExtras(createExtras(remoteActionTemplate.extras));
+        return intent;
+    }
+
+    private static Bundle createExtras(NamedVariant[] namedVariants) {
+        if (namedVariants == null) {
+            return Bundle.EMPTY;
+        }
+        Bundle bundle = new Bundle();
+        for (NamedVariant namedVariant : namedVariants) {
+            switch (namedVariant.getType()) {
+                case NamedVariant.TYPE_INT:
+                    bundle.putInt(namedVariant.getName(), namedVariant.getInt());
+                    break;
+                case NamedVariant.TYPE_LONG:
+                    bundle.putLong(namedVariant.getName(), namedVariant.getLong());
+                    break;
+                case NamedVariant.TYPE_FLOAT:
+                    bundle.putFloat(namedVariant.getName(), namedVariant.getFloat());
+                    break;
+                case NamedVariant.TYPE_DOUBLE:
+                    bundle.putDouble(namedVariant.getName(), namedVariant.getDouble());
+                    break;
+                case NamedVariant.TYPE_BOOL:
+                    bundle.putBoolean(namedVariant.getName(), namedVariant.getBool());
+                    break;
+                case NamedVariant.TYPE_STRING:
+                    bundle.putString(namedVariant.getName(), namedVariant.getString());
+                    break;
+                default:
+                    Log.w(TAG,
+                            "Unsupported type found in createExtras : " + namedVariant.getType());
+            }
+        }
+        return bundle;
+    }
+}
diff --git a/core/java/android/view/textclassifier/TextClassificationConstants.java b/core/java/android/view/textclassifier/TextClassificationConstants.java
index 7f928f7..ee9e04e 100644
--- a/core/java/android/view/textclassifier/TextClassificationConstants.java
+++ b/core/java/android/view/textclassifier/TextClassificationConstants.java
@@ -47,6 +47,7 @@
  * entity_list_not_editable                 (String[])
  * entity_list_editable                     (String[])
  * lang_id_threshold_override               (float)
+ * template_intent_factory_enabled          (boolean)
  * </pre>
  *
  * <p>
@@ -97,6 +98,7 @@
             "notification_conversation_action_types_default";
     private static final String LANG_ID_THRESHOLD_OVERRIDE =
             "lang_id_threshold_override";
+    private static final String TEMPLATE_INTENT_FACTORY_ENABLED = "template_intent_factory_enabled";
 
     private static final boolean LOCAL_TEXT_CLASSIFIER_ENABLED_DEFAULT = true;
     private static final boolean SYSTEM_TEXT_CLASSIFIER_ENABLED_DEFAULT = true;
@@ -137,6 +139,7 @@
      * @see EntityConfidence
      */
     private static final float LANG_ID_THRESHOLD_OVERRIDE_DEFAULT = -1f;
+    private static final boolean TEMPLATE_INTENT_FACTORY_ENABLED_DEFAULT = true;
 
     private final boolean mSystemTextClassifierEnabled;
     private final boolean mLocalTextClassifierEnabled;
@@ -155,6 +158,7 @@
     private final List<String> mInAppConversationActionTypesDefault;
     private final List<String> mNotificationConversationActionTypesDefault;
     private final float mLangIdThresholdOverride;
+    private final boolean mTemplateIntentFactoryEnabled;
 
     private TextClassificationConstants(@Nullable String settings) {
         final KeyValueListParser parser = new KeyValueListParser(',');
@@ -215,6 +219,8 @@
         mLangIdThresholdOverride = parser.getFloat(
                 LANG_ID_THRESHOLD_OVERRIDE,
                 LANG_ID_THRESHOLD_OVERRIDE_DEFAULT);
+        mTemplateIntentFactoryEnabled = parser.getBoolean(
+                TEMPLATE_INTENT_FACTORY_ENABLED, TEMPLATE_INTENT_FACTORY_ENABLED_DEFAULT);
     }
 
     /** Load from a settings string. */
@@ -290,6 +296,10 @@
         return mLangIdThresholdOverride;
     }
 
+    public boolean isTemplateIntentFactoryEnabled() {
+        return mTemplateIntentFactoryEnabled;
+    }
+
     private static List<String> parseStringList(String listStr) {
         return Collections.unmodifiableList(Arrays.asList(listStr.split(STRING_LIST_DELIMITER)));
     }
@@ -315,6 +325,7 @@
         pw.printPair("getNotificationConversationActionTypes",
                 mNotificationConversationActionTypesDefault);
         pw.printPair("getLangIdThresholdOverride", mLangIdThresholdOverride);
+        pw.printPair("isTemplateIntentFactoryEnabled", mTemplateIntentFactoryEnabled);
         pw.decreaseIndent();
         pw.println();
     }
diff --git a/core/java/android/view/textclassifier/TextClassifierImpl.java b/core/java/android/view/textclassifier/TextClassifierImpl.java
index 7782079..c297928 100644
--- a/core/java/android/view/textclassifier/TextClassifierImpl.java
+++ b/core/java/android/view/textclassifier/TextClassifierImpl.java
@@ -16,30 +16,21 @@
 
 package android.view.textclassifier;
 
-import static java.time.temporal.ChronoUnit.MILLIS;
-
 import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.annotation.WorkerThread;
 import android.app.PendingIntent;
 import android.app.RemoteAction;
-import android.app.SearchManager;
 import android.content.ComponentName;
-import android.content.ContentUris;
 import android.content.Context;
 import android.content.Intent;
 import android.content.pm.PackageManager;
 import android.content.pm.ResolveInfo;
 import android.graphics.drawable.Icon;
 import android.icu.util.ULocale;
-import android.net.Uri;
 import android.os.Bundle;
 import android.os.LocaleList;
 import android.os.ParcelFileDescriptor;
-import android.os.UserManager;
-import android.provider.Browser;
-import android.provider.CalendarContract;
-import android.provider.ContactsContract;
 
 import com.android.internal.annotations.GuardedBy;
 import com.android.internal.annotations.VisibleForTesting;
@@ -53,19 +44,15 @@
 import java.io.File;
 import java.io.FileNotFoundException;
 import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.net.URLEncoder;
 import java.time.Instant;
 import java.time.ZonedDateTime;
 import java.util.ArrayList;
-import java.util.Arrays;
 import java.util.Collection;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Locale;
 import java.util.Map;
 import java.util.Objects;
-import java.util.concurrent.TimeUnit;
 
 /**
  * Default implementation of the {@link TextClassifier} interface.
@@ -128,6 +115,8 @@
     private final ModelFileManager mLangIdModelFileManager;
     private final ModelFileManager mActionsModelFileManager;
 
+    private final IntentFactory mIntentFactory;
+
     public TextClassifierImpl(
             Context context, TextClassificationConstants settings, TextClassifier fallback) {
         mContext = Preconditions.checkNotNull(context);
@@ -155,6 +144,10 @@
                         UPDATED_ACTIONS_MODEL,
                         ActionsSuggestionsModel::getVersion,
                         ActionsSuggestionsModel::getLocales));
+
+        mIntentFactory = mSettings.isTemplateIntentFactoryEnabled()
+                ? new TemplateIntentFactory(new LegacyIntentFactory())
+                : new LegacyIntentFactory();
     }
 
     public TextClassifierImpl(Context context, TextClassificationConstants settings) {
@@ -198,7 +191,8 @@
                                     new AnnotatorModel.ClassificationOptions(
                                             refTime.toInstant().toEpochMilli(),
                                             refTime.getZone().getId(),
-                                            localesString));
+                                            localesString),
+                                    mContext);
                     final int size = results.length;
                     for (int i = 0; i < size; i++) {
                         tsBuilder.setEntityType(results[i].getCollection(), results[i].getScore());
@@ -241,7 +235,8 @@
                                         new AnnotatorModel.ClassificationOptions(
                                                 refTime.toInstant().toEpochMilli(),
                                                 refTime.getZone().getId(),
-                                                localesString));
+                                                localesString),
+                                        mContext);
                 if (results.length > 0) {
                     return createClassificationResult(
                             results, string,
@@ -560,8 +555,9 @@
         AnnotatorModel.ClassificationResult highestScoringResult =
                 typeCount > 0 ? classifications[0] : null;
         for (int i = 0; i < typeCount; i++) {
-            builder.setEntityType(classifications[i].getCollection(),
-                                  classifications[i].getScore());
+            builder.setEntityType(
+                    classifications[i].getCollection(),
+                    classifications[i].getScore());
             if (classifications[i].getScore() > highestScoringResult.getScore()) {
                 highestScoringResult = classifications[i];
             }
@@ -572,9 +568,13 @@
                 : 0.5f /* TODO: Load this from the langId model. */;
         boolean isPrimaryAction = true;
         final ArrayList<Intent> sourceIntents = new ArrayList<>();
-        for (LabeledIntent labeledIntent : IntentFactory.create(
-                mContext, classifiedText, isForeignText(classifiedText, foreignTextThreshold),
-                referenceTime, highestScoringResult)) {
+        List<LabeledIntent> labeledIntents = mIntentFactory.create(
+                mContext,
+                classifiedText,
+                isForeignText(classifiedText, foreignTextThreshold),
+                referenceTime,
+                highestScoringResult);
+        for (LabeledIntent labeledIntent : labeledIntents) {
             final RemoteAction action = labeledIntent.asRemoteAction(mContext);
             if (action == null) {
                 continue;
@@ -720,11 +720,13 @@
             mRequestCode = requestCode;
         }
 
-        String getTitle() {
+        @VisibleForTesting
+        public String getTitle() {
             return mTitle;
         }
 
-        String getDescription() {
+        @VisibleForTesting
+        public String getDescription() {
             return mDescription;
         }
 
@@ -733,7 +735,8 @@
             return mIntent;
         }
 
-        int getRequestCode() {
+        @VisibleForTesting
+        public int getRequestCode() {
             return mRequestCode;
         }
 
@@ -769,233 +772,4 @@
             return action;
         }
     }
-
-    /**
-     * Creates intents based on the classification type.
-     */
-    @VisibleForTesting
-    public static final class IntentFactory {
-
-        private static final long MIN_EVENT_FUTURE_MILLIS = TimeUnit.MINUTES.toMillis(5);
-        private static final long DEFAULT_EVENT_DURATION = TimeUnit.HOURS.toMillis(1);
-
-        private IntentFactory() {}
-
-        @NonNull
-        public static List<LabeledIntent> create(
-                Context context,
-                String text,
-                boolean foreignText,
-                @Nullable Instant referenceTime,
-                @Nullable AnnotatorModel.ClassificationResult classification) {
-            final String type = classification != null
-                    ? classification.getCollection().trim().toLowerCase(Locale.ENGLISH)
-                    : "";
-            text = text.trim();
-            final List<LabeledIntent> actions;
-            switch (type) {
-                case TextClassifier.TYPE_EMAIL:
-                    actions = createForEmail(context, text);
-                    break;
-                case TextClassifier.TYPE_PHONE:
-                    actions = createForPhone(context, text);
-                    break;
-                case TextClassifier.TYPE_ADDRESS:
-                    actions = createForAddress(context, text);
-                    break;
-                case TextClassifier.TYPE_URL:
-                    actions = createForUrl(context, text);
-                    break;
-                case TextClassifier.TYPE_DATE:  // fall through
-                case TextClassifier.TYPE_DATE_TIME:
-                    if (classification.getDatetimeResult() != null) {
-                        final Instant parsedTime = Instant.ofEpochMilli(
-                                classification.getDatetimeResult().getTimeMsUtc());
-                        actions = createForDatetime(context, type, referenceTime, parsedTime);
-                    } else {
-                        actions = new ArrayList<>();
-                    }
-                    break;
-                case TextClassifier.TYPE_FLIGHT_NUMBER:
-                    actions = createForFlight(context, text);
-                    break;
-                case TextClassifier.TYPE_DICTIONARY:
-                    actions = createForDictionary(context, text);
-                    break;
-                default:
-                    actions = new ArrayList<>();
-                    break;
-            }
-            if (foreignText) {
-                insertTranslateAction(actions, context, text);
-            }
-            actions.forEach(
-                    action -> action.getIntent()
-                            .putExtra(TextClassifier.EXTRA_FROM_TEXT_CLASSIFIER, true));
-            return actions;
-        }
-
-        @NonNull
-        private static List<LabeledIntent> createForEmail(Context context, String text) {
-            final List<LabeledIntent> actions = new ArrayList<>();
-            actions.add(new LabeledIntent(
-                    context.getString(com.android.internal.R.string.email),
-                    context.getString(com.android.internal.R.string.email_desc),
-                    new Intent(Intent.ACTION_SENDTO)
-                            .setData(Uri.parse(String.format("mailto:%s", text))),
-                    LabeledIntent.DEFAULT_REQUEST_CODE));
-            actions.add(new LabeledIntent(
-                    context.getString(com.android.internal.R.string.add_contact),
-                    context.getString(com.android.internal.R.string.add_contact_desc),
-                    new Intent(Intent.ACTION_INSERT_OR_EDIT)
-                            .setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE)
-                            .putExtra(ContactsContract.Intents.Insert.EMAIL, text),
-                    text.hashCode()));
-            return actions;
-        }
-
-        @NonNull
-        private static List<LabeledIntent> createForPhone(Context context, String text) {
-            final List<LabeledIntent> actions = new ArrayList<>();
-            final UserManager userManager = context.getSystemService(UserManager.class);
-            final Bundle userRestrictions = userManager != null
-                    ? userManager.getUserRestrictions() : new Bundle();
-            if (!userRestrictions.getBoolean(UserManager.DISALLOW_OUTGOING_CALLS, false)) {
-                actions.add(new LabeledIntent(
-                        context.getString(com.android.internal.R.string.dial),
-                        context.getString(com.android.internal.R.string.dial_desc),
-                        new Intent(Intent.ACTION_DIAL).setData(
-                                Uri.parse(String.format("tel:%s", text))),
-                        LabeledIntent.DEFAULT_REQUEST_CODE));
-            }
-            actions.add(new LabeledIntent(
-                    context.getString(com.android.internal.R.string.add_contact),
-                    context.getString(com.android.internal.R.string.add_contact_desc),
-                    new Intent(Intent.ACTION_INSERT_OR_EDIT)
-                            .setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE)
-                            .putExtra(ContactsContract.Intents.Insert.PHONE, text),
-                    text.hashCode()));
-            if (!userRestrictions.getBoolean(UserManager.DISALLOW_SMS, false)) {
-                actions.add(new LabeledIntent(
-                        context.getString(com.android.internal.R.string.sms),
-                        context.getString(com.android.internal.R.string.sms_desc),
-                        new Intent(Intent.ACTION_SENDTO)
-                                .setData(Uri.parse(String.format("smsto:%s", text))),
-                        LabeledIntent.DEFAULT_REQUEST_CODE));
-            }
-            return actions;
-        }
-
-        @NonNull
-        private static List<LabeledIntent> createForAddress(Context context, String text) {
-            final List<LabeledIntent> actions = new ArrayList<>();
-            try {
-                final String encText = URLEncoder.encode(text, "UTF-8");
-                actions.add(new LabeledIntent(
-                        context.getString(com.android.internal.R.string.map),
-                        context.getString(com.android.internal.R.string.map_desc),
-                        new Intent(Intent.ACTION_VIEW)
-                                .setData(Uri.parse(String.format("geo:0,0?q=%s", encText))),
-                        LabeledIntent.DEFAULT_REQUEST_CODE));
-            } catch (UnsupportedEncodingException e) {
-                Log.e(LOG_TAG, "Could not encode address", e);
-            }
-            return actions;
-        }
-
-        @NonNull
-        private static List<LabeledIntent> createForUrl(Context context, String text) {
-            if (Uri.parse(text).getScheme() == null) {
-                text = "http://" + text;
-            }
-            final List<LabeledIntent> actions = new ArrayList<>();
-            actions.add(new LabeledIntent(
-                    context.getString(com.android.internal.R.string.browse),
-                    context.getString(com.android.internal.R.string.browse_desc),
-                    new Intent(Intent.ACTION_VIEW, Uri.parse(text))
-                            .putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName()),
-                    LabeledIntent.DEFAULT_REQUEST_CODE));
-            return actions;
-        }
-
-        @NonNull
-        private static List<LabeledIntent> createForDatetime(
-                Context context, String type, @Nullable Instant referenceTime,
-                Instant parsedTime) {
-            if (referenceTime == null) {
-                // If no reference time was given, use now.
-                referenceTime = Instant.now();
-            }
-            List<LabeledIntent> actions = new ArrayList<>();
-            actions.add(createCalendarViewIntent(context, parsedTime));
-            final long millisUntilEvent = referenceTime.until(parsedTime, MILLIS);
-            if (millisUntilEvent > MIN_EVENT_FUTURE_MILLIS) {
-                actions.add(createCalendarCreateEventIntent(context, parsedTime, type));
-            }
-            return actions;
-        }
-
-        @NonNull
-        private static List<LabeledIntent> createForFlight(Context context, String text) {
-            final List<LabeledIntent> actions = new ArrayList<>();
-            actions.add(new LabeledIntent(
-                    context.getString(com.android.internal.R.string.view_flight),
-                    context.getString(com.android.internal.R.string.view_flight_desc),
-                    new Intent(Intent.ACTION_WEB_SEARCH)
-                            .putExtra(SearchManager.QUERY, text),
-                    text.hashCode()));
-            return actions;
-        }
-
-        @NonNull
-        private static LabeledIntent createCalendarViewIntent(Context context, Instant parsedTime) {
-            Uri.Builder builder = CalendarContract.CONTENT_URI.buildUpon();
-            builder.appendPath("time");
-            ContentUris.appendId(builder, parsedTime.toEpochMilli());
-            return new LabeledIntent(
-                    context.getString(com.android.internal.R.string.view_calendar),
-                    context.getString(com.android.internal.R.string.view_calendar_desc),
-                    new Intent(Intent.ACTION_VIEW).setData(builder.build()),
-                    LabeledIntent.DEFAULT_REQUEST_CODE);
-        }
-
-        @NonNull
-        private static LabeledIntent createCalendarCreateEventIntent(
-                Context context, Instant parsedTime, @EntityType String type) {
-            final boolean isAllDay = TextClassifier.TYPE_DATE.equals(type);
-            return new LabeledIntent(
-                    context.getString(com.android.internal.R.string.add_calendar_event),
-                    context.getString(com.android.internal.R.string.add_calendar_event_desc),
-                    new Intent(Intent.ACTION_INSERT)
-                            .setData(CalendarContract.Events.CONTENT_URI)
-                            .putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, isAllDay)
-                            .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME,
-                                    parsedTime.toEpochMilli())
-                            .putExtra(CalendarContract.EXTRA_EVENT_END_TIME,
-                                    parsedTime.toEpochMilli() + DEFAULT_EVENT_DURATION),
-                    parsedTime.hashCode());
-        }
-
-        private static void insertTranslateAction(
-                List<LabeledIntent> actions, Context context, String text) {
-            actions.add(new LabeledIntent(
-                    context.getString(com.android.internal.R.string.translate),
-                    context.getString(com.android.internal.R.string.translate_desc),
-                    new Intent(Intent.ACTION_TRANSLATE)
-                            // TODO: Probably better to introduce a "translate" scheme instead of
-                            // using EXTRA_TEXT.
-                            .putExtra(Intent.EXTRA_TEXT, text),
-                    text.hashCode()));
-        }
-
-        @NonNull
-        private static List<LabeledIntent> createForDictionary(Context context, String text) {
-            return Arrays.asList(new LabeledIntent(
-                    context.getString(com.android.internal.R.string.define),
-                    context.getString(com.android.internal.R.string.define_desc),
-                    new Intent(Intent.ACTION_DEFINE)
-                            .putExtra(Intent.EXTRA_TEXT, text),
-                    text.hashCode()));
-        }
-    }
 }
diff --git a/core/java/com/android/internal/app/procstats/ProcessState.java b/core/java/com/android/internal/app/procstats/ProcessState.java
index 4071c82..0e4897f 100644
--- a/core/java/com/android/internal/app/procstats/ProcessState.java
+++ b/core/java/com/android/internal/app/procstats/ProcessState.java
@@ -77,6 +77,7 @@
         STATE_PERSISTENT,               // ActivityManager.PROCESS_STATE_PERSISTENT
         STATE_PERSISTENT,               // ActivityManager.PROCESS_STATE_PERSISTENT_UI
         STATE_TOP,                      // ActivityManager.PROCESS_STATE_TOP
+        STATE_IMPORTANT_FOREGROUND,     // ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE_LOCATION
         STATE_IMPORTANT_FOREGROUND,     // ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
         STATE_IMPORTANT_FOREGROUND,     // ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
         STATE_IMPORTANT_FOREGROUND,     // ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND
diff --git a/core/java/com/android/internal/os/BatteryStatsImpl.java b/core/java/com/android/internal/os/BatteryStatsImpl.java
index c6afee2..650a194 100644
--- a/core/java/com/android/internal/os/BatteryStatsImpl.java
+++ b/core/java/com/android/internal/os/BatteryStatsImpl.java
@@ -9795,7 +9795,7 @@
             int uidRunningState;
             // Make special note of Foreground Services
             final boolean userAwareService =
-                    (procState == ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE);
+                    (ActivityManager.isForegroundService(procState));
             uidRunningState = BatteryStats.mapToInternalProcessState(procState);
 
             if (mProcessState == uidRunningState && userAwareService == mInForegroundService) {
diff --git a/core/java/com/android/internal/os/Zygote.java b/core/java/com/android/internal/os/Zygote.java
index 069413f..bc7cf87 100644
--- a/core/java/com/android/internal/os/Zygote.java
+++ b/core/java/com/android/internal/os/Zygote.java
@@ -132,8 +132,6 @@
      * */
     protected static FileDescriptor sBlastulaPoolEventFD;
 
-    private static final ZygoteHooks VM_HOOKS = new ZygoteHooks();
-
     /**
      * An extraArg passed when a zygote process is forking a child-zygote, specifying a name
      * in the abstract socket namespace. This socket name is what the new child zygote
@@ -246,7 +244,7 @@
             int[][] rlimits, int mountExternal, String seInfo, String niceName, int[] fdsToClose,
             int[] fdsToIgnore, boolean startChildZygote, String instructionSet, String appDataDir,
             String packageName, String[] packagesForUID, String[] visibleVolIDs) {
-        VM_HOOKS.preFork();
+        ZygoteHooks.preFork();
         // Resets nice priority for zygote process.
         resetNicePriority();
         int pid = nativeForkAndSpecialize(
@@ -260,7 +258,7 @@
             // Note that this event ends at the end of handleChildProc,
             Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "PostFork");
         }
-        VM_HOOKS.postForkCommon();
+        ZygoteHooks.postForkCommon();
         return pid;
     }
 
@@ -311,7 +309,7 @@
          *
          * TODO (chriswailes): Look into moving this to immediately after the fork.
          */
-        VM_HOOKS.postForkCommon();
+        ZygoteHooks.postForkCommon();
     }
 
     private static native void nativeSpecializeBlastula(int uid, int gid, int[] gids,
@@ -349,7 +347,7 @@
      */
     public static int forkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
             int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
-        VM_HOOKS.preFork();
+        ZygoteHooks.preFork();
         // Resets nice priority for zygote process.
         resetNicePriority();
         int pid = nativeForkSystemServer(
@@ -359,7 +357,7 @@
         if (pid == 0) {
             Trace.setTracingEnabled(true, runtimeFlags);
         }
-        VM_HOOKS.postForkCommon();
+        ZygoteHooks.postForkCommon();
         return pid;
     }
 
@@ -434,7 +432,7 @@
 
             // Disable some VM functionality and reset some system values
             // before forking.
-            VM_HOOKS.preFork();
+            ZygoteHooks.preFork();
             resetNicePriority();
 
             while (blastulaPoolCount++ < sBlastulaPoolMax) {
@@ -447,7 +445,7 @@
 
             // Re-enable runtime services for the Zygote.  Blastula services
             // are re-enabled in specializeBlastula.
-            VM_HOOKS.postForkCommon();
+            ZygoteHooks.postForkCommon();
 
             Log.i("zygote", "Filled the blastula pool. New blastulas: " + numBlastulasToSpawn);
         }
@@ -864,12 +862,12 @@
 
     private static void callPostForkSystemServerHooks() {
         // SystemServer specific post fork hooks run before child post fork hooks.
-        VM_HOOKS.postForkSystemServer();
+        ZygoteHooks.postForkSystemServer();
     }
 
     private static void callPostForkChildHooks(int runtimeFlags, boolean isSystemServer,
             boolean isZygote, String instructionSet) {
-        VM_HOOKS.postForkChild(runtimeFlags, isSystemServer, isZygote, instructionSet);
+        ZygoteHooks.postForkChild(runtimeFlags, isSystemServer, isZygote, instructionSet);
     }
 
     /**
diff --git a/core/java/com/android/internal/statusbar/IStatusBarService.aidl b/core/java/com/android/internal/statusbar/IStatusBarService.aidl
index d61f10e..d355745 100644
--- a/core/java/com/android/internal/statusbar/IStatusBarService.aidl
+++ b/core/java/com/android/internal/statusbar/IStatusBarService.aidl
@@ -69,7 +69,7 @@
     void onNotificationDirectReplied(String key);
     void onNotificationSmartSuggestionsAdded(String key, int smartReplyCount, int smartActionCount,
             boolean generatedByAsssistant);
-    void onNotificationSmartReplySent(in String key, in int replyIndex, in CharSequence reply, boolean generatedByAssistant);
+    void onNotificationSmartReplySent(in String key, in int replyIndex, in CharSequence reply, boolean generatedByAssistant, in int notificationLocation);
     void onNotificationSettingsViewed(String key);
     void setSystemUiVisibility(int displayId, int vis, int mask, String cause);
 
diff --git a/core/proto/android/providers/settings/global.proto b/core/proto/android/providers/settings/global.proto
index 66cd109..e0eaf14 100644
--- a/core/proto/android/providers/settings/global.proto
+++ b/core/proto/android/providers/settings/global.proto
@@ -230,12 +230,7 @@
     }
     optional Connectivity connectivity = 32;
 
-    message ContentCapture {
-      option (android.msg_privacy).dest = DEST_EXPLICIT;
-
-      optional SettingProto service_explicitly_enabled = 1 [ (android.privacy).dest = DEST_AUTOMATIC ];
-    }
-    optional ContentCapture content_capture = 145;
+    reserved 145; // Used to be ContentCapture, which moved to DeviceConfig
 
     optional SettingProto contact_metadata_sync_enabled = 33 [ (android.privacy).dest = DEST_AUTOMATIC ];
     optional SettingProto contacts_database_wal_enabled = 34 [ (android.privacy).dest = DEST_AUTOMATIC ];
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index 7184c7a..1a402c0 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -115,6 +115,7 @@
     <protected-broadcast android:name="android.app.action.BUGREPORT_FAILED" />
     <protected-broadcast android:name="android.app.action.BUGREPORT_SHARE" />
     <protected-broadcast android:name="android.app.action.SHOW_DEVICE_MONITORING_DIALOG" />
+    <protected-broadcast android:name="android.intent.action.PENDING_INCIDENT_REPORTS_CHANGED" />
 
     <protected-broadcast android:name="android.appwidget.action.APPWIDGET_UPDATE_OPTIONS" />
     <protected-broadcast android:name="android.appwidget.action.APPWIDGET_DELETED" />
@@ -2798,6 +2799,20 @@
     <permission android:name="android.permission.SIGNAL_PERSISTENT_PROCESSES"
         android:protectionLevel="signature|privileged|development" />
 
+    <!-- @hide @SystemApi @TestApi
+         Allow an application to approve incident and bug reports to be
+         shared off-device.  There can be only one application installed on the
+         device with this permission, and since this is a privileged permission, it
+         must be in priv-app.
+        <p>Not for use by third-party applications. -->
+    <permission android:name="android.permission.APPROVE_INCIDENT_REPORTS"
+        android:protectionLevel="signature|incidentReportApprover" />
+
+    <!-- @hide Allow an application to approve an incident or bug report approval from
+        the system. -->
+    <permission android:name="android.permission.REQUEST_INCIDENT_REPORT_APPROVAL"
+        android:protectionLevel="signature|privileged" />
+
     <!-- ==================================== -->
     <!-- Private permissions                  -->
     <!-- ==================================== -->
diff --git a/core/res/res/values/attrs_manifest.xml b/core/res/res/values/attrs_manifest.xml
index de6468d..0abe456 100644
--- a/core/res/res/values/attrs_manifest.xml
+++ b/core/res/res/values/attrs_manifest.xml
@@ -277,6 +277,9 @@
         <!-- Additional flag from base permission type: this permission automatically
             granted to device configurator -->
         <flag name="configurator" value="0x80000" />
+        <!-- Additional flag from base permission type: this permission designates the app
+            that will approve the sharing of incident reports. -->
+        <flag name="incidentReportApprover" value="0x100000" />
     </attr>
 
     <!-- Flags indicating more context for a permission group. -->
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index 1db8135..67b0652 100644
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -3493,6 +3493,13 @@
     -->
     <string name="config_defaultAttentionService" translatable="false"></string>
 
+    <!-- The package name for the incident report approver app.
+        This app is usually PermissionController or an app that replaces it.  When
+        a bugreport or incident report with EXPLICT-level sharing flags is going to be
+        shared, this app will be sent the PENDING_INCIDENT_REPORTS_CHANGED broadcast.
+    -->
+    <string name="config_incidentReportApproverPackage" translatable="false">com.android.permissioncontroller</string>
+
     <!-- The package name for the system's content capture service.
          This service must be trusted, as it can be activated without explicit consent of the user.
          If no service with the specified name exists on the device, content capture will be
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index aefa9df..09d6c26 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -3515,6 +3515,7 @@
   <java-symbol type="layout" name="car_user_switching_dialog" />
   <java-symbol type="id" name="user_loading_avatar" />
   <java-symbol type="id" name="user_loading" />
+  <java-symbol type="style" name="Theme.DeviceDefault.Light.Dialog.Alert.UserSwitchingDialog" />
 
   <java-symbol type="string" name="battery_saver_description_with_learn_more" />
 
@@ -3580,4 +3581,6 @@
   <!-- For Attention Service -->
   <java-symbol type="integer" name="config_attentionMaximumExtension" />
   <java-symbol type="integer" name="config_attentionApiTimeout" />
+
+  <java-symbol type="string" name="config_incidentReportApproverPackage" />
 </resources>
diff --git a/core/tests/coretests/src/android/provider/SettingsBackupTest.java b/core/tests/coretests/src/android/provider/SettingsBackupTest.java
index ca2e3ed..0b5bde7 100644
--- a/core/tests/coretests/src/android/provider/SettingsBackupTest.java
+++ b/core/tests/coretests/src/android/provider/SettingsBackupTest.java
@@ -192,7 +192,6 @@
                     Settings.Global.CONNECTIVITY_METRICS_BUFFER_SIZE,
                     Settings.Global.CONNECTIVITY_SAMPLING_INTERVAL_IN_SECONDS,
                     Settings.Global.CONTACT_METADATA_SYNC_ENABLED,
-                    Settings.Global.CONTENT_CAPTURE_SERVICE_EXPLICITLY_ENABLED,
                     Settings.Global.CONVERSATION_ACTIONS_UPDATE_CONTENT_URL,
                     Settings.Global.CONVERSATION_ACTIONS_UPDATE_METADATA_URL,
                     Settings.Global.CONTACTS_DATABASE_WAL_ENABLED,
@@ -609,6 +608,7 @@
                  Settings.Secure.CMAS_ADDITIONAL_BROADCAST_PKG,
                  Settings.Secure.COMPLETED_CATEGORY_PREFIX,
                  Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS,
+                 Settings.Secure.CONTENT_CAPTURE_ENABLED,
                  Settings.Secure.DEFAULT_INPUT_METHOD,
                  Settings.Secure.DEVICE_PAIRED,
                  Settings.Secure.DIALER_DEFAULT_APPLICATION,
diff --git a/core/tests/coretests/src/android/view/textclassifier/IntentFactoryTest.java b/core/tests/coretests/src/android/view/textclassifier/IntentFactoryTest.java
deleted file mode 100644
index 3fc8e4c..0000000
--- a/core/tests/coretests/src/android/view/textclassifier/IntentFactoryTest.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 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.view.textclassifier;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import android.content.Intent;
-
-import androidx.test.InstrumentationRegistry;
-import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
-
-import com.google.android.textclassifier.AnnotatorModel;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.List;
-
-@SmallTest
-@RunWith(AndroidJUnit4.class)
-public class IntentFactoryTest {
-
-    private static final String TEXT = "text";
-
-    @Test
-    public void create_typeDictionary() {
-        AnnotatorModel.ClassificationResult classificationResult =
-                new AnnotatorModel.ClassificationResult(
-                        TextClassifier.TYPE_DICTIONARY,
-                        1.0f,
-                        null,
-                        null);
-
-        List<TextClassifierImpl.LabeledIntent> intents = TextClassifierImpl.IntentFactory.create(
-                InstrumentationRegistry.getContext(),
-                TEXT,
-                false,
-                null,
-                classificationResult);
-
-        assertThat(intents).hasSize(1);
-        TextClassifierImpl.LabeledIntent labeledIntent = intents.get(0);
-        Intent intent = labeledIntent.getIntent();
-        assertThat(intent.getAction()).isEqualTo(Intent.ACTION_DEFINE);
-        assertThat(intent.getStringExtra(Intent.EXTRA_TEXT)).isEqualTo(TEXT);
-        assertThat(
-                intent.getBooleanExtra(TextClassifier.EXTRA_FROM_TEXT_CLASSIFIER, false)).isTrue();
-    }
-}
diff --git a/core/tests/coretests/src/android/view/textclassifier/LegacyIntentFactoryTest.java b/core/tests/coretests/src/android/view/textclassifier/LegacyIntentFactoryTest.java
new file mode 100644
index 0000000..73d3eec
--- /dev/null
+++ b/core/tests/coretests/src/android/view/textclassifier/LegacyIntentFactoryTest.java
@@ -0,0 +1,105 @@
+/*
+ * Copyright (C) 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.view.textclassifier;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.content.Intent;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
+import com.google.android.textclassifier.AnnotatorModel;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.List;
+
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class LegacyIntentFactoryTest {
+
+    private static final String TEXT = "text";
+
+    private LegacyIntentFactory mLegacyIntentFactory;
+
+    @Before
+    public void setup() {
+        mLegacyIntentFactory = new LegacyIntentFactory();
+    }
+
+    @Test
+    public void create_typeDictionary() {
+        AnnotatorModel.ClassificationResult classificationResult =
+                new AnnotatorModel.ClassificationResult(
+                        TextClassifier.TYPE_DICTIONARY,
+                        1.0f,
+                        null,
+                        null,
+                        null,
+                        null,
+                        null,
+                        null,
+                        null,
+                        null);
+
+        List<TextClassifierImpl.LabeledIntent> intents = mLegacyIntentFactory.create(
+                InstrumentationRegistry.getContext(),
+                TEXT,
+                /* foreignText */ false,
+                null,
+                classificationResult);
+
+        assertThat(intents).hasSize(1);
+        TextClassifierImpl.LabeledIntent labeledIntent = intents.get(0);
+        Intent intent = labeledIntent.getIntent();
+        assertThat(intent.getAction()).isEqualTo(Intent.ACTION_DEFINE);
+        assertThat(intent.getStringExtra(Intent.EXTRA_TEXT)).isEqualTo(TEXT);
+        assertThat(
+                intent.getBooleanExtra(TextClassifier.EXTRA_FROM_TEXT_CLASSIFIER, false)).isTrue();
+    }
+
+    @Test
+    public void create_translateAndDictionary() {
+        AnnotatorModel.ClassificationResult classificationResult =
+                new AnnotatorModel.ClassificationResult(
+                        TextClassifier.TYPE_DICTIONARY,
+                        1.0f,
+                        null,
+                        null,
+                        null,
+                        null,
+                        null,
+                        null,
+                        null,
+                        null);
+
+        List<TextClassifierImpl.LabeledIntent> intents = mLegacyIntentFactory.create(
+                InstrumentationRegistry.getContext(),
+                TEXT,
+                /* foreignText */ true,
+                null,
+                classificationResult);
+
+        assertThat(intents).hasSize(2);
+        assertThat(intents.get(0).getIntent().getAction()).isEqualTo(Intent.ACTION_DEFINE);
+        assertThat(intents.get(1).getIntent().getAction()).isEqualTo(Intent.ACTION_TRANSLATE);
+    }
+}
diff --git a/core/tests/coretests/src/android/view/textclassifier/TemplateIntentFactoryTest.java b/core/tests/coretests/src/android/view/textclassifier/TemplateIntentFactoryTest.java
new file mode 100644
index 0000000..0fcf359
--- /dev/null
+++ b/core/tests/coretests/src/android/view/textclassifier/TemplateIntentFactoryTest.java
@@ -0,0 +1,218 @@
+/*
+ * 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.
+ */
+
+package android.view.textclassifier;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.content.Intent;
+import android.net.Uri;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
+import com.google.android.textclassifier.AnnotatorModel;
+import com.google.android.textclassifier.NamedVariant;
+import com.google.android.textclassifier.RemoteActionTemplate;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+import java.util.List;
+
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class TemplateIntentFactoryTest {
+
+    private static final String TEXT = "text";
+    private static final String TITLE = "Map";
+    private static final String DESCRIPTION = "Check the map";
+    private static final String ACTION = Intent.ACTION_VIEW;
+    private static final String DATA = Uri.parse("http://www.android.com").toString();
+    private static final String TYPE = "text/html";
+    private static final Integer FLAG = Intent.FLAG_ACTIVITY_NEW_TASK;
+    private static final String[] CATEGORY =
+            new String[]{Intent.CATEGORY_DEFAULT, Intent.CATEGORY_APP_BROWSER};
+    private static final String PACKAGE_NAME = "pkg.name";
+    private static final String KEY_ONE = "key1";
+    private static final String VALUE_ONE = "value1";
+    private static final String KEY_TWO = "key2";
+    private static final int VALUE_TWO = 42;
+
+    private static final NamedVariant[] NAMED_VARIANTS = new NamedVariant[]{
+            new NamedVariant(KEY_ONE, VALUE_ONE),
+            new NamedVariant(KEY_TWO, VALUE_TWO)
+    };
+    private static final Integer REQUEST_CODE = 10;
+
+    @Mock
+    private IntentFactory mFallback;
+    private TemplateIntentFactory mTemplateIntentFactory;
+
+    @Before
+    public void setup() {
+        MockitoAnnotations.initMocks(this);
+        mTemplateIntentFactory = new TemplateIntentFactory(mFallback);
+    }
+
+    @Test
+    public void create_full() {
+        RemoteActionTemplate remoteActionTemplate = new RemoteActionTemplate(
+                TITLE,
+                DESCRIPTION,
+                ACTION,
+                DATA,
+                TYPE,
+                FLAG,
+                CATEGORY,
+                /* packageName */ null,
+                NAMED_VARIANTS,
+                REQUEST_CODE
+        );
+
+        AnnotatorModel.ClassificationResult classificationResult =
+                new AnnotatorModel.ClassificationResult(
+                        TextClassifier.TYPE_ADDRESS,
+                        1.0f,
+                        null,
+                        null,
+                        null,
+                        null,
+                        null,
+                        null,
+                        null,
+                        new RemoteActionTemplate[]{remoteActionTemplate});
+
+        List<TextClassifierImpl.LabeledIntent> intents = mTemplateIntentFactory.create(
+                InstrumentationRegistry.getContext(),
+                TEXT,
+                false,
+                null,
+                classificationResult);
+
+        assertThat(intents).hasSize(1);
+        TextClassifierImpl.LabeledIntent labeledIntent = intents.get(0);
+        assertThat(labeledIntent.getTitle()).isEqualTo(TITLE);
+        assertThat(labeledIntent.getDescription()).isEqualTo(DESCRIPTION);
+        assertThat(labeledIntent.getRequestCode()).isEqualTo(REQUEST_CODE);
+        Intent intent = labeledIntent.getIntent();
+        assertThat(intent.getAction()).isEqualTo(ACTION);
+        assertThat(intent.getData().toString()).isEqualTo(DATA);
+        assertThat(intent.getType()).isEqualTo(TYPE);
+        assertThat(intent.getFlags()).isEqualTo(FLAG);
+        assertThat(intent.getCategories()).containsExactly((Object[]) CATEGORY);
+        assertThat(intent.getPackage()).isNull();
+        assertThat(
+                intent.getStringExtra(KEY_ONE)).isEqualTo(VALUE_ONE);
+        assertThat(intent.getIntExtra(KEY_TWO, 0)).isEqualTo(VALUE_TWO);
+        assertThat(
+                intent.getBooleanExtra(TextClassifier.EXTRA_FROM_TEXT_CLASSIFIER, false)).isTrue();
+    }
+
+    @Test
+    public void create_pacakgeIsNotNull() {
+        RemoteActionTemplate remoteActionTemplate = new RemoteActionTemplate(
+                TITLE,
+                DESCRIPTION,
+                ACTION,
+                DATA,
+                TYPE,
+                FLAG,
+                CATEGORY,
+                PACKAGE_NAME,
+                NAMED_VARIANTS,
+                REQUEST_CODE
+        );
+
+        AnnotatorModel.ClassificationResult classificationResult =
+                new AnnotatorModel.ClassificationResult(
+                        TextClassifier.TYPE_ADDRESS,
+                        1.0f,
+                        null,
+                        null,
+                        null,
+                        null,
+                        null,
+                        null,
+                        null,
+                        new RemoteActionTemplate[]{remoteActionTemplate});
+
+        List<TextClassifierImpl.LabeledIntent> intents = mTemplateIntentFactory.create(
+                InstrumentationRegistry.getContext(),
+                TEXT,
+                false,
+                null,
+                classificationResult);
+
+        assertThat(intents).hasSize(0);
+    }
+
+    @Test
+    public void create_minimal() {
+        RemoteActionTemplate remoteActionTemplate = new RemoteActionTemplate(
+                null,
+                null,
+                null,
+                null,
+                null,
+                null,
+                null,
+                null,
+                null,
+                null
+        );
+
+        AnnotatorModel.ClassificationResult classificationResult =
+                new AnnotatorModel.ClassificationResult(
+                        TextClassifier.TYPE_ADDRESS,
+                        1.0f,
+                        null,
+                        null,
+                        null,
+                        null,
+                        null,
+                        null,
+                        null,
+                        new RemoteActionTemplate[]{remoteActionTemplate});
+
+        List<TextClassifierImpl.LabeledIntent> intents = mTemplateIntentFactory.create(
+                InstrumentationRegistry.getContext(),
+                TEXT,
+                false,
+                null,
+                classificationResult);
+
+        assertThat(intents).hasSize(1);
+        TextClassifierImpl.LabeledIntent labeledIntent = intents.get(0);
+        assertThat(labeledIntent.getTitle()).isNull();
+        assertThat(labeledIntent.getDescription()).isNull();
+        assertThat(labeledIntent.getRequestCode()).isEqualTo(
+                TextClassifierImpl.LabeledIntent.DEFAULT_REQUEST_CODE);
+        Intent intent = labeledIntent.getIntent();
+        assertThat(intent.getAction()).isNull();
+        assertThat(intent.getData()).isNull();
+        assertThat(intent.getType()).isNull();
+        assertThat(intent.getFlags()).isEqualTo(0);
+        assertThat(intent.getCategories()).isNull();
+        assertThat(intent.getPackage()).isNull();
+        assertThat(
+                intent.getBooleanExtra(TextClassifier.EXTRA_FROM_TEXT_CLASSIFIER, false)).isTrue();
+    }
+}
diff --git a/data/etc/platform.xml b/data/etc/platform.xml
index fb43e41..44d71e2 100644
--- a/data/etc/platform.xml
+++ b/data/etc/platform.xml
@@ -169,6 +169,7 @@
     <assign-permission name="android.permission.DUMP" uid="incidentd" />
     <assign-permission name="android.permission.PACKAGE_USAGE_STATS" uid="incidentd" />
     <assign-permission name="android.permission.INTERACT_ACROSS_USERS" uid="incidentd" />
+    <assign-permission name="android.permission.REQUEST_INCIDENT_REPORT_APPROVAL" uid="incidentd" />
 
     <assign-permission name="android.permission.ACCESS_LOWPAN_STATE" uid="lowpan" />
     <assign-permission name="android.permission.MANAGE_LOWPAN_INTERFACES" uid="lowpan" />
diff --git a/data/etc/privapp-permissions-platform.xml b/data/etc/privapp-permissions-platform.xml
index 1684138..a47ab87 100644
--- a/data/etc/privapp-permissions-platform.xml
+++ b/data/etc/privapp-permissions-platform.xml
@@ -141,6 +141,8 @@
         <permission name="android.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS"/>
         <permission name="android.permission.GET_APP_OPS_STATS"/>
         <permission name="android.permission.UPDATE_APP_OPS_STATS"/>
+        <permission name="android.permission.REQUEST_INCIDENT_REPORT_APPROVAL"/>
+        <permission name="android.permission.APPROVE_INCIDENT_REPORTS"/>
     </privapp-permissions>
 
     <privapp-permissions package="com.android.phone">
@@ -327,6 +329,7 @@
         <permission name="android.permission.USE_RESERVED_DISK"/>
         <permission name="android.permission.WRITE_MEDIA_STORAGE"/>
         <permission name="android.permission.WRITE_SECURE_SETTINGS"/>
+        <permission name="android.permission.REQUEST_INCIDENT_REPORT_APPROVAL"/>
     </privapp-permissions>
 
     <privapp-permissions package="com.android.statementservice">
diff --git a/data/fonts/fonts.xml b/data/fonts/fonts.xml
index 21531ab..626bbf00 100644
--- a/data/fonts/fonts.xml
+++ b/data/fonts/fonts.xml
@@ -65,6 +65,7 @@
         <font weight="400" style="italic">NotoSerif-Italic.ttf</font>
         <font weight="700" style="italic">NotoSerif-BoldItalic.ttf</font>
     </family>
+    <alias name="serif-bold" to="serif" weight="700" />
     <alias name="times" to="serif" />
     <alias name="times new roman" to="serif" />
     <alias name="palatino" to="serif" />
diff --git a/libs/hwui/SkiaCanvas.cpp b/libs/hwui/SkiaCanvas.cpp
index 54a91f4..f328a53 100644
--- a/libs/hwui/SkiaCanvas.cpp
+++ b/libs/hwui/SkiaCanvas.cpp
@@ -694,11 +694,8 @@
         paintCopy.setStyle(SkPaint::kFill_Style);
     }
 
-    SkRect bounds =
-            SkRect::MakeLTRB(boundsLeft + x, boundsTop + y, boundsRight + x, boundsBottom + y);
-
     SkTextBlobBuilder builder;
-    const SkTextBlobBuilder::RunBuffer& buffer = builder.allocRunPos(font, count, &bounds);
+    const SkTextBlobBuilder::RunBuffer& buffer = builder.allocRunPos(font, count);
     glyphFunc(buffer.glyphs, buffer.pos);
 
     sk_sp<SkTextBlob> textBlob(builder.make());
diff --git a/media/jni/Android.bp b/media/jni/Android.bp
index 0fb4d2a..f1bb13d 100644
--- a/media/jni/Android.bp
+++ b/media/jni/Android.bp
@@ -116,7 +116,7 @@
         "libhidlbase",
         "libhidlmemory",
         "libhidltransport",
-        "libhwbinder",
+        "libhwbinder_noltopgo",
         "libbinderthreadstate",
 
         // MediaPlayer2 implementation
diff --git a/packages/SystemUI/res/drawable/stat_sys_signal_null.xml b/packages/CarSystemUI/res/drawable/stat_sys_signal_null.xml
similarity index 100%
rename from packages/SystemUI/res/drawable/stat_sys_signal_null.xml
rename to packages/CarSystemUI/res/drawable/stat_sys_signal_null.xml
diff --git a/packages/CarSystemUI/res/layout/car_status_bar_header.xml b/packages/CarSystemUI/res/layout/car_status_bar_header.xml
index e446072..81c7108 100644
--- a/packages/CarSystemUI/res/layout/car_status_bar_header.xml
+++ b/packages/CarSystemUI/res/layout/car_status_bar_header.xml
@@ -22,6 +22,7 @@
     android:layout_height="@dimen/status_bar_height">
 
     <include layout="@layout/car_top_navigation_bar"
+        android:id="@+id/qs_car_top_bar"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:layout_weight="1"
diff --git a/packages/CarSystemUI/res/layout/notification_center_activity.xml b/packages/CarSystemUI/res/layout/notification_center_activity.xml
new file mode 100644
index 0000000..7c83303
--- /dev/null
+++ b/packages/CarSystemUI/res/layout/notification_center_activity.xml
@@ -0,0 +1,50 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+    Copyright (C) 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.
+-->
+<com.android.car.notification.CarNotificationView
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:app="http://schemas.android.com/apk/res-auto"
+    android:id="@+id/notification_view"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent">
+
+    <View
+         android:id="@+id/glass_pane"
+         android:layout_width="match_parent"
+         android:layout_height="match_parent"
+         app:layout_constraintTop_toTopOf="parent"
+         app:layout_constraintBottom_toBottomOf="parent"
+         app:layout_constraintStart_toStartOf="parent"
+         app:layout_constraintEnd_toEndOf="parent"
+         android:translationZ="2dp"
+        />
+
+    <androidx.car.widget.PagedListView
+        android:id="@+id/notifications"
+        android:layout_width="0dp"
+        android:layout_height="0dp"
+        android:orientation="vertical"
+        android:theme="@style/PagedListTheme"
+        app:gutter="none"
+        app:itemSpacing="@dimen/item_spacing"
+        app:layout_constraintTop_toTopOf="parent"
+        app:layout_constraintBottom_toBottomOf="parent"
+        app:layout_constraintStart_toStartOf="parent"
+        app:layout_constraintEnd_toEndOf="parent"
+        app:scrollBarEnabled="false"
+        app:showPagedListViewDivider="false"/>
+
+</com.android.car.notification.CarNotificationView>
diff --git a/packages/CarSystemUI/res/values/colors.xml b/packages/CarSystemUI/res/values/colors.xml
index c510ab6..1e38f26 100644
--- a/packages/CarSystemUI/res/values/colors.xml
+++ b/packages/CarSystemUI/res/values/colors.xml
@@ -37,8 +37,8 @@
     <color name="status_bar_background_color">#33000000</color>
     <drawable name="system_bar_background">@color/status_bar_background_color</drawable>
 
-    <!-- The scrim color for the background of the notifications shade. -->
-    <color name="scrim_behind_color">#172026</color>
+    <!-- The background color of the notification shade -->
+    <color name="notification_shade_background_color">#99000000</color>
 
     <!-- The color of the dividing line between grouped notifications. -->
     <color name="notification_divider_color">@*android:color/notification_action_list</color>
diff --git a/packages/CarSystemUI/res/values/config.xml b/packages/CarSystemUI/res/values/config.xml
index 2e05c38..c9f9dea 100644
--- a/packages/CarSystemUI/res/values/config.xml
+++ b/packages/CarSystemUI/res/values/config.xml
@@ -34,6 +34,7 @@
     <string-array name="config_systemUIServiceComponents" translatable="false">
         <item>com.android.systemui.Dependency$DependencyCreator</item>
         <item>com.android.systemui.util.NotificationChannels</item>
+        <item>com.android.systemui.notifications.NotificationsUI</item>
         <item>com.android.systemui.statusbar.CommandQueue$CommandQueueStart</item>
         <item>com.android.systemui.keyguard.KeyguardViewMediator</item>
         <item>com.android.systemui.recents.Recents</item>
@@ -52,6 +53,5 @@
         <item>com.android.systemui.globalactions.GlobalActionsComponent</item>
         <item>com.android.systemui.ScreenDecorations</item>
         <item>com.android.systemui.SliceBroadcastRelayHandler</item>
-        <item>com.android.systemui.notifications.NotificationsUI</item>
     </string-array>
 </resources>
diff --git a/packages/CarSystemUI/res/values/integers_car.xml b/packages/CarSystemUI/res/values/integers_car.xml
index 472c957..777283d 100644
--- a/packages/CarSystemUI/res/values/integers_car.xml
+++ b/packages/CarSystemUI/res/values/integers_car.xml
@@ -24,4 +24,12 @@
     <!-- If the number is negative, the feature is disabled.
          If it's zero, we switch to guest immediately as we start driving. -->
     <integer name="driving_on_keyguard_timeout_ms">30000</integer>
+
+    <!--Percentage of the screen height, from the bottom, that a notification panel being
+    partially closed at will result in it remaining open if released-->
+    <integer name="notification_settle_open_percentage">20</integer>
+    <!--Percentage of the screen height, from the bottom, that a notification panel being peeked
+    at will result in remaining closed the panel if released-->
+    <integer name="notification_settle_close_percentage">80</integer>
+
 </resources>
diff --git a/packages/CarSystemUI/res/values/themes.xml b/packages/CarSystemUI/res/values/themes.xml
index 8a5961e..8d1a4d7 100644
--- a/packages/CarSystemUI/res/values/themes.xml
+++ b/packages/CarSystemUI/res/values/themes.xml
@@ -21,4 +21,7 @@
     <!--This Theme contains attributes required for components from the car support lib -->
     <style name="PagedListTheme" parent="Theme.CarSupportWrapper.NoActionBar">
     </style>
+
+    <style name="Theme.Notification" parent="Theme.DeviceDefault.NoActionBar.Notification">
+    </style>
 </resources>
diff --git a/packages/CarSystemUI/src/com/android/systemui/notifications/NotificationsUI.java b/packages/CarSystemUI/src/com/android/systemui/notifications/NotificationsUI.java
index 5e63b90..ca343d1 100644
--- a/packages/CarSystemUI/src/com/android/systemui/notifications/NotificationsUI.java
+++ b/packages/CarSystemUI/src/com/android/systemui/notifications/NotificationsUI.java
@@ -16,6 +16,10 @@
 
 package com.android.systemui.notifications;
 
+import android.animation.Animator;
+import android.animation.AnimatorListenerAdapter;
+import android.animation.ValueAnimator;
+import android.annotation.SuppressLint;
 import android.app.ActivityManager;
 import android.car.Car;
 import android.car.CarNotConnectedException;
@@ -23,29 +27,48 @@
 import android.content.ComponentName;
 import android.content.Context;
 import android.content.ServiceConnection;
+import android.content.res.Configuration;
 import android.graphics.PixelFormat;
 import android.os.IBinder;
 import android.os.ServiceManager;
 import android.util.Log;
+import android.view.ContextThemeWrapper;
+import android.view.GestureDetector;
+import android.view.MotionEvent;
 import android.view.View;
 import android.view.ViewGroup;
+import android.view.ViewTreeObserver;
 import android.view.WindowManager;
 
+import androidx.annotation.NonNull;
+import androidx.recyclerview.widget.RecyclerView;
+
 import com.android.car.notification.CarNotificationListener;
+import com.android.car.notification.CarNotificationView;
 import com.android.car.notification.CarUxRestrictionManagerWrapper;
 import com.android.car.notification.NotificationClickHandlerFactory;
 import com.android.car.notification.NotificationViewController;
 import com.android.car.notification.PreprocessingManager;
 import com.android.internal.statusbar.IStatusBarService;
+import com.android.systemui.Dependency;
 import com.android.systemui.R;
 import com.android.systemui.SystemUI;
+import com.android.systemui.statusbar.FlingAnimationUtils;
+import com.android.systemui.statusbar.policy.ConfigurationController;
 
 /**
  * Standalone SystemUI for displaying Notifications that have been designed to be used in the car
  */
-public class NotificationsUI extends SystemUI {
+public class NotificationsUI extends SystemUI
+        implements ConfigurationController.ConfigurationListener {
 
     private static final String TAG = "NotificationsUI";
+    // used to calculate how fast to open or close the window
+    private static final float DEFAULT_FLING_VELOCITY = 0;
+    // max time a fling animation takes
+    private static final float FLING_ANIMATION_MAX_TIME = 0.5f;
+    // acceleration rate for the fling animation
+    private static final float FLING_SPEED_UP_FACTOR = 0.6f;
     private CarNotificationListener mCarNotificationListener;
     private CarUxRestrictionsManager mCarUxRestrictionsManager;
     private NotificationClickHandlerFactory mClickHandlerFactory;
@@ -53,8 +76,20 @@
     private ViewGroup mCarNotificationWindow;
     private NotificationViewController mNotificationViewController;
     private boolean mIsShowing;
+    private boolean mIsTracking;
+    private boolean mNotificationListAtBottom;
+    private boolean mNotificationListAtBottomAtTimeOfTouch;
     private CarUxRestrictionManagerWrapper mCarUxRestrictionManagerWrapper =
             new CarUxRestrictionManagerWrapper();
+    // Used in the Notification panel touch listener
+    private GestureDetector mGestureDetector;
+    // Used in scrollable content of the notifications
+    private GestureDetector mScrollUpDetector;
+    private View mContent;
+    private View.OnTouchListener mOnTouchListener;
+    private FlingAnimationUtils mFlingAnimationUtils;
+    private static int sSettleOpenPercentage;
+    private static int sSettleClosePercentage;
 
     /**
      * Inits the window that hosts the notifications and establishes the connections
@@ -62,32 +97,41 @@
      */
     @Override
     public void start() {
+        sSettleOpenPercentage = mContext.getResources().getInteger(
+                R.integer.notification_settle_open_percentage);
+        sSettleClosePercentage = mContext.getResources().getInteger(
+                R.integer.notification_settle_close_percentage);
         WindowManager windowManager =
                 (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
+        mFlingAnimationUtils = new FlingAnimationUtils(mContext,
+                FLING_ANIMATION_MAX_TIME, FLING_SPEED_UP_FACTOR);
         mCarNotificationListener = new CarNotificationListener();
+        // create a notification click handler that closes the notification ui if the an activity
+        // is launched successfully
         mClickHandlerFactory = new NotificationClickHandlerFactory(
                 IStatusBarService.Stub.asInterface(
                         ServiceManager.getService(Context.STATUS_BAR_SERVICE)),
                 launchResult -> {
                     if (launchResult == ActivityManager.START_TASK_TO_FRONT
                             || launchResult == ActivityManager.START_SUCCESS) {
-                        closeCarNotifications();
+                        closeCarNotifications(DEFAULT_FLING_VELOCITY);
                     }
                 });
         mCarNotificationListener.registerAsSystemService(mContext, mCarUxRestrictionManagerWrapper,
                 mClickHandlerFactory);
         mCar = Car.createCar(mContext, mCarConnectionListener);
         mCar.connect();
-
-
-        mCarNotificationWindow = (ViewGroup) View.inflate(mContext,
+        NotificationGestureListener gestureListener = new NotificationGestureListener();
+        mGestureDetector = new GestureDetector(mContext, gestureListener);
+        mScrollUpDetector = new GestureDetector(mContext, new ScrollUpDetector());
+        mOnTouchListener = new NotificationPanelTouchListener();
+        mCarNotificationWindow = (ViewGroup) View.inflate(new ContextThemeWrapper(mContext,
+                        R.style.Theme_Notification),
                 R.layout.navigation_bar_window, null);
-        View.inflate(mContext,
-                com.android.car.notification.R.layout.notification_center_activity,
-                mCarNotificationWindow);
-        mCarNotificationWindow.findViewById(
-                com.android.car.notification.R.id.exit_button_container)
-                .setOnClickListener(v -> toggleShowingCarNotifications());
+        mCarNotificationWindow
+                .setBackgroundColor(mContext.getColor(R.color.notification_shade_background_color));
+
+        inflateNotificationContent();
 
         WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(
                 ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT,
@@ -101,15 +145,222 @@
         // start in the hidden state
         mCarNotificationWindow.setVisibility(View.GONE);
         windowManager.addView(mCarNotificationWindow, layoutParams);
+
+        // Add this object to the SystemUI component registry such that the status bar
+        // can get a reference to it.
+        putComponent(NotificationsUI.class, this);
+        Dependency.get(ConfigurationController.class).addCallback(this);
+    }
+
+    @SuppressLint("ClickableViewAccessibility")
+    private void inflateNotificationContent() {
+        if (mNotificationViewController != null) {
+            mNotificationViewController.disable();
+        }
+        mCarNotificationWindow.removeAllViews();
+
+        mContent = View.inflate(new ContextThemeWrapper(mContext,
+                        com.android.car.notification.R.style.Theme_Notification),
+                R.layout.notification_center_activity,
+                mCarNotificationWindow);
+        // set the click handler such that we can dismiss the UI when a notification is clicked
+        CarNotificationView noteView = mCarNotificationWindow.findViewById(R.id.notification_view);
+        noteView.setClickHandlerFactory(mClickHandlerFactory);
+
+        mContent.setOnTouchListener(mOnTouchListener);
+        // set initial translation after size is calculated
+        mContent.getViewTreeObserver().addOnGlobalLayoutListener(
+                new ViewTreeObserver.OnGlobalLayoutListener() {
+                    @Override
+                    public void onGlobalLayout() {
+                        mContent.getViewTreeObserver().removeOnGlobalLayoutListener(this);
+                        if (!mIsShowing && !mIsTracking) {
+                            mContent.setTranslationY(mContent.getHeight() * -1);
+                        }
+                    }
+                });
+
+        RecyclerView notificationList = mCarNotificationWindow
+                .findViewById(com.android.car.notification.R.id.recycler_view);
+        // register a scroll listener so we can figure out if we are at the bottom of the
+        // list of notifications
+        notificationList.addOnScrollListener(new RecyclerView.OnScrollListener() {
+            @Override
+            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
+                super.onScrolled(recyclerView, dx, dy);
+                if (!notificationList.canScrollVertically(1)) {
+                    mNotificationListAtBottom = true;
+                    return;
+                }
+                mNotificationListAtBottom = false;
+                mNotificationListAtBottomAtTimeOfTouch = false;
+            }
+        });
+        // add a touch listener such that when the user scrolls up and they are at the bottom
+        // of the list we can start the closing of the view.
+        notificationList.setOnTouchListener(new NotificationListTouchListener());
+
+        // There's a view installed at a higher z-order such that we can intercept the ACTION_DOWN
+        // to set the initial click state.
+        mCarNotificationWindow.findViewById(R.id.glass_pane).setOnTouchListener((v, event) -> {
+            if (event.getActionMasked() == MotionEvent.ACTION_UP) {
+                mNotificationListAtBottomAtTimeOfTouch = false;
+            }
+            if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
+                mNotificationListAtBottomAtTimeOfTouch = mNotificationListAtBottom;
+                // register the down event with the gesture detectors so then know where the down
+                // started. This is needed because at this point we don't know which listener
+                // is going to handle scroll and fling events.
+                mGestureDetector.onTouchEvent(event);
+                mScrollUpDetector.onTouchEvent(event);
+            }
+            return false;
+        });
+
         mNotificationViewController = new NotificationViewController(
                 mCarNotificationWindow
                         .findViewById(com.android.car.notification.R.id.notification_view),
                 PreprocessingManager.getInstance(mContext),
                 mCarNotificationListener,
-                mCarUxRestrictionManagerWrapper
-        );
-        // Add to the SystemUI component registry
-        putComponent(NotificationsUI.class, this);
+                mCarUxRestrictionManagerWrapper);
+        mNotificationViewController.enable();
+    }
+
+    // allows for day night switch
+    @Override
+    public void onConfigChanged(Configuration newConfig) {
+        inflateNotificationContent();
+    }
+
+    public View.OnTouchListener getDragDownListener() {
+        return mOnTouchListener;
+    }
+
+    /**
+     * This listener is attached to the notification list UI to intercept gestures if the user
+     * is scrolling up when the notification list is at the bottom
+     */
+    private class ScrollUpDetector extends GestureDetector.SimpleOnGestureListener {
+
+        @Override
+        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
+            return distanceY > 0;
+        }
+    }
+
+    private class NotificationListTouchListener implements View.OnTouchListener {
+
+        @Override
+        public boolean onTouch(View v, MotionEvent event) {
+            // reset mNotificationListAtBottomAtTimeOfTouch here since the "glass pane" will not
+            // get the up event
+            if (event.getActionMasked() == MotionEvent.ACTION_UP) {
+                mNotificationListAtBottomAtTimeOfTouch = false;
+            }
+            boolean wasScrolledUp = mScrollUpDetector.onTouchEvent(event);
+
+            if (mIsTracking
+                    || (mNotificationListAtBottomAtTimeOfTouch && mNotificationListAtBottom
+                    && wasScrolledUp)) {
+                mOnTouchListener.onTouch(v, event);
+                // touch event should not be propagated further
+                return true;
+            }
+            return false;
+        }
+    }
+
+    /**
+     * Touch listener installed on the notification panel. It is also used by the Nav and StatusBar
+     */
+    private class NotificationPanelTouchListener implements View.OnTouchListener {
+
+        @Override
+        public boolean onTouch(View v, MotionEvent event) {
+            boolean consumed = mGestureDetector.onTouchEvent(event);
+            if (consumed) {
+                return true;
+            }
+            if (!mIsTracking || event.getActionMasked() != MotionEvent.ACTION_UP) {
+                return false;
+            }
+
+            float percentFromBottom =
+                    Math.abs(mContent.getTranslationY() / mContent.getHeight()) * 100;
+            if (mIsShowing) {
+                if (percentFromBottom < sSettleOpenPercentage) {
+                    // panel started to close but did not cross minimum threshold thus we open
+                    // it back up
+                    openCarNotifications(DEFAULT_FLING_VELOCITY);
+                    return true;
+                }
+                // panel was lifted more than the threshold thus we close it the rest of the way
+                closeCarNotifications(DEFAULT_FLING_VELOCITY);
+                return true;
+            }
+
+            if (percentFromBottom > sSettleClosePercentage) {
+                // panel was only peeked at thus close it back up
+                closeCarNotifications(DEFAULT_FLING_VELOCITY);
+                return true;
+            }
+            // panel has been open more than threshold thus open it the rest of the way
+            openCarNotifications(DEFAULT_FLING_VELOCITY);
+            return true;
+
+        }
+    }
+
+    /**
+     * Listener called by mGestureDetector. This will be initiated from the
+     * NotificationPanelTouchListener
+     */
+    private class NotificationGestureListener extends GestureDetector.SimpleOnGestureListener {
+        private static final int SWIPE_UP_MIN_DISTANCE = 75;
+        private static final int SWIPE_DOWN_MIN_DISTANCE = 25;
+        private static final int SWIPE_MAX_OFF_PATH = 75;
+        private static final int SWIPE_THRESHOLD_VELOCITY = 200;
+
+        @Override
+        public boolean onScroll(MotionEvent event1, MotionEvent event2, float distanceX,
+                float distanceY) {
+            mIsTracking = true;
+            mCarNotificationWindow.setVisibility(View.VISIBLE);
+
+            mContent.setTranslationY(Math.min(mContent.getTranslationY() - distanceY, 0));
+            if (mContent.getTranslationY() == 0) {
+                mIsTracking = false;
+            }
+            return true;
+        }
+
+        @Override
+        public boolean onFling(MotionEvent event1, MotionEvent event2,
+                float velocityX, float velocityY) {
+            if (Math.abs(event1.getX() - event2.getX()) > SWIPE_MAX_OFF_PATH
+                    || Math.abs(velocityY) < SWIPE_THRESHOLD_VELOCITY) {
+                // swipe was not vertical or was not fast enough
+                return false;
+            }
+
+            boolean isUp = velocityY < 0;
+            float distanceDelta = Math.abs(event1.getY() - event2.getY());
+
+            if (isUp && distanceDelta > SWIPE_UP_MIN_DISTANCE) {
+                // fling up
+                mIsTracking = false;
+                closeCarNotifications(Math.abs(velocityY));
+                return true;
+
+            } else if (!isUp && distanceDelta > SWIPE_DOWN_MIN_DISTANCE) {
+                // fling down
+                mIsTracking = false;
+                openCarNotifications(velocityY);
+                return true;
+            }
+
+            return false;
+        }
     }
 
     /**
@@ -139,38 +390,56 @@
     };
 
     /**
-     * Toggles the visiblity of the notifications
+     * Toggles the visibility of the notifications
      */
     public void toggleShowingCarNotifications() {
         if (mCarNotificationWindow.getVisibility() == View.VISIBLE) {
-            closeCarNotifications();
+            closeCarNotifications(DEFAULT_FLING_VELOCITY);
             return;
         }
-        openCarNotifications();
+        openCarNotifications(DEFAULT_FLING_VELOCITY);
     }
 
     /**
      * Hides the notifications
      */
-    public void closeCarNotifications() {
-        mCarNotificationWindow.setVisibility(View.GONE);
+    public void closeCarNotifications(float velocityY) {
+        float closedTranslation = mContent.getHeight() * -1;
+        ValueAnimator animator =
+                ValueAnimator.ofFloat(mContent.getTranslationY(), closedTranslation);
+        animator.addUpdateListener(
+                animation -> mContent.setTranslationY((Float) animation.getAnimatedValue()));
+        mFlingAnimationUtils.apply(
+                animator, mContent.getTranslationY(), closedTranslation, velocityY);
+        animator.addListener(new AnimatorListenerAdapter() {
+            @Override
+            public void onAnimationEnd(Animator animation) {
+                mCarNotificationWindow.setVisibility(View.GONE);
+            }
+        });
+        animator.start();
         mNotificationViewController.disable();
         mIsShowing = false;
+        mIsTracking = false;
+        RecyclerView notificationListView = mCarNotificationWindow.findViewById(
+                com.android.car.notification.R.id.recycler_view);
+        notificationListView.scrollToPosition(0);
     }
 
     /**
      * Sets the notifications to visible
      */
-    public void openCarNotifications() {
+    public void openCarNotifications(float velocityY) {
         mCarNotificationWindow.setVisibility(View.VISIBLE);
+
+        ValueAnimator animator = ValueAnimator.ofFloat(mContent.getTranslationY(), 0);
+        animator.addUpdateListener(
+                animation -> mContent.setTranslationY((Float) animation.getAnimatedValue()));
+        mFlingAnimationUtils.apply(animator, mContent.getTranslationY(), 0, velocityY);
+        animator.start();
+
         mNotificationViewController.enable();
         mIsShowing = true;
-    }
-
-    /**
-     * Returns {@code true} if notifications are currently on the screen
-     */
-    public boolean isShowing() {
-        return mIsShowing;
+        mIsTracking = false;
     }
 }
diff --git a/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarNavigationBarView.java b/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarNavigationBarView.java
index 0cba351..afefa1b 100644
--- a/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarNavigationBarView.java
+++ b/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarNavigationBarView.java
@@ -18,6 +18,7 @@
 
 import android.content.Context;
 import android.util.AttributeSet;
+import android.view.MotionEvent;
 import android.view.View;
 import android.widget.LinearLayout;
 
@@ -37,6 +38,8 @@
     private CarStatusBar mCarStatusBar;
     private Context mContext;
     private View mLockScreenButtons;
+    private OnTouchListener mStatusBarWindowTouchListener;
+
 
     public CarNavigationBarView(Context context, AttributeSet attrs) {
         super(context, attrs);
@@ -62,11 +65,22 @@
             mDarkIconManager.setShouldLog(true);
             Dependency.get(StatusBarIconController.class).addIconGroup(mDarkIconManager);
         }
+    }
 
+    @Override
+    public boolean onInterceptTouchEvent(MotionEvent ev) {
+        if (mStatusBarWindowTouchListener == null) {
+            return false;
+        }
+        // forward touch events to the status bar window so it can add a drag down
+        // windows if required (Notification shade)
+        mStatusBarWindowTouchListener.onTouch(this, ev);
+        return false;
     }
 
     void setStatusBar(CarStatusBar carStatusBar) {
         mCarStatusBar = carStatusBar;
+        mStatusBarWindowTouchListener = carStatusBar.getStatusBarWindowTouchListener();
     }
 
     protected void onNotificationsClick(View v) {
diff --git a/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java b/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java
index b37c5e6..e66a4624 100644
--- a/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java
+++ b/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java
@@ -211,6 +211,7 @@
     @Override
     public void showKeyguard() {
         super.showKeyguard();
+        getComponent(NotificationsUI.class).closeCarNotifications(0);
         if (mNavigationBarView != null) {
             mNavigationBarView.showKeyguardButtons();
         }
@@ -264,6 +265,12 @@
             mBatteryMeterView.setVisibility(View.GONE);
         });
         addTemperatureViewToController(mStatusBarWindow);
+        // The following are the ui elements that the user would call the status bar.
+        // This will set the status bar so it they can make call backs.
+        CarNavigationBarView topBar = mStatusBarWindow.findViewById(R.id.car_top_bar);
+        topBar.setStatusBar(this);
+        CarNavigationBarView qsTopBar = mStatusBarWindow.findViewById(R.id.qs_car_top_bar);
+        qsTopBar.setStatusBar(this);
     }
 
     @Override
@@ -339,6 +346,7 @@
             lp.setTitle("CarNavigationBar");
             lp.windowAnimations = 0;
             mWindowManager.addView(mNavigationBarWindow, lp);
+            mNavigationBarWindow.setOnTouchListener(getStatusBarWindowTouchListener());
         }
         if (mShowLeft) {
             int width = mContext.getResources().getDimensionPixelSize(
@@ -458,10 +466,8 @@
 
     @Override
     protected View.OnTouchListener getStatusBarWindowTouchListener() {
-        // Usually, a touch on the background window will dismiss the notification shade. However,
-        // for the car use-case, the shade should remain unless the user switches to a different
-        // facet (e.g. phone).
-        return null;
+        // Gets the car specific notification touch listener
+        return getComponent(NotificationsUI.class).getDragDownListener();
     }
 
     @Override
diff --git a/packages/ExtServices/src/android/ext/services/notification/Assistant.java b/packages/ExtServices/src/android/ext/services/notification/Assistant.java
index ce58d4e..fe931ff 100644
--- a/packages/ExtServices/src/android/ext/services/notification/Assistant.java
+++ b/packages/ExtServices/src/android/ext/services/notification/Assistant.java
@@ -215,9 +215,9 @@
             return null;
         }
         NotificationEntry entry = new NotificationEntry(mPackageManager, sbn, channel);
-        ArrayList<Notification.Action> actions = mSmartActionsHelper.suggestActions(entry);
-        ArrayList<CharSequence> replies = mSmartActionsHelper.suggestReplies(entry);
-        return createEnqueuedNotificationAdjustment(entry, actions, replies);
+        SmartActionsHelper.SmartSuggestions suggestions = mSmartActionsHelper.suggest(entry);
+        return createEnqueuedNotificationAdjustment(
+                entry, suggestions.actions, suggestions.replies);
     }
 
     /** A convenience helper for creating an adjustment for an SBN. */
diff --git a/packages/ExtServices/src/android/ext/services/notification/AssistantSettings.java b/packages/ExtServices/src/android/ext/services/notification/AssistantSettings.java
index 406b44d..d99c356 100644
--- a/packages/ExtServices/src/android/ext/services/notification/AssistantSettings.java
+++ b/packages/ExtServices/src/android/ext/services/notification/AssistantSettings.java
@@ -46,24 +46,6 @@
     private static final Uri NOTIFICATION_NEW_INTERRUPTION_MODEL_URI =
             Settings.Secure.getUriFor(Settings.Secure.NOTIFICATION_NEW_INTERRUPTION_MODEL);
 
-    /**
-     * Flag determining whether the Notification Assistant should generate replies for
-     * notifications.
-     * <p>
-     * This flag belongs to the namespace: {@link DeviceConfig#NAMESPACE_NOTIFICATION_ASSISTANT}.
-     */
-    @VisibleForTesting
-    static final String KEY_GENERATE_REPLIES = "notification_assistant_generate_replies";
-
-    /**
-     * Flag determining whether the Notification Assistant should generate contextual actions in
-     * notifications.
-     * <p>
-     * This flag belongs to the namespace: {@link DeviceConfig#NAMESPACE_NOTIFICATION_ASSISTANT}.
-     */
-    @VisibleForTesting
-    static final String KEY_GENERATE_ACTIONS = "notification_assistant_generate_actions";
-
     private final KeyValueListParser mParser = new KeyValueListParser(',');
     private final ContentResolver mResolver;
     private final int mUserId;
@@ -118,7 +100,7 @@
 
     private void registerDeviceConfigs() {
         DeviceConfig.addOnPropertyChangedListener(
-                DeviceConfig.NAMESPACE_NOTIFICATION_ASSISTANT,
+                DeviceConfig.NotificationAssistant.NAMESPACE,
                 this::postToHandler,
                 this::onDeviceConfigPropertyChanged);
 
@@ -132,7 +114,7 @@
 
     @VisibleForTesting
     void onDeviceConfigPropertyChanged(String namespace, String name, String value) {
-        if (!DeviceConfig.NAMESPACE_NOTIFICATION_ASSISTANT.equals(namespace)) {
+        if (!DeviceConfig.NotificationAssistant.NAMESPACE.equals(namespace)) {
             Log.e(LOG_TAG, "Received update from DeviceConfig for unrelated namespace: "
                     + namespace + " " + name + "=" + value);
             return;
@@ -143,8 +125,8 @@
 
     private void updateFromDeviceConfigFlags() {
         String generateRepliesFlag = DeviceConfig.getProperty(
-                DeviceConfig.NAMESPACE_NOTIFICATION_ASSISTANT,
-                KEY_GENERATE_REPLIES);
+                DeviceConfig.NotificationAssistant.NAMESPACE,
+                DeviceConfig.NotificationAssistant.GENERATE_REPLIES);
         if (TextUtils.isEmpty(generateRepliesFlag)) {
             mGenerateReplies = DEFAULT_GENERATE_REPLIES;
         } else {
@@ -154,8 +136,8 @@
         }
 
         String generateActionsFlag = DeviceConfig.getProperty(
-                DeviceConfig.NAMESPACE_NOTIFICATION_ASSISTANT,
-                KEY_GENERATE_ACTIONS);
+                DeviceConfig.NotificationAssistant.NAMESPACE,
+                DeviceConfig.NotificationAssistant.GENERATE_ACTIONS);
         if (TextUtils.isEmpty(generateActionsFlag)) {
             mGenerateActions = DEFAULT_GENERATE_ACTIONS;
         } else {
diff --git a/packages/ExtServices/src/android/ext/services/notification/SmartActionsHelper.java b/packages/ExtServices/src/android/ext/services/notification/SmartActionsHelper.java
index 5acf4fb..48a3974 100644
--- a/packages/ExtServices/src/android/ext/services/notification/SmartActionsHelper.java
+++ b/packages/ExtServices/src/android/ext/services/notification/SmartActionsHelper.java
@@ -92,6 +92,23 @@
         mSettings = settings;
     }
 
+    @NonNull
+    SmartSuggestions suggest(@NonNull NotificationEntry entry) {
+        // Whenever suggest() is called on a notification, its previous session is ended.
+        mNotificationKeyToResultIdCache.remove(entry.getSbn().getKey());
+
+        ArrayList<Notification.Action> actions = suggestActions(entry);
+        ArrayList<CharSequence> replies = suggestReplies(entry);
+
+        // Not logging subsequent events of this notification if we didn't generate any suggestion
+        // for it.
+        if (replies.isEmpty() && actions.isEmpty()) {
+            mNotificationKeyToResultIdCache.remove(entry.getSbn().getKey());
+        }
+
+        return new SmartSuggestions(replies, actions);
+    }
+
     /**
      * Adds action adjustments based on the notification contents.
      */
@@ -115,6 +132,7 @@
                 messages.get(messages.size() - 1).getText(), MAX_SMART_ACTIONS);
     }
 
+    @NonNull
     ArrayList<CharSequence> suggestReplies(@NonNull NotificationEntry entry) {
         if (!mSettings.mGenerateReplies) {
             return EMPTY_REPLY_LIST;
@@ -146,7 +164,7 @@
                 .collect(Collectors.toCollection(ArrayList::new));
 
         String resultId = conversationActionsResult.getId();
-        if (resultId != null && !replies.isEmpty()) {
+        if (resultId != null) {
             mNotificationKeyToResultIdCache.put(entry.getSbn().getKey(), resultId);
         }
         return replies;
@@ -385,4 +403,15 @@
         }
         return actions;
     }
+
+    static class SmartSuggestions {
+        public final ArrayList<CharSequence> replies;
+        public final ArrayList<Notification.Action> actions;
+
+        SmartSuggestions(
+                ArrayList<CharSequence> replies, ArrayList<Notification.Action> actions) {
+            this.replies = replies;
+            this.actions = actions;
+        }
+    }
 }
diff --git a/packages/ExtServices/tests/src/android/ext/services/notification/AssistantSettingsTest.java b/packages/ExtServices/tests/src/android/ext/services/notification/AssistantSettingsTest.java
index 51b723d..597051a 100644
--- a/packages/ExtServices/tests/src/android/ext/services/notification/AssistantSettingsTest.java
+++ b/packages/ExtServices/tests/src/android/ext/services/notification/AssistantSettingsTest.java
@@ -71,9 +71,14 @@
 
     @Test
     public void testGenerateRepliesDisabled() {
+        DeviceConfig.setProperty(
+                DeviceConfig.NotificationAssistant.NAMESPACE,
+                DeviceConfig.NotificationAssistant.GENERATE_REPLIES,
+                "false",
+                false /* makeDefault */);
         mAssistantSettings.onDeviceConfigPropertyChanged(
-                DeviceConfig.NAMESPACE_NOTIFICATION_ASSISTANT,
-                AssistantSettings.KEY_GENERATE_REPLIES,
+                DeviceConfig.NotificationAssistant.NAMESPACE,
+                DeviceConfig.NotificationAssistant.GENERATE_REPLIES,
                 "false");
 
         assertFalse(mAssistantSettings.mGenerateReplies);
@@ -81,9 +86,14 @@
 
     @Test
     public void testGenerateRepliesEnabled() {
+        DeviceConfig.setProperty(
+                DeviceConfig.NotificationAssistant.NAMESPACE,
+                DeviceConfig.NotificationAssistant.GENERATE_REPLIES,
+                "true",
+                false /* makeDefault */);
         mAssistantSettings.onDeviceConfigPropertyChanged(
-                DeviceConfig.NAMESPACE_NOTIFICATION_ASSISTANT,
-                AssistantSettings.KEY_GENERATE_REPLIES,
+                DeviceConfig.NotificationAssistant.NAMESPACE,
+                DeviceConfig.NotificationAssistant.GENERATE_REPLIES,
                 "true");
 
         assertTrue(mAssistantSettings.mGenerateReplies);
@@ -91,16 +101,26 @@
 
     @Test
     public void testGenerateRepliesEmptyFlag() {
+        DeviceConfig.setProperty(
+                DeviceConfig.NotificationAssistant.NAMESPACE,
+                DeviceConfig.NotificationAssistant.GENERATE_REPLIES,
+                "false",
+                false /* makeDefault */);
         mAssistantSettings.onDeviceConfigPropertyChanged(
-                DeviceConfig.NAMESPACE_NOTIFICATION_ASSISTANT,
-                AssistantSettings.KEY_GENERATE_REPLIES,
+                DeviceConfig.NotificationAssistant.NAMESPACE,
+                DeviceConfig.NotificationAssistant.GENERATE_REPLIES,
                 "false");
 
         assertFalse(mAssistantSettings.mGenerateReplies);
 
+        DeviceConfig.setProperty(
+                DeviceConfig.NotificationAssistant.NAMESPACE,
+                DeviceConfig.NotificationAssistant.GENERATE_REPLIES,
+                "",
+                false /* makeDefault */);
         mAssistantSettings.onDeviceConfigPropertyChanged(
-                DeviceConfig.NAMESPACE_NOTIFICATION_ASSISTANT,
-                AssistantSettings.KEY_GENERATE_REPLIES,
+                DeviceConfig.NotificationAssistant.NAMESPACE,
+                DeviceConfig.NotificationAssistant.GENERATE_REPLIES,
                 "");
 
         // Go back to the default value.
@@ -109,9 +129,14 @@
 
     @Test
     public void testGenerateActionsDisabled() {
+        DeviceConfig.setProperty(
+                DeviceConfig.NotificationAssistant.NAMESPACE,
+                DeviceConfig.NotificationAssistant.GENERATE_ACTIONS,
+                "false",
+                false /* makeDefault */);
         mAssistantSettings.onDeviceConfigPropertyChanged(
-                DeviceConfig.NAMESPACE_NOTIFICATION_ASSISTANT,
-                AssistantSettings.KEY_GENERATE_ACTIONS,
+                DeviceConfig.NotificationAssistant.NAMESPACE,
+                DeviceConfig.NotificationAssistant.GENERATE_ACTIONS,
                 "false");
 
         assertFalse(mAssistantSettings.mGenerateActions);
@@ -119,9 +144,14 @@
 
     @Test
     public void testGenerateActionsEnabled() {
+        DeviceConfig.setProperty(
+                DeviceConfig.NotificationAssistant.NAMESPACE,
+                DeviceConfig.NotificationAssistant.GENERATE_ACTIONS,
+                "true",
+                false /* makeDefault */);
         mAssistantSettings.onDeviceConfigPropertyChanged(
-                DeviceConfig.NAMESPACE_NOTIFICATION_ASSISTANT,
-                AssistantSettings.KEY_GENERATE_ACTIONS,
+                DeviceConfig.NotificationAssistant.NAMESPACE,
+                DeviceConfig.NotificationAssistant.GENERATE_ACTIONS,
                 "true");
 
         assertTrue(mAssistantSettings.mGenerateActions);
@@ -129,16 +159,26 @@
 
     @Test
     public void testGenerateActionsEmptyFlag() {
+        DeviceConfig.setProperty(
+                DeviceConfig.NotificationAssistant.NAMESPACE,
+                DeviceConfig.NotificationAssistant.GENERATE_ACTIONS,
+                "false",
+                false /* makeDefault */);
         mAssistantSettings.onDeviceConfigPropertyChanged(
-                DeviceConfig.NAMESPACE_NOTIFICATION_ASSISTANT,
-                AssistantSettings.KEY_GENERATE_ACTIONS,
+                DeviceConfig.NotificationAssistant.NAMESPACE,
+                DeviceConfig.NotificationAssistant.GENERATE_ACTIONS,
                 "false");
 
         assertFalse(mAssistantSettings.mGenerateActions);
 
+        DeviceConfig.setProperty(
+                DeviceConfig.NotificationAssistant.NAMESPACE,
+                DeviceConfig.NotificationAssistant.GENERATE_ACTIONS,
+                "",
+                false /* makeDefault */);
         mAssistantSettings.onDeviceConfigPropertyChanged(
-                DeviceConfig.NAMESPACE_NOTIFICATION_ASSISTANT,
-                AssistantSettings.KEY_GENERATE_ACTIONS,
+                DeviceConfig.NotificationAssistant.NAMESPACE,
+                DeviceConfig.NotificationAssistant.GENERATE_ACTIONS,
                 "");
 
         // Go back to the default value.
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
index 856b167..3877c90 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
@@ -422,12 +422,6 @@
                 Settings.Global.CONTACTS_DATABASE_WAL_ENABLED,
                 GlobalSettingsProto.CONTACTS_DATABASE_WAL_ENABLED);
 
-        final long contentCaptureToken = p.start(GlobalSettingsProto.CONTENT_CAPTURE);
-        dumpSetting(s, p,
-                Settings.Global.CONTENT_CAPTURE_SERVICE_EXPLICITLY_ENABLED,
-                GlobalSettingsProto.ContentCapture.SERVICE_EXPLICITLY_ENABLED);
-        p.end(contentCaptureToken);
-
         final long dataToken = p.start(GlobalSettingsProto.DATA);
         // Settings.Global.DEFAULT_RESTRICT_BACKGROUND_DATA intentionally excluded.
         dumpSetting(s, p,
diff --git a/packages/SystemUI/res/drawable/ic_access_alarms_small.xml b/packages/SystemUI/res/drawable/ic_access_alarms_small.xml
deleted file mode 100644
index f6e5ceb..0000000
--- a/packages/SystemUI/res/drawable/ic_access_alarms_small.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-<!--
-Copyright (C) 2017 The Android Open Source Project
-
-   Licensed under the Apache License, Version 2.0 (the "License");
-    you may not use this file except in compliance with the License.
-    You may obtain a copy of the License at
-
-         http://www.apache.org/licenses/LICENSE-2.0
-
-    Unless required by applicable law or agreed to in writing, software
-    distributed under the License is distributed on an "AS IS" BASIS,
-    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-    See the License for the specific language governing permissions and
-    limitations under the License.
--->
-<vector xmlns:android="http://schemas.android.com/apk/res/android"
-    android:width="16dp"
-    android:height="16dp"
-    android:viewportWidth="24.0"
-    android:viewportHeight="24.0">
-    <path
-        android:pathData="M21.35,6.49c-0.35,0.42 -0.98,0.47 -1.4,0.12l-3.07,-2.57a1,1 0,1 1,1.29 -1.53l3.07,2.57c0.42,0.35 0.47,0.98 0.11,1.41zM7.24,2.63a1,1 0,0 0,-1.41 -0.13L2.77,5.07A0.996,0.996 0,1 0,4.05 6.6l3.06,-2.57c0.43,-0.35 0.48,-0.98 0.13,-1.4zM11.75,8c-0.41,0 -0.75,0.34 -0.75,0.75v4.68c0,0.35 0.18,0.68 0.49,0.86l3.65,2.19c0.34,0.2 0.78,0.1 0.98,-0.24a0.71,0.71 0,0 0,-0.25 -0.99l-3.37,-2v-4.5c0,-0.41 -0.34,-0.75 -0.75,-0.75zM12,5.9c-3.91,0 -7.1,3.18 -7.1,7.1s3.19,7.1 7.1,7.1 7.1,-3.18 7.1,-7.1 -3.19,-7.1 -7.1,-7.1M12,4a9,9 0,1 1,-0.001 18.001A9,9 0,0 1,12 4z"
-        android:fillColor="#FFFFFFFF"/>
-</vector>
diff --git a/packages/SystemUI/res/drawable/ic_delete.xml b/packages/SystemUI/res/drawable/ic_delete.xml
deleted file mode 100644
index 3580fdf..0000000
--- a/packages/SystemUI/res/drawable/ic_delete.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-<!--
-Copyright (C) 2015 The Android Open Source Project
-
-   Licensed under the Apache License, Version 2.0 (the "License");
-    you may not use this file except in compliance with the License.
-    You may obtain a copy of the License at
-
-         http://www.apache.org/licenses/LICENSE-2.0
-
-    Unless required by applicable law or agreed to in writing, software
-    distributed under the License is distributed on an "AS IS" BASIS,
-    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-    See the License for the specific language governing permissions and
-    limitations under the License.
--->
-<vector xmlns:android="http://schemas.android.com/apk/res/android"
-        android:width="24.0dp"
-        android:height="24.0dp"
-        android:viewportWidth="24.0"
-        android:viewportHeight="24.0">
-    <path
-        android:fillColor="#FFFFFFFF"
-        android:pathData="M15,4V3H9v1H4v2h1v13c0,1.1 0.9,2 2,2h10c1.1,0 2,-0.9 2,-2V6h1V4H15zM17,19H7V6h10V19z"/>
-    <path
-        android:fillColor="#FFFFFFFF"
-        android:pathData="M9,8h2v9h-2z"/>
-    <path
-        android:fillColor="#FFFFFFFF"
-        android:pathData="M13,8h2v9h-2z"/>
-</vector>
diff --git a/packages/SystemUI/res/drawable/ic_fingerprint.xml b/packages/SystemUI/res/drawable/ic_fingerprint.xml
deleted file mode 100644
index 7bbd39d..0000000
--- a/packages/SystemUI/res/drawable/ic_fingerprint.xml
+++ /dev/null
@@ -1,67 +0,0 @@
-<!--
-  ~ Copyright (C) 2017 The Android Open Source Project
-  ~
-  ~ Licensed under the Apache License, Version 2.0 (the "License");
-  ~ you may not use this file except in compliance with the License.
-  ~ You may obtain a copy of the License at
-  ~
-  ~      http://www.apache.org/licenses/LICENSE-2.0
-  ~
-  ~ Unless required by applicable law or agreed to in writing, software
-  ~ distributed under the License is distributed on an "AS IS" BASIS,
-  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-  ~ See the License for the specific language governing permissions and
-  ~ limitations under the License
-  -->
-<vector
-    xmlns:android="http://schemas.android.com/apk/res/android"
-    android:width="32dp"
-    android:viewportWidth="24"
-    android:height="32dp"
-    android:viewportHeight="24" >
-    <group
-        android:translateX="12"
-        android:translateY="12.4"
-        android:scaleX="0.738"
-        android:scaleY="0.738" >
-        <group
-            android:translateX="33"
-            android:translateY="34" >
-            <path
-                android:pathData="M -25.3591003418,-24.4138946533 c -0.569000244141,0.106399536133 -1.12660217285,0.140594482422 -1.45460510254,0.140594482422 c -1.29689025879,0.0 -2.53239440918,-0.343307495117 -3.62019348145,-1.12400817871 c -1.67700195312,-1.20349121094 -2.76950073242,-3.17008972168 -2.76950073242,-5.39189147949"
-                android:strokeColor="?attr/wallpaperTextColor"
-                android:strokeAlpha="0.5"
-                android:strokeWidth="1.45"
-                android:strokeLineCap="round" />
-            <path
-                android:name="ridge_7_path"
-                android:pathData="M -36.1409912109,-21.7843475342 c -1.00540161133,-1.19300842285 -1.57499694824,-1.9181060791 -2.36520385742,-3.50170898438 c -0.827560424805,-1.65869140625 -1.31352233887,-3.49159240723 -1.31352233887,-5.48489379883 c 0.0,-3.66279602051 2.96932983398,-6.63220214844 6.63221740723,-6.63220214844 c 3.6628112793,0.0 6.63220214844,2.96940612793 6.63220214844,6.63220214844"
-                android:strokeColor="?attr/wallpaperTextColor"
-                android:strokeAlpha="0.5"
-                android:strokeWidth="1.45"
-                android:strokeLineCap="round" />
-            <path
-                android:pathData="M -42.1907958984,-25.6756896973 c -0.758117675781,-2.14370727539 -0.896545410156,-3.86891174316 -0.896545410156,-5.12921142578 c 0.0,-1.46069335938 0.249176025391,-2.84799194336 0.814682006836,-4.09748840332 c 1.56153869629,-3.45030212402 5.03434753418,-5.85076904297 9.0679473877,-5.85076904297 c 5.49430847168,0.0 9.94830322266,4.4539642334 9.94830322266,9.94825744629 c 0.0,1.83151245117 -1.48460388184,3.31610107422 -3.31610107422,3.31610107422 c -1.83149719238,0.0 -3.31610107422,-1.48469543457 -3.31610107422,-3.31610107422 c 0.0,-1.83139038086 -1.48458862305,-3.31610107422 -3.31610107422,-3.31610107422 c -1.83149719238,0.0 -3.31610107422,1.48471069336 -3.31610107422,3.31610107422 c 0.0,2.57020568848 0.989517211914,4.88710021973 2.60510253906,6.5865020752 c 1.22210693359,1.28550720215 2.43139648438,2.09950256348 4.47590637207,2.69030761719"
-                android:strokeColor="?attr/wallpaperTextColor"
-                android:strokeAlpha="0.5"
-                android:strokeWidth="1.45"
-                android:strokeLineCap="round" />
-            <path
-                android:pathData="M -44.0646514893,-38.1672973633 c 1.19026184082,-1.77430725098 2.67503356934,-3.24531555176 4.55902099609,-4.27278137207 c 1.88395690918,-1.0274810791 4.04466247559,-1.61137390137 6.34175109863,-1.61137390137 c 2.28761291504,0.0 4.43991088867,0.579071044922 6.31831359863,1.59861755371 c 1.8784942627,1.01954650879 3.36059570312,2.4796295166 4.55279541016,4.24153137207"
-                android:strokeColor="?attr/wallpaperTextColor"
-                android:strokeAlpha="0.5"
-                android:strokeWidth="1.45"
-                android:strokeLineCap="round" />
-            <group
-                android:translateX="-97.5"
-                android:translateY="-142.5" >
-                <path
-                    android:pathData="M 71.7812347412,97.0507202148 c -2.27149963379,-1.31344604492 -4.71360778809,-2.07006835938 -7.56221008301,-2.07006835938 c -2.84869384766,0.0 -5.23320007324,0.779556274414 -7.34411621094,2.07006835938"
-                    android:strokeColor="?attr/wallpaperTextColor"
-                    android:strokeAlpha="0.5"
-                    android:strokeWidth="1.45"
-                    android:strokeLineCap="round" />
-            </group>
-        </group>
-    </group>
-</vector>
diff --git a/packages/SystemUI/res/drawable/ic_lock_open_24dp.xml b/packages/SystemUI/res/drawable/ic_lock_open_24dp.xml
deleted file mode 100644
index 232cf70..0000000
--- a/packages/SystemUI/res/drawable/ic_lock_open_24dp.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<!--
-Copyright (C) 2017 The Android Open Source Project
-
-   Licensed under the Apache License, Version 2.0 (the "License");
-    you may not use this file except in compliance with the License.
-    You may obtain a copy of the License at
-
-         http://www.apache.org/licenses/LICENSE-2.0
-
-    Unless required by applicable law or agreed to in writing, software
-    distributed under the License is distributed on an "AS IS" BASIS,
-    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-    See the License for the specific language governing permissions and
-    limitations under the License.
--->
-<vector xmlns:android="http://schemas.android.com/apk/res/android"
-        android:width="24.0dp"
-        android:height="24.0dp"
-        android:viewportWidth="24.0"
-        android:viewportHeight="24.0">
-
-    <path
-        android:fillColor="?attr/wallpaperTextColor"
-        android:pathData="M12.0,17.0c1.1,0.0 2.0,-0.9 2.0,-2.0s-0.9,-2.0 -2.0,-2.0c-1.1,0.0 -2.0,0.9 -2.0,2.0S10.9,17.0 12.0,17.0zM18.0,8.0l-1.0,0.0L17.0,6.0c0.0,-2.8 -2.2,-5.0 -5.0,-5.0C9.2,1.0 7.0,3.2 7.0,6.0l1.9,0.0c0.0,-1.7 1.4,-3.1 3.1,-3.1c1.7,0.0 3.1,1.4 3.1,3.1l0.0,2.0L6.0,8.0c-1.1,0.0 -2.0,0.9 -2.0,2.0l0.0,10.0c0.0,1.1 0.9,2.0 2.0,2.0l12.0,0.0c1.1,0.0 2.0,-0.9 2.0,-2.0L20.0,10.0C20.0,8.9 19.1,8.0 18.0,8.0zM18.0,20.0L6.0,20.0L6.0,10.0l12.0,0.0L18.0,20.0z"/>
-</vector>
diff --git a/packages/SystemUI/res/drawable/ic_sysbar_back_carmode.xml b/packages/SystemUI/res/drawable/ic_sysbar_back_carmode.xml
deleted file mode 100644
index 5844b2e..0000000
--- a/packages/SystemUI/res/drawable/ic_sysbar_back_carmode.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<vector xmlns:android="http://schemas.android.com/apk/res/android"
-        android:width="44dp"
-        android:height="44dp"
-        android:viewportWidth="44.0"
-        android:viewportHeight="44.0">
-    <path
-        android:pathData="M9,22.06C9,21.22 9.51,20.42 10.36,19.95L31.56,7.87C32.57,7.3 33.42,7.49 33.89,7.75C34.92,8.33 35,9.44 35,9.91L35,34.09C35,34.65 34.92,35.69 33.91,36.25C33.46,36.51 32.66,36.69 31.67,36.14L10.26,24.05C9.49,23.61 9,22.87 9,22.06L9,22.06ZM31.5,12L13.5,22.04L31.5,32L31.5,12Z"
-        android:strokeColor="#00000000"
-        android:fillType="evenOdd"
-        android:fillColor="#F8F9FA"
-        android:strokeWidth="1"/>
-</vector>
diff --git a/packages/SystemUI/res/drawable/ic_sysbar_home_carmode.xml b/packages/SystemUI/res/drawable/ic_sysbar_home_carmode.xml
deleted file mode 100644
index e07bf6f..0000000
--- a/packages/SystemUI/res/drawable/ic_sysbar_home_carmode.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<vector xmlns:android="http://schemas.android.com/apk/res/android"
-        android:width="44dp"
-        android:height="44dp"
-        android:viewportWidth="44.0"
-        android:viewportHeight="44.0">
-    <path
-        android:pathData="M22.39,22.39m-14.54,0a14.54,14.54 0,1 1,29.07 0a14.54,14.54 0,1 1,-29.07 0"
-        android:fillType="evenOdd"
-        android:strokeColor="#F8F9FA"
-        android:fillColor="#00000000"
-        android:strokeWidth="4"/>
-</vector>
diff --git a/packages/SystemUI/res/layout/status_bar_alarm_group.xml b/packages/SystemUI/res/layout/status_bar_alarm_group.xml
deleted file mode 100644
index 3528f9e..0000000
--- a/packages/SystemUI/res/layout/status_bar_alarm_group.xml
+++ /dev/null
@@ -1,59 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-     Copyright (C) 2016 The Android Open Source Project
-
-     Licensed under the Apache License, Version 2.0 (the "License");
-     you may not use this file except in compliance with the License.
-     You may obtain a copy of the License at
-
-          http://www.apache.org/licenses/LICENSE-2.0
-
-     Unless required by applicable law or agreed to in writing, software
-     distributed under the License is distributed on an "AS IS" BASIS,
-     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-     See the License for the specific language governing permissions and
-     limitations under the License.
--->
-<LinearLayout
-    xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:systemui="http://schemas.android.com/apk/res-auto"
-    android:id="@+id/date_time_alarm_group"
-    android:layout_width="wrap_content"
-    android:layout_height="wrap_content"
-    android:padding="4dp"
-    android:gravity="center_vertical"
-    android:orientation="horizontal"
-    android:background="?android:attr/selectableItemBackground">
-
-    <com.android.systemui.statusbar.policy.DateView
-        android:id="@+id/date"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:singleLine="true"
-        android:textAppearance="@style/TextAppearance.StatusBar.Expanded.Date"
-        android:textSize="@dimen/qs_time_collapsed_size"
-        android:gravity="center_vertical"
-        systemui:datePattern="@string/abbrev_wday_month_day_no_year_alarm" />
-
-    <com.android.systemui.statusbar.AlphaOptimizedImageView
-        android:id="@+id/alarm_status_collapsed"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:src="@drawable/ic_access_alarms_small"
-        android:tint="?android:attr/textColorPrimary"
-        android:paddingStart="6dp"
-        android:paddingEnd="6dp"
-        android:gravity="center"
-        android:visibility="gone" />
-
-    <com.android.systemui.statusbar.AlphaOptimizedButton
-        android:id="@+id/alarm_status"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:textAppearance="@style/TextAppearance.StatusBar.Expanded.Clock"
-        android:gravity="center_vertical"
-        android:background="@null"
-        android:clickable="false"
-        android:visibility="gone" />
-
-</LinearLayout>
diff --git a/packages/SystemUI/res/values/config.xml b/packages/SystemUI/res/values/config.xml
index f2be2e7..76eb85e 100644
--- a/packages/SystemUI/res/values/config.xml
+++ b/packages/SystemUI/res/values/config.xml
@@ -463,6 +463,10 @@
          show none. -->
     <integer name="config_smart_replies_in_notifications_min_num_system_generated_replies">0</integer>
 
+    <!-- Smart replies in notifications: Maximum number of smart actions to show in notifications.
+         -->
+    <integer name="config_smart_replies_in_notifications_max_num_actions">-1</integer>
+
     <!-- Screenshot editing default activity.  Must handle ACTION_EDIT image/png intents.
          Blank sends the user to the Chooser first.
          This name is in the ComponentName flattened format (package/class)  -->
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BadgedImageView.java b/packages/SystemUI/src/com/android/systemui/bubbles/BadgedImageView.java
index 36a813b..1154515 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/BadgedImageView.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BadgedImageView.java
@@ -16,7 +16,9 @@
 package com.android.systemui.bubbles;
 
 import android.content.Context;
+import android.content.res.TypedArray;
 import android.graphics.Canvas;
+import android.graphics.Color;
 import android.graphics.Path;
 import android.graphics.Point;
 import android.graphics.Rect;
@@ -38,6 +40,7 @@
 
     private float mDotScale = 0f;
     private int mUpdateDotColor;
+    private int mBubbleDefaultBgColor;
     private boolean mShowUpdateDot;
     private boolean mOnLeft;
 
@@ -59,6 +62,11 @@
         setScaleType(ScaleType.CENTER_CROP);
         mIconSize = getResources().getDimensionPixelSize(R.dimen.individual_bubble_size);
         mDotRenderer = new BadgeRenderer(mIconSize);
+
+        TypedArray ta = context.obtainStyledAttributes(
+                new int[] {android.R.attr.colorBackgroundFloating});
+        mBubbleDefaultBgColor = ta.getColor(0, Color.WHITE);
+        ta.recycle();
     }
 
     // TODO: Clipping oval path isn't great: rerender image into a separate, rounded bitmap and
@@ -70,6 +78,7 @@
         mClipPath.addOval(getPaddingStart(), getPaddingTop(),
                 getWidth() - getPaddingEnd(), getHeight() - getPaddingBottom(), Path.Direction.CW);
         canvas.clipPath(mClipPath);
+        canvas.drawColor(mBubbleDefaultBgColor);
         super.onDraw(canvas);
 
         // After we've circle cropped what we're showing, restore so we don't clip the badge
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleController.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleController.java
index da29ab4..e3f6add 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleController.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleController.java
@@ -26,6 +26,7 @@
 import android.annotation.Nullable;
 import android.app.INotificationManager;
 import android.app.Notification;
+import android.app.NotificationChannel;
 import android.app.PendingIntent;
 import android.content.Context;
 import android.content.pm.ActivityInfo;
@@ -414,7 +415,8 @@
     /**
      * Whether the notification has been developer configured to bubble and is allowed by the user.
      */
-    private boolean shouldBubble(NotificationEntry entry) {
+    @VisibleForTesting
+    protected boolean shouldBubble(NotificationEntry entry) {
         StatusBarNotification n = entry.notification;
         boolean canAppOverlay = false;
         try {
@@ -424,8 +426,9 @@
             Log.w(TAG, "Error calling NoMan to determine if app can overlay", e);
         }
 
-        boolean canChannelOverlay = mNotificationEntryManager.getNotificationData().getChannel(
-                entry.key).canBubble();
+        NotificationChannel channel = mNotificationEntryManager.getNotificationData().getChannel(
+                entry.key);
+        boolean canChannelOverlay = channel != null && channel.canBubble();
         boolean hasOverlayIntent = n.getNotification().getBubbleMetadata() != null
                 && n.getNotification().getBubbleMetadata().getIntent() != null;
         return DEBUG_ENABLE_AUTO_BUBBLE && hasOverlayIntent && canChannelOverlay && canAppOverlay;
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleStackView.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleStackView.java
index b584f67..83fd970 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleStackView.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleStackView.java
@@ -23,6 +23,7 @@
 import android.app.PendingIntent;
 import android.content.Context;
 import android.content.res.Resources;
+import android.graphics.Outline;
 import android.graphics.Point;
 import android.graphics.PointF;
 import android.graphics.Rect;
@@ -32,6 +33,7 @@
 import android.view.MotionEvent;
 import android.view.View;
 import android.view.ViewGroup;
+import android.view.ViewOutlineProvider;
 import android.view.ViewTreeObserver;
 import android.view.WindowInsets;
 import android.view.WindowManager;
@@ -674,6 +676,17 @@
             BubbleView bv = (BubbleView) mBubbleContainer.getChildAt(i);
             bv.updateDotVisibility();
             bv.setZ(bubbsCount - i);
+
+            // Draw the shadow around the circle inscribed within the bubble's bounds. This
+            // (intentionally) does not draw a shadow behind the update dot, which should be drawing
+            // its own shadow since it's on a different (higher) plane.
+            bv.setOutlineProvider(new ViewOutlineProvider() {
+                @Override
+                public void getOutline(View view, Outline outline) {
+                    outline.setOval(0, 0, mBubbleSize, mBubbleSize);
+                }
+            });
+            bv.setClipToOutline(false);
         }
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QuickQSPanel.java b/packages/SystemUI/src/com/android/systemui/qs/QuickQSPanel.java
index 6f847c8..995dc66 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QuickQSPanel.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QuickQSPanel.java
@@ -274,8 +274,6 @@
                     if (record.tileView.getVisibility() == GONE) continue;
                     previousView = record.tileView.updateAccessibilityOrder(previousView);
                 }
-                mRecords.get(0).tileView.setAccessibilityTraversalAfter(
-                        R.id.alarm_status_collapsed);
                 mRecords.get(mRecords.size() - 1).tileView.setAccessibilityTraversalBefore(
                         R.id.expand_indicator);
             }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/SmartReplyController.java b/packages/SystemUI/src/com/android/systemui/statusbar/SmartReplyController.java
index a2abcd2..5a8f71d 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/SmartReplyController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/SmartReplyController.java
@@ -56,12 +56,13 @@
      * Notifies StatusBarService a smart reply is sent.
      */
     public void smartReplySent(NotificationEntry entry, int replyIndex, CharSequence reply,
-            boolean generatedByAssistant) {
+            boolean generatedByAssistant, int notificationLocation) {
         mCallback.onSmartReplySent(entry, reply);
         mSendingKeys.add(entry.key);
         try {
             mBarService.onNotificationSmartReplySent(
-                    entry.notification.getKey(), replyIndex, reply, generatedByAssistant);
+                    entry.notification.getKey(), replyIndex, reply, generatedByAssistant,
+                    notificationLocation);
         } catch (RemoteException e) {
             // Nothing to do, system going down
         }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/SmartReplyConstants.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/SmartReplyConstants.java
index db04620..b22150b 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/SmartReplyConstants.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/SmartReplyConstants.java
@@ -47,6 +47,7 @@
             "edit_choices_before_sending";
     private static final String KEY_SHOW_IN_HEADS_UP = "show_in_heads_up";
     private static final String KEY_MIN_NUM_REPLIES = "min_num_system_generated_replies";
+    private static final String KEY_MAX_NUM_ACTIONS = "max_num_actions";
 
     private final boolean mDefaultEnabled;
     private final boolean mDefaultRequiresP;
@@ -54,6 +55,7 @@
     private final boolean mDefaultEditChoicesBeforeSending;
     private final boolean mDefaultShowInHeadsUp;
     private final int mDefaultMinNumSystemGeneratedReplies;
+    private final int mDefaultMaxNumActions;
 
     private boolean mEnabled;
     private boolean mRequiresTargetingP;
@@ -61,6 +63,7 @@
     private boolean mEditChoicesBeforeSending;
     private boolean mShowInHeadsUp;
     private int mMinNumSystemGeneratedReplies;
+    private int mMaxNumActions;
 
     private final Context mContext;
     private final KeyValueListParser mParser = new KeyValueListParser(',');
@@ -83,6 +86,8 @@
                 R.bool.config_smart_replies_in_notifications_show_in_heads_up);
         mDefaultMinNumSystemGeneratedReplies = resources.getInteger(
                 R.integer.config_smart_replies_in_notifications_min_num_system_generated_replies);
+        mDefaultMaxNumActions = resources.getInteger(
+                R.integer.config_smart_replies_in_notifications_max_num_actions);
 
         mContext.getContentResolver().registerContentObserver(
                 Settings.Global.getUriFor(Settings.Global.SMART_REPLIES_IN_NOTIFICATIONS_FLAGS),
@@ -112,6 +117,7 @@
             mShowInHeadsUp = mParser.getBoolean(KEY_SHOW_IN_HEADS_UP, mDefaultShowInHeadsUp);
             mMinNumSystemGeneratedReplies =
                     mParser.getInt(KEY_MIN_NUM_REPLIES, mDefaultMinNumSystemGeneratedReplies);
+            mMaxNumActions = mParser.getInt(KEY_MAX_NUM_ACTIONS, mDefaultMaxNumActions);
         }
     }
 
@@ -170,4 +176,12 @@
     public int getMinNumSystemGeneratedReplies() {
         return mMinNumSystemGeneratedReplies;
     }
+
+    /**
+     * Returns the maximum number smart actions to show in a notification, or -1 if there shouldn't
+     * be a limit.
+     */
+    public int getMaxNumActions() {
+        return mMaxNumActions;
+    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/SmartReplyView.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/SmartReplyView.java
index 07c6587..1d2d6f7 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/SmartReplyView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/SmartReplyView.java
@@ -38,6 +38,7 @@
 import com.android.systemui.statusbar.SmartReplyController;
 import com.android.systemui.statusbar.notification.NotificationUtils;
 import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.logging.NotificationLogger;
 import com.android.systemui.statusbar.phone.KeyguardDismissUtil;
 
 import java.text.BreakIterator;
@@ -258,8 +259,9 @@
                 return false;
             }
 
-            smartReplyController.smartReplySent(
-                    entry, replyIndex, b.getText(), smartReplies.fromAssistant);
+            smartReplyController.smartReplySent(entry, replyIndex, b.getText(),
+                    smartReplies.fromAssistant,
+                    NotificationLogger.getNotificationLocation(entry).toMetricsEventEnum());
             Bundle results = new Bundle();
             results.putString(smartReplies.remoteInput.getResultKey(), choice.toString());
             Intent intent = new Intent().addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
@@ -372,8 +374,17 @@
         // reply button is added.
         SmartSuggestionMeasures actionsMeasures = null;
 
+        final int maxNumActions = mConstants.getMaxNumActions();
+        int numShownActions = 0;
+
         for (View child : smartSuggestions) {
             final LayoutParams lp = (LayoutParams) child.getLayoutParams();
+            if (maxNumActions != -1 // -1 means 'no limit'
+                    && lp.buttonType == SmartButtonType.ACTION
+                    && numShownActions >= maxNumActions) {
+                // We've reached the maximum number of actions, don't add another one!
+                continue;
+            }
 
             child.setPadding(accumulatedMeasures.mButtonPaddingHorizontal, child.getPaddingTop(),
                     accumulatedMeasures.mButtonPaddingHorizontal, child.getPaddingBottom());
@@ -457,6 +468,9 @@
 
             lp.show = true;
             displayedChildCount++;
+            if (lp.buttonType == SmartButtonType.ACTION) {
+                numShownActions++;
+            }
         }
 
         if (mSmartRepliesGeneratedByAssistant) {
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java
index 44ff4a7..6a3bd73 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java
@@ -73,6 +73,7 @@
     private NotificationTestHelper mNotificationTestHelper;
     private ExpandableNotificationRow mRow;
     private ExpandableNotificationRow mRow2;
+    private ExpandableNotificationRow mNoChannelRow;
 
     @Mock
     private NotificationData mNotificationData;
@@ -92,10 +93,12 @@
         mNotificationTestHelper = new NotificationTestHelper(mContext);
         mRow = mNotificationTestHelper.createBubble();
         mRow2 = mNotificationTestHelper.createBubble();
+        mNoChannelRow = mNotificationTestHelper.createBubble();
 
         // Return non-null notification data from the NEM
         when(mNotificationEntryManager.getNotificationData()).thenReturn(mNotificationData);
         when(mNotificationData.getChannel(mRow.getEntry().key)).thenReturn(mRow.getEntry().channel);
+        when(mNotificationData.getChannel(mNoChannelRow.getEntry().key)).thenReturn(null);
 
         mBubbleController = new TestableBubbleController(mContext, mStatusBarWindowController);
 
@@ -184,6 +187,11 @@
         assertTrue(mRow.getEntry().showInShadeWhenBubble());
     }
 
+    @Test
+    public void testNotificationWithoutChannel() {
+        assertFalse(mBubbleController.shouldBubble(mNoChannelRow.getEntry()));
+    }
+
     static class TestableBubbleController extends BubbleController {
 
         TestableBubbleController(Context context,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/SmartReplyControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/SmartReplyControllerTest.java
index 6cca434..f34e1a6 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/SmartReplyControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/SmartReplyControllerTest.java
@@ -33,6 +33,7 @@
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 
+import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
 import com.android.internal.statusbar.IStatusBarService;
 import com.android.systemui.R;
 import com.android.systemui.SysuiTestCase;
@@ -97,7 +98,8 @@
 
     @Test
     public void testSendSmartReply_updatesRemoteInput() {
-        mSmartReplyController.smartReplySent(mEntry, TEST_CHOICE_INDEX, TEST_CHOICE_TEXT, false);
+        mSmartReplyController.smartReplySent(mEntry, TEST_CHOICE_INDEX, TEST_CHOICE_TEXT, false,
+                MetricsEvent.LOCATION_UNKNOWN);
 
         // Sending smart reply should make calls to NotificationEntryManager
         // to update the notification with reply and spinner.
@@ -107,21 +109,23 @@
 
     @Test
     public void testSendSmartReply_logsToStatusBar() throws RemoteException {
-        mSmartReplyController.smartReplySent(mEntry, TEST_CHOICE_INDEX, TEST_CHOICE_TEXT, false);
+        mSmartReplyController.smartReplySent(mEntry, TEST_CHOICE_INDEX, TEST_CHOICE_TEXT, false,
+                MetricsEvent.LOCATION_UNKNOWN);
 
         // Check we log the result to the status bar service.
         verify(mIStatusBarService).onNotificationSmartReplySent(mSbn.getKey(),
-                TEST_CHOICE_INDEX, TEST_CHOICE_TEXT, false);
+                TEST_CHOICE_INDEX, TEST_CHOICE_TEXT, false, MetricsEvent.LOCATION_UNKNOWN);
     }
 
 
     @Test
     public void testSendSmartReply_logsToStatusBar_generatedByAssistant() throws RemoteException {
-        mSmartReplyController.smartReplySent(mEntry, TEST_CHOICE_INDEX, TEST_CHOICE_TEXT, true);
+        mSmartReplyController.smartReplySent(mEntry, TEST_CHOICE_INDEX, TEST_CHOICE_TEXT, true,
+                MetricsEvent.LOCATION_UNKNOWN);
 
         // Check we log the result to the status bar service.
         verify(mIStatusBarService).onNotificationSmartReplySent(mSbn.getKey(),
-                TEST_CHOICE_INDEX, TEST_CHOICE_TEXT, true);
+                TEST_CHOICE_INDEX, TEST_CHOICE_TEXT, true, MetricsEvent.LOCATION_UNKNOWN);
     }
 
     @Test
@@ -137,14 +141,16 @@
 
     @Test
     public void testSendSmartReply_reportsSending() {
-        mSmartReplyController.smartReplySent(mEntry, TEST_CHOICE_INDEX, TEST_CHOICE_TEXT, false);
+        mSmartReplyController.smartReplySent(mEntry, TEST_CHOICE_INDEX, TEST_CHOICE_TEXT, false,
+                MetricsEvent.LOCATION_UNKNOWN);
 
         assertTrue(mSmartReplyController.isSendingSmartReply(mSbn.getKey()));
     }
 
     @Test
     public void testSendingSmartReply_afterRemove_shouldReturnFalse() {
-        mSmartReplyController.smartReplySent(mEntry, TEST_CHOICE_INDEX, TEST_CHOICE_TEXT, false);
+        mSmartReplyController.smartReplySent(mEntry, TEST_CHOICE_INDEX, TEST_CHOICE_TEXT, false,
+                MetricsEvent.LOCATION_UNKNOWN);
         mSmartReplyController.stopSending(mEntry);
 
         assertFalse(mSmartReplyController.isSendingSmartReply(mSbn.getKey()));
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/SmartReplyConstantsTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/SmartReplyConstantsTest.java
index 03b7c95..bc0f742 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/SmartReplyConstantsTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/SmartReplyConstantsTest.java
@@ -176,6 +176,19 @@
         assertFalse(mConstants.getShowInHeadsUp());
     }
 
+    @Test
+    public void testMaxNumActionsWithNoConfig() {
+        assertTrue(mConstants.isEnabled());
+        assertEquals(-1, mConstants.getMaxNumActions());
+    }
+
+    @Test
+    public void testMaxNumActionsSet() {
+        overrideSetting("enabled=true,max_num_actions=10");
+        triggerConstantsOnChange();
+        assertEquals(10, mConstants.getMaxNumActions());
+    }
+
     private void overrideSetting(String flags) {
         Settings.Global.putString(mContext.getContentResolver(),
                 Settings.Global.SMART_REPLIES_IN_NOTIFICATIONS_FLAGS, flags);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/SmartReplyViewTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/SmartReplyViewTest.java
index d1c4d01..5570122 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/SmartReplyViewTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/SmartReplyViewTest.java
@@ -45,6 +45,7 @@
 import android.widget.Button;
 import android.widget.LinearLayout;
 
+import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
 import com.android.systemui.R;
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.plugins.ActivityStarter;
@@ -117,6 +118,7 @@
         // Any number of replies are fine.
         when(mConstants.getMinNumSystemGeneratedReplies()).thenReturn(0);
         when(mConstants.getMaxSqueezeRemeasureAttempts()).thenReturn(3);
+        when(mConstants.getMaxNumActions()).thenReturn(-1);
 
         final Resources res = mContext.getResources();
         mSingleLinePaddingHorizontal = res.getDimensionPixelSize(
@@ -189,7 +191,7 @@
         setSmartReplies(TEST_CHOICES);
         mView.getChildAt(2).performClick();
         verify(mLogger).smartReplySent(mEntry, 2, TEST_CHOICES[2],
-                false /* generatedByAsssitant */);
+                false /* generatedByAsssitant */, MetricsEvent.LOCATION_UNKNOWN);
     }
 
     @Test
@@ -197,7 +199,7 @@
         setSmartReplies(TEST_CHOICES, true);
         mView.getChildAt(2).performClick();
         verify(mLogger).smartReplySent(mEntry, 2, TEST_CHOICES[2],
-                true /* generatedByAsssitant */);
+                true /* generatedByAsssitant */, MetricsEvent.LOCATION_UNKNOWN);
     }
 
     @Test
@@ -1027,4 +1029,66 @@
         // smart actions
         assertReplyButtonShownWithEqualMeasures(expectedView.getChildAt(0), mView.getChildAt(1));
     }
+
+    /**
+     * Test that we don't show more than the maximum number of actions declared in {@link
+     * SmartReplyConstants}.
+     */
+    @Test
+    public void testMeasure_maxNumActions() {
+        when(mConstants.getMaxNumActions()).thenReturn(2);
+
+        String[] choices = new String[] {};
+        String[] actions = new String[] {"a1", "a2", "a3", "a4"};
+
+        // All replies should be displayed as single-line smart reply buttons.
+        ViewGroup expectedView = buildExpectedView(new String[] {},
+                1 /* lineCount */, createActions(new String[] {"a1", "a2"}));
+        expectedView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
+
+        setSmartRepliesAndActions(choices, actions);
+        mView.measure(
+                MeasureSpec.makeMeasureSpec(expectedView.getMeasuredWidth(), MeasureSpec.AT_MOST),
+                MeasureSpec.UNSPECIFIED);
+
+        assertEqualMeasures(expectedView, mView);
+        assertReplyButtonShownWithEqualMeasures(
+                expectedView.getChildAt(0), mView.getChildAt(0)); // a1
+        assertReplyButtonShownWithEqualMeasures(
+                expectedView.getChildAt(1), mView.getChildAt(1)); // a2
+        assertReplyButtonHidden(mView.getChildAt(2)); // a3
+        assertReplyButtonHidden(mView.getChildAt(3)); // a4
+    }
+
+    /**
+     * Test that setting maximum number of actions to -1 means there's no limit to number of actions
+     * to show.
+     */
+    @Test
+    public void testMeasure_maxNumActions_noLimit() {
+        when(mConstants.getMaxNumActions()).thenReturn(-1);
+
+        String[] choices = new String[] {};
+        String[] actions = new String[] {"a1", "a2", "a3", "a4"};
+
+        // All replies should be displayed as single-line smart reply buttons.
+        ViewGroup expectedView = buildExpectedView(new String[] {},
+                1 /* lineCount */, createActions(new String[] {"a1", "a2", "a3", "a4"}));
+        expectedView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
+
+        setSmartRepliesAndActions(choices, actions);
+        mView.measure(
+                MeasureSpec.makeMeasureSpec(expectedView.getMeasuredWidth(), MeasureSpec.AT_MOST),
+                MeasureSpec.UNSPECIFIED);
+
+        assertEqualMeasures(expectedView, mView);
+        assertReplyButtonShownWithEqualMeasures(
+                expectedView.getChildAt(0), mView.getChildAt(0)); // a1
+        assertReplyButtonShownWithEqualMeasures(
+                expectedView.getChildAt(1), mView.getChildAt(1)); // a2
+        assertReplyButtonShownWithEqualMeasures(
+                expectedView.getChildAt(2), mView.getChildAt(2)); // a3
+        assertReplyButtonShownWithEqualMeasures(
+                expectedView.getChildAt(3), mView.getChildAt(3)); // a4
+    }
 }
diff --git a/packages/overlays/FontNotoSerifSourceOverlay/Android.mk b/packages/overlays/FontNotoSerifSourceOverlay/Android.mk
new file mode 100644
index 0000000..6f3c4f7
--- /dev/null
+++ b/packages/overlays/FontNotoSerifSourceOverlay/Android.mk
@@ -0,0 +1,31 @@
+#
+#  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.
+#
+
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_RRO_THEME := FontNotoSerifSource
+LOCAL_CERTIFICATE := platform
+LOCAL_PRODUCT_MODULE := true
+
+LOCAL_SRC_FILES := $(call all-subdir-java-files)
+
+LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res
+
+LOCAL_PACKAGE_NAME := FontNotoSerifSourceOverlay
+LOCAL_SDK_VERSION := current
+
+include $(BUILD_RRO_PACKAGE)
diff --git a/packages/overlays/FontNotoSerifSourceOverlay/AndroidManifest.xml b/packages/overlays/FontNotoSerifSourceOverlay/AndroidManifest.xml
new file mode 100644
index 0000000..54b8dbf
--- /dev/null
+++ b/packages/overlays/FontNotoSerifSourceOverlay/AndroidManifest.xml
@@ -0,0 +1,31 @@
+<!--
+/**
+ * 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.
+ */
+-->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.android.theme.font.notoserifsource"
+    android:versionCode="1"
+    android:versionName="1.0">
+    <overlay android:targetPackage="android"
+        android:category="android.theme.customization.font"
+        android:priority="1"/>
+
+    <application android:label="@string/font_notoserif_source_overlay" android:hasCode="false">
+        <meta-data
+            android:name="android.theme.customization.REQUIRED_SYSTEM_FONTS"
+            android:value="serif,serif-bold,source-sans-pro,source-sans-pro-medium" />
+    </application>
+</manifest>
diff --git a/packages/overlays/FontNotoSerifSourceOverlay/res/values/config.xml b/packages/overlays/FontNotoSerifSourceOverlay/res/values/config.xml
new file mode 100644
index 0000000..e63bea0
--- /dev/null
+++ b/packages/overlays/FontNotoSerifSourceOverlay/res/values/config.xml
@@ -0,0 +1,28 @@
+<!--
+/**
+ * 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.
+ */
+-->
+<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+     <!-- Name of a font family to use for body text. -->
+    <string name="config_bodyFontFamily" translatable="false">source-sans-pro</string>
+    <!-- Name of a font family to use for medium body text. -->
+    <string name="config_bodyFontFamilyMedium" translatable="false">source-sans-pro-semi-bold</string>
+    <!-- Name of a font family to use for headlines. If empty, falls back to platform default -->
+    <string name="config_headlineFontFamily" translatable="false">serif</string>
+    <!-- Name of the font family used for system surfaces where the font should use medium weight -->
+    <string name="config_headlineFontFamilyMedium" translatable="false">serif-bold</string>
+</resources>
+
diff --git a/packages/overlays/FontNotoSerifSourceOverlay/res/values/strings.xml b/packages/overlays/FontNotoSerifSourceOverlay/res/values/strings.xml
new file mode 100644
index 0000000..ab839c2
--- /dev/null
+++ b/packages/overlays/FontNotoSerifSourceOverlay/res/values/strings.xml
@@ -0,0 +1,21 @@
+<!--
+/**
+ * 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.
+ */
+-->
+<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <!-- Headline / Body font Noto Serif / Source Sans Pro overlay -->
+    <string name="font_notoserif_source_overlay" translatable="false">Noto Serif / Source Sans Pro</string>
+</resources>
diff --git a/packages/overlays/IconPackCircularOverlay/Android.mk b/packages/overlays/IconPackCircularOverlay/Android.mk
new file mode 100644
index 0000000..010eb81
--- /dev/null
+++ b/packages/overlays/IconPackCircularOverlay/Android.mk
@@ -0,0 +1,31 @@
+#
+#  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.
+#
+
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_RRO_THEME := IconPackCircular
+LOCAL_CERTIFICATE := platform
+LOCAL_PRODUCT_MODULE := true
+
+LOCAL_SRC_FILES := $(call all-subdir-java-files)
+
+LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res
+
+LOCAL_PACKAGE_NAME := IconPackCircularOverlay
+LOCAL_SDK_VERSION := current
+
+include $(BUILD_RRO_PACKAGE)
diff --git a/packages/overlays/IconPackCircularOverlay/AndroidManifest.xml b/packages/overlays/IconPackCircularOverlay/AndroidManifest.xml
new file mode 100644
index 0000000..6f0124d
--- /dev/null
+++ b/packages/overlays/IconPackCircularOverlay/AndroidManifest.xml
@@ -0,0 +1,24 @@
+<!--
+/**
+ * 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.
+ */
+-->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.android.theme.icon_pack.circular"
+    android:versionCode="1"
+    android:versionName="1.0">
+    <overlay android:targetPackage="android" android:category="android.theme.customization.icon_pack" android:priority="1"/>
+    <application android:label="Circular" android:hasCode="false"/>
+</manifest>
diff --git a/packages/overlays/IconPackCircularOverlay/res/drawable/ic_wifi_signal_0.xml b/packages/overlays/IconPackCircularOverlay/res/drawable/ic_wifi_signal_0.xml
new file mode 100644
index 0000000..e1ca60d
--- /dev/null
+++ b/packages/overlays/IconPackCircularOverlay/res/drawable/ic_wifi_signal_0.xml
@@ -0,0 +1,51 @@
+<!--
+/**
+ * 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.
+ */
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+    android:width="24dp"
+    android:height="24dp"
+    android:viewportWidth="24"
+    android:viewportHeight="24">
+
+    <path
+        android:pathData="M 0 0 H 24 V 24 H 0 V 0 Z" />
+    <path
+        android:pathData="M 0 0 H 24 V 24 H 0 V 0 Z" />
+    <path
+        android:fillColor="#000000"
+        android:fillAlpha="0.3"
+        android:strokeAlpha="0.3"
+        android:strokeWidth="1"
+        android:pathData="M 11.99 16.5 C 12.8184271247 16.5 13.49 17.1715728753 13.49 18 C 13.49 18.8284271247 12.8184271247 19.5 11.99 19.5 C 11.1615728753 19.5 10.49 18.8284271247 10.49 18 C 10.49 17.1715728753 11.1615728753 16.5 11.99 16.5 Z" />
+    <path
+        android:fillColor="#000000"
+        android:fillAlpha="0.3"
+        android:strokeAlpha="0.3"
+        android:strokeWidth="1"
+        android:pathData="M18.76,11.8a0.54 0.54 ,0,0,0,0.36-0.14 0.51 0.51,0,0,0,0-0.71A10.08,10.08,0,0,0,4.87,11a0.5 0.5 ,0,0,0,0,0.71 0.51 0.51,0,0,0,0.71,0,9.07,9.07,0,0,1,12.83,0A0.54 0.54 ,0,0,0,18.76,11.8Z" />
+    <path
+        android:fillColor="#000000"
+        android:fillAlpha="0.3"
+        android:strokeAlpha="0.3"
+        android:strokeWidth="1"
+        android:pathData="M2.15,8.85a0.48 0.48 ,0,0,0,0.7,0,12.8,12.8,0,0,1,18.3,0,0.48 0.48 ,0,0,0,0.7,0,0.48 0.48 ,0,0,0,0-0.7,13.77,13.77,0,0,0-19.7,0A0.48 0.48 ,0,0,0,2.15,8.85Z" />
+    <path
+        android:fillColor="#000000"
+        android:fillAlpha="0.3"
+        android:strokeAlpha="0.3"
+        android:strokeWidth="1"
+        android:pathData="M15.93,14.64a0.49 0.49 ,0,0,0,0.35-0.15 0.5 0.5,0,0,0,0-0.71,6.08,6.08,0,0,0-8.58,0,0.51 0.51 ,0,0,0,0,0.71 0.5 0.5,0,0,0,0.71,0,5.08,5.08,0,0,1,7.16,0A0.51 0.51 ,0,0,0,15.93,14.64Z" />
+</vector>
diff --git a/packages/overlays/IconPackCircularOverlay/res/drawable/ic_wifi_signal_1.xml b/packages/overlays/IconPackCircularOverlay/res/drawable/ic_wifi_signal_1.xml
new file mode 100644
index 0000000..06ac16d
--- /dev/null
+++ b/packages/overlays/IconPackCircularOverlay/res/drawable/ic_wifi_signal_1.xml
@@ -0,0 +1,49 @@
+<!--
+/**
+ * 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.
+ */
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+    android:width="24dp"
+    android:height="24dp"
+    android:viewportWidth="24"
+    android:viewportHeight="24">
+
+    <path
+        android:pathData="M 0 0 H 24 V 24 H 0 V 0 Z" />
+    <path
+        android:pathData="M 0 0 H 24 V 24 H 0 V 0 Z" />
+    <path
+        android:fillColor="#000000"
+        android:pathData="M 11.99 16.5 C 12.8184271247 16.5 13.49 17.1715728753 13.49 18 C 13.49 18.8284271247 12.8184271247 19.5 11.99 19.5 C 11.1615728753 19.5 10.49 18.8284271247 10.49 18 C 10.49 17.1715728753 11.1615728753 16.5 11.99 16.5 Z" />
+    <path
+        android:fillColor="#000000"
+        android:fillAlpha="0.3"
+        android:strokeAlpha="0.3"
+        android:strokeWidth="1"
+        android:pathData="M18.76,11.8a0.54 0.54 ,0,0,0,0.36-0.14 0.51 0.51,0,0,0,0-0.71A10.08,10.08,0,0,0,4.87,11a0.5 0.5 ,0,0,0,0,0.71 0.51 0.51,0,0,0,0.71,0,9.07,9.07,0,0,1,12.83,0A0.54 0.54 ,0,0,0,18.76,11.8Z" />
+    <path
+        android:fillColor="#000000"
+        android:fillAlpha="0.3"
+        android:strokeAlpha="0.3"
+        android:strokeWidth="1"
+        android:pathData="M21.85,8.15a13.77,13.77,0,0,0-19.7,0,0.49 0.49 ,0,0,0,0.7 0.7 ,12.8,12.8,0,0,1,18.3,0,0.48 0.48 ,0,0,0,0.7,0A0.48 0.48 ,0,0,0,21.85,8.15Z" />
+    <path
+        android:fillColor="#000000"
+        android:fillAlpha="0.3"
+        android:strokeAlpha="0.3"
+        android:strokeWidth="1"
+        android:pathData="M15.93,14.64a0.49 0.49 ,0,0,0,0.35-0.15 0.5 0.5,0,0,0,0-0.71,6.08,6.08,0,0,0-8.58,0,0.51 0.51 ,0,0,0,0,0.71 0.5 0.5,0,0,0,0.71,0,5.08,5.08,0,0,1,7.16,0A0.51 0.51 ,0,0,0,15.93,14.64Z" />
+</vector>
diff --git a/packages/overlays/IconPackCircularOverlay/res/drawable/ic_wifi_signal_2.xml b/packages/overlays/IconPackCircularOverlay/res/drawable/ic_wifi_signal_2.xml
new file mode 100644
index 0000000..844fabf
--- /dev/null
+++ b/packages/overlays/IconPackCircularOverlay/res/drawable/ic_wifi_signal_2.xml
@@ -0,0 +1,46 @@
+<!--
+/**
+ * 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.
+ */
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+    android:width="24dp"
+    android:height="24dp"
+    android:viewportWidth="24"
+    android:viewportHeight="24">
+
+    <path
+        android:pathData="M 0 0 H 24 V 24 H 0 V 0 Z" />
+    <path
+        android:pathData="M 0 0 H 24 V 24 H 0 V 0 Z" />
+    <path
+        android:fillColor="#000000"
+        android:pathData="M 11.99 16.5 C 12.8184271247 16.5 13.49 17.1715728753 13.49 18 C 13.49 18.8284271247 12.8184271247 19.5 11.99 19.5 C 11.1615728753 19.5 10.49 18.8284271247 10.49 18 C 10.49 17.1715728753 11.1615728753 16.5 11.99 16.5 Z" />
+    <path
+        android:fillColor="#000000"
+        android:fillAlpha="0.3"
+        android:strokeAlpha="0.3"
+        android:strokeWidth="1"
+        android:pathData="M18.76,11.8a0.54 0.54 ,0,0,0,0.36-0.14 0.51 0.51,0,0,0,0-0.71A10.08,10.08,0,0,0,4.87,11a0.5 0.5 ,0,0,0,0,0.71 0.51 0.51,0,0,0,0.71,0,9.07,9.07,0,0,1,12.83,0A0.54 0.54 ,0,0,0,18.76,11.8Z" />
+    <path
+        android:fillColor="#000000"
+        android:fillAlpha="0.3"
+        android:strokeAlpha="0.3"
+        android:strokeWidth="1"
+        android:pathData="M21.85,8.15a13.77,13.77,0,0,0-19.7,0,0.49 0.49 ,0,0,0,0.7 0.7 ,12.8,12.8,0,0,1,18.3,0,0.48 0.48 ,0,0,0,0.7,0A0.48 0.48 ,0,0,0,21.85,8.15Z" />
+    <path
+        android:fillColor="#000000"
+        android:pathData="M15.93,14.64a0.49 0.49 ,0,0,0,0.35-0.15 0.5 0.5,0,0,0,0-0.71,6.08,6.08,0,0,0-8.58,0,0.51 0.51 ,0,0,0,0,0.71 0.5 0.5,0,0,0,0.71,0,5.07,5.07,0,0,1,7.16,0A0.51 0.51 ,0,0,0,15.93,14.64Z" />
+</vector>
diff --git a/packages/overlays/IconPackCircularOverlay/res/drawable/ic_wifi_signal_3.xml b/packages/overlays/IconPackCircularOverlay/res/drawable/ic_wifi_signal_3.xml
new file mode 100644
index 0000000..3a01032
--- /dev/null
+++ b/packages/overlays/IconPackCircularOverlay/res/drawable/ic_wifi_signal_3.xml
@@ -0,0 +1,43 @@
+<!--
+/**
+ * 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.
+ */
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+    android:width="24dp"
+    android:height="24dp"
+    android:viewportWidth="24"
+    android:viewportHeight="24">
+
+    <path
+        android:pathData="M 0 0 H 24 V 24 H 0 V 0 Z" />
+    <path
+        android:pathData="M 0 0 H 24 V 24 H 0 V 0 Z" />
+    <path
+        android:fillColor="#000000"
+        android:pathData="M 11.99 16.5 C 12.8184271247 16.5 13.49 17.1715728753 13.49 18 C 13.49 18.8284271247 12.8184271247 19.5 11.99 19.5 C 11.1615728753 19.5 10.49 18.8284271247 10.49 18 C 10.49 17.1715728753 11.1615728753 16.5 11.99 16.5 Z" />
+    <path
+        android:fillColor="#000000"
+        android:pathData="M18.76,11.8a0.54 0.54 ,0,0,0,0.36-0.14 0.51 0.51,0,0,0,0-0.71A10.08,10.08,0,0,0,4.87,11a0.5 0.5 ,0,0,0,0,0.71 0.51 0.51,0,0,0,0.71,0,9.07,9.07,0,0,1,12.83,0A0.54 0.54 ,0,0,0,18.76,11.8Z" />
+    <path
+        android:fillColor="#000000"
+        android:fillAlpha="0.3"
+        android:strokeAlpha="0.3"
+        android:strokeWidth="1"
+        android:pathData="M21.5,9a0.47 0.47 ,0,0,0,0.35-0.15 0.48 0.48,0,0,0,0-0.7,13.77,13.77,0,0,0-19.7,0,0.49 0.49 ,0,0,0,0.7 0.7 ,12.8,12.8,0,0,1,18.3,0A0.47 0.47 ,0,0,0,21.5,9Z" />
+    <path
+        android:fillColor="#000000"
+        android:pathData="M15.93,14.64a0.49 0.49 ,0,0,0,0.35-0.15 0.5 0.5,0,0,0,0-0.71,6.08,6.08,0,0,0-8.58,0,0.51 0.51 ,0,0,0,0,0.71 0.5 0.5,0,0,0,0.71,0,5.07,5.07,0,0,1,7.16,0A0.51 0.51 ,0,0,0,15.93,14.64Z" />
+</vector>
diff --git a/packages/overlays/IconPackCircularOverlay/res/drawable/ic_wifi_signal_4.xml b/packages/overlays/IconPackCircularOverlay/res/drawable/ic_wifi_signal_4.xml
new file mode 100644
index 0000000..3512d44ad
--- /dev/null
+++ b/packages/overlays/IconPackCircularOverlay/res/drawable/ic_wifi_signal_4.xml
@@ -0,0 +1,40 @@
+<!--
+/**
+ * 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.
+ */
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+    android:width="24dp"
+    android:height="24dp"
+    android:viewportWidth="24"
+    android:viewportHeight="24">
+
+    <path
+        android:pathData="M 0 0 H 24 V 24 H 0 V 0 Z" />
+    <path
+        android:pathData="M 0 0 H 24 V 24 H 0 V 0 Z" />
+    <path
+        android:fillColor="#000000"
+        android:pathData="M 11.99 16.5 C 12.8184271247 16.5 13.49 17.1715728753 13.49 18 C 13.49 18.8284271247 12.8184271247 19.5 11.99 19.5 C 11.1615728753 19.5 10.49 18.8284271247 10.49 18 C 10.49 17.1715728753 11.1615728753 16.5 11.99 16.5 Z" />
+    <path
+        android:fillColor="#000000"
+        android:pathData="M18.76,11.8a0.54 0.54 ,0,0,0,0.36-0.14 0.51 0.51,0,0,0,0-0.71A10.08,10.08,0,0,0,4.87,11a0.5 0.5 ,0,0,0,0,0.71 0.51 0.51,0,0,0,0.71,0,9.07,9.07,0,0,1,12.83,0A0.54 0.54 ,0,0,0,18.76,11.8Z" />
+    <path
+        android:fillColor="#000000"
+        android:pathData="M21.5,9a0.47 0.47 ,0,0,0,0.35-0.15 0.48 0.48,0,0,0,0-0.7,13.77,13.77,0,0,0-19.7,0,0.49 0.49 ,0,0,0,0.7 0.7 ,12.8,12.8,0,0,1,18.3,0A0.47 0.47 ,0,0,0,21.5,9Z" />
+    <path
+        android:fillColor="#000000"
+        android:pathData="M15.93,14.64a0.49 0.49 ,0,0,0,0.35-0.15 0.5 0.5,0,0,0,0-0.71,6.08,6.08,0,0,0-8.58,0,0.51 0.51 ,0,0,0,0,0.71 0.5 0.5,0,0,0,0.71,0,5.08,5.08,0,0,1,7.16,0A0.51 0.51 ,0,0,0,15.93,14.64Z" />
+</vector>
diff --git a/packages/overlays/IconPackFilledOverlay/Android.mk b/packages/overlays/IconPackFilledOverlay/Android.mk
new file mode 100644
index 0000000..14bc1d6
--- /dev/null
+++ b/packages/overlays/IconPackFilledOverlay/Android.mk
@@ -0,0 +1,30 @@
+#
+#  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.
+#
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_RRO_THEME := IconPackFilled
+LOCAL_CERTIFICATE := platform
+LOCAL_PRODUCT_MODULE := true
+
+LOCAL_SRC_FILES := $(call all-subdir-java-files)
+
+LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res
+
+LOCAL_PACKAGE_NAME := IconPackFilledOverlay
+LOCAL_SDK_VERSION := current
+
+include $(BUILD_RRO_PACKAGE)
diff --git a/packages/overlays/IconPackFilledOverlay/AndroidManifest.xml b/packages/overlays/IconPackFilledOverlay/AndroidManifest.xml
new file mode 100644
index 0000000..bf507cd
--- /dev/null
+++ b/packages/overlays/IconPackFilledOverlay/AndroidManifest.xml
@@ -0,0 +1,24 @@
+<!--
+/**
+ * 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.
+ */
+-->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.android.theme.icon_pack.filled"
+    android:versionCode="1"
+    android:versionName="1.0">
+    <overlay android:targetPackage="android" android:category="android.theme.customization.icon_pack" android:priority="1"/>
+    <application android:label="Filled" android:hasCode="false"/>
+</manifest>
diff --git a/packages/overlays/IconPackFilledOverlay/res/drawable/ic_wifi_signal_0.xml b/packages/overlays/IconPackFilledOverlay/res/drawable/ic_wifi_signal_0.xml
new file mode 100644
index 0000000..7ff3d08
--- /dev/null
+++ b/packages/overlays/IconPackFilledOverlay/res/drawable/ic_wifi_signal_0.xml
@@ -0,0 +1,32 @@
+<!--
+/**
+ * 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.
+ */
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+    android:width="24dp"
+    android:height="24dp"
+    android:viewportWidth="24"
+    android:viewportHeight="24">
+
+    <path
+        android:pathData="M 0 0 H 24 V 24 H 0 V 0 Z" />
+    <path
+        android:fillColor="#000000"
+        android:fillAlpha="0.3"
+        android:strokeAlpha="0.3"
+        android:strokeWidth="1"
+        android:pathData="M23.66,8.11a1.06,1.06,0,0,0-0.22-1.54A20.58,20.58,0,0,0,12,3,20.55,20.55,0,0,0,0.56,6.57,1.07,1.07,0,0,0,0.33,8.11L11.16,21.6a1.07,1.07,0,0,0,1.66,0Z" />
+</vector>
diff --git a/packages/overlays/IconPackFilledOverlay/res/drawable/ic_wifi_signal_1.xml b/packages/overlays/IconPackFilledOverlay/res/drawable/ic_wifi_signal_1.xml
new file mode 100644
index 0000000..f83e6d5
--- /dev/null
+++ b/packages/overlays/IconPackFilledOverlay/res/drawable/ic_wifi_signal_1.xml
@@ -0,0 +1,35 @@
+<!--
+/**
+ * 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.
+ */
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+    android:width="24dp"
+    android:height="24dp"
+    android:viewportWidth="24"
+    android:viewportHeight="24">
+
+    <path
+        android:pathData="M 0 0 H 24 V 24 H 0 V 0 Z" />
+    <path
+        android:fillColor="#000000"
+        android:fillAlpha="0.3"
+        android:strokeAlpha="0.3"
+        android:strokeWidth="1"
+        android:pathData="M23.66,8.11a1.06,1.06,0,0,0-0.22-1.54A20.58,20.58,0,0,0,12,3,20.55,20.55,0,0,0,0.56,6.57,1.07,1.07,0,0,0,0.33,8.11L11.16,21.6a1.07,1.07,0,0,0,1.66,0Z" />
+    <path
+        android:fillColor="#000000"
+        android:pathData="M12.82,21.6l5.11-6.36a9,9,0,0,0-11.87,0l5.1,6.35A1.07,1.07,0,0,0,12.82,21.6Z" />
+</vector>
diff --git a/packages/overlays/IconPackFilledOverlay/res/drawable/ic_wifi_signal_2.xml b/packages/overlays/IconPackFilledOverlay/res/drawable/ic_wifi_signal_2.xml
new file mode 100644
index 0000000..2bcaf2a
--- /dev/null
+++ b/packages/overlays/IconPackFilledOverlay/res/drawable/ic_wifi_signal_2.xml
@@ -0,0 +1,35 @@
+<!--
+/**
+ * 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.
+ */
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+    android:width="24dp"
+    android:height="24dp"
+    android:viewportWidth="24"
+    android:viewportHeight="24">
+
+    <path
+        android:pathData="M 0 0 H 24 V 24 H 0 V 0 Z" />
+    <path
+        android:fillColor="#000000"
+        android:fillAlpha="0.3"
+        android:strokeAlpha="0.3"
+        android:strokeWidth="1"
+        android:pathData="M23.66,8.11a1.06,1.06,0,0,0-0.22-1.54A20.58,20.58,0,0,0,12,3,20.55,20.55,0,0,0,0.56,6.57,1.07,1.07,0,0,0,0.33,8.11L11.16,21.6a1.07,1.07,0,0,0,1.66,0Z" />
+    <path
+        android:fillColor="#000000"
+        android:pathData="M12.82,21.6l7-8.7a12,12,0,0,0-15.63,0l7,8.7A1.07,1.07,0,0,0,12.82,21.6Z" />
+</vector>
diff --git a/packages/overlays/IconPackFilledOverlay/res/drawable/ic_wifi_signal_3.xml b/packages/overlays/IconPackFilledOverlay/res/drawable/ic_wifi_signal_3.xml
new file mode 100644
index 0000000..82b4c9d
--- /dev/null
+++ b/packages/overlays/IconPackFilledOverlay/res/drawable/ic_wifi_signal_3.xml
@@ -0,0 +1,35 @@
+<!--
+/**
+ * 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.
+ */
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+    android:width="24dp"
+    android:height="24dp"
+    android:viewportWidth="24"
+    android:viewportHeight="24">
+
+    <path
+        android:pathData="M 0 0 H 24 V 24 H 0 V 0 Z" />
+    <path
+        android:fillColor="#000000"
+        android:fillAlpha="0.3"
+        android:strokeAlpha="0.3"
+        android:strokeWidth="1"
+        android:pathData="M23.66,8.11a1.06,1.06,0,0,0-0.22-1.54A20.58,20.58,0,0,0,12,3,20.55,20.55,0,0,0,0.56,6.57,1.07,1.07,0,0,0,0.33,8.11L11.16,21.6a1.07,1.07,0,0,0,1.66,0Z" />
+    <path
+        android:fillColor="#000000"
+        android:pathData="M12.82,21.6l8.25-10.26a14,14,0,0,0-18.14,0l8.23,10.26A1.07,1.07,0,0,0,12.82,21.6Z" />
+</vector>
diff --git a/packages/overlays/IconPackFilledOverlay/res/drawable/ic_wifi_signal_4.xml b/packages/overlays/IconPackFilledOverlay/res/drawable/ic_wifi_signal_4.xml
new file mode 100644
index 0000000..45cf95f
--- /dev/null
+++ b/packages/overlays/IconPackFilledOverlay/res/drawable/ic_wifi_signal_4.xml
@@ -0,0 +1,29 @@
+<!--
+/**
+ * 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.
+ */
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+    android:width="24dp"
+    android:height="24dp"
+    android:viewportWidth="24"
+    android:viewportHeight="24">
+
+    <path
+        android:pathData="M 0 0 H 24 V 24 H 0 V 0 Z" />
+    <path
+        android:fillColor="#000000"
+        android:pathData="M12,3A20.55,20.55,0,0,0,0.56,6.57,1.07,1.07,0,0,0,0.33,8.11L11.16,21.6a1.07,1.07,0,0,0,1.66,0L23.66,8.11a1.06,1.06,0,0,0-0.22-1.54A20.58,20.58,0,0,0,12,3Z" />
+</vector>
diff --git a/packages/overlays/IconPackRoundedOverlay/Android.mk b/packages/overlays/IconPackRoundedOverlay/Android.mk
new file mode 100644
index 0000000..075ed28
--- /dev/null
+++ b/packages/overlays/IconPackRoundedOverlay/Android.mk
@@ -0,0 +1,30 @@
+#
+#  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.
+#
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_RRO_THEME := IconPackRounded
+LOCAL_CERTIFICATE := platform
+LOCAL_PRODUCT_MODULE := true
+
+LOCAL_SRC_FILES := $(call all-subdir-java-files)
+
+LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res
+
+LOCAL_PACKAGE_NAME := IconPackRoundedOverlay
+LOCAL_SDK_VERSION := current
+
+include $(BUILD_RRO_PACKAGE)
diff --git a/packages/overlays/IconPackRoundedOverlay/AndroidManifest.xml b/packages/overlays/IconPackRoundedOverlay/AndroidManifest.xml
new file mode 100644
index 0000000..8014733
--- /dev/null
+++ b/packages/overlays/IconPackRoundedOverlay/AndroidManifest.xml
@@ -0,0 +1,24 @@
+<!--
+/**
+ * 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.
+ */
+-->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.android.theme.icon_pack.rounded"
+    android:versionCode="1"
+    android:versionName="1.0">
+    <overlay android:targetPackage="android" android:category="android.theme.customization.icon_pack" android:priority="1"/>
+    <application android:label="Rounded" android:hasCode="false"/>
+</manifest>
diff --git a/packages/overlays/IconPackRoundedOverlay/res/drawable/ic_wifi_signal_0.xml b/packages/overlays/IconPackRoundedOverlay/res/drawable/ic_wifi_signal_0.xml
new file mode 100644
index 0000000..089974d
--- /dev/null
+++ b/packages/overlays/IconPackRoundedOverlay/res/drawable/ic_wifi_signal_0.xml
@@ -0,0 +1,50 @@
+<!--
+/**
+ * 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.
+ */
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+    android:width="24dp"
+    android:height="24dp"
+    android:viewportWidth="24"
+    android:viewportHeight="24">
+
+    <path
+        android:pathData="M 0 0 H 24 V 24 H 0 V 0 Z" />
+    <path
+        android:fillColor="#000000"
+        android:fillAlpha="0.3"
+        android:strokeAlpha="0.3"
+        android:strokeWidth="1"
+        android:pathData="M22.8,7.25a0.73 0.73 ,0,0,1,0,1l0,0a0.83 0.83 ,0,0,1-1.05,0,13.16,13.16,0,0,0-9.7-4,13.34,13.34,0,0,0-9.7,4,0.72 0.72 ,0,0,1-1,0l0,0a0.76 0.76 ,0,0,1,0-1.05A14.77,14.77,0,0,1,12,2.8,14.51,14.51,0,0,1,22.8,7.25Z" />
+    <path
+        android:fillColor="#000000"
+        android:fillAlpha="0.3"
+        android:strokeAlpha="0.3"
+        android:strokeWidth="1"
+        android:pathData="M8.3,14.8a0.73 0.73 ,0,0,1-1,0l0,0a0.76 0.76 ,0,0,1,0-1,6.73,6.73,0,0,1,9.52,0l0,0h0a0.75 0.75 ,0,0,1,0.12,1.05 0.75 0.75,0,0,1-1.05 0.12 l-0.07-0.07a0,0,0,0,1-0.05,0h0A5.28,5.28,0,0,0,8.3,14.8Z" />
+    <path
+        android:fillColor="#000000"
+        android:fillAlpha="0.3"
+        android:strokeAlpha="0.3"
+        android:strokeWidth="1"
+        android:pathData="M20.05,10.75A0.74 0.74 ,0,0,1,19,11.8h0a10.15,10.15,0,0,0-6.95-3,9.93,9.93,0,0,0-7,3,0.74 0.74 ,0,0,1-1-1.05,11.36,11.36,0,0,1,8.05-3.5A11.43,11.43,0,0,1,20.05,10.75Z" />
+    <path
+        android:fillColor="#000000"
+        android:fillAlpha="0.3"
+        android:strokeAlpha="0.3"
+        android:strokeWidth="1"
+        android:pathData="M 12 17 C 12.8284271247 17 13.5 17.6715728753 13.5 18.5 C 13.5 19.3284271247 12.8284271247 20 12 20 C 11.1715728753 20 10.5 19.3284271247 10.5 18.5 C 10.5 17.6715728753 11.1715728753 17 12 17 Z" />
+</vector>
diff --git a/packages/overlays/IconPackRoundedOverlay/res/drawable/ic_wifi_signal_1.xml b/packages/overlays/IconPackRoundedOverlay/res/drawable/ic_wifi_signal_1.xml
new file mode 100644
index 0000000..e51879e
--- /dev/null
+++ b/packages/overlays/IconPackRoundedOverlay/res/drawable/ic_wifi_signal_1.xml
@@ -0,0 +1,47 @@
+<!--
+/**
+ * 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.
+ */
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+    android:width="24dp"
+    android:height="24dp"
+    android:viewportWidth="24"
+    android:viewportHeight="24">
+
+    <path
+        android:pathData="M 0 0 H 24 V 24 H 0 V 0 Z" />
+    <path
+        android:fillColor="#000000"
+        android:fillAlpha="0.3"
+        android:strokeAlpha="0.3"
+        android:strokeWidth="1"
+        android:pathData="M16.77,13.71a6.74,6.74,0,0,0-9.54,0,0.75 0.75 ,0,0,0,1.06,1.06h0a5.25,5.25,0,0,1,7.42,0h0a0.08 0.08 ,0,0,1,0,0,0.75 0.75 ,0,0,0,1.17-1,0.8 0.8 ,0,0,0-0.17-0.15Z" />
+    <path
+        android:fillColor="#000000"
+        android:pathData="M 12 17 C 12.8284271247 17 13.5 17.6715728753 13.5 18.5 C 13.5 19.3284271247 12.8284271247 20 12 20 C 11.1715728753 20 10.5 19.3284271247 10.5 18.5 C 10.5 17.6715728753 11.1715728753 17 12 17 Z" />
+    <path
+        android:fillColor="#000000"
+        android:fillAlpha="0.3"
+        android:strokeAlpha="0.3"
+        android:strokeWidth="1"
+        android:pathData="M20,10.73a11.51,11.51,0,0,0-8-3.5,11.55,11.55,0,0,0-8,3.5 0.75 0.75,0,0,0,0.95,1.15A0.38 0.38 ,0,0,0,5,11.77a10.12,10.12,0,0,1,7-3,10.1,10.1,0,0,1,7,3,0.75 0.75 ,0,0,0,1.06,0,0.77 0.77 ,0,0,0,0-1.07Z" />
+    <path
+        android:fillColor="#000000"
+        android:fillAlpha="0.3"
+        android:strokeAlpha="0.3"
+        android:strokeWidth="1"
+        android:pathData="M22.79,7.23A14.76,14.76,0,0,0,12,2.75,14.72,14.72,0,0,0,1.23,7.2a0.75 0.75 ,0,0,0,1.07,1,13.25,13.25,0,0,1,9.7-4,13.27,13.27,0,0,1,9.72,4,0.75 0.75 ,0,0,0,1.07-1Z" />
+</vector>
diff --git a/packages/overlays/IconPackRoundedOverlay/res/drawable/ic_wifi_signal_2.xml b/packages/overlays/IconPackRoundedOverlay/res/drawable/ic_wifi_signal_2.xml
new file mode 100644
index 0000000..77343af
--- /dev/null
+++ b/packages/overlays/IconPackRoundedOverlay/res/drawable/ic_wifi_signal_2.xml
@@ -0,0 +1,44 @@
+<!--
+/**
+ * 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.
+ */
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+    android:width="24dp"
+    android:height="24dp"
+    android:viewportWidth="24"
+    android:viewportHeight="24">
+
+    <path
+        android:pathData="M 0 0 H 24 V 24 H 0 V 0 Z" />
+    <path
+        android:fillColor="#000000"
+        android:pathData="M16.77,13.71a6.74,6.74,0,0,0-9.54,0,0.75 0.75 ,0,0,0,1.06,1.06h0a5.25,5.25,0,0,1,7.42,0h0a0.08 0.08 ,0,0,1,0,0,0.75 0.75 ,0,0,0,1.17-1,0.8 0.8 ,0,0,0-0.17-0.15Z" />
+    <path
+        android:fillColor="#000000"
+        android:pathData="M 12 17 C 12.8284271247 17 13.5 17.6715728753 13.5 18.5 C 13.5 19.3284271247 12.8284271247 20 12 20 C 11.1715728753 20 10.5 19.3284271247 10.5 18.5 C 10.5 17.6715728753 11.1715728753 17 12 17 Z" />
+    <path
+        android:fillColor="#000000"
+        android:fillAlpha="0.3"
+        android:strokeAlpha="0.3"
+        android:strokeWidth="1"
+        android:pathData="M20,10.73a11.51,11.51,0,0,0-8-3.5,11.55,11.55,0,0,0-8,3.5 0.75 0.75,0,0,0,0.95,1.15A0.38 0.38 ,0,0,0,5,11.77a10.12,10.12,0,0,1,7-3,10.1,10.1,0,0,1,7,3,0.75 0.75 ,0,0,0,1.06,0,0.77 0.77 ,0,0,0,0-1.07Z" />
+    <path
+        android:fillColor="#000000"
+        android:fillAlpha="0.3"
+        android:strokeAlpha="0.3"
+        android:strokeWidth="1"
+        android:pathData="M22.79,7.23A14.76,14.76,0,0,0,12,2.75,14.72,14.72,0,0,0,1.23,7.2a0.75 0.75 ,0,0,0,1.07,1,13.25,13.25,0,0,1,9.7-4,13.27,13.27,0,0,1,9.72,4,0.75 0.75 ,0,0,0,1.07-1Z" />
+</vector>
diff --git a/packages/overlays/IconPackRoundedOverlay/res/drawable/ic_wifi_signal_3.xml b/packages/overlays/IconPackRoundedOverlay/res/drawable/ic_wifi_signal_3.xml
new file mode 100644
index 0000000..0b89382
--- /dev/null
+++ b/packages/overlays/IconPackRoundedOverlay/res/drawable/ic_wifi_signal_3.xml
@@ -0,0 +1,41 @@
+<!--
+/**
+ * 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.
+ */
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+    android:width="24dp"
+    android:height="24dp"
+    android:viewportWidth="24"
+    android:viewportHeight="24">
+
+    <path
+        android:pathData="M 0 0 H 24 V 24 H 0 V 0 Z" />
+    <path
+        android:fillColor="#000000"
+        android:pathData="M16.77,13.71a6.74,6.74,0,0,0-9.54,0,0.75 0.75 ,0,0,0,1.06,1.06h0a5.25,5.25,0,0,1,7.42,0h0a0.08 0.08 ,0,0,1,0,0,0.75 0.75 ,0,0,0,1.17-1,0.8 0.8 ,0,0,0-0.17-0.15Z" />
+    <path
+        android:fillColor="#000000"
+        android:pathData="M 12 17 C 12.8284271247 17 13.5 17.6715728753 13.5 18.5 C 13.5 19.3284271247 12.8284271247 20 12 20 C 11.1715728753 20 10.5 19.3284271247 10.5 18.5 C 10.5 17.6715728753 11.1715728753 17 12 17 Z" />
+    <path
+        android:fillColor="#000000"
+        android:pathData="M20,10.73a11.51,11.51,0,0,0-8-3.5,11.55,11.55,0,0,0-8,3.5 0.75 0.75,0,0,0,0.95,1.15A0.38 0.38 ,0,0,0,5,11.77a10.12,10.12,0,0,1,7-3,10.1,10.1,0,0,1,7,3,0.75 0.75 ,0,0,0,1.06,0,0.77 0.77 ,0,0,0,0-1.07Z" />
+    <path
+        android:fillColor="#000000"
+        android:fillAlpha="0.3"
+        android:strokeAlpha="0.3"
+        android:strokeWidth="1"
+        android:pathData="M22.79,7.23A14.76,14.76,0,0,0,12,2.75,14.72,14.72,0,0,0,1.23,7.2a0.75 0.75 ,0,0,0,1.07,1,13.25,13.25,0,0,1,9.7-4,13.27,13.27,0,0,1,9.72,4,0.75 0.75 ,0,0,0,1.07-1Z" />
+</vector>
diff --git a/packages/overlays/IconPackRoundedOverlay/res/drawable/ic_wifi_signal_4.xml b/packages/overlays/IconPackRoundedOverlay/res/drawable/ic_wifi_signal_4.xml
new file mode 100644
index 0000000..f02bc83
--- /dev/null
+++ b/packages/overlays/IconPackRoundedOverlay/res/drawable/ic_wifi_signal_4.xml
@@ -0,0 +1,38 @@
+<!--
+/**
+ * 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.
+ */
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+    android:width="24dp"
+    android:height="24dp"
+    android:viewportWidth="24"
+    android:viewportHeight="24">
+
+    <path
+        android:pathData="M 0 0 H 24 V 24 H 0 V 0 Z" />
+    <path
+        android:fillColor="#000000"
+        android:pathData="M20,11.79a0.77 0.77 ,0,0,0,0-1.07h0a11.59,11.59,0,0,0-8-3.5,11.63,11.63,0,0,0-8,3.5 0.77 0.77,0,0,0,0,1.07 0.76 0.76,0,0,0,1.07,0,10.12,10.12,0,0,1,7-3,10.12,10.12,0,0,1,7,3A0.75 0.75 ,0,0,0,20,11.79Z" />
+    <path
+        android:fillColor="#000000"
+        android:pathData="M15.78,14.82a0.57 0.57 ,0,0,0,0.16 0.15 0.75 0.75 ,0,0,0,1-0.2 0.76 0.76,0,0,0-0.2-1,6.77,6.77,0,0,0-9.55,0,0.76 0.76 ,0,0,0,0,1,0.75 0.75 ,0,0,0,1.06,0h0a5.24,5.24,0,0,1,7.42,0A0.08 0.08 ,0,0,0,15.78,14.82Z" />
+    <path
+        android:fillColor="#000000"
+        android:pathData="M 12 17 C 12.8284271247 17 13.5 17.6715728753 13.5 18.5 C 13.5 19.3284271247 12.8284271247 20 12 20 C 11.1715728753 20 10.5 19.3284271247 10.5 18.5 C 10.5 17.6715728753 11.1715728753 17 12 17 Z" />
+    <path
+        android:fillColor="#000000"
+        android:pathData="M2.3,8.25a13.25,13.25,0,0,1,9.7-4,13.27,13.27,0,0,1,9.72,4,0.73 0.73 ,0,0,0,1,0,0.75 0.75 ,0,0,0,0.05-1.06A14.76,14.76,0,0,0,12,2.75,14.76,14.76,0,0,0,1.22,7.2a0.77 0.77 ,0,0,0,0,1A0.75 0.75 ,0,0,0,2.3,8.25Z" />
+</vector>
diff --git a/proto/src/wifi.proto b/proto/src/wifi.proto
index 542f069..84647a6 100644
--- a/proto/src/wifi.proto
+++ b/proto/src/wifi.proto
@@ -33,11 +33,11 @@
   // Number of open networks in the saved networks.
   optional int32 num_open_networks = 3;
 
-  // Number of personal networks.
-  optional int32 num_personal_networks = 4;
+  // Number of legacy personal networks.
+  optional int32 num_legacy_personal_networks = 4;
 
-  // Number of enterprise networks.
-  optional int32 num_enterprise_networks = 5;
+  // Number of legacy enterprise networks.
+  optional int32 num_legacy_enterprise_networks = 5;
 
   // Does the user have location setting enabled.
   optional bool is_location_enabled = 6;
@@ -206,11 +206,11 @@
   // Total number of scan results for open networks
   optional int32 num_open_network_scan_results = 40;
 
-  // Total number of scan results for personal networks
-  optional int32 num_personal_network_scan_results = 41;
+  // Total number of scan results for legacy personal networks
+  optional int32 num_legacy_personal_network_scan_results = 41;
 
-  // Total number of scan results for enterprise networks
-  optional int32 num_enterprise_network_scan_results = 42;
+  // Total number of scan results for legacy enterprise networks
+  optional int32 num_legacy_enterprise_network_scan_results = 42;
 
   // Total number of scan results for hidden networks
   optional int32 num_hidden_network_scan_results = 43;
@@ -497,6 +497,24 @@
 
   // Easy Connect (DPP) metrics
   optional WifiDppLog wifi_dpp_log = 130;
+
+  // Number of Enhanced Open (OWE) networks in the saved networks.
+  optional int32 num_enhanced_open_networks = 131;
+
+  // Number of WPA3-Personal networks.
+  optional int32 num_wpa3_personal_networks = 132;
+
+  // Number of WPA3-Enterprise networks.
+  optional int32 num_wpa3_enterprise_networks = 133;
+
+  // Total number of scan results for Enhanced open networks
+  optional int32 num_enhanced_open_network_scan_results = 134;
+
+  // Total number of scan results for WPA3-Personal networks
+  optional int32 num_wpa3_personal_network_scan_results = 135;
+
+  // Total number of scan results for WPA3-Enterprise networks
+  optional int32 num_wpa3_enterprise_network_scan_results = 136;
 }
 
 // Information that gets logged for every WiFi connection.
diff --git a/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureManagerService.java b/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureManagerService.java
index 6108aaa..75ee99f 100644
--- a/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureManagerService.java
+++ b/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureManagerService.java
@@ -20,10 +20,16 @@
 import static android.content.Context.CONTENT_CAPTURE_MANAGER_SERVICE;
 
 import android.annotation.NonNull;
+import android.annotation.Nullable;
 import android.annotation.UserIdInt;
 import android.app.ActivityManagerInternal;
 import android.content.ComponentName;
+import android.content.ContentResolver;
 import android.content.Context;
+import android.content.pm.PackageManager;
+import android.content.pm.PackageManager.NameNotFoundException;
+import android.content.pm.UserInfo;
+import android.database.ContentObserver;
 import android.os.Binder;
 import android.os.Bundle;
 import android.os.IBinder;
@@ -32,8 +38,11 @@
 import android.os.ShellCallback;
 import android.os.UserHandle;
 import android.os.UserManager;
+import android.provider.Settings;
 import android.util.LocalLog;
 import android.util.Slog;
+import android.util.SparseBooleanArray;
+import android.view.contentcapture.ContentCaptureManager;
 import android.view.contentcapture.IContentCaptureManager;
 import android.view.contentcapture.UserDataRemovalRequest;
 
@@ -49,6 +58,7 @@
 import java.io.FileDescriptor;
 import java.io.PrintWriter;
 import java.util.ArrayList;
+import java.util.List;
 
 /**
  * A service used to observe the contents of the screen.
@@ -60,23 +70,43 @@
 public final class ContentCaptureManagerService extends
         AbstractMasterSystemService<ContentCaptureManagerService, ContentCapturePerUserService> {
 
-    private static final String TAG = ContentCaptureManagerService.class.getSimpleName();
-
     static final String RECEIVER_BUNDLE_EXTRA_SESSIONS = "sessions";
 
     private static final int MAX_TEMP_SERVICE_DURATION_MS = 1_000 * 60 * 2; // 2 minutes
 
-    @GuardedBy("mLock")
-    private ActivityManagerInternal mAm;
-
     private final LocalService mLocalService = new LocalService();
 
     private final LocalLog mRequestsHistory = new LocalLog(20);
 
+    @GuardedBy("mLock")
+    private ActivityManagerInternal mAm;
+
+    /**
+     * Users disabled by {@link android.provider.Settings.Secure#CONTENT_CAPTURE_ENABLED}.
+     */
+    @GuardedBy("mLock")
+    @Nullable
+    private SparseBooleanArray mDisabledUsers;
+
+
     public ContentCaptureManagerService(@NonNull Context context) {
         super(context, new FrameworkResourcesServiceNameResolver(context,
                 com.android.internal.R.string.config_defaultContentCaptureService),
                 UserManager.DISALLOW_CONTENT_CAPTURE);
+        // Sets which serviecs are disabled
+        final UserManager um = getContext().getSystemService(UserManager.class);
+        final List<UserInfo> users = um.getUsers();
+        for (int i = 0; i < users.size(); i++) {
+            final int userId = users.get(i).id;
+            final boolean disabled = isDisabledBySettings(userId);
+            if (disabled) {
+                Slog.i(mTag, "user " + userId + " disabled by settings");
+                if (mDisabledUsers == null) {
+                    mDisabledUsers = new SparseBooleanArray(1);
+                }
+                mDisabledUsers.put(userId, true);
+            }
+        }
     }
 
     @Override // from AbstractMasterSystemService
@@ -100,7 +130,7 @@
 
     @Override // from AbstractMasterSystemService
     protected void enforceCallingPermissionForManagement() {
-        getContext().enforceCallingPermission(MANAGE_CONTENT_CAPTURE, TAG);
+        getContext().enforceCallingPermission(MANAGE_CONTENT_CAPTURE, mTag);
     }
 
     @Override // from AbstractMasterSystemService
@@ -108,9 +138,86 @@
         return MAX_TEMP_SERVICE_DURATION_MS;
     }
 
+    @Override // from AbstractMasterSystemService
+    protected void registerForExtraSettingsChanges(@NonNull ContentResolver resolver,
+            @NonNull ContentObserver observer) {
+        resolver.registerContentObserver(Settings.Secure.getUriFor(
+                Settings.Secure.CONTENT_CAPTURE_ENABLED), false, observer,
+                UserHandle.USER_ALL);
+    }
+
+    @Override // from AbstractMasterSystemService
+    protected void onSettingsChanged(@UserIdInt int userId, @NonNull String property) {
+        switch (property) {
+            case Settings.Secure.CONTENT_CAPTURE_ENABLED:
+                setContentCaptureFeatureEnabledFromSettings(userId);
+                return;
+            default:
+                Slog.w(mTag, "Unexpected property (" + property + "); updating cache instead");
+        }
+    }
+
+    @Override // from AbstractMasterSystemService
+    protected boolean isDisabledLocked(@UserIdInt int userId) {
+        return isDisabledBySettingsLocked(userId) || super.isDisabledLocked(userId);
+    }
+
+    private boolean isDisabledBySettingsLocked(@UserIdInt int userId) {
+        return mDisabledUsers != null && mDisabledUsers.get(userId);
+    }
+
+    private void setContentCaptureFeatureEnabledFromSettings(@UserIdInt int userId) {
+        setContentCaptureFeatureEnabledForUser(userId, !isDisabledBySettings(userId));
+    }
+
+    private boolean isDisabledBySettings(@UserIdInt int userId) {
+        final String property = Settings.Secure.CONTENT_CAPTURE_ENABLED;
+        final String value = Settings.Secure.getStringForUser(getContext().getContentResolver(),
+                property, userId);
+        if (value == null) {
+            if (verbose) {
+                Slog.v(mTag, "isDisabledBySettings(): assuming false as '" + property
+                        + "' is not set");
+            }
+            return false;
+        }
+
+        try {
+            return !Boolean.valueOf(value);
+        } catch (Exception e) {
+            Slog.w(mTag, "Invalid value for property " + property + ": " + value);
+        }
+        return false;
+    }
+
+    private void setContentCaptureFeatureEnabledForUser(@UserIdInt int userId, boolean enabled) {
+        synchronized (mLock) {
+            if (mDisabledUsers == null) {
+                mDisabledUsers = new SparseBooleanArray();
+            }
+            final boolean alreadyEnabled = !mDisabledUsers.get(userId);
+            if (!(enabled ^ alreadyEnabled)) {
+                if (debug) {
+                    Slog.d(mTag, "setContentCaptureFeatureEnabledForUser(): already " + enabled);
+                }
+                return;
+            }
+            if (enabled) {
+                Slog.i(mTag, "setContentCaptureFeatureEnabled(): enabling service for user "
+                        + userId);
+                mDisabledUsers.delete(userId);
+            } else {
+                Slog.i(mTag, "setContentCaptureFeatureEnabled(): disabling service for user "
+                        + userId);
+                mDisabledUsers.put(userId, true);
+            }
+            updateCachedServiceLocked(userId, !enabled);
+        }
+    }
+
     // Called by Shell command.
     void destroySessions(@UserIdInt int userId, @NonNull IResultReceiver receiver) {
-        Slog.i(TAG, "destroySessions() for userId " + userId);
+        Slog.i(mTag, "destroySessions() for userId " + userId);
         enforceCallingPermissionForManagement();
 
         synchronized (mLock) {
@@ -133,7 +240,7 @@
 
     // Called by Shell command.
     void listSessions(int userId, IResultReceiver receiver) {
-        Slog.i(TAG, "listSessions() for userId " + userId);
+        Slog.i(mTag, "listSessions() for userId " + userId);
         enforceCallingPermissionForManagement();
 
         final Bundle resultData = new Bundle();
@@ -174,6 +281,64 @@
         return mAm;
     }
 
+    @GuardedBy("mLock")
+    private boolean assertCalledByServiceLocked(@NonNull String methodName, @UserIdInt int userId,
+            int callingUid, @NonNull IResultReceiver result) {
+        final boolean isService = isCalledByServiceLocked(methodName, userId, callingUid);
+        if (isService) return true;
+
+        try {
+            result.send(ContentCaptureManager.RESULT_CODE_NOT_SERVICE,
+                    /* resultData= */ null);
+        } catch (RemoteException e) {
+            Slog.w(mTag, "Unable to send isContentCaptureFeatureEnabled(): " + e);
+        }
+        return false;
+    }
+
+    @GuardedBy("mLock")
+    private boolean isCalledByServiceLocked(@NonNull String methodName, @UserIdInt int userId,
+            int callingUid) {
+
+        final String serviceName = mServiceNameResolver.getServiceName(userId);
+        if (serviceName == null) {
+            Slog.e(mTag, methodName + ": called by UID " + callingUid
+                    + ", but there's no service set for user " + userId);
+            return false;
+        }
+
+        final ComponentName serviceComponent  = ComponentName.unflattenFromString(serviceName);
+        if (serviceComponent == null) {
+            Slog.w(mTag, methodName + ": invalid service name: " + serviceName);
+            return false;
+        }
+
+        final String servicePackageName = serviceComponent.getPackageName();
+
+        final PackageManager pm = getContext().getPackageManager();
+        final int serviceUid;
+        try {
+            serviceUid = pm.getPackageUidAsUser(servicePackageName, UserHandle.getCallingUserId());
+        } catch (NameNotFoundException e) {
+            Slog.w(mTag, methodName + ": could not verify UID for " + serviceName);
+            return false;
+        }
+        if (callingUid != serviceUid) {
+            Slog.e(mTag, methodName + ": called by UID " + callingUid + ", but service UID is "
+                    + serviceUid);
+            return false;
+        }
+
+        return true;
+    }
+
+    @Override // from AbstractMasterSystemService
+    protected void dumpLocked(String prefix, PrintWriter pw) {
+        super.dumpLocked(prefix, pw);
+
+        pw.print(prefix); pw.print("Disabled users: "); pw.println(mDisabledUsers);
+    }
+
     final class ContentCaptureManagerServiceStub extends IContentCaptureManager.Stub {
 
         @Override
@@ -222,8 +387,7 @@
                 result.send(/* resultCode= */ 0,
                         SyncResultReceiver.bundleFor(connectedServiceComponentName));
             } catch (RemoteException e) {
-                // Ignore exception as we need to be resilient against app behavior.
-                Slog.w(TAG, "Unable to send service component name: " + e);
+                Slog.w(mTag, "Unable to send service component name: " + e);
             }
         }
 
@@ -238,8 +402,52 @@
         }
 
         @Override
+        public void isContentCaptureFeatureEnabled(@NonNull IResultReceiver result) {
+            final int userId = UserHandle.getCallingUserId();
+            boolean enabled;
+            synchronized (mLock) {
+                final boolean isService = assertCalledByServiceLocked(
+                        "isContentCaptureFeatureEnabled()", userId, Binder.getCallingUid(), result);
+                if (!isService) return;
+
+                enabled = !isDisabledBySettingsLocked(userId);
+            }
+            try {
+                result.send(enabled ? ContentCaptureManager.RESULT_CODE_TRUE
+                        : ContentCaptureManager.RESULT_CODE_FALSE, /* resultData= */null);
+            } catch (RemoteException e) {
+                Slog.w(mTag, "Unable to send isContentCaptureFeatureEnabled(): " + e);
+            }
+        }
+
+        @Override
+        public void setContentCaptureFeatureEnabled(boolean enabled,
+                @NonNull IResultReceiver result) {
+            final int userId = UserHandle.getCallingUserId();
+            final boolean isService;
+            synchronized (mLock) {
+                isService = assertCalledByServiceLocked("setContentCaptureFeatureEnabled()", userId,
+                        Binder.getCallingUid(), result);
+            }
+            if (!isService) return;
+
+            final long token = Binder.clearCallingIdentity();
+            try {
+                Settings.Secure.putStringForUser(getContext().getContentResolver(),
+                        Settings.Secure.CONTENT_CAPTURE_ENABLED, Boolean.toString(enabled), userId);
+            } finally {
+                Binder.restoreCallingIdentity(token);
+            }
+            try {
+                result.send(ContentCaptureManager.RESULT_CODE_TRUE, /* resultData= */null);
+            } catch (RemoteException e) {
+                Slog.w(mTag, "Unable to send setContentCaptureFeatureEnabled(): " + e);
+            }
+        }
+
+        @Override
         public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
-            if (!DumpUtils.checkDumpPermission(getContext(), TAG, pw)) return;
+            if (!DumpUtils.checkDumpPermission(getContext(), mTag, pw)) return;
 
             boolean showHistory = true;
             if (args != null) {
@@ -252,7 +460,7 @@
                             pw.println("Usage: dumpsys content_capture [--no-history]");
                             return;
                         default:
-                            Slog.w(TAG, "Ignoring invalid dump arg: " + arg);
+                            Slog.w(mTag, "Ignoring invalid dump arg: " + arg);
                     }
                 }
             }
diff --git a/services/core/java/com/android/server/TelephonyRegistry.java b/services/core/java/com/android/server/TelephonyRegistry.java
index 10b126f..2f1510e 100644
--- a/services/core/java/com/android/server/TelephonyRegistry.java
+++ b/services/core/java/com/android/server/TelephonyRegistry.java
@@ -52,6 +52,7 @@
 import android.telephony.TelephonyManager;
 import android.telephony.data.ApnSetting;
 import android.telephony.emergency.EmergencyNumber;
+import android.telephony.ims.ImsReasonInfo;
 import android.util.LocalLog;
 import android.util.StatsLog;
 
@@ -227,6 +228,8 @@
 
     private int mCallDisconnectCause = DisconnectCause.NOT_VALID;
 
+    private List<ImsReasonInfo> mImsReasonInfo = null;
+
     private int mCallPreciseDisconnectCause = PreciseDisconnectCause.NOT_VALID;
 
     private boolean mCarrierNetworkChangeState = false;
@@ -377,6 +380,7 @@
         mCellLocation = new Bundle[numPhones];
         mCellInfo = new ArrayList<List<CellInfo>>();
         mSrvccState = new int[numPhones];
+        mImsReasonInfo = new ArrayList<ImsReasonInfo>();
         mPhysicalChannelConfigs = new ArrayList<List<PhysicalChannelConfig>>();
         mEmergencyNumberList = new HashMap<>();
         for (int i = 0; i < numPhones; i++) {
@@ -394,6 +398,7 @@
             mCallForwarding[i] =  false;
             mCellLocation[i] = new Bundle();
             mCellInfo.add(i, null);
+            mImsReasonInfo.add(i, null);
             mSrvccState[i] = TelephonyManager.SRVCC_STATE_HANDOVER_NONE;
             mPhysicalChannelConfigs.add(i, new ArrayList<PhysicalChannelConfig>());
         }
@@ -739,6 +744,13 @@
                             remove(r.binder);
                         }
                     }
+                    if ((events & PhoneStateListener.LISTEN_IMS_CALL_DISCONNECT_CAUSES) != 0) {
+                        try {
+                            r.callback.onImsCallDisconnectCauseChanged(mImsReasonInfo.get(phoneId));
+                        } catch (RemoteException ex) {
+                            remove(r.binder);
+                        }
+                    }
                     if ((events & PhoneStateListener.LISTEN_PRECISE_DATA_CONNECTION_STATE) != 0) {
                         try {
                             r.callback.onPreciseDataConnectionStateChanged(
@@ -1591,6 +1603,34 @@
         }
     }
 
+    public void notifyImsDisconnectCause(int subId, ImsReasonInfo imsReasonInfo) {
+        if (!checkNotifyPermission("notifyImsCallDisconnectCause()")) {
+            return;
+        }
+        int phoneId = SubscriptionManager.getPhoneId(subId);
+        synchronized (mRecords) {
+            if (validatePhoneId(phoneId)) {
+                mImsReasonInfo.set(phoneId, imsReasonInfo);
+                for (Record r : mRecords) {
+                    if (r.matchPhoneStateListenerEvent(
+                            PhoneStateListener.LISTEN_IMS_CALL_DISCONNECT_CAUSES)
+                            && idMatch(r.subId, subId, phoneId)) {
+                        try {
+                            if (DBG_LOC) {
+                                log("notifyImsCallDisconnectCause: mImsReasonInfo="
+                                        + imsReasonInfo + " r=" + r);
+                            }
+                            r.callback.onImsCallDisconnectCauseChanged(mImsReasonInfo.get(phoneId));
+                        } catch (RemoteException ex) {
+                            mRemoveList.add(r.binder);
+                        }
+                    }
+                }
+            }
+            handleRemoveListLocked();
+        }
+    }
+
     public void notifyPreciseDataConnectionFailed(String apnType,
             String apn, @DataFailCause.FailCause int failCause) {
         if (!checkNotifyPermission("notifyPreciseDataConnectionFailed()")) {
@@ -1627,7 +1667,7 @@
         int phoneId = SubscriptionManager.getPhoneId(subId);
         synchronized (mRecords) {
             if (validatePhoneId(phoneId)) {
-                mSrvccState[phoneId]  = state;
+                mSrvccState[phoneId] = state;
                 for (Record r : mRecords) {
                     if (r.matchPhoneStateListenerEvent(
                             PhoneStateListener.LISTEN_SRVCC_STATE_CHANGED) &&
@@ -1837,6 +1877,7 @@
                 pw.println("mDataConnectionState=" + mDataConnectionState[i]);
                 pw.println("mCellLocation=" + mCellLocation[i]);
                 pw.println("mCellInfo=" + mCellInfo.get(i));
+                pw.println("mImsCallDisconnectCause=" + mImsReasonInfo.get(i).toString());
                 pw.decreaseIndent();
             }
             pw.println("mPreciseDataConnectionState=" + mPreciseDataConnectionState);
@@ -2126,6 +2167,11 @@
                     android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE, null);
         }
 
+        if ((events & PhoneStateListener.LISTEN_IMS_CALL_DISCONNECT_CAUSES) != 0) {
+            mContext.enforceCallingOrSelfPermission(
+                    android.Manifest.permission.READ_PRECISE_PHONE_STATE, null);
+        }
+
         return true;
     }
 
diff --git a/services/core/java/com/android/server/am/ActiveServices.java b/services/core/java/com/android/server/am/ActiveServices.java
index 5d6c2f0..15d7efb 100644
--- a/services/core/java/com/android/server/am/ActiveServices.java
+++ b/services/core/java/com/android/server/am/ActiveServices.java
@@ -1438,14 +1438,16 @@
 
     private void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
         boolean anyForeground = false;
-        for (int i=proc.services.size()-1; i>=0; i--) {
+        int fgServiceTypes = 0;
+        for (int i = proc.services.size() - 1; i >= 0; i--) {
             ServiceRecord sr = proc.services.valueAt(i);
             if (sr.isForeground || sr.fgRequired) {
                 anyForeground = true;
+                fgServiceTypes |= sr.serviceInfo.mForegroundServiceType;
                 break;
             }
         }
-        mAm.updateProcessForegroundLocked(proc, anyForeground, oomAdj);
+        mAm.updateProcessForegroundLocked(proc, anyForeground, fgServiceTypes, oomAdj);
     }
 
     private void updateWhitelistManagerLocked(ProcessRecord proc) {
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index d9f3c02..ffed2e0 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -4559,7 +4559,7 @@
         app.curAdj = app.setAdj = app.verifiedAdj = ProcessList.INVALID_ADJ;
         app.setCurrentSchedulingGroup(app.setSchedGroup = ProcessList.SCHED_GROUP_DEFAULT);
         app.forcingToImportant = null;
-        updateProcessForegroundLocked(app, false, false);
+        updateProcessForegroundLocked(app, false, 0, false);
         app.hasShownUi = false;
         app.setDebugging(false);
         app.cached = false;
@@ -5335,7 +5335,7 @@
                     return;
                 }
                 pr.forcingToImportant = null;
-                updateProcessForegroundLocked(pr, false, false);
+                updateProcessForegroundLocked(pr, false, 0, false);
             }
             updateOomAdjLocked();
         }
@@ -13249,7 +13249,7 @@
         app.makeInactive(mProcessStats);
         app.waitingToKill = null;
         app.forcingToImportant = null;
-        updateProcessForegroundLocked(app, false, false);
+        updateProcessForegroundLocked(app, false, 0, false);
         app.setHasForegroundActivities(false);
         app.hasShownUi = false;
         app.treatLikeActivity = false;
@@ -16118,9 +16118,12 @@
 
     @GuardedBy("this")
     final void updateProcessForegroundLocked(ProcessRecord proc, boolean isForeground,
-            boolean oomAdj) {
-        if (isForeground != proc.hasForegroundServices()) {
-            proc.setHasForegroundServices(isForeground);
+            int fgServiceTypes, boolean oomAdj) {
+        final boolean hasFgServiceLocationType =
+                (fgServiceTypes & ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION) != 0;
+        if (isForeground != proc.hasForegroundServices()
+                || proc.hasLocationForegroundServices() != hasFgServiceLocationType) {
+            proc.setHasForegroundServices(isForeground, fgServiceTypes);
             ArrayList<ProcessRecord> curProcs = mForegroundPackages.get(proc.info.packageName,
                     proc.info.uid);
             if (isForeground) {
diff --git a/services/core/java/com/android/server/am/BroadcastDispatcher.java b/services/core/java/com/android/server/am/BroadcastDispatcher.java
index 0d46379..6371cd3 100644
--- a/services/core/java/com/android/server/am/BroadcastDispatcher.java
+++ b/services/core/java/com/android/server/am/BroadcastDispatcher.java
@@ -312,7 +312,7 @@
         final Intent intent = r.intent;
         // Any in-flight broadcast has already been popped, and cannot be replaced.
         // (This preserves existing behavior of the replacement API)
-        for (int i = list.size() - 1; i >= 0; i++) {
+        for (int i = list.size() - 1; i >= 0; i--) {
             old = list.get(i);
             if (old.userId == r.userId && intent.filterEquals(old.intent)) {
                 if (DEBUG_BROADCAST) {
diff --git a/services/core/java/com/android/server/am/CarUserSwitchingDialog.java b/services/core/java/com/android/server/am/CarUserSwitchingDialog.java
index 7599afa..c7de7b1 100644
--- a/services/core/java/com/android/server/am/CarUserSwitchingDialog.java
+++ b/services/core/java/com/android/server/am/CarUserSwitchingDialog.java
@@ -65,7 +65,9 @@
         setCancelable(false);
         Resources res = getContext().getResources();
         // Custom view due to alignment and font size requirements
-        View view = LayoutInflater.from(getContext()).inflate(R.layout.car_user_switching_dialog,
+        getContext().setTheme(R.style.Theme_DeviceDefault_Light_Dialog_Alert_UserSwitchingDialog);
+        View view = LayoutInflater.from(getContext()).inflate(
+                R.layout.car_user_switching_dialog,
                 null);
 
         UserManager userManager =
diff --git a/services/core/java/com/android/server/am/OomAdjuster.java b/services/core/java/com/android/server/am/OomAdjuster.java
index 1e03f6c..6e8646e 100644
--- a/services/core/java/com/android/server/am/OomAdjuster.java
+++ b/services/core/java/com/android/server/am/OomAdjuster.java
@@ -897,11 +897,13 @@
         }
 
         if (adj > ProcessList.PERCEPTIBLE_APP_ADJ
-                || procState > ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) {
+                || procState > ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE_LOCATION) {
             if (app.hasForegroundServices()) {
                 // The user is aware of this app, so make it visible.
                 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
-                procState = ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
+                procState = app.hasLocationForegroundServices()
+                        ? ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE_LOCATION
+                        : ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
                 app.cached = false;
                 app.adjType = "fg-service";
                 schedGroup = ProcessList.SCHED_GROUP_DEFAULT;
@@ -1507,6 +1509,7 @@
             switch (procState) {
                 case ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE:
                 case ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE:
+                case ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE_LOCATION:
                     // Something else is keeping it at this level, just leave it.
                     break;
                 case ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND:
diff --git a/services/core/java/com/android/server/am/ProcessList.java b/services/core/java/com/android/server/am/ProcessList.java
index 003ddd1..c2e7763 100644
--- a/services/core/java/com/android/server/am/ProcessList.java
+++ b/services/core/java/com/android/server/am/ProcessList.java
@@ -738,6 +738,9 @@
             case ActivityManager.PROCESS_STATE_TOP:
                 procState = "TOP ";
                 break;
+            case ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE_LOCATION:
+                procState = "FGSL";
+                break;
             case ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE:
                 procState = "FGS ";
                 break;
@@ -804,10 +807,11 @@
                 return AppProtoEnums.PROCESS_STATE_PERSISTENT_UI;
             case ActivityManager.PROCESS_STATE_TOP:
                 return AppProtoEnums.PROCESS_STATE_TOP;
-            case ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE:
-                return AppProtoEnums.PROCESS_STATE_BOUND_FOREGROUND_SERVICE;
+            case ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE_LOCATION:
             case ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE:
                 return AppProtoEnums.PROCESS_STATE_FOREGROUND_SERVICE;
+            case ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE:
+                return AppProtoEnums.PROCESS_STATE_BOUND_FOREGROUND_SERVICE;
             case ActivityManager.PROCESS_STATE_TOP_SLEEPING:
                 return AppProtoEnums.PROCESS_STATE_TOP_SLEEPING;
             case ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND:
@@ -932,6 +936,7 @@
         PROC_MEM_PERSISTENT,            // ActivityManager.PROCESS_STATE_PERSISTENT
         PROC_MEM_PERSISTENT,            // ActivityManager.PROCESS_STATE_PERSISTENT_UI
         PROC_MEM_TOP,                   // ActivityManager.PROCESS_STATE_TOP
+        PROC_MEM_IMPORTANT,             // ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE_LOCATION
         PROC_MEM_IMPORTANT,             // ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
         PROC_MEM_IMPORTANT,             // ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
         PROC_MEM_IMPORTANT,             // ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND
diff --git a/services/core/java/com/android/server/am/ProcessRecord.java b/services/core/java/com/android/server/am/ProcessRecord.java
index 054c830..7e52463 100644
--- a/services/core/java/com/android/server/am/ProcessRecord.java
+++ b/services/core/java/com/android/server/am/ProcessRecord.java
@@ -31,6 +31,7 @@
 import android.content.ComponentName;
 import android.content.Context;
 import android.content.pm.ApplicationInfo;
+import android.content.pm.ServiceInfo;
 import android.content.res.CompatibilityInfo;
 import android.os.Binder;
 import android.os.Debug;
@@ -169,6 +170,7 @@
     private boolean mHasClientActivities;  // Are there any client services with activities?
     boolean hasStartedServices; // Are there any started services running in this process?
     private boolean mHasForegroundServices; // Running any services that are foreground?
+    private int mFgServiceTypes; // Type of foreground service, if there is a foreground service.
     private boolean mHasForegroundActivities; // Running any activities that are foreground?
     boolean repForegroundActivities; // Last reported foreground activities.
     boolean systemNoUi;         // This is a system process, but not currently showing UI.
@@ -1051,8 +1053,9 @@
         return mRequiredAbi;
     }
 
-    void setHasForegroundServices(boolean hasForegroundServices) {
+    void setHasForegroundServices(boolean hasForegroundServices, int fgServiceTypes) {
         mHasForegroundServices = hasForegroundServices;
+        mFgServiceTypes = fgServiceTypes;
         mWindowProcessController.setHasForegroundServices(hasForegroundServices);
     }
 
@@ -1060,6 +1063,11 @@
         return mHasForegroundServices;
     }
 
+    boolean hasLocationForegroundServices() {
+        return mHasForegroundServices
+                && (mFgServiceTypes & ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION) != 0;
+    }
+
     void setHasForegroundActivities(boolean hasForegroundActivities) {
         mHasForegroundActivities = hasForegroundActivities;
         mWindowProcessController.setHasForegroundActivities(hasForegroundActivities);
diff --git a/services/core/java/com/android/server/appop/AppOpsService.java b/services/core/java/com/android/server/appop/AppOpsService.java
index 26d2d17..0e33090 100644
--- a/services/core/java/com/android/server/appop/AppOpsService.java
+++ b/services/core/java/com/android/server/appop/AppOpsService.java
@@ -22,6 +22,7 @@
 import static android.app.AppOpsManager.UID_STATE_CACHED;
 import static android.app.AppOpsManager.UID_STATE_FOREGROUND;
 import static android.app.AppOpsManager.UID_STATE_FOREGROUND_SERVICE;
+import static android.app.AppOpsManager.UID_STATE_FOREGROUND_SERVICE_LOCATION;
 import static android.app.AppOpsManager.UID_STATE_LAST_NON_RESTRICTED;
 import static android.app.AppOpsManager.UID_STATE_PERSISTENT;
 import static android.app.AppOpsManager.UID_STATE_TOP;
@@ -141,6 +142,8 @@
         UID_STATE_PERSISTENT,           // ActivityManager.PROCESS_STATE_PERSISTENT
         UID_STATE_PERSISTENT,           // ActivityManager.PROCESS_STATE_PERSISTENT_UI
         UID_STATE_TOP,                  // ActivityManager.PROCESS_STATE_TOP
+        UID_STATE_FOREGROUND_SERVICE_LOCATION,
+                                        // ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE_LOCATION
         UID_STATE_FOREGROUND_SERVICE,   // ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
         UID_STATE_FOREGROUND,           // ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
         UID_STATE_FOREGROUND,           // ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND
@@ -163,6 +166,7 @@
     static final String[] UID_STATE_NAMES = new String[] {
             "pers ",    // UID_STATE_PERSISTENT
             "top  ",    // UID_STATE_TOP
+            "fgsvcl",   // UID_STATE_FOREGROUND_SERVICE_LOCATION
             "fgsvc",    // UID_STATE_FOREGROUND_SERVICE
             "fg   ",    // UID_STATE_FOREGROUND
             "bg   ",    // UID_STATE_BACKGROUND
@@ -172,6 +176,7 @@
     static final String[] UID_STATE_TIME_ATTRS = new String[] {
             "tp",       // UID_STATE_PERSISTENT
             "tt",       // UID_STATE_TOP
+            "tfsl",     // UID_STATE_FOREGROUND_SERVICE_LOCATION
             "tfs",      // UID_STATE_FOREGROUND_SERVICE
             "tf",       // UID_STATE_FOREGROUND
             "tb",       // UID_STATE_BACKGROUND
@@ -181,6 +186,7 @@
     static final String[] UID_STATE_REJECT_ATTRS = new String[] {
             "rp",       // UID_STATE_PERSISTENT
             "rt",       // UID_STATE_TOP
+            "rfsl",     // UID_STATE_FOREGROUND_SERVICE_LOCATION
             "rfs",      // UID_STATE_FOREGROUND_SERVICE
             "rf",       // UID_STATE_FOREGROUND
             "rb",       // UID_STATE_BACKGROUND
@@ -843,7 +849,7 @@
     public void updateUidProcState(int uid, int procState) {
         synchronized (this) {
             final UidState uidState = getUidStateLocked(uid, true);
-            final int newState = PROCESS_STATE_TO_UID_STATE[procState];
+            int newState = PROCESS_STATE_TO_UID_STATE[procState];
             if (uidState != null && uidState.pendingState != newState) {
                 final int oldPendingState = uidState.pendingState;
                 uidState.pendingState = newState;
@@ -2791,9 +2797,13 @@
                         case "tt":
                             op.time[AppOpsManager.UID_STATE_TOP] = Long.parseLong(value);
                             break;
+                        case "tfsl":
+                            op.time[AppOpsManager.UID_STATE_FOREGROUND_SERVICE_LOCATION] =
+                                    Long.parseLong(value);
+                            break;
                         case "tfs":
-                            op.time[AppOpsManager.UID_STATE_FOREGROUND_SERVICE]
-                                    = Long.parseLong(value);
+                            op.time[AppOpsManager.UID_STATE_FOREGROUND_SERVICE] =
+                                    Long.parseLong(value);
                             break;
                         case "tf":
                             op.time[AppOpsManager.UID_STATE_FOREGROUND] = Long.parseLong(value);
@@ -2805,27 +2815,31 @@
                             op.time[AppOpsManager.UID_STATE_CACHED] = Long.parseLong(value);
                             break;
                         case "rp":
-                            op.rejectTime[AppOpsManager.UID_STATE_PERSISTENT]
-                                    = Long.parseLong(value);
+                            op.rejectTime[AppOpsManager.UID_STATE_PERSISTENT] =
+                                    Long.parseLong(value);
                             break;
                         case "rt":
                             op.rejectTime[AppOpsManager.UID_STATE_TOP] = Long.parseLong(value);
                             break;
+                        case "rfsl":
+                            op.rejectTime[AppOpsManager.UID_STATE_FOREGROUND_SERVICE_LOCATION] =
+                                    Long.parseLong(value);
+                            break;
                         case "rfs":
-                            op.rejectTime[AppOpsManager.UID_STATE_FOREGROUND_SERVICE]
-                                    = Long.parseLong(value);
+                            op.rejectTime[AppOpsManager.UID_STATE_FOREGROUND_SERVICE] =
+                                    Long.parseLong(value);
                             break;
                         case "rf":
-                            op.rejectTime[AppOpsManager.UID_STATE_FOREGROUND]
-                                    = Long.parseLong(value);
+                            op.rejectTime[AppOpsManager.UID_STATE_FOREGROUND] =
+                                    Long.parseLong(value);
                             break;
                         case "rb":
-                            op.rejectTime[AppOpsManager.UID_STATE_BACKGROUND]
-                                    = Long.parseLong(value);
+                            op.rejectTime[AppOpsManager.UID_STATE_BACKGROUND] =
+                                    Long.parseLong(value);
                             break;
                         case "rc":
-                            op.rejectTime[AppOpsManager.UID_STATE_CACHED]
-                                    = Long.parseLong(value);
+                            op.rejectTime[AppOpsManager.UID_STATE_CACHED] =
+                                    Long.parseLong(value);
                             break;
                         case "t":
                             // Backwards compat.
diff --git a/services/core/java/com/android/server/incident/IncidentCompanionService.java b/services/core/java/com/android/server/incident/IncidentCompanionService.java
new file mode 100644
index 0000000..3ebba00
--- /dev/null
+++ b/services/core/java/com/android/server/incident/IncidentCompanionService.java
@@ -0,0 +1,545 @@
+/*
+ * Copyright (C) 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 com.android.server.incident;
+
+import android.app.ActivityManager;
+import android.app.AppOpsManager;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.content.pm.UserInfo;
+import android.net.Uri;
+import android.os.Binder;
+import android.os.Handler;
+import android.os.IIncidentAuthListener;
+import android.os.IIncidentCompanion;
+import android.os.IncidentManager;
+import android.os.RemoteException;
+import android.os.SystemClock;
+import android.os.UserHandle;
+import android.os.UserManager;
+import android.util.Log;
+
+import com.android.internal.util.DumpUtils;
+import com.android.server.SystemService;
+
+import java.io.FileDescriptor;
+import java.io.PrintWriter;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+// TODO: User changes should deny everything that's pending.
+
+/**
+ * Helper service for incidentd and dumpstated to provide user feedback
+ * and authorization for bug and inicdent reports to be taken.
+ */
+public class IncidentCompanionService extends SystemService {
+    static final String TAG = "IncidentCompanionService";
+
+    private final Handler mHandler = new Handler();
+    private final RequestQueue mRequestQueue = new RequestQueue(mHandler);
+    private final PackageManager mPackageManager;
+    private final AppOpsManager mAppOpsManager;
+
+    //
+    // All fields below must be protected by mLock
+    //
+    private final Object mLock = new Object();
+    private final ArrayList<PendingReportRec> mPending = new ArrayList();
+
+    /**
+     * The next ID we'll use when we make a PendingReportRec.
+     */
+    private int mNextPendingId = 1;
+
+    /**
+     * One for each authorization that's pending.
+     */
+    private final class PendingReportRec {
+        public int id;
+        public String callingPackage;
+        public int flags;
+        public IIncidentAuthListener listener;
+        public long addedRealtime;
+        public long addedWalltime;
+
+        /**
+         * Construct a PendingReportRec, with an auto-incremented id.
+         */
+        PendingReportRec(String callingPackage, int flags, IIncidentAuthListener listener) {
+            this.id = mNextPendingId++;
+            this.callingPackage = callingPackage;
+            this.flags = flags;
+            this.listener = listener;
+            this.addedRealtime = SystemClock.elapsedRealtime();
+            this.addedWalltime = System.currentTimeMillis();
+        }
+
+        /**
+         * Get the Uri that contains the flattened data.
+         */
+        Uri getUri() {
+            return (new Uri.Builder())
+                    .scheme(IncidentManager.URI_SCHEME)
+                    .authority(IncidentManager.URI_AUTHORITY)
+                    .path(IncidentManager.URI_PATH)
+                    .appendQueryParameter(IncidentManager.URI_PARAM_ID, Integer.toString(id))
+                    .appendQueryParameter(IncidentManager.URI_PARAM_CALLING_PACKAGE, callingPackage)
+                    .appendQueryParameter(IncidentManager.URI_PARAM_FLAGS, Integer.toString(flags))
+                    .appendQueryParameter(IncidentManager.URI_PARAM_TIMESTAMP,
+                            Long.toString(addedWalltime))
+                    .build();
+        }
+    }
+
+    /**
+     * Implementation of the IIncidentCompanion binder interface.
+     */
+    private final class BinderService extends IIncidentCompanion.Stub {
+        /**
+         * ONEWAY binder call to initiate authorizing the report.  The actual logic is posted
+         * to mRequestQueue, and may happen later.  The security checks need to happen here.
+         */
+        @Override
+        public void authorizeReport(int callingUid, final String callingPackage, final int flags,
+                final IIncidentAuthListener listener) {
+            enforceRequestAuthorizationPermission();
+
+            final long ident = Binder.clearCallingIdentity();
+            try {
+                // Starting the system server is complicated, and rather than try to
+                // have a complicated lifecycle that we share with dumpstated and incidentd,
+                // we will accept the request, and then display it whenever it becomes possible to.
+                mRequestQueue.enqueue(listener.asBinder(), true, () -> {
+                    authorizeReportImpl(callingUid, callingPackage, flags, listener);
+                });
+            } finally {
+                Binder.restoreCallingIdentity(ident);
+            }
+        }
+
+        /**
+         * ONEWAY binder call to cancel the inbound authorization request.
+         * <p>
+         * This is a oneway call, and so is authorizeReport, so the
+         * caller's ordering is preserved.  The other calls on this object are synchronous, so
+         * their ordering is not guaranteed with respect to these calls.  So the implementation
+         * sends out extra broadcasts to allow for eventual consistency.
+         */
+        public void cancelAuthorization(final IIncidentAuthListener listener) {
+            enforceRequestAuthorizationPermission();
+
+            // Caller can cancel if they don't want it anymore, and mRequestQueue elides
+            // authorize/cancel pairs.
+            final long ident = Binder.clearCallingIdentity();
+            try {
+                mRequestQueue.enqueue(listener.asBinder(), false, () -> {
+                    cancelReportImpl(listener);
+                });
+            } finally {
+                Binder.restoreCallingIdentity(ident);
+            }
+        }
+
+        /**
+         * SYNCHRONOUS binder call to get the list of reports that are pending confirmation
+         * by the user.
+         */
+        @Override
+        public List<String> getPendingReports() {
+            enforceAuthorizePermission();
+
+            synchronized (mLock) {
+                final int size = mPending.size();
+                final ArrayList<String> result = new ArrayList(size);
+                for (int i = 0; i < size; i++) {
+                    result.add(mPending.get(i).getUri().toString());
+                }
+                return result;
+            }
+        }
+
+        /**
+         * ONEWAY binder call to mark a report as approved.
+         */
+        @Override
+        public void approveReport(String uri) {
+            enforceAuthorizePermission();
+
+            final long ident = Binder.clearCallingIdentity();
+            try {
+                final PendingReportRec rec;
+                synchronized (mLock) {
+                    rec = findAndRemovePendingReportRecLocked(uri);
+                    if (rec == null) {
+                        Log.e(TAG, "confirmApproved: Couldn't find record for uri: " + uri);
+                        return;
+                    }
+                }
+
+                // Re-do the broadcast, so whoever is listening knows the list changed,
+                // in case another one was added in the meantime.
+                sendBroadcast();
+
+                Log.i(TAG, "Approved report: " + uri);
+                try {
+                    rec.listener.onReportApproved();
+                } catch (RemoteException ex) {
+                    Log.w(TAG, "Failed calling back for approval for: " + uri, ex);
+                }
+            } finally {
+                Binder.restoreCallingIdentity(ident);
+            }
+        }
+
+        /**
+         * ONEWAY binder call to mark a report as NOT approved.
+         */
+        @Override
+        public void denyReport(String uri) {
+            enforceAuthorizePermission();
+
+            final long ident = Binder.clearCallingIdentity();
+            try {
+                final PendingReportRec rec;
+                synchronized (mLock) {
+                    rec = findAndRemovePendingReportRecLocked(uri);
+                    if (rec == null) {
+                        Log.e(TAG, "confirmDenied: Couldn't find record for uri: " + uri);
+                        return;
+                    }
+                }
+
+                // Re-do the broadcast, so whoever is listening knows the list changed,
+                // in case another one was added in the meantime.
+                sendBroadcast();
+
+                Log.i(TAG, "Denied report: " + uri);
+                try {
+                    rec.listener.onReportDenied();
+                } catch (RemoteException ex) {
+                    Log.w(TAG, "Failed calling back for denial for: " + uri, ex);
+                }
+            } finally {
+                Binder.restoreCallingIdentity(ident);
+            }
+        }
+
+        /**
+         * Implementation of adb shell dumpsys debugreportcompanion.
+         */
+        @Override
+        protected void dump(FileDescriptor fd, final PrintWriter writer, String[] args) {
+            if (!DumpUtils.checkDumpPermission(getContext(), TAG, writer)) {
+                return;
+            }
+            if (args.length == 0) {
+                // Standard text dumpsys
+                final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
+                synchronized (mLock) {
+                    final int size = mPending.size();
+                    writer.println("mPending: (" + size + ")");
+                    for (int i = 0; i < size; i++) {
+                        final PendingReportRec entry = mPending.get(i);
+                        writer.println(String.format("  %11d %s: %s", entry.addedRealtime,
+                                    df.format(new Date(entry.addedWalltime)),
+                                    entry.getUri().toString()));
+                    }
+                }
+            }
+        }
+
+        private void enforceRequestAuthorizationPermission() {
+            getContext().enforceCallingOrSelfPermission(
+                    android.Manifest.permission.REQUEST_INCIDENT_REPORT_APPROVAL, null);
+        }
+
+        private void enforceAuthorizePermission() {
+            getContext().enforceCallingOrSelfPermission(
+                    android.Manifest.permission.APPROVE_INCIDENT_REPORTS, null);
+        }
+
+    }
+
+    /**
+     * Construct new IncidentCompanionService with the context.
+     */
+    public IncidentCompanionService(Context context) {
+        super(context);
+        mPackageManager = context.getPackageManager();
+        mAppOpsManager = context.getSystemService(AppOpsManager.class);
+    }
+
+    /**
+     * Initialize the service.  It is still not safe to do UI until
+     * onBootPhase(SystemService.PHASE_BOOT_COMPLETED).
+     */
+    @Override
+    public void onStart() {
+        publishBinderService(Context.INCIDENT_COMPANION_SERVICE, new BinderService());
+    }
+
+    /**
+     * Handle the boot process... Starts everything running once the system is
+     * up enough for us to do UI.
+     */
+    @Override
+    public void onBootPhase(int phase) {
+        super.onBootPhase(phase);
+        switch (phase) {
+            case SystemService.PHASE_BOOT_COMPLETED:
+                // Release the enqueued work.
+                mRequestQueue.start();
+                break;
+        }
+    }
+
+    /**
+     * Start the confirmation process.
+     */
+    private void authorizeReportImpl(int callingUid, final String callingPackage, int flags,
+            final IIncidentAuthListener listener) {
+        // Enforce that the calling package pertains to the callingUid.
+        if (!isPackageInUid(callingUid, callingPackage)) {
+            Log.w(TAG, "Calling uid " + callingUid + " doesn't match package "
+                    + callingPackage);
+            denyReportBeforeAddingRec(listener, callingPackage);
+            return;
+        }
+
+        // Find the primary user of this device.
+        final int primaryUser = getAndValidateUser();
+        if (primaryUser == UserHandle.USER_NULL) {
+            denyReportBeforeAddingRec(listener, callingPackage);
+            return;
+        }
+
+        // Find the approver app (hint: it's PermissionController).
+        final ComponentName receiver = getApproverComponent(primaryUser);
+        if (receiver == null) {
+            // We couldn't find an approver... so deny the request here and now, before we
+            // do anything else.
+            denyReportBeforeAddingRec(listener, callingPackage);
+            return;
+        }
+
+        // Save the record for when the PermissionController comes back to authorize it.
+        PendingReportRec rec = null;
+        synchronized (mLock) {
+            rec = new PendingReportRec(callingPackage, flags, listener);
+            mPending.add(rec);
+        }
+
+        try {
+            listener.asBinder().linkToDeath(() -> {
+                Log.i(TAG, "Got death notification listener=" + listener);
+                cancelReportImpl(listener, receiver, primaryUser);
+            }, 0);
+        } catch (RemoteException ex) {
+            Log.e(TAG, "Remote died while trying to register death listener: " + rec.getUri());
+            // First, remove from our list.
+            cancelReportImpl(listener, receiver, primaryUser);
+        }
+
+        // Go tell Permission controller to start asking the user.
+        sendBroadcast(receiver, primaryUser);
+    }
+
+    /**
+     * Cancel a pending report request (because of an explicit call to cancel)
+     */
+    private void cancelReportImpl(IIncidentAuthListener listener) {
+        final int primaryUser = getAndValidateUser();
+        final ComponentName receiver = getApproverComponent(primaryUser);
+        if (primaryUser != UserHandle.USER_NULL && receiver != null) {
+            cancelReportImpl(listener, receiver, primaryUser);
+        }
+    }
+
+    /**
+     * Cancel a pending report request (either because of an explicit call to cancel
+     * by the calling app, or because of a binder death).
+     */
+    private void cancelReportImpl(IIncidentAuthListener listener, ComponentName receiver,
+            int primaryUser) {
+        // First, remove from our list.
+        synchronized (mLock) {
+            removePendingReportRecLocked(listener);
+        }
+        // Second, call back to PermissionController to say it's canceled.
+        sendBroadcast(receiver, primaryUser);
+    }
+
+    /**
+     * Send an extra copy of the broadcast, to tell them that the list has changed
+     * because of an addition or removal.  This function is less aggressive than
+     * authorizeReportImpl in logging about failures, because this is for use in
+     * cleanup cases to keep the apps' list in sync with ours.
+     */
+    private void sendBroadcast() {
+        final int primaryUser = getAndValidateUser();
+        if (primaryUser == UserHandle.USER_NULL) {
+            return;
+        }
+        final ComponentName receiver = getApproverComponent(primaryUser);
+        if (receiver == null) {
+            return;
+        }
+        sendBroadcast(receiver, primaryUser);
+    }
+
+    /**
+     * Send the confirmation broadcast.
+     */
+    private void sendBroadcast(ComponentName receiver, int primaryUser) {
+        final Intent intent = new Intent(Intent.ACTION_PENDING_INCIDENT_REPORTS_CHANGED);
+        intent.setComponent(receiver);
+
+        // Send it to the primary user.
+        getContext().sendBroadcastAsUser(intent, UserHandle.getUserHandleForUid(primaryUser),
+                android.Manifest.permission.APPROVE_INCIDENT_REPORTS);
+    }
+
+    /**
+     * Remove a PendingReportRec keyed by uri, and return it.
+     */
+    private PendingReportRec findAndRemovePendingReportRecLocked(String uriString) {
+        final Uri uri = Uri.parse(uriString);
+        final int id;
+        try {
+            final String idStr = uri.getQueryParameter(IncidentManager.URI_PARAM_ID);
+            id = Integer.parseInt(idStr);
+        } catch (NumberFormatException ex) {
+            Log.w(TAG, "Can't parse id from: " + uriString);
+            return null;
+        }
+        final int size = mPending.size();
+        for (int i = 0; i < size; i++) {
+            final PendingReportRec rec = mPending.get(i);
+            if (rec.id == id) {
+                mPending.remove(i);
+                return rec;
+            }
+        }
+        return null;
+    }
+
+    /**
+     * Remove a PendingReportRec keyed by listener.
+     */
+    private void removePendingReportRecLocked(IIncidentAuthListener listener) {
+        final int size = mPending.size();
+        for (int i = 0; i < size; i++) {
+            final PendingReportRec rec = mPending.get(i);
+            if (rec.listener.asBinder() == listener.asBinder()) {
+                Log.i(TAG, "  ...Removed PendingReportRec index=" + i + ": " + rec.getUri());
+                mPending.remove(i);
+            }
+        }
+    }
+
+    /**
+     * Just call listener.deny() (wrapping the RemoteException), without try to
+     * add it to the list.
+     */
+    private void denyReportBeforeAddingRec(IIncidentAuthListener listener, String pkg) {
+        try {
+            listener.onReportDenied();
+        } catch (RemoteException ex) {
+            Log.w(TAG, "Failed calling back for denial for " + pkg, ex);
+        }
+    }
+
+    /**
+     * Check whether the current user is the primary user, and return the user id if they are.
+     * Returns UserHandle.USER_NULL if not valid.
+     */
+    private int getAndValidateUser() {
+        // Current user
+        UserInfo currentUser;
+        try {
+            currentUser = ActivityManager.getService().getCurrentUser();
+        } catch (RemoteException ex) {
+            // We're already inside the system process.
+            throw new RuntimeException(ex);
+        }
+
+        // Primary user
+        final UserManager um = UserManager.get(getContext());
+        final UserInfo primaryUser = um.getPrimaryUser();
+
+        // Check that we're using the right user.
+        if (currentUser == null) {
+            Log.w(TAG, "No current user.  Nobody to approve the report."
+                    + " The report will be denied.");
+            return UserHandle.USER_NULL;
+        }
+        if (primaryUser == null) {
+            Log.w(TAG, "No primary user.  Nobody to approve the report."
+                    + " The report will be denied.");
+            return UserHandle.USER_NULL;
+        }
+        if (primaryUser.id != currentUser.id) {
+            Log.w(TAG, "Only the primary user can approve bugreports, but they are not"
+                    + " the current user. The report will be denied.");
+            return UserHandle.USER_NULL;
+        }
+
+        return primaryUser.id;
+    }
+
+    /**
+     * Return the ComponentName of the BroadcastReceiver that will approve reports.
+     * The system must have zero or one of these installed.  We only look on the
+     * system partition.  When the broadcast happens, the component will also need
+     * have the APPROVE_INCIDENT_REPORTS permission.
+     */
+    private ComponentName getApproverComponent(int userId) {
+        // Find the one true BroadcastReceiver
+        final Intent intent = new Intent(Intent.ACTION_PENDING_INCIDENT_REPORTS_CHANGED);
+        final List<ResolveInfo> matches = mPackageManager.queryBroadcastReceiversAsUser(intent,
+                PackageManager.MATCH_SYSTEM_ONLY | PackageManager.MATCH_DIRECT_BOOT_AWARE
+                | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userId);
+        if (matches.size() == 1) {
+            return matches.get(0).getComponentInfo().getComponentName();
+        } else {
+            Log.w(TAG, "Didn't find exactly one BroadcastReceiver to handle "
+                    + Intent.ACTION_PENDING_INCIDENT_REPORTS_CHANGED
+                    + ". The report will be denied. size="
+                    + matches.size() + ": matches=" + matches);
+            return null;
+        }
+    }
+
+    /**
+     * Return whether the package is one of the packages installed for the uid.
+     */
+    private boolean isPackageInUid(int uid, String packageName) {
+        try {
+            mAppOpsManager.checkPackage(uid, packageName);
+            return true;
+        } catch (SecurityException ex) {
+            return false;
+        }
+    }
+}
+
diff --git a/services/core/java/com/android/server/incident/RequestQueue.java b/services/core/java/com/android/server/incident/RequestQueue.java
new file mode 100644
index 0000000..85758e2
--- /dev/null
+++ b/services/core/java/com/android/server/incident/RequestQueue.java
@@ -0,0 +1,155 @@
+/*
+ * Copyright (C) 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 com.android.server.incident;
+
+import android.os.Handler;
+import android.os.IBinder;
+
+import java.util.ArrayList;
+
+/**
+ * Class to enqueue work until the system is ready.
+ */
+class RequestQueue {
+    /*
+     * All fields are protected by synchronized (mPending)
+     */
+
+    /**
+     * Requests that we can't start yet because system server isn't booted enough yet.
+     * Set to null when we have started.
+     */
+    private ArrayList<Rec> mPending = new ArrayList();
+
+    /**
+     * Where to run the requests.
+     */
+    private final Handler mHandler;
+
+    /**
+     * Whether someone has called start() yet.
+     */
+    private boolean mStarted;
+
+    /**
+     * Queue item.
+     */
+    private class Rec {
+        /**
+         * Key for the record.
+         */
+        public final IBinder key;
+
+        /**
+         * True / false pairs will be elided by enqueue().
+         */
+        public final boolean value;
+
+        /**
+         * The runnable to run.
+         */
+        public final Runnable runnable;
+
+        /**
+         * Constructor
+         */
+        Rec(IBinder key, boolean value, Runnable runnable) {
+            this.key = key;
+            this.value = value;
+            this.runnable = runnable;
+        }
+    }
+
+    /**
+     * Handler on the main thread.
+     */
+    private final Runnable mWorker = new Runnable() {
+        @Override
+        public void run() {
+            ArrayList<Rec> copy = null;
+            synchronized (mPending) {
+                if (mPending.size() > 0) {
+                    copy = new ArrayList<Rec>(mPending);
+                    mPending.clear();
+                }
+            }
+            if (copy != null) {
+                final int size = copy.size();
+                for (int i = 0; i < size; i++) {
+                    copy.get(i).runnable.run();
+                }
+            }
+        }
+    };
+
+    /**
+     * Construct RequestQueue.
+     *
+     * @param handler Handler to use.
+     */
+    RequestQueue(Handler handler) {
+        mHandler = handler;
+    }
+
+    /**
+     * We're now ready to go.  Start any previously pending runnables.
+     */
+    public void start() {
+        synchronized (mPending) {
+            if (!mStarted) {
+                if (mPending.size() > 0) {
+                    mHandler.post(mWorker);
+                }
+                mStarted = true;
+            }
+        }
+    }
+
+    /**
+     * If we can run this now, then do it on the Handler provided in the constructor.
+     * If not, then enqueue it until start is called.
+     *
+     * The queue will elide keys with pairs of true/false values, so the user doesn't
+     * see confirmations that were previously canceled.
+     */
+    public void enqueue(IBinder key, boolean value, Runnable runnable) {
+        synchronized (mPending) {
+            boolean skip = false;
+            if (!value) {
+                for (int i = mPending.size() - 1; i >= 0; i--) {
+                    final Rec r = mPending.get(i);
+                    if (r.key == key) {
+                        if (r.value) {
+                            skip = true;
+                            mPending.remove(i);
+                            break;
+                        }
+                    }
+                }
+            }
+            if (!skip) {
+                mPending.add(new Rec(key, value, runnable));
+            }
+            if (mStarted) {
+                // Already started. Post now.
+                mHandler.post(mWorker);
+            }
+        }
+    }
+}
+
diff --git a/services/core/java/com/android/server/infra/AbstractMasterSystemService.java b/services/core/java/com/android/server/infra/AbstractMasterSystemService.java
index 8e26097..532aa01 100644
--- a/services/core/java/com/android/server/infra/AbstractMasterSystemService.java
+++ b/services/core/java/com/android/server/infra/AbstractMasterSystemService.java
@@ -117,7 +117,7 @@
      */
     @GuardedBy("mLock")
     @Nullable
-    private final SparseBooleanArray mDisabledUsers;
+    private final SparseBooleanArray mDisabledByUserRestriction;
 
     /**
      * Cache of services per user id.
@@ -148,9 +148,9 @@
 
         }
         if (disallowProperty == null) {
-            mDisabledUsers = null;
+            mDisabledByUserRestriction = null;
         } else {
-            mDisabledUsers = new SparseBooleanArray();
+            mDisabledByUserRestriction = new SparseBooleanArray();
             // Hookup with UserManager to disable service when necessary.
             final UserManager um = context.getSystemService(UserManager.class);
             final UserManagerInternal umi = LocalServices.getService(UserManagerInternal.class);
@@ -159,15 +159,15 @@
                 final int userId = users.get(i).id;
                 final boolean disabled = umi.getUserRestriction(userId, disallowProperty);
                 if (disabled) {
-                    Slog.i(mTag, "Disabling for user " + userId);
-                    mDisabledUsers.put(userId, disabled);
+                    Slog.i(mTag, "Disabling by restrictions user " + userId);
+                    mDisabledByUserRestriction.put(userId, disabled);
                 }
             }
             umi.addUserRestrictionsListener((userId, newRestrictions, prevRestrictions) -> {
                 final boolean disabledNow =
                         newRestrictions.getBoolean(disallowProperty, false);
                 synchronized (mLock) {
-                    final boolean disabledBefore = mDisabledUsers.get(userId);
+                    final boolean disabledBefore = mDisabledByUserRestriction.get(userId);
                     if (disabledBefore == disabledNow) {
                         // Nothing changed, do nothing.
                         if (debug) {
@@ -176,7 +176,7 @@
                         }
                     }
                     Slog.i(mTag, "Updating for user " + userId + ": disabled=" + disabledNow);
-                    mDisabledUsers.put(userId, disabledNow);
+                    mDisabledByUserRestriction.put(userId, disabledNow);
                     updateCachedServiceLocked(userId, disabledNow);
                 }
             });
@@ -414,7 +414,7 @@
      * given user.
      */
     protected boolean isDisabledLocked(@UserIdInt int userId) {
-        return mDisabledUsers == null ? false : mDisabledUsers.get(userId);
+        return mDisabledByUserRestriction == null ? false : mDisabledByUserRestriction.get(userId);
     }
 
     /**
@@ -523,7 +523,8 @@
                     mServiceNameResolver.dumpShort(pw, userId); pw.println();
                 }
             }
-            pw.print(prefix); pw.print("Disabled users: "); pw.println(mDisabledUsers);
+            pw.print(prefix); pw.print("Users disabled by restriction: ");
+            pw.println(mDisabledByUserRestriction);
             pw.print(prefix); pw.print("Allow instant service: "); pw.println(mAllowInstantService);
             final String settingsProperty = getServiceSettingsProperty();
             if (settingsProperty != null) {
diff --git a/services/core/java/com/android/server/job/JobSchedulerService.java b/services/core/java/com/android/server/job/JobSchedulerService.java
index 65a078b..19d10ec 100644
--- a/services/core/java/com/android/server/job/JobSchedulerService.java
+++ b/services/core/java/com/android/server/job/JobSchedulerService.java
@@ -810,6 +810,8 @@
             MAX_JOB_COUNTS_SCREEN_OFF.low.parse(mParser);
             MAX_JOB_COUNTS_SCREEN_OFF.critical.parse(mParser);
 
+            SCREEN_OFF_JOB_CONCURRENCY_INCREASE_DELAY_MS.parse(mParser);
+
             MAX_STANDARD_RESCHEDULE_COUNT = mParser.getInt(KEY_MAX_STANDARD_RESCHEDULE_COUNT,
                     DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT);
             MAX_WORK_RESCHEDULE_COUNT = mParser.getInt(KEY_MAX_WORK_RESCHEDULE_COUNT,
diff --git a/services/core/java/com/android/server/location/GnssNetworkConnectivityHandler.java b/services/core/java/com/android/server/location/GnssNetworkConnectivityHandler.java
index c38373f..90d16cb 100644
--- a/services/core/java/com/android/server/location/GnssNetworkConnectivityHandler.java
+++ b/services/core/java/com/android/server/location/GnssNetworkConnectivityHandler.java
@@ -34,7 +34,6 @@
 import java.net.UnknownHostException;
 import java.util.Arrays;
 import java.util.HashMap;
-import java.util.concurrent.ConcurrentHashMap;
 
 /**
  * Handles network connection requests and network state change updates for AGPS data download.
@@ -80,10 +79,11 @@
 
     private static final int HASH_MAP_INITIAL_CAPACITY_TO_TRACK_CONNECTED_NETWORKS = 5;
 
-    // keeps track of networks and their state as notified by the network request callbacks.
+    // Keeps track of networks and their state as notified by the network request callbacks.
     // Limit initial capacity to 5 as the number of connected networks will likely be small.
-    private ConcurrentHashMap<Network, NetworkAttributes> mAvailableNetworkAttributes =
-            new ConcurrentHashMap<>(HASH_MAP_INITIAL_CAPACITY_TO_TRACK_CONNECTED_NETWORKS);
+    // NOTE: Must be accessed/modified only through the mHandler thread.
+    private HashMap<Network, NetworkAttributes> mAvailableNetworkAttributes =
+            new HashMap<>(HASH_MAP_INITIAL_CAPACITY_TO_TRACK_CONNECTED_NETWORKS);
 
     private final ConnectivityManager mConnMgr;
 
@@ -159,7 +159,7 @@
     /**
      * Interface to listen for network availability changes.
      */
-    public interface GnssNetworkListener {
+    interface GnssNetworkListener {
         void onNetworkAvailable();
     }
 
@@ -177,12 +177,7 @@
         mSuplConnectivityCallback = createSuplConnectivityCallback();
     }
 
-    public void registerNetworkCallbacks() {
-        mAvailableNetworkAttributes.clear();
-        if (mNetworkConnectivityCallback != null) {
-            mConnMgr.unregisterNetworkCallback(mNetworkConnectivityCallback);
-        }
-
+    void registerNetworkCallbacks() {
         // register for connectivity change events.
         NetworkRequest.Builder networkRequestBuilder = new NetworkRequest.Builder();
         networkRequestBuilder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
@@ -190,14 +185,14 @@
         networkRequestBuilder.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
         NetworkRequest networkRequest = networkRequestBuilder.build();
         mNetworkConnectivityCallback = createNetworkConnectivityCallback();
-        mConnMgr.registerNetworkCallback(networkRequest, mNetworkConnectivityCallback);
+        mConnMgr.registerNetworkCallback(networkRequest, mNetworkConnectivityCallback, mHandler);
     }
 
     /**
      * @return {@code true} if there is a data network available for outgoing connections,
      * {@code false} otherwise.
      */
-    public boolean isDataNetworkConnected() {
+    boolean isDataNetworkConnected() {
         NetworkInfo activeNetworkInfo = mConnMgr.getActiveNetworkInfo();
         return activeNetworkInfo != null && activeNetworkInfo.isConnected();
     }
@@ -205,15 +200,15 @@
     /**
      * called from native code to update AGPS status
      */
-    public void onReportAGpsStatus(int agpsType, int agpsStatus, byte[] suplIpAddr) {
+    void onReportAGpsStatus(int agpsType, int agpsStatus, byte[] suplIpAddr) {
         switch (agpsStatus) {
             case GPS_REQUEST_AGPS_DATA_CONN:
                 if (DEBUG) Log.d(TAG, "GPS_REQUEST_AGPS_DATA_CONN");
-                requestSuplConnection(agpsType, suplIpAddr);
+                runOnHandler(() -> handleRequestSuplConnection(agpsType, suplIpAddr));
                 break;
             case GPS_RELEASE_AGPS_DATA_CONN:
                 if (DEBUG) Log.d(TAG, "GPS_RELEASE_AGPS_DATA_CONN");
-                releaseSuplConnection(GPS_RELEASE_AGPS_DATA_CONN);
+                runOnHandler(() -> handleReleaseSuplConnection(GPS_RELEASE_AGPS_DATA_CONN));
                 break;
             case GPS_AGPS_DATA_CONNECTED:
                 if (DEBUG) Log.d(TAG, "GPS_AGPS_DATA_CONNECTED");
@@ -263,7 +258,7 @@
                 mGnssNetworkListener.onNetworkAvailable();
 
                 // Always on, notify HAL so it can get data it needs
-                updateNetworkState(network, true, capabilities);
+                handleUpdateNetworkState(network, true, capabilities);
             }
 
             @Override
@@ -276,7 +271,7 @@
 
                 Log.i(TAG, "Network connection lost. Available networks count: "
                         + mAvailableNetworkCapabilities.size());
-                updateNetworkState(network, false, null);
+                handleUpdateNetworkState(network, false, null);
             }
         };
     }
@@ -287,42 +282,25 @@
             public void onAvailable(Network network) {
                 if (DEBUG) Log.d(TAG, "SUPL network connection available.");
                 // Specific to a change to a SUPL enabled network becoming ready
-                suplConnectionAvailable(network);
+                handleSuplConnectionAvailable(network);
             }
 
             @Override
             public void onLost(Network network) {
                 Log.i(TAG, "SUPL network connection lost.");
-                releaseSuplConnection(GPS_RELEASE_AGPS_DATA_CONN);
+                handleReleaseSuplConnection(GPS_RELEASE_AGPS_DATA_CONN);
             }
 
             @Override
             public void onUnavailable() {
                 Log.i(TAG, "SUPL network connection request timed out.");
                 // Could not setup the connection to the network in the specified time duration.
-                releaseSuplConnection(GPS_AGPS_DATA_CONN_FAILED);
+                handleReleaseSuplConnection(GPS_AGPS_DATA_CONN_FAILED);
             }
         };
     }
 
-    private void requestSuplConnection(int agpsType, byte[] suplIpAddr) {
-        postEvent(() -> handleRequestSuplConnection(agpsType, suplIpAddr));
-    }
-
-    private void suplConnectionAvailable(Network network) {
-        postEvent(() -> handleSuplConnectionAvailable(network));
-    }
-
-    private void releaseSuplConnection(int connStatus) {
-        postEvent(() -> handleReleaseSuplConnection(connStatus));
-    }
-
-    private void updateNetworkState(Network network, boolean isConnected,
-            NetworkCapabilities capabilities) {
-        postEvent(() -> handleUpdateNetworkState(network, isConnected, capabilities));
-    }
-
-    private void postEvent(Runnable event) {
+    private void runOnHandler(Runnable event) {
         // hold a wake lock until this message is delivered
         // note that this assumes the message will not be removed from the queue before
         // it is handled (otherwise the wake lock would be leaked).
@@ -486,6 +464,7 @@
         mConnMgr.requestNetwork(
                 request,
                 mSuplConnectivityCallback,
+                mHandler,
                 SUPL_NETWORK_REQUEST_TIMEOUT_MILLIS);
     }
 
diff --git a/services/core/java/com/android/server/notification/NotificationDelegate.java b/services/core/java/com/android/server/notification/NotificationDelegate.java
index c2dc554..be15fda 100644
--- a/services/core/java/com/android/server/notification/NotificationDelegate.java
+++ b/services/core/java/com/android/server/notification/NotificationDelegate.java
@@ -60,7 +60,8 @@
      * @param clickedIndex the index of clicked reply
      * @param reply the reply that is sent
      * @param generatedByAssistant specifies is the reply generated by NAS
+     * @param notificationLocation the location of the notification containing the smart reply
      */
     void onNotificationSmartReplySent(String key, int clickedIndex, CharSequence reply,
-            boolean generatedByAssistant);
+            boolean generatedByAssistant, int notificationLocation);
 }
diff --git a/services/core/java/com/android/server/notification/NotificationManagerService.java b/services/core/java/com/android/server/notification/NotificationManagerService.java
index 238eed4..467b192 100644
--- a/services/core/java/com/android/server/notification/NotificationManagerService.java
+++ b/services/core/java/com/android/server/notification/NotificationManagerService.java
@@ -929,14 +929,19 @@
 
         @Override
         public void onNotificationSmartReplySent(String key, int replyIndex, CharSequence reply,
-                boolean generatedByAssistant) {
+                boolean generatedByAssistant, int notificationLocation) {
 
             synchronized (mNotificationLock) {
                 NotificationRecord r = mNotificationsByKey.get(key);
                 if (r != null) {
                     LogMaker logMaker = r.getLogMaker()
                             .setCategory(MetricsEvent.SMART_REPLY_ACTION)
-                            .setSubtype(replyIndex);
+                            .setSubtype(replyIndex)
+                            .addTaggedData(
+                                    MetricsEvent.NOTIFICATION_SMART_SUGGESTION_ASSISTANT_GENERATED,
+                                    generatedByAssistant ? 1 : 0)
+                            .addTaggedData(MetricsEvent.NOTIFICATION_LOCATION,
+                                    notificationLocation);
                     mMetricsLogger.write(logMaker);
                     // Treat clicking on a smart reply as a user interaction.
                     reportUserInteraction(r);
diff --git a/services/core/java/com/android/server/pm/LauncherAppsService.java b/services/core/java/com/android/server/pm/LauncherAppsService.java
index d5089cb..c2ac27a 100644
--- a/services/core/java/com/android/server/pm/LauncherAppsService.java
+++ b/services/core/java/com/android/server/pm/LauncherAppsService.java
@@ -837,7 +837,11 @@
                         PackageManager.MATCH_DIRECT_BOOT_AWARE
                                 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
                         callingUid, user.getIdentifier());
-                return info != null;
+                // Note we don't check "exported" because if the caller has the same UID as the
+                // callee's UID, it can still be launched.
+                // (If an app doesn't export a front door activity and causes issues with the
+                // launcher, that's just the app's bug.)
+                return info != null && info.isEnabled();
             } finally {
                 Binder.restoreCallingIdentity(ident);
             }
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index 265d07a..d2547d9 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -1350,6 +1350,7 @@
     final @Nullable String mDocumenterPackage;
     final @Nullable String mConfiguratorPackage;
     final @Nullable String mAppPredictionServicePackage;
+    final @Nullable String mIncidentReportApproverPackage;
     final @NonNull String mServicesSystemSharedLibraryPackageName;
     final @NonNull String mSharedSystemSharedLibraryPackageName;
 
@@ -2879,6 +2880,7 @@
             mConfiguratorPackage =
                     mContext.getString(R.string.config_deviceConfiguratorPackageName);
             mAppPredictionServicePackage = getAppPredictionServicePackageName();
+            mIncidentReportApproverPackage = getIncidentReportApproverPackageName();
 
             // Now that we know all of the shared libraries, update all clients to have
             // the correct library paths.
@@ -20112,6 +20114,10 @@
         return contentCaptureServiceName.substring(0, separatorIndex);
     }
 
+    public String getIncidentReportApproverPackageName() {
+        return mContext.getString(R.string.config_incidentReportApproverPackage);
+    }
+
     @Override
     public void setApplicationEnabledSetting(String appPackageName,
             int newState, int flags, int userId, String callingPackage) {
@@ -23275,6 +23281,8 @@
                     return mDocumenterPackage;
                 case PackageManagerInternal.PACKAGE_CONFIGURATOR:
                     return mConfiguratorPackage;
+                case PackageManagerInternal.PACKAGE_INCIDENT_REPORT_APPROVER:
+                    return mIncidentReportApproverPackage;
             }
             return null;
         }
diff --git a/services/core/java/com/android/server/pm/permission/BasePermission.java b/services/core/java/com/android/server/pm/permission/BasePermission.java
index 17f8347..848cee0 100644
--- a/services/core/java/com/android/server/pm/permission/BasePermission.java
+++ b/services/core/java/com/android/server/pm/permission/BasePermission.java
@@ -251,6 +251,9 @@
         return (protectionLevel & PermissionInfo.PROTECTION_FLAG_CONFIGURATOR)
             != 0;
     }
+    public boolean isIncidentReportApprover() {
+        return (protectionLevel & PermissionInfo.PROTECTION_FLAG_INCIDENT_REPORT_APPROVER) != 0;
+    }
 
     public void transfer(@NonNull String origPackageName, @NonNull String newPackageName) {
         if (!origPackageName.equals(sourcePackageName)) {
diff --git a/services/core/java/com/android/server/pm/permission/PermissionManagerService.java b/services/core/java/com/android/server/pm/permission/PermissionManagerService.java
index 3c89d78..22780e6 100644
--- a/services/core/java/com/android/server/pm/permission/PermissionManagerService.java
+++ b/services/core/java/com/android/server/pm/permission/PermissionManagerService.java
@@ -1716,6 +1716,14 @@
                 // this app is the documenter, then it gets the permission.
                 allowed = true;
             }
+            if (!allowed && bp.isIncidentReportApprover()
+                    && pkg.packageName.equals(mPackageManagerInt.getKnownPackageName(
+                            PackageManagerInternal.PACKAGE_INCIDENT_REPORT_APPROVER,
+                            UserHandle.USER_SYSTEM))) {
+                // If this permission is to be granted to the incident report approver and
+                // this app is the incident report approver, then it gets the permission.
+                allowed = true;
+            }
         }
         return allowed;
     }
diff --git a/services/core/java/com/android/server/policy/role/LegacyRoleResolutionPolicy.java b/services/core/java/com/android/server/policy/role/LegacyRoleResolutionPolicy.java
index 7f2dedb..bfe7725 100644
--- a/services/core/java/com/android/server/policy/role/LegacyRoleResolutionPolicy.java
+++ b/services/core/java/com/android/server/policy/role/LegacyRoleResolutionPolicy.java
@@ -22,6 +22,8 @@
 import android.content.Context;
 import android.os.Debug;
 import android.provider.Settings;
+import android.telecom.TelecomManager;
+import android.text.TextUtils;
 import android.util.Log;
 import android.util.Slog;
 
@@ -102,6 +104,15 @@
                             ComponentName.unflattenFromString(legacyAssistant).getPackageName());
                 }
             }
+            case RoleManager.ROLE_DIALER: {
+                String setting = Settings.Secure.getStringForUser(
+                        mContext.getContentResolver(),
+                        Settings.Secure.DIALER_DEFAULT_APPLICATION, userId);
+
+                return CollectionUtils.singletonOrEmpty(!TextUtils.isEmpty(setting)
+                        ? setting
+                        : mContext.getSystemService(TelecomManager.class).getSystemDialerPackage());
+            }
             default: {
                 Slog.e(LOG_TAG, "Don't know how to find legacy role holders for " + roleName);
                 return Collections.emptyList();
diff --git a/services/core/java/com/android/server/role/RemoteRoleControllerService.java b/services/core/java/com/android/server/role/RemoteRoleControllerService.java
index cc3064e..be2544d 100644
--- a/services/core/java/com/android/server/role/RemoteRoleControllerService.java
+++ b/services/core/java/com/android/server/role/RemoteRoleControllerService.java
@@ -32,12 +32,14 @@
 import android.os.UserHandle;
 import android.rolecontrollerservice.IRoleControllerService;
 import android.rolecontrollerservice.RoleControllerService;
+import android.util.Log;
 import android.util.Slog;
 
 import com.android.internal.util.function.pooled.PooledLambda;
 import com.android.server.FgThread;
 
 import java.util.ArrayDeque;
+import java.util.Arrays;
 import java.util.Queue;
 
 /**
@@ -226,10 +228,21 @@
 
             private boolean mCallbackNotified;
 
+            @Nullable
+            private final String mDebugName;
+
             private Call(@NonNull CallExecutor callExecutor,
                     @NonNull IRoleManagerCallback callback) {
                 mCallExecutor = callExecutor;
                 mCallback = callback;
+                mDebugName = DEBUG
+                        ? Arrays.stream(Thread.currentThread().getStackTrace())
+                                .filter(s -> s.getClassName().equals(
+                                        RemoteRoleControllerService.class.getName()))
+                                .findFirst()
+                                .get()
+                                .getMethodName()
+                        : null;
             }
 
             @WorkerThread
@@ -254,6 +267,10 @@
 
             @WorkerThread
             private void notifyCallback(boolean success) {
+                if (DEBUG) {
+                    Log.i(LOG_TAG, "notifyCallback(" + this
+                            + ", success = " + success + ")");
+                }
                 if (mCallbackNotified) {
                     return;
                 }
@@ -273,7 +290,7 @@
 
             @Override
             public String toString() {
-                return "Call with callback: " + mCallback;
+                return DEBUG ? mDebugName : "Call with callback: " + mCallback;
             }
 
             @FunctionalInterface
diff --git a/services/core/java/com/android/server/role/RoleManagerService.java b/services/core/java/com/android/server/role/RoleManagerService.java
index 7d8c7c9..03ec57b 100644
--- a/services/core/java/com/android/server/role/RoleManagerService.java
+++ b/services/core/java/com/android/server/role/RoleManagerService.java
@@ -207,6 +207,7 @@
             // for a given role before adding a migration statement for it here
             migrateRoleIfNecessary(RoleManager.ROLE_SMS, userId);
             migrateRoleIfNecessary(RoleManager.ROLE_ASSISTANT, userId);
+            migrateRoleIfNecessary(RoleManager.ROLE_DIALER, userId);
 
             // Some vital packages state has changed since last role grant
             // Run grants again
diff --git a/services/core/java/com/android/server/statusbar/StatusBarManagerService.java b/services/core/java/com/android/server/statusbar/StatusBarManagerService.java
index 7e87c29..9617529 100644
--- a/services/core/java/com/android/server/statusbar/StatusBarManagerService.java
+++ b/services/core/java/com/android/server/statusbar/StatusBarManagerService.java
@@ -1266,13 +1266,13 @@
 
     @Override
     public void onNotificationSmartReplySent(
-            String key, int replyIndex, CharSequence reply, boolean generatedByAssistant)
-            throws RemoteException {
+            String key, int replyIndex, CharSequence reply, boolean generatedByAssistant,
+            int notificationLocation) throws RemoteException {
         enforceStatusBarService();
         long identity = Binder.clearCallingIdentity();
         try {
             mNotificationDelegate.onNotificationSmartReplySent(key, replyIndex, reply,
-                    generatedByAssistant);
+                    generatedByAssistant, notificationLocation);
         } finally {
             Binder.restoreCallingIdentity(identity);
         }
diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java
index 8373b44..752c24e 100644
--- a/services/core/java/com/android/server/wm/WindowManagerService.java
+++ b/services/core/java/com/android/server/wm/WindowManagerService.java
@@ -6056,6 +6056,7 @@
                 pw.println("    d[isplays]: active display contents");
                 pw.println("    t[okens]: token list");
                 pw.println("    w[indows]: window list");
+                pw.println("    trace: write Winscope trace to file");
                 pw.println("  cmd may also be a NAME to dump windows.  NAME may");
                 pw.println("    be a partial substring in a window name, a");
                 pw.println("    Window hex object identifier, or");
@@ -6129,6 +6130,11 @@
                     mRoot.forAllWindows(w -> {pw.println(w);}, true /* traverseTopToBottom */);
                 }
                 return;
+            } else if ("trace".equals(cmd)) {
+                synchronized (mGlobalLock) {
+                    mWindowTracing.writeTraceToFile();
+                }
+                return;
             } else {
                 // Dumping a single name?
                 if (!dumpWindows(pw, cmd, args, opti, dumpAll)) {
diff --git a/services/core/java/com/android/server/wm/WindowManagerShellCommand.java b/services/core/java/com/android/server/wm/WindowManagerShellCommand.java
index 6865ce3..83e3c71 100644
--- a/services/core/java/com/android/server/wm/WindowManagerShellCommand.java
+++ b/services/core/java/com/android/server/wm/WindowManagerShellCommand.java
@@ -72,8 +72,7 @@
                     // XXX this should probably be changed to use openFileForSystem() to create
                     // the output trace file, so the shell gets the correct semantics for where
                     // trace files can be written.
-                    return mInternal.mWindowTracing.onShellCommand(this,
-                            getNextArgRequired());
+                    return mInternal.mWindowTracing.onShellCommand(this);
                 case "set-user-rotation":
                     return runSetDisplayUserRotation(pw);
                 case "set-fix-to-user-rotation":
diff --git a/services/core/java/com/android/server/wm/WindowTraceBuffer.java b/services/core/java/com/android/server/wm/WindowTraceBuffer.java
index 936ee85..2f672f2 100644
--- a/services/core/java/com/android/server/wm/WindowTraceBuffer.java
+++ b/services/core/java/com/android/server/wm/WindowTraceBuffer.java
@@ -23,12 +23,15 @@
 import android.os.Trace;
 import android.util.proto.ProtoOutputStream;
 
+import com.android.internal.annotations.VisibleForTesting;
+
 import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.OutputStream;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.LinkedBlockingQueue;
+import java.util.ArrayDeque;
+import java.util.Arrays;
+import java.util.Queue;
 
 /**
  * Buffer used for window tracing.
@@ -36,16 +39,15 @@
 abstract class WindowTraceBuffer {
     private static final long MAGIC_NUMBER_VALUE = ((long) MAGIC_NUMBER_H << 32) | MAGIC_NUMBER_L;
 
-    final Object mBufferSizeLock = new Object();
-    final BlockingQueue<byte[]> mBuffer;
+    final Object mBufferLock = new Object();
+    final Queue<byte[]> mBuffer = new ArrayDeque<>();
+    final File mTraceFile;
     int mBufferSize;
     private final int mBufferCapacity;
-    private final File mTraceFile;
 
     WindowTraceBuffer(int size, File traceFile) throws IOException {
         mBufferCapacity = size;
         mTraceFile = traceFile;
-        mBuffer = new LinkedBlockingQueue<>();
 
         initTraceFile();
     }
@@ -57,65 +59,45 @@
     /**
      * Inserts the specified element into this buffer.
      *
-     * This method is synchronized with {@code #take()} and {@code #clear()}
-     * for consistency.
-     *
      * @param proto the element to add
-     * @return {@code true} if the inserted item was inserted into the buffer
      * @throws IllegalStateException if the element cannot be added because it is larger
      *                               than the buffer size.
      */
-    boolean add(ProtoOutputStream proto) throws InterruptedException {
+    void add(ProtoOutputStream proto) {
         byte[] protoBytes = proto.getBytes();
         int protoLength = protoBytes.length;
         if (protoLength > mBufferCapacity) {
             throw new IllegalStateException("Trace object too large for the buffer. Buffer size:"
                     + mBufferCapacity + " Object size: " + protoLength);
         }
-        synchronized (mBufferSizeLock) {
-            boolean canAdd = canAdd(protoBytes);
+        synchronized (mBufferLock) {
+            boolean canAdd = canAdd(protoLength);
             if (canAdd) {
                 mBuffer.offer(protoBytes);
                 mBufferSize += protoLength;
             }
-            return canAdd;
+            mBufferLock.notify();
         }
     }
 
-    void writeNextBufferElementToFile() throws IOException {
-        byte[] proto;
+    /**
+     * Stops the buffer execution and flush all buffer content to the disk.
+     *
+     * @throws IOException if the buffer cannot write its contents to the {@link #mTraceFile}
+     */
+    void dump() throws IOException, InterruptedException {
         try {
-            proto = take();
-        } catch (InterruptedException e) {
-            Thread.currentThread().interrupt();
-            return;
-        }
-
-        try {
-            Trace.traceBegin(Trace.TRACE_TAG_WINDOW_MANAGER, "writeToFile");
-            try (OutputStream os = new FileOutputStream(mTraceFile, true)) {
-                os.write(proto);
-            }
+            Trace.traceBegin(Trace.TRACE_TAG_WINDOW_MANAGER, "writeTraceToFile");
+            writeTraceToFile();
         } finally {
             Trace.traceEnd(Trace.TRACE_TAG_WINDOW_MANAGER);
         }
     }
 
-    /**
-     * Retrieves and removes the head of this queue, waiting if necessary
-     * until an element becomes available.
-     *
-     * This method is synchronized with {@code #add(ProtoOutputStream)} and {@code #clear()}
-     * for consistency.
-     *
-     * @return the head of this buffer, or {@code null} if this buffer is empty
-     */
-    private byte[] take() throws InterruptedException {
-        byte[] item = mBuffer.take();
-        synchronized (mBufferSizeLock) {
-            mBufferSize -= item.length;
-            return item;
-        }
+    @VisibleForTesting
+    boolean contains(byte[] other) {
+        return mBuffer.stream()
+                .anyMatch(p -> Arrays.equals(p, other));
     }
 
     private void initTraceFile() throws IOException {
@@ -132,25 +114,31 @@
      * Checks if the element can be added to the buffer. The element is already certain to be
      * smaller than the overall buffer size.
      *
-     * @param protoBytes byte array representation of the Proto object to add
-     * @return <tt>true<</tt> if the element can be added to the buffer or not
+     * @param protoLength byte array representation of the Proto object to add
+     * @return {@code true} if the element can be added to the buffer or not
      */
-    abstract boolean canAdd(byte[] protoBytes) throws InterruptedException;
+    abstract boolean canAdd(int protoLength);
 
     /**
      * Flush all buffer content to the disk.
      *
      * @throws IOException if the buffer cannot write its contents to the {@link #mTraceFile}
      */
-    abstract void writeToDisk() throws IOException, InterruptedException;
+    abstract void writeTraceToFile() throws IOException, InterruptedException;
 
     /**
-     * Builder for a {@code WindowTraceBuffer} which creates a {@link WindowTraceQueueBuffer}
+     * Builder for a {@code WindowTraceBuffer} which creates a {@link WindowTraceRingBuffer} for
+     * continuous mode or a {@link WindowTraceQueueBuffer} otherwise
      */
     static class Builder {
+        private boolean mContinuous;
         private File mTraceFile;
         private int mBufferCapacity;
 
+        Builder setContinuousMode(boolean continuous) {
+            mContinuous = continuous;
+            return this;
+        }
 
         Builder setTraceFile(File traceFile) {
             mTraceFile = traceFile;
@@ -175,7 +163,11 @@
                 throw new IllegalArgumentException("A valid trace file must be specified.");
             }
 
-            return new WindowTraceQueueBuffer(mBufferCapacity, mTraceFile);
+            if (mContinuous) {
+                return new WindowTraceRingBuffer(mBufferCapacity, mTraceFile);
+            } else {
+                return new WindowTraceQueueBuffer(mBufferCapacity, mTraceFile);
+            }
         }
     }
 }
diff --git a/services/core/java/com/android/server/wm/WindowTraceQueueBuffer.java b/services/core/java/com/android/server/wm/WindowTraceQueueBuffer.java
index b7fc7ac..eaedde9 100644
--- a/services/core/java/com/android/server/wm/WindowTraceQueueBuffer.java
+++ b/services/core/java/com/android/server/wm/WindowTraceQueueBuffer.java
@@ -18,10 +18,14 @@
 
 import static android.os.Build.IS_USER;
 
+import android.util.Log;
+
 import com.android.internal.annotations.VisibleForTesting;
 
 import java.io.File;
+import java.io.FileOutputStream;
 import java.io.IOException;
+import java.io.OutputStream;
 
 /**
  * A buffer structure backed by a {@link java.util.concurrent.BlockingQueue} to store the first
@@ -29,14 +33,17 @@
  * Once the buffer is full it will no longer accepts new elements.
  */
 class WindowTraceQueueBuffer extends WindowTraceBuffer {
-    private Thread mWriterThread;
+    private static final String TAG = "WindowTracing";
+
+    private Thread mConsumerThread;
     private boolean mCancel;
 
     @VisibleForTesting
-    WindowTraceQueueBuffer(int size, File traceFile, boolean startWriterThread) throws IOException {
+    WindowTraceQueueBuffer(int size, File traceFile, boolean startConsumerThread)
+            throws IOException {
         super(size, traceFile);
-        if (startWriterThread) {
-            initializeWriterThread();
+        if (startConsumerThread) {
+            initializeConsumerThread();
         }
     }
 
@@ -44,45 +51,56 @@
         this(size, traceFile, !IS_USER);
     }
 
-    private void initializeWriterThread() {
+    private void initializeConsumerThread() {
         mCancel = false;
-        mWriterThread = new Thread(() -> {
+        mConsumerThread = new Thread(() -> {
             try {
                 loop();
+            } catch (InterruptedException e) {
+                Log.i(TAG, "Interrupting trace consumer thread");
             } catch (IOException e) {
-                throw new IllegalStateException("Failed to execute trace write loop thread", e);
+                Log.e(TAG, "Failed to execute trace consumer thread", e);
             }
         }, "window_tracing");
-        mWriterThread.start();
+        mConsumerThread.start();
     }
 
-    private void loop() throws IOException {
+    private void loop() throws IOException, InterruptedException {
         while (!mCancel) {
-            writeNextBufferElementToFile();
-        }
-    }
+            byte[] proto;
+            synchronized (mBufferLock) {
+                mBufferLock.wait();
 
-    private void restartWriterThread() throws InterruptedException {
-        if (mWriterThread != null) {
-            mCancel = true;
-            mWriterThread.interrupt();
-            mWriterThread.join();
-            initializeWriterThread();
+                proto = mBuffer.poll();
+                if (proto != null) {
+                    mBufferSize -= proto.length;
+                }
+            }
+
+            if (proto != null) {
+                try (OutputStream os = new FileOutputStream(mTraceFile, true)) {
+                    os.write(proto);
+                }
+            }
         }
     }
 
     @Override
-    boolean canAdd(byte[] protoBytes) {
+    boolean canAdd(int protoLength) {
         long availableSpace = getAvailableSpace();
-        return availableSpace >= protoBytes.length;
+        return availableSpace >= protoLength;
     }
 
     @Override
-    void writeToDisk() throws InterruptedException {
-        while (!mBuffer.isEmpty()) {
-            mBufferSizeLock.wait();
-            mBufferSizeLock.notify();
+    void writeTraceToFile() throws InterruptedException {
+        synchronized (mBufferLock) {
+            mCancel = true;
+            mBufferLock.notify();
         }
-        restartWriterThread();
+
+        if (mConsumerThread != null) {
+            mConsumerThread.join();
+            mConsumerThread = null;
+        }
     }
 }
diff --git a/services/core/java/com/android/server/wm/WindowTraceRingBuffer.java b/services/core/java/com/android/server/wm/WindowTraceRingBuffer.java
new file mode 100644
index 0000000..7c69f23
--- /dev/null
+++ b/services/core/java/com/android/server/wm/WindowTraceRingBuffer.java
@@ -0,0 +1,68 @@
+/*
+ * 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.
+ */
+
+package com.android.server.wm;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+
+/**
+ * A ring buffer to store the {@code #size size} bytes of window trace data.
+ * The buffer operates on a trace entry level, that is, if the new trace data is larger than the
+ * available buffer space, the buffer will discard as many full trace entries as necessary to fit
+ * the new trace.
+ */
+class WindowTraceRingBuffer extends WindowTraceBuffer {
+    WindowTraceRingBuffer(int size, File traceFile) throws IOException {
+        super(size, traceFile);
+    }
+
+    @Override
+    boolean canAdd(int protoLength) {
+        long availableSpace = getAvailableSpace();
+
+        while (availableSpace < protoLength) {
+            discardOldest();
+            availableSpace = getAvailableSpace();
+        }
+
+        return true;
+    }
+
+    @Override
+    void writeTraceToFile() throws IOException {
+        synchronized (mBufferLock) {
+            try (OutputStream os = new FileOutputStream(mTraceFile, true)) {
+                while (!mBuffer.isEmpty()) {
+                    byte[] proto;
+                    proto = mBuffer.poll();
+                    mBufferSize -= proto.length;
+                    os.write(proto);
+                }
+            }
+        }
+    }
+
+    private void discardOldest() {
+        byte[] item = mBuffer.poll();
+        if (item == null) {
+            throw new IllegalStateException("No element to discard from buffer");
+        }
+        mBufferSize -= item.length;
+    }
+}
diff --git a/services/core/java/com/android/server/wm/WindowTracing.java b/services/core/java/com/android/server/wm/WindowTracing.java
index 63539c4..4c9a917 100644
--- a/services/core/java/com/android/server/wm/WindowTracing.java
+++ b/services/core/java/com/android/server/wm/WindowTracing.java
@@ -53,6 +53,7 @@
 
     private WindowTraceBuffer mTraceBuffer;
 
+    private boolean mContinuousMode;
     private boolean mEnabled;
     private volatile boolean mEnabledLockFree;
 
@@ -70,13 +71,11 @@
         synchronized (mLock) {
             logAndPrintln(pw, "Start tracing to " + mBufferBuilder.getFile() + ".");
             if (mTraceBuffer != null) {
-                try {
-                    mTraceBuffer.writeToDisk();
-                } catch (InterruptedException e) {
-                    logAndPrintln(pw, "Error: Unable to flush the previous buffer.");
-                }
+                writeTraceToFileLocked();
             }
-            mTraceBuffer = mBufferBuilder.build();
+            mTraceBuffer = mBufferBuilder
+                    .setContinuousMode(mContinuousMode)
+                    .build();
             mEnabled = mEnabledLockFree = true;
         }
     }
@@ -104,29 +103,29 @@
                     logAndPrintln(pw, "ERROR: tracing was re-enabled while waiting for flush.");
                     throw new IllegalStateException("tracing enabled while waiting for flush.");
                 }
-                try {
-                    mTraceBuffer.writeToDisk();
-                } catch (IOException e) {
-                    Log.e(TAG, "Unable to write buffer to file", e);
-                } catch (InterruptedException e) {
-                    Log.e(TAG, "Unable to interrupt window tracing file write thread", e);
-                }
+                writeTraceToFileLocked();
+                mTraceBuffer = null;
             }
             logAndPrintln(pw, "Trace written to " + mBufferBuilder.getFile() + ".");
         }
     }
 
+    private void setContinuousMode(boolean continuous, PrintWriter pw) {
+        logAndPrintln(pw, "Setting window tracing continuous mode to " + continuous);
+
+        if (mEnabled) {
+            logAndPrintln(pw, "Trace is currently active, change will take effect once the "
+                    + "trace is restarted.");
+        }
+        mContinuousMode = continuous;
+    }
+
     private void appendTraceEntry(ProtoOutputStream proto) {
         if (!mEnabledLockFree) {
             return;
         }
 
-        try {
-            mTraceBuffer.add(proto);
-        } catch (InterruptedException e) {
-            Log.e(TAG, "Unable to add element to trace", e);
-            Thread.currentThread().interrupt();
-        }
+        mTraceBuffer.add(proto);
     }
 
     boolean isEnabled() {
@@ -138,9 +137,10 @@
         return new WindowTracing(file);
     }
 
-    int onShellCommand(ShellCommand shell, String cmd) {
+    int onShellCommand(ShellCommand shell) {
         PrintWriter pw = shell.getOutPrintWriter();
         try {
+            String cmd = shell.getNextArgRequired();
             switch (cmd) {
                 case "start":
                     startTrace(pw);
@@ -148,6 +148,9 @@
                 case "stop":
                     stopTrace(pw);
                     return 0;
+                case "continuous":
+                    setContinuousMode(Boolean.valueOf(shell.getNextArgRequired()), pw);
+                    return 0;
                 default:
                     pw.println("Unknown command: " + cmd);
                     return -1;
@@ -162,6 +165,7 @@
         if (!isEnabled()) {
             return;
         }
+
         ProtoOutputStream os = new ProtoOutputStream();
         long tokenOuter = os.start(ENTRY);
         os.write(ELAPSED_REALTIME_NANOS, SystemClock.elapsedRealtimeNanos());
@@ -179,4 +183,33 @@
         appendTraceEntry(os);
         Trace.traceEnd(Trace.TRACE_TAG_WINDOW_MANAGER);
     }
+
+    /**
+     * Writes the trace buffer to disk. This method has no internal synchronization and should be
+     * externally synchronized
+     */
+    private void writeTraceToFileLocked() {
+        if (mTraceBuffer == null) {
+            return;
+        }
+
+        try {
+            mTraceBuffer.dump();
+        } catch (IOException e) {
+            Log.e(TAG, "Unable to write buffer to file", e);
+        } catch (InterruptedException e) {
+            Log.e(TAG, "Unable to interrupt window tracing file write thread", e);
+        }
+    }
+
+    /**
+     * Writes the trace buffer to disk and clones it into a new file for the bugreport.
+     * This method is synchronized with {@code #startTrace(PrintWriter)} and
+     * {@link #stopTrace(PrintWriter)}.
+     */
+    void writeTraceToFile() {
+        synchronized (mLock) {
+            writeTraceToFileLocked();
+        }
+    }
 }
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
index f79f9bc..51bdbb3 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
@@ -1925,7 +1925,11 @@
         }
 
         AlarmManager getAlarmManager() {
-            return (AlarmManager) mContext.getSystemService(AlarmManager.class);
+            return mContext.getSystemService(AlarmManager.class);
+        }
+
+        ConnectivityManager getConnectivityManager() {
+            return mContext.getSystemService(ConnectivityManager.class);
         }
 
         IWindowManager getIWindowManager() {
@@ -6308,7 +6312,8 @@
      * @throws UnsupportedOperationException if the package does not support being set as always-on.
      */
     @Override
-    public boolean setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage, boolean lockdown)
+    public boolean setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage, boolean lockdown,
+            List<String> lockdownWhitelist)
             throws SecurityException {
         enforceProfileOrDeviceOwner(admin);
 
@@ -6316,11 +6321,23 @@
         final long token = mInjector.binderClearCallingIdentity();
         try {
             if (vpnPackage != null && !isPackageInstalledForUser(vpnPackage, userId)) {
-                return false;
+                Slog.w(LOG_TAG, "Non-existent VPN package specified: " + vpnPackage);
+                throw new ServiceSpecificException(
+                        DevicePolicyManager.ERROR_VPN_PACKAGE_NOT_FOUND, vpnPackage);
             }
-            ConnectivityManager connectivityManager = (ConnectivityManager)
-                    mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
-            if (!connectivityManager.setAlwaysOnVpnPackageForUser(userId, vpnPackage, lockdown)) {
+
+            if (vpnPackage != null && lockdown && lockdownWhitelist != null) {
+                for (String packageName : lockdownWhitelist) {
+                    if (!isPackageInstalledForUser(packageName, userId)) {
+                        Slog.w(LOG_TAG, "Non-existent package in VPN whitelist: " + packageName);
+                        throw new ServiceSpecificException(
+                                DevicePolicyManager.ERROR_VPN_PACKAGE_NOT_FOUND, packageName);
+                    }
+                }
+            }
+            // If some package is uninstalled after the check above, it will be ignored by CM.
+            if (!mInjector.getConnectivityManager().setAlwaysOnVpnPackageForUser(
+                    userId, vpnPackage, lockdown, lockdownWhitelist)) {
                 throw new UnsupportedOperationException();
             }
             DevicePolicyEventLogger
@@ -6337,16 +6354,40 @@
     }
 
     @Override
-    public String getAlwaysOnVpnPackage(ComponentName admin)
+    public String getAlwaysOnVpnPackage(ComponentName admin) throws SecurityException {
+        enforceProfileOrDeviceOwner(admin);
+
+        final int userId = mInjector.userHandleGetCallingUserId();
+        final long token = mInjector.binderClearCallingIdentity();
+        try {
+            return mInjector.getConnectivityManager().getAlwaysOnVpnPackageForUser(userId);
+        } finally {
+            mInjector.binderRestoreCallingIdentity(token);
+        }
+    }
+
+    @Override
+    public boolean isAlwaysOnVpnLockdownEnabled(ComponentName admin) throws SecurityException {
+        enforceProfileOrDeviceOwner(admin);
+
+        final int userId = mInjector.userHandleGetCallingUserId();
+        final long token = mInjector.binderClearCallingIdentity();
+        try {
+            return mInjector.getConnectivityManager().isVpnLockdownEnabled(userId);
+        } finally {
+            mInjector.binderRestoreCallingIdentity(token);
+        }
+    }
+
+    @Override
+    public List<String> getAlwaysOnVpnLockdownWhitelist(ComponentName admin)
             throws SecurityException {
         enforceProfileOrDeviceOwner(admin);
 
         final int userId = mInjector.userHandleGetCallingUserId();
         final long token = mInjector.binderClearCallingIdentity();
-        try{
-            ConnectivityManager connectivityManager = (ConnectivityManager)
-                    mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
-            return connectivityManager.getAlwaysOnVpnPackageForUser(userId);
+        try {
+            return mInjector.getConnectivityManager().getVpnLockdownWhitelist(userId);
         } finally {
             mInjector.binderRestoreCallingIdentity(token);
         }
@@ -6819,9 +6860,7 @@
         enforceDeviceOwner(who);
         long token = mInjector.binderClearCallingIdentity();
         try {
-            ConnectivityManager connectivityManager = (ConnectivityManager)
-                    mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
-            connectivityManager.setGlobalProxy(proxyInfo);
+            mInjector.getConnectivityManager().setGlobalProxy(proxyInfo);
         } finally {
             mInjector.binderRestoreCallingIdentity(token);
         }
diff --git a/services/java/com/android/server/SystemServer.java b/services/java/com/android/server/SystemServer.java
index 5861368..e378dd6 100644
--- a/services/java/com/android/server/SystemServer.java
+++ b/services/java/com/android/server/SystemServer.java
@@ -55,6 +55,7 @@
 import android.os.Trace;
 import android.os.UserHandle;
 import android.os.storage.IStorageManager;
+import android.provider.DeviceConfig;
 import android.provider.Settings;
 import android.sysprop.VoldProperties;
 import android.text.TextUtils;
@@ -91,6 +92,7 @@
 import com.android.server.dreams.DreamManagerService;
 import com.android.server.emergency.EmergencyAffordanceService;
 import com.android.server.hdmi.HdmiControlService;
+import com.android.server.incident.IncidentCompanionService;
 import com.android.server.input.InputManagerService;
 import com.android.server.inputmethod.InputMethodManagerService;
 import com.android.server.inputmethod.MultiClientInputMethodManagerService;
@@ -1856,6 +1858,11 @@
         mSystemServiceManager.startService(StatsCompanionService.Lifecycle.class);
         traceEnd();
 
+        // Incidentd and dumpstated helper
+        traceBeginAndSlog("StartIncidentCompanionService");
+        mSystemServiceManager.startService(IncidentCompanionService.class);
+        traceEnd();
+
         if (safeMode) {
             traceBeginAndSlog("EnterSafeModeAndDisableJitCompilation");
             mActivityManagerService.enterSafeMode();
@@ -2212,10 +2219,9 @@
     }
 
     private void startContentCaptureService(@NonNull Context context) {
-
-        // Check if it was explicitly enabled by Settings
-        final String settings = Settings.Global.getString(context.getContentResolver(),
-                Settings.Global.CONTENT_CAPTURE_SERVICE_EXPLICITLY_ENABLED);
+        // Check if it was explicitly enabled by DeviceConfig
+        final String settings = DeviceConfig.getProperty(DeviceConfig.ContentCapture.NAMESPACE,
+                DeviceConfig.ContentCapture.PROPERTY_CONTENTCAPTURE_ENABLED);
         if (settings == null) {
             // Better be safe than sorry...
             Slog.d(TAG, "ContentCaptureService disabled because its not set by OEM");
@@ -2224,7 +2230,7 @@
         switch (settings) {
             case "always":
                 // Should be used only during development
-                Slog.d(TAG, "ContentCaptureService explicitly enabled by Settings");
+                Slog.d(TAG, "ContentCaptureService explicitly enabled by DeviceConfig");
                 break;
             case "default":
                 // Default case: check if OEM overlaid the resource that defines the service.
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 5b02266..a01d589 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
@@ -1151,6 +1151,10 @@
         return null;
     }
 
+    public String getIncidentReportApproverPackageName() throws RemoteException {
+        return null;
+    }
+
     @Override
     public boolean isPackageStateProtected(String packageName, int userId) throws RemoteException {
         return false;
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java b/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
index 4a4fece..5d46f0f 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
@@ -3858,7 +3858,7 @@
         mService.addNotification(r);
 
         mService.mNotificationDelegate.onNotificationSmartReplySent(
-                r.getKey(), replyIndex, reply, generatedByAssistant);
+                r.getKey(), replyIndex, reply, generatedByAssistant, NOTIFICATION_LOCATION_UNKNOWN);
         verify(mAssistants).notifyAssistantSuggestedReplySent(
                 eq(r.sbn), eq(reply), eq(generatedByAssistant));
     }
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowTraceBufferTest.java b/services/tests/wmtests/src/com/android/server/wm/WindowTraceBufferTest.java
index 8d83497..df3ef55 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowTraceBufferTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowTraceBufferTest.java
@@ -19,8 +19,6 @@
 import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
 
 import static com.android.server.wm.WindowManagerTraceFileProto.MAGIC_NUMBER;
-import static com.android.server.wm.WindowManagerTraceFileProto.MAGIC_NUMBER_H;
-import static com.android.server.wm.WindowManagerTraceFileProto.MAGIC_NUMBER_L;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
@@ -31,13 +29,14 @@
 
 import androidx.test.filters.SmallTest;
 
+import com.android.internal.util.Preconditions;
+
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
 
 import java.io.File;
 import java.io.IOException;
-import java.util.Arrays;
 
 
 /**
@@ -49,8 +48,6 @@
 @SmallTest
 @Presubmit
 public class WindowTraceBufferTest {
-    private static final long MAGIC_NUMBER_VALUE = ((long) MAGIC_NUMBER_H << 32) | MAGIC_NUMBER_L;
-
     private File mFile;
 
     @Before
@@ -81,18 +78,22 @@
 
         buffer.add(toWrite1);
         assertTrue("First element should be in the list",
-                buffer.mBuffer.stream().anyMatch(p -> Arrays.equals(p, toWrite1Bytes)));
+                buffer.contains(toWrite1Bytes));
 
         buffer.add(toWrite2);
         assertTrue("First element should be in the list",
-                buffer.mBuffer.stream().anyMatch(p -> Arrays.equals(p, toWrite1Bytes)));
+                buffer.contains(toWrite1Bytes));
         assertTrue("Second element should be in the list",
-                buffer.mBuffer.stream().anyMatch(p -> Arrays.equals(p, toWrite2Bytes)));
+                buffer.contains(toWrite2Bytes));
 
         buffer.add(toWrite3);
 
+        assertTrue("First element should be in the list",
+                buffer.contains(toWrite1Bytes));
+        assertTrue("Second element should be in the list",
+                buffer.contains(toWrite2Bytes));
         assertTrue("Third element should not be in the list",
-                buffer.mBuffer.stream().noneMatch(p -> Arrays.equals(p, toWrite3Bytes)));
+                !buffer.contains(toWrite3Bytes));
 
         assertEquals("Buffer should have 2 elements", buffer.mBuffer.size(), 2);
         assertEquals(String.format("Buffer is full, used space should be %d", bufferCapacity),
@@ -101,6 +102,111 @@
                 buffer.getAvailableSpace(), 0);
     }
 
+    @Test
+    public void testTraceRingBuffer_addItem() throws Exception {
+        ProtoOutputStream toWrite = getDummy(1);
+        final int objectSize = toWrite.getBytes().length;
+
+        final WindowTraceBuffer buffer = buildRingBuffer(objectSize);
+
+        Preconditions.checkArgument(buffer.mBuffer.isEmpty());
+
+        buffer.add(toWrite);
+
+        assertEquals("Item was not added to the buffer", buffer.mBuffer.size(), 1);
+        assertEquals("Total buffer getSize differs from inserted object",
+                buffer.mBufferSize, objectSize);
+        assertEquals("Available buffer space does not match used one",
+                buffer.getAvailableSpace(), 0);
+    }
+
+    @Test
+    public void testTraceRingBuffer_addItemMustOverwriteOne() throws Exception {
+        ProtoOutputStream toWrite1 = getDummy(1);
+        ProtoOutputStream toWrite2 = getDummy(2);
+        ProtoOutputStream toWrite3 = getDummy(3);
+        byte[] toWrite1Bytes = toWrite1.getBytes();
+        byte[] toWrite2Bytes = toWrite2.getBytes();
+        byte[] toWrite3Bytes = toWrite3.getBytes();
+        final int objectSize = toWrite1.getBytes().length;
+
+        final int bufferCapacity = objectSize * 2 + 1;
+        final WindowTraceBuffer buffer = buildRingBuffer(bufferCapacity);
+
+        buffer.add(toWrite1);
+        assertTrue("First element should be in the list",
+                buffer.contains(toWrite1Bytes));
+
+        buffer.add(toWrite2);
+        assertTrue("First element should be in the list",
+                buffer.contains(toWrite1Bytes));
+        assertTrue("Second element should be in the list",
+                buffer.contains(toWrite2Bytes));
+
+        buffer.add(toWrite3);
+        assertTrue("First element should not be in the list",
+                !buffer.contains(toWrite1Bytes));
+        assertTrue("Second element should be in the list",
+                buffer.contains(toWrite2Bytes));
+        assertTrue("Third element should be in the list",
+                buffer.contains(toWrite3Bytes));
+        assertEquals("Buffer should have 2 elements", buffer.mBuffer.size(), 2);
+        assertEquals(String.format("Buffer is full, used space should be %d", bufferCapacity),
+                buffer.mBufferSize, bufferCapacity - 1);
+        assertEquals(" Buffer is full, available space should be 0",
+                buffer.getAvailableSpace(), 1);
+    }
+
+    @Test
+    public void testTraceRingBuffer_addItemMustOverwriteMultiple() throws Exception {
+        ProtoOutputStream toWriteSmall1 = getDummy(1);
+        ProtoOutputStream toWriteSmall2 = getDummy(2);
+        byte[] toWriteSmall1Bytes = toWriteSmall1.getBytes();
+        byte[] toWriteSmall2Bytes = toWriteSmall2.getBytes();
+        final int objectSize = toWriteSmall1.getBytes().length;
+
+        final int bufferCapacity = objectSize * 2;
+        final WindowTraceBuffer buffer = buildRingBuffer(bufferCapacity);
+
+        ProtoOutputStream toWriteBig = new ProtoOutputStream();
+        toWriteBig.write(MAGIC_NUMBER, 1);
+        toWriteBig.write(MAGIC_NUMBER, 2);
+        byte[] toWriteBigBytes = toWriteBig.getBytes();
+        toWriteBig.flush();
+
+        buffer.add(toWriteSmall1);
+        assertTrue("First element should be in the list",
+                buffer.contains(toWriteSmall1Bytes));
+
+        buffer.add(toWriteSmall2);
+        assertTrue("First element should be in the list",
+                buffer.contains(toWriteSmall1Bytes));
+        assertTrue("Second element should be in the list",
+                buffer.contains(toWriteSmall2Bytes));
+
+        buffer.add(toWriteBig);
+        assertTrue("Third element should overwrite all others",
+                !buffer.contains(toWriteSmall1Bytes));
+        assertTrue("Third element should overwrite all others",
+                !buffer.contains(toWriteSmall2Bytes));
+        assertTrue("Third element should overwrite all others",
+                buffer.contains(toWriteBigBytes));
+
+        assertEquals(" Buffer should have only 1 big element", buffer.mBuffer.size(), 1);
+        assertEquals(String.format(" Buffer is full, used space should be %d", bufferCapacity),
+                buffer.mBufferSize, bufferCapacity);
+        assertEquals(" Buffer is full, available space should be 0",
+                buffer.getAvailableSpace(), 0);
+    }
+
+    private WindowTraceBuffer buildRingBuffer(int capacity) throws IOException {
+        return new WindowTraceBuffer.Builder()
+                .setContinuousMode(true)
+                .setBufferCapacity(capacity)
+                .setTraceFile(mFile)
+                .build();
+    }
+
     private ProtoOutputStream getDummy(int value) {
         ProtoOutputStream toWrite = new ProtoOutputStream();
         toWrite.write(MAGIC_NUMBER, value);
diff --git a/telecomm/java/android/telecom/DefaultDialerManager.java b/telecomm/java/android/telecom/DefaultDialerManager.java
index 2680af7..b2fa5d4 100644
--- a/telecomm/java/android/telecom/DefaultDialerManager.java
+++ b/telecomm/java/android/telecom/DefaultDialerManager.java
@@ -15,17 +15,22 @@
 package android.telecom;
 
 import android.app.ActivityManager;
+import android.app.role.RoleManager;
+import android.app.role.RoleManagerCallback;
 import android.content.Context;
 import android.content.Intent;
 import android.content.pm.ActivityInfo;
 import android.content.pm.PackageManager;
 import android.content.pm.ResolveInfo;
 import android.net.Uri;
+import android.os.AsyncTask;
+import android.os.Binder;
 import android.os.Process;
 import android.os.UserHandle;
-import android.provider.Settings;
 import android.text.TextUtils;
 
+import com.android.internal.util.CollectionUtils;
+
 import java.util.ArrayList;
 import java.util.List;
 
@@ -64,25 +69,24 @@
      * */
     public static boolean setDefaultDialerApplication(Context context, String packageName,
             int user) {
-        // Get old package name
-        String oldPackageName = Settings.Secure.getStringForUser(context.getContentResolver(),
-                Settings.Secure.DIALER_DEFAULT_APPLICATION, user);
+        long identity = Binder.clearCallingIdentity();
+        try {
+            context.getSystemService(RoleManager.class).addRoleHolderAsUser(
+                    RoleManager.ROLE_DIALER, packageName, UserHandle.of(user),
+                    AsyncTask.THREAD_POOL_EXECUTOR, new RoleManagerCallback() {
+                        @Override
+                        public void onSuccess() {}
 
-        if (packageName != null && oldPackageName != null && packageName.equals(oldPackageName)) {
-            // No change
-            return false;
-        }
-
-        // Only make the change if the new package belongs to a valid phone application
-        List<String> packageNames = getInstalledDialerApplications(context, user);
-
-        if (packageNames.contains(packageName)) {
-            // Update the secure setting.
-            Settings.Secure.putStringForUser(context.getContentResolver(),
-                    Settings.Secure.DIALER_DEFAULT_APPLICATION, packageName, user);
+                        @Override
+                        public void onFailure() {
+                            Log.w(TAG, "Failed to set default dialer to %s for user %s",
+                                    packageName, user);
+                        }
+                    });
             return true;
+        } finally {
+            Binder.restoreCallingIdentity(identity);
         }
-        return false;
     }
 
     /**
@@ -116,28 +120,12 @@
      * @hide
      * */
     public static String getDefaultDialerApplication(Context context, int user) {
-        String defaultPackageName = Settings.Secure.getStringForUser(context.getContentResolver(),
-                Settings.Secure.DIALER_DEFAULT_APPLICATION, user);
-
-        final List<String> packageNames = getInstalledDialerApplications(context, user);
-
-        // Verify that the default dialer has not been disabled or uninstalled.
-        if (packageNames.contains(defaultPackageName)) {
-            return defaultPackageName;
-        }
-
-        // No user-set dialer found, fallback to system dialer
-        String systemDialerPackageName = getTelecomManager(context).getSystemDialerPackage();
-
-        if (TextUtils.isEmpty(systemDialerPackageName)) {
-            // No system dialer configured at build time
-            return null;
-        }
-
-        if (packageNames.contains(systemDialerPackageName)) {
-            return systemDialerPackageName;
-        } else {
-            return null;
+        long identity = Binder.clearCallingIdentity();
+        try {
+            return CollectionUtils.firstOrNull(context.getSystemService(RoleManager.class)
+                    .getRoleHoldersAsUser(RoleManager.ROLE_DIALER, UserHandle.of(user)));
+        } finally {
+            Binder.restoreCallingIdentity(identity);
         }
     }
 
diff --git a/telephony/java/android/telephony/CarrierConfigManager.java b/telephony/java/android/telephony/CarrierConfigManager.java
index 349880d..068b68e 100644
--- a/telephony/java/android/telephony/CarrierConfigManager.java
+++ b/telephony/java/android/telephony/CarrierConfigManager.java
@@ -2424,34 +2424,55 @@
             "5g_icon_configuration_string";
 
     /**
-     * Controls RSRP threshold at which AlternativeNetworkService will decide whether
+     * Controls RSRP threshold at which OpportunisticNetworkService will decide whether
      * the opportunistic network is good enough for internet data.
      */
     public static final String KEY_OPPORTUNISTIC_NETWORK_ENTRY_THRESHOLD_RSRP_INT =
             "opportunistic_network_entry_threshold_rsrp_int";
 
     /**
-     * Controls RSSNR threshold at which AlternativeNetworkService will decide whether
+     * Controls RSSNR threshold at which OpportunisticNetworkService will decide whether
      * the opportunistic network is good enough for internet data.
      */
     public static final String KEY_OPPORTUNISTIC_NETWORK_ENTRY_THRESHOLD_RSSNR_INT =
             "opportunistic_network_entry_threshold_rssnr_int";
 
     /**
-     * Controls RSRP threshold below which AlternativeNetworkService will decide whether
+     * Controls RSRP threshold below which OpportunisticNetworkService will decide whether
      * the opportunistic network available is not good enough for internet data.
      */
     public static final String KEY_OPPORTUNISTIC_NETWORK_EXIT_THRESHOLD_RSRP_INT =
             "opportunistic_network_exit_threshold_rsrp_int";
 
     /**
-     * Controls RSSNR threshold below which AlternativeNetworkService will decide whether
+     * Controls RSSNR threshold below which OpportunisticNetworkService will decide whether
      * the opportunistic network available is not good enough for internet data.
      */
     public static final String KEY_OPPORTUNISTIC_NETWORK_EXIT_THRESHOLD_RSSNR_INT =
             "opportunistic_network_exit_threshold_rssnr_int";
 
     /**
+     * Controls bandwidth threshold in Kbps at which OpportunisticNetworkService will decide whether
+     * the opportunistic network is good enough for internet data.
+     */
+    public static final String KEY_OPPORTUNISTIC_NETWORK_ENTRY_THRESHOLD_BANDWIDTH_INT =
+            "opportunistic_network_entry_threshold_bandwidth_int";
+
+    /**
+     * Controls hysteresis time in milli seconds for which OpportunisticNetworkService
+     * will wait before attaching to a network.
+     */
+    public static final String KEY_OPPORTUNISTIC_NETWORK_ENTRY_OR_EXIT_HYSTERESIS_TIME_LONG =
+            "opportunistic_network_entry_or_exit_hysteresis_time_long";
+
+    /**
+     * Controls hysteresis time in milli seconds for which OpportunisticNetworkService
+     * will wait before switching data to a network.
+     */
+    public static final String KEY_OPPORTUNISTIC_NETWORK_DATA_SWITCH_HYSTERESIS_TIME_LONG =
+            "opportunistic_network_data_switch_hysteresis_time_long";
+
+    /**
      * GPS configs. See android.hardware.gnss@1.0 IGnssConfiguration.
      * @hide
      */
@@ -2938,6 +2959,12 @@
         sDefaults.putInt(KEY_OPPORTUNISTIC_NETWORK_ENTRY_THRESHOLD_RSSNR_INT, 45);
         /* Default value is minimum RSSNR level needed for SIGNAL_STRENGTH_MODERATE */
         sDefaults.putInt(KEY_OPPORTUNISTIC_NETWORK_EXIT_THRESHOLD_RSSNR_INT, 10);
+        /* Default value is 1024 kbps */
+        sDefaults.putInt(KEY_OPPORTUNISTIC_NETWORK_ENTRY_THRESHOLD_BANDWIDTH_INT, 1024);
+        /* Default value is 10 seconds */
+        sDefaults.putInt(KEY_OPPORTUNISTIC_NETWORK_ENTRY_OR_EXIT_HYSTERESIS_TIME_LONG, 10000);
+        /* Default value is 10 seconds. */
+        sDefaults.putInt(KEY_OPPORTUNISTIC_NETWORK_DATA_SWITCH_HYSTERESIS_TIME_LONG, 10000);
         sDefaults.putAll(Gps.getDefaults());
     }
 
diff --git a/telephony/java/android/telephony/PhoneCapability.java b/telephony/java/android/telephony/PhoneCapability.java
index 2ebfa53..21dad77 100644
--- a/telephony/java/android/telephony/PhoneCapability.java
+++ b/telephony/java/android/telephony/PhoneCapability.java
@@ -33,15 +33,17 @@
     public final int maxActiveVoiceCalls;
     public final int maxActiveData;
     public final int max5G;
+    public final boolean validationBeforeSwitchSupported;
     public final List<ModemInfo> logicalModemList;
 
     public PhoneCapability(int maxActiveVoiceCalls, int maxActiveData, int max5G,
-            List<ModemInfo> logicalModemList) {
+            List<ModemInfo> logicalModemList, boolean validationBeforeSwitchSupported) {
         this.maxActiveVoiceCalls = maxActiveVoiceCalls;
         this.maxActiveData = maxActiveData;
         this.max5G = max5G;
         // Make sure it's not null.
         this.logicalModemList = logicalModemList == null ? new ArrayList<>() : logicalModemList;
+        this.validationBeforeSwitchSupported = validationBeforeSwitchSupported;
     }
 
     @Override
@@ -55,13 +57,15 @@
         maxActiveVoiceCalls = in.readInt();
         maxActiveData = in.readInt();
         max5G = in.readInt();
+        validationBeforeSwitchSupported = in.readBoolean();
         logicalModemList = new ArrayList<>();
         in.readList(logicalModemList, ModemInfo.class.getClassLoader());
     }
 
     @Override
     public int hashCode() {
-        return Objects.hash(maxActiveVoiceCalls, maxActiveData, max5G, logicalModemList);
+        return Objects.hash(maxActiveVoiceCalls, maxActiveData, max5G, logicalModemList,
+                validationBeforeSwitchSupported);
     }
 
     @Override
@@ -79,6 +83,7 @@
         return (maxActiveVoiceCalls == s.maxActiveVoiceCalls
                 && maxActiveData == s.maxActiveData
                 && max5G == s.max5G
+                && validationBeforeSwitchSupported == s.validationBeforeSwitchSupported
                 && logicalModemList.equals(s.logicalModemList));
     }
 
@@ -96,6 +101,7 @@
         dest.writeInt(maxActiveVoiceCalls);
         dest.writeInt(maxActiveData);
         dest.writeInt(max5G);
+        dest.writeBoolean(validationBeforeSwitchSupported);
         dest.writeList(logicalModemList);
     }
 
diff --git a/telephony/java/android/telephony/PhoneStateListener.java b/telephony/java/android/telephony/PhoneStateListener.java
index af324de..fea1b7b 100644
--- a/telephony/java/android/telephony/PhoneStateListener.java
+++ b/telephony/java/android/telephony/PhoneStateListener.java
@@ -28,6 +28,7 @@
 import android.os.HandlerExecutor;
 import android.os.Looper;
 import android.telephony.emergency.EmergencyNumber;
+import android.telephony.ims.ImsReasonInfo;
 
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.telephony.IPhoneStateListener;
@@ -347,6 +348,20 @@
     @SystemApi
     public static final int LISTEN_CALL_ATTRIBUTES_CHANGED                 = 0x04000000;
 
+    /**
+     * Listen for IMS call disconnect causes which contains
+     * {@link android.telephony.ims.ImsReasonInfo}
+     *
+     * {@more}
+     * Requires Permission: {@link android.Manifest.permission#READ_PRECISE_PHONE_STATE
+     * READ_PRECISE_PHONE_STATE}
+     *
+     * @see #onImsCallDisconnectCauseChanged(ImsReasonInfo)
+     * @hide
+     */
+    @SystemApi
+    public static final int LISTEN_IMS_CALL_DISCONNECT_CAUSES              = 0x08000000;
+
     /*
      * Subscription used to listen to the phone state changes
      * @hide
@@ -578,6 +593,17 @@
     }
 
     /**
+     * Callback invoked when Ims call disconnect cause changes.
+     * @param imsReasonInfo {@link ImsReasonInfo} contains details on why IMS call failed.
+     *
+     * @hide
+     */
+    @SystemApi
+    public void onImsCallDisconnectCauseChanged(@NonNull ImsReasonInfo imsReasonInfo) {
+        // default implementation empty
+    }
+
+    /**
      * Callback invoked when data connection state changes with precise information.
      * @param dataConnectionState {@link PreciseDataConnectionState}
      *
@@ -981,6 +1007,16 @@
             Binder.withCleanCallingIdentity(
                     () -> mExecutor.execute(() -> psl.onPreferredDataSubIdChanged(subId)));
         }
+
+        public void onImsCallDisconnectCauseChanged(ImsReasonInfo disconnectCause) {
+            PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
+            if (psl == null) return;
+
+            Binder.withCleanCallingIdentity(
+                    () -> mExecutor.execute(
+                            () -> psl.onImsCallDisconnectCauseChanged(disconnectCause)));
+
+        }
     }
 
 
diff --git a/telephony/java/android/telephony/SubscriptionInfo.java b/telephony/java/android/telephony/SubscriptionInfo.java
index a3b3374..17acf2b 100644
--- a/telephony/java/android/telephony/SubscriptionInfo.java
+++ b/telephony/java/android/telephony/SubscriptionInfo.java
@@ -578,10 +578,10 @@
     }
 
     /**
-     * @return the cardId of the SIM card which contains the subscription.
-     * @hide
+     * Returns the card ID of the SIM card which contains the subscription (see
+     * {@link UiccCardInfo#getCardId()}.
+     * @return the cardId
      */
-    @SystemApi
     public int getCardId() {
         return this.mCardId;
     }
diff --git a/telephony/java/android/telephony/TelephonyManager.java b/telephony/java/android/telephony/TelephonyManager.java
index 80ee0a7..ecfc401 100644
--- a/telephony/java/android/telephony/TelephonyManager.java
+++ b/telephony/java/android/telephony/TelephonyManager.java
@@ -227,10 +227,9 @@
     public static final int SRVCC_STATE_HANDOVER_CANCELED  = 3;
 
     /**
-     * An invalid card identifier.
-     * @hide
+     * An invalid UICC card identifier. See {@link #getCardIdForDefaultEuicc()} and
+     * {@link UiccCardInfo#getCardId()}.
      */
-    @SystemApi
     public static final int INVALID_CARD_ID = -1;
 
     /** @hide */
@@ -3162,14 +3161,8 @@
      * unique to a device, and always refer to the same UICC or eUICC card unless the device goes
      * through a factory reset.
      *
-     * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
-     *
      * @return card ID of the default eUICC card.
-     * @hide
      */
-    @SystemApi
-    @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
-    @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
     public int getCardIdForDefaultEuicc() {
         try {
             ITelephony telephony = getITelephony();
@@ -3183,25 +3176,37 @@
     }
 
     /**
-     * Gets information about currently inserted UICCs and eUICCs. See {@link UiccCardInfo} for more
-     * details on the kind of information available.
+     * Gets information about currently inserted UICCs and enabled eUICCs.
+     * <p>
+     * Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
+     * <p>
+     * If the caller has carrier priviliges on any active subscription, then they have permission to
+     * get simple information like the card ID ({@link UiccCardInfo#getCardId()}), whether the card
+     * is an eUICC ({@link UiccCardInfo#isEuicc()}), and the slot index where the card is inserted
+     * ({@link UiccCardInfo#getSlotIndex()}).
+     * <p>
+     * To get private information such as the EID ({@link UiccCardInfo#getEid()}) or ICCID
+     * ({@link UiccCardInfo#getIccId()}), the caller must have carrier priviliges on that specific
+     * UICC or eUICC card.
+     * <p>
+     * See {@link UiccCardInfo} for more details on the kind of information available.
      *
-     * @return UiccCardInfo an array of UiccCardInfo objects, representing information on the
-     * currently inserted UICCs and eUICCs.
-     *
-     * @hide
+     * @return a list of UiccCardInfo objects, representing information on the currently inserted
+     * UICCs and eUICCs. Each UiccCardInfo in the list will have private information filtered out if
+     * the caller does not have adequate permissions for that card.
      */
-    @SystemApi
     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
-    public UiccCardInfo[] getUiccCardsInfo() {
+    public List<UiccCardInfo> getUiccCardsInfo() {
         try {
             ITelephony telephony = getITelephony();
             if (telephony == null) {
-                return null;
+                Log.e(TAG, "Error in getUiccCardsInfo: unable to connect to Telephony service.");
+                return new ArrayList<UiccCardInfo>();
             }
-            return telephony.getUiccCardsInfo();
+            return telephony.getUiccCardsInfo(mContext.getOpPackageName());
         } catch (RemoteException e) {
-            return null;
+            Log.e(TAG, "Error in getUiccCardsInfo: " + e);
+            return new ArrayList<UiccCardInfo>();
         }
     }
 
@@ -9095,6 +9100,9 @@
     @SystemApi
     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
     public int setAllowedCarriers(int slotIndex, List<CarrierIdentifier> carriers) {
+        if (carriers == null || !SubscriptionManager.isValidPhoneId(slotIndex)) {
+            return -1;
+        }
         // Execute the method setCarrierRestrictionRules with an empty excluded list and
         // indicating priority for the allowed list.
         CarrierRestrictionRules carrierRestrictionRules = CarrierRestrictionRules.newBuilder()
@@ -9105,7 +9113,7 @@
 
         int result = setCarrierRestrictionRules(carrierRestrictionRules);
 
-        // Convert boolean result into int, as required by this method.
+        // Convert result into int, as required by this method.
         if (result == SET_CARRIER_RESTRICTION_SUCCESS) {
             return carriers.size();
         } else {
@@ -9198,9 +9206,11 @@
     @SystemApi
     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
     public List<CarrierIdentifier> getAllowedCarriers(int slotIndex) {
-        CarrierRestrictionRules carrierRestrictionRule = getCarrierRestrictionRules();
-        if (carrierRestrictionRule != null) {
-            return carrierRestrictionRule.getAllowedCarriers();
+        if (SubscriptionManager.isValidPhoneId(slotIndex)) {
+            CarrierRestrictionRules carrierRestrictionRule = getCarrierRestrictionRules();
+            if (carrierRestrictionRule != null) {
+                return carrierRestrictionRule.getAllowedCarriers();
+            }
         }
         return new ArrayList<CarrierIdentifier>(0);
     }
diff --git a/telephony/java/android/telephony/UiccCardInfo.java b/telephony/java/android/telephony/UiccCardInfo.java
index 45e4704..19f357a 100644
--- a/telephony/java/android/telephony/UiccCardInfo.java
+++ b/telephony/java/android/telephony/UiccCardInfo.java
@@ -15,7 +15,6 @@
  */
 package android.telephony;
 
-import android.annotation.SystemApi;
 import android.os.Parcel;
 import android.os.Parcelable;
 
@@ -23,10 +22,8 @@
 
 /**
  * The UiccCardInfo represents information about a currently inserted UICC or embedded eUICC.
- * @hide
  */
-@SystemApi
-public class UiccCardInfo implements Parcelable {
+public final class UiccCardInfo implements Parcelable {
 
     private final boolean mIsEuicc;
     private final int mCardId;
@@ -95,6 +92,9 @@
     /**
      * Get the embedded ID (EID) of the eUICC. If the UiccCardInfo is not an eUICC
      * (see {@link #isEuicc()}), returns null.
+     * <p>
+     * Note that this field may be omitted if the caller does not have the correct permissions
+     * (see {@link TelephonyManager#getUiccCardsInfo()}).
      */
     public String getEid() {
         if (!mIsEuicc) {
@@ -105,6 +105,9 @@
 
     /**
      * Get the ICCID of the UICC.
+     * <p>
+     * Note that this field may be omitted if the caller does not have the correct permissions
+     * (see {@link TelephonyManager#getUiccCardsInfo()}).
      */
     public String getIccId() {
         return mIccId;
@@ -117,6 +120,16 @@
         return mSlotIndex;
     }
 
+    /**
+     * Returns a copy of the UiccCardinfo with the clears the EID and ICCID set to null. These
+     * values are generally private and require carrier privileges to view.
+     *
+     * @hide
+     */
+    public UiccCardInfo getUnprivileged() {
+        return new UiccCardInfo(mIsEuicc, mCardId, null, null, mSlotIndex);
+    }
+
     @Override
     public boolean equals(Object obj) {
         if (this == obj) {
diff --git a/telephony/java/com/android/internal/telephony/IPhoneStateListener.aidl b/telephony/java/com/android/internal/telephony/IPhoneStateListener.aidl
index 3dbebe8..322ce45 100644
--- a/telephony/java/com/android/internal/telephony/IPhoneStateListener.aidl
+++ b/telephony/java/com/android/internal/telephony/IPhoneStateListener.aidl
@@ -27,6 +27,7 @@
 import android.telephony.ServiceState;
 import android.telephony.SignalStrength;
 import android.telephony.emergency.EmergencyNumber;
+import android.telephony.ims.ImsReasonInfo;
 
 oneway interface IPhoneStateListener {
     void onServiceStateChanged(in ServiceState serviceState);
@@ -58,5 +59,6 @@
     void onCallAttributesChanged(in CallAttributes callAttributes);
     void onEmergencyNumberListChanged(in Map emergencyNumberList);
     void onCallDisconnectCauseChanged(in int disconnectCause, in int preciseDisconnectCause);
+    void onImsCallDisconnectCauseChanged(in ImsReasonInfo imsReasonInfo);
 }
 
diff --git a/telephony/java/com/android/internal/telephony/ITelephony.aidl b/telephony/java/com/android/internal/telephony/ITelephony.aidl
index 8237d39..a23e803 100644
--- a/telephony/java/com/android/internal/telephony/ITelephony.aidl
+++ b/telephony/java/com/android/internal/telephony/ITelephony.aidl
@@ -1492,25 +1492,34 @@
      * Get the card ID of the default eUICC card. If there is no eUICC, returns
      * {@link #INVALID_CARD_ID}.
      *
-     * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
-     *
      * @param subId subscription ID used for authentication
      * @param callingPackage package making the call
      * @return card ID of the default eUICC card.
-     * @hide
      */
-    int getCardIdForDefaultEuicc(int subId, String callingPackage); 
+    int getCardIdForDefaultEuicc(int subId, String callingPackage);
 
     /**
-     * Gets information about currently inserted UICCs and eUICCs. See {@link UiccCardInfo} for more
-     * details on the kind of information available.
+     * Gets information about currently inserted UICCs and enabled eUICCs.
+     * <p>
+     * Requires that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
+     * <p>
+     * If the caller has carrier priviliges on any active subscription, then they have permission to
+     * get simple information like the card ID ({@link UiccCardInfo#getCardId()}), whether the card
+     * is an eUICC ({@link UiccCardInfo#isEuicc()}), and the slot index where the card is inserted
+     * ({@link UiccCardInfo#getSlotIndex()}).
+     * <p>
+     * To get private information such as the EID ({@link UiccCardInfo#getEid()}) or ICCID
+     * ({@link UiccCardInfo#getIccId()}), the caller must have carrier priviliges on that specific
+     * UICC or eUICC card.
+     * <p>
+     * See {@link UiccCardInfo} for more details on the kind of information available.
      *
-     * @return UiccCardInfo an array of UiccCardInfo objects, representing information on the
-     * currently inserted UICCs and eUICCs.
-     *
-     * @hide
+     * @param callingPackage package making the call, used to evaluate carrier privileges 
+     * @return a list of UiccCardInfo objects, representing information on the currently inserted
+     * UICCs and eUICCs. Each UiccCardInfo in the list will have private information filtered out if
+     * the caller does not have adequate permissions for that card.
      */
-    UiccCardInfo[] getUiccCardsInfo();
+    List<UiccCardInfo> getUiccCardsInfo(String callingPackage);
 
     /**
      * Get slot info for all the UICC slots.
diff --git a/telephony/java/com/android/internal/telephony/ITelephonyRegistry.aidl b/telephony/java/com/android/internal/telephony/ITelephonyRegistry.aidl
index 2be1f41..e9eba32 100644
--- a/telephony/java/com/android/internal/telephony/ITelephonyRegistry.aidl
+++ b/telephony/java/com/android/internal/telephony/ITelephonyRegistry.aidl
@@ -22,6 +22,7 @@
 import android.os.Bundle;
 import android.telephony.CallQuality;
 import android.telephony.CellInfo;
+import android.telephony.ims.ImsReasonInfo;
 import android.telephony.PhoneCapability;
 import android.telephony.PhysicalChannelConfig;
 import android.telephony.ServiceState;
@@ -84,4 +85,5 @@
     void notifyRadioPowerStateChanged(in int state);
     void notifyEmergencyNumberList();
     void notifyCallQualityChanged(in CallQuality callQuality, int phoneId);
+    void notifyImsDisconnectCause(int subId, in ImsReasonInfo imsReasonInfo);
 }
diff --git a/telephony/java/com/android/internal/telephony/SmsApplication.java b/telephony/java/com/android/internal/telephony/SmsApplication.java
index a508b06..d3420ee 100644
--- a/telephony/java/com/android/internal/telephony/SmsApplication.java
+++ b/telephony/java/com/android/internal/telephony/SmsApplication.java
@@ -51,7 +51,6 @@
 import java.util.Collection;
 import java.util.HashMap;
 import java.util.List;
-import java.util.concurrent.CompletableFuture;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
@@ -635,20 +634,10 @@
             }
 
             // Update the setting.
-            CompletableFuture<Void> res = new CompletableFuture<>();
+            RoleManagerCallback.Future res = new RoleManagerCallback.Future();
             context.getSystemService(RoleManager.class).addRoleHolderAsUser(
                     RoleManager.ROLE_SMS, applicationData.mPackageName, UserHandle.of(userId),
-                    AsyncTask.THREAD_POOL_EXECUTOR, new RoleManagerCallback() {
-                        @Override
-                        public void onSuccess() {
-                            res.complete(null);
-                        }
-
-                        @Override
-                        public void onFailure() {
-                            res.completeExceptionally(new RuntimeException());
-                        }
-                    });
+                    AsyncTask.THREAD_POOL_EXECUTOR, res);
             try {
                 res.get(5, TimeUnit.SECONDS);
             } catch (InterruptedException | ExecutionException | TimeoutException e) {
diff --git a/tests/ActivityTests/src/com/google/android/test/activity/ActivityTestMain.java b/tests/ActivityTests/src/com/google/android/test/activity/ActivityTestMain.java
index 2581e08..d5549cc 100644
--- a/tests/ActivityTests/src/com/google/android/test/activity/ActivityTestMain.java
+++ b/tests/ActivityTests/src/com/google/android/test/activity/ActivityTestMain.java
@@ -77,6 +77,7 @@
     static final int MSG_SPAM_ALARM = 2;
     static final int MSG_SLOW_RECEIVER = 3;
     static final int MSG_SLOW_ALARM_RECEIVER = 4;
+    static final int MSG_REPLACE_BROADCAST = 5;
 
     final Handler mHandler = new Handler() {
         @Override
@@ -138,6 +139,20 @@
                     Log.i(TAG, "Setting alarm for now + 5 seconds");
                     am.setExact(AlarmManager.ELAPSED_REALTIME, now + 5_000, pi);
                 } break;
+                case MSG_REPLACE_BROADCAST: {
+                    Intent intent = new Intent(ActivityTestMain.this, SlowReceiver.class);
+                    intent.setAction(SLOW_RECEIVER_ACTION);
+                    intent.putExtra(SLOW_RECEIVER_EXTRA, 1);
+                    sendOrderedBroadcast(intent, null, mSlowReceiverCompletion, mHandler,
+                            Activity.RESULT_OK, null, null);
+                    intent.putExtra(SLOW_RECEIVER_EXTRA, 2);
+                    sendOrderedBroadcast(intent, null, mSlowReceiverCompletion, mHandler,
+                            Activity.RESULT_OK, null, null);
+                    intent.putExtra(SLOW_RECEIVER_EXTRA, 5038);
+                    intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
+                    sendOrderedBroadcast(intent, null, mSlowReceiverCompletion, mHandler,
+                            Activity.RESULT_OK, null, null);
+                } break;
             }
             super.handleMessage(msg);
         }
@@ -418,6 +433,12 @@
                 return true;
             }
         });
+        menu.add("Replace broadcast").setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
+            @Override public boolean onMenuItemClick(MenuItem item) {
+                scheduleReplaceBroadcast();
+                return true;
+            }
+        });
         menu.add("Stack Doc").setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
             @Override public boolean onMenuItemClick(MenuItem item) {
                 ActivityManager.AppTask task = findDocTask();
@@ -616,6 +637,11 @@
         mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SLOW_ALARM_RECEIVER), 500);
     }
 
+    void scheduleReplaceBroadcast() {
+        mHandler.removeMessages(MSG_REPLACE_BROADCAST);
+        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_REPLACE_BROADCAST), 500);
+    }
+
     private View scrollWrap(View view) {
         ScrollView scroller = new ScrollView(this);
         scroller.addView(view, new ScrollView.LayoutParams(ScrollView.LayoutParams.MATCH_PARENT,
diff --git a/tools/aapt2/link/ManifestFixer.cpp b/tools/aapt2/link/ManifestFixer.cpp
index 5812ec4..85bf6f2 100644
--- a/tools/aapt2/link/ManifestFixer.cpp
+++ b/tools/aapt2/link/ManifestFixer.cpp
@@ -213,27 +213,6 @@
   return true;
 }
 
-static bool AddDeprecatedUsesFeatures(xml::Element* el, SourcePathDiagnostics* diag) {
-  if (xml::Attribute* attr = el->FindAttribute(xml::kSchemaAndroid, "name")) {
-    if (attr->value.empty()) {
-      return true;
-    }
-
-    // Add "android.hardware.fingerprint" when "android.hardware.biometric.fingerprint" is found,
-    // since the former is deprecated in Q and the latter is not present pre-Q. (see b/115639644)
-    if (attr->value == "android.hardware.biometrics.fingerprint") {
-      auto element = el->CloneElement([&](const xml::Element& el, xml::Element* out_el) {
-        xml::Attribute* cloned_attr = out_el->FindOrCreateAttribute(xml::kSchemaAndroid, "name");
-        cloned_attr->value = "android.hardware.fingerprint";
-      });
-
-      el->parent->AppendChild(std::move(element));
-    }
-  }
-
-  return true;
-}
-
 bool ManifestFixer::BuildRules(xml::XmlActionExecutor* executor,
                                IDiagnostics* diag) {
   // First verify some options.
@@ -268,7 +247,6 @@
   // Common <uses-feature> actions.
   xml::XmlNodeAction uses_feature_action;
   uses_feature_action.Action(VerifyUsesFeature);
-  uses_feature_action.Action(AddDeprecatedUsesFeatures);
 
   // Common component actions.
   xml::XmlNodeAction component_action;
diff --git a/tools/aapt2/link/ManifestFixer_test.cpp b/tools/aapt2/link/ManifestFixer_test.cpp
index fcc9f55..adea627 100644
--- a/tools/aapt2/link/ManifestFixer_test.cpp
+++ b/tools/aapt2/link/ManifestFixer_test.cpp
@@ -832,36 +832,4 @@
   EXPECT_THAT(Verify(input), NotNull());
 }
 
-TEST_F(ManifestFixerTest, UsesFeatureAddDeprecated) {
-  std::string input = R"(
-      <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-          package="android">
-        <uses-feature android:name="android.hardware.biometrics.fingerprint" />
-        <feature-group>
-          <uses-feature android:name="android.hardware.biometrics.fingerprint" />
-        </feature-group>
-      </manifest>)";
-
-  std::unique_ptr<xml::XmlResource> manifest = Verify(input);
-  ASSERT_THAT(manifest, NotNull());
-  EXPECT_THAT(manifest->root->FindChildWithAttribute("", "uses-feature",
-                                                     xml::kSchemaAndroid, "name",
-                                                     "android.hardware.biometrics.fingerprint"),
-              Ne(nullptr));
-  EXPECT_THAT(manifest->root->FindChildWithAttribute("", "uses-feature",
-                                                     xml::kSchemaAndroid, "name",
-                                                     "android.hardware.fingerprint"),
-              Ne(nullptr));
-
-  xml::Element* feature_group = manifest->root->FindChild("", "feature-group");
-  ASSERT_THAT(feature_group, Ne(nullptr));
-
-  EXPECT_THAT(feature_group->FindChildWithAttribute("", "uses-feature", xml::kSchemaAndroid, "name",
-                                                    "android.hardware.biometrics.fingerprint"),
-              Ne(nullptr));
-  EXPECT_THAT(feature_group->FindChildWithAttribute("", "uses-feature", xml::kSchemaAndroid, "name",
-                                                    "android.hardware.fingerprint"),
-              Ne(nullptr));
-}
-
 }  // namespace aapt
diff --git a/tools/processors/view_inspector/src/java/android/processor/view/inspector/InspectablePropertyProcessor.java b/tools/processors/view_inspector/src/java/android/processor/view/inspector/InspectablePropertyProcessor.java
index 42ae890..50c79da 100644
--- a/tools/processors/view_inspector/src/java/android/processor/view/inspector/InspectablePropertyProcessor.java
+++ b/tools/processors/view_inspector/src/java/android/processor/view/inspector/InspectablePropertyProcessor.java
@@ -352,6 +352,8 @@
                 } else {
                     return Property.Type.OBJECT;
                 }
+            case ARRAY:
+                return Property.Type.OBJECT;
             default:
                 throw new ProcessingException(
                         String.format("Unsupported return type %s.", returnType),
diff --git a/wifi/java/android/net/wifi/WifiConfiguration.java b/wifi/java/android/net/wifi/WifiConfiguration.java
index 96493de..c50e6a7 100644
--- a/wifi/java/android/net/wifi/WifiConfiguration.java
+++ b/wifi/java/android/net/wifi/WifiConfiguration.java
@@ -49,8 +49,9 @@
  * A class representing a configured Wi-Fi network, including the
  * security configuration.
  *
- * @deprecated Use {@link WifiNetworkConfigBuilder} to create {@link NetworkSpecifier} and
- * {@link WifiNetworkSuggestion}. This will become a system use only object in the future.
+ * @deprecated Use {@link WifiNetworkSpecifier.Builder} to create {@link NetworkSpecifier} and
+ * {@link WifiNetworkSuggestion.Builder} to create {@link WifiNetworkSuggestion}. This will become a
+ * system use only object in the future.
  */
 @Deprecated
 public class WifiConfiguration implements Parcelable {
diff --git a/wifi/java/android/net/wifi/WifiManager.java b/wifi/java/android/net/wifi/WifiManager.java
index e5733ed..289f99d 100644
--- a/wifi/java/android/net/wifi/WifiManager.java
+++ b/wifi/java/android/net/wifi/WifiManager.java
@@ -947,8 +947,8 @@
     /**
      * Directed broadcast intent action indicating that the device has connected to one of the
      * network suggestions provided by the app. This will be sent post connection to a network
-     * which was created with {@link WifiNetworkConfigBuilder#setIsAppInteractionRequired()} flag
-     * set.
+     * which was created with {@link WifiNetworkSuggestion.Builder#setIsAppInteractionRequired()}
+     * flag set.
      * <p>
      * Note: The broadcast is sent to the app only if it holds
      * {@link android.Manifest.permission#ACCESS_FINE_LOCATION ACCESS_FINE_LOCATION} permission.
@@ -1171,7 +1171,7 @@
      * of {@link WifiConfiguration} objects.
      *
      * @deprecated
-     * a) See {@link WifiNetworkConfigBuilder#buildNetworkSpecifier()} for new
+     * a) See {@link WifiNetworkSpecifier.Builder#build()} for new
      * mechanism to trigger connection to a Wi-Fi network.
      * b) See {@link #addNetworkSuggestions(List)},
      * {@link #removeNetworkSuggestions(List)} for new API to add Wi-Fi networks for consideration
@@ -1323,7 +1323,7 @@
      *         Returns {@code -1} on failure.
      *
      * @deprecated
-     * a) See {@link WifiNetworkConfigBuilder#buildNetworkSpecifier()} for new
+     * a) See {@link WifiNetworkSpecifier.Builder#build()} for new
      * mechanism to trigger connection to a Wi-Fi network.
      * b) See {@link #addNetworkSuggestions(List)},
      * {@link #removeNetworkSuggestions(List)} for new API to add Wi-Fi networks for consideration
@@ -1358,7 +1358,7 @@
      *         existing network.
      *
      * @deprecated
-     * a) See {@link WifiNetworkConfigBuilder#buildNetworkSpecifier()} for new
+     * a) See {@link WifiNetworkSpecifier.Builder#build()} for new
      * mechanism to trigger connection to a Wi-Fi network.
      * b) See {@link #addNetworkSuggestions(List)},
      * {@link #removeNetworkSuggestions(List)} for new API to add Wi-Fi networks for consideration
@@ -1647,8 +1647,8 @@
      * for a detailed explanation of the parameters.
      * When the device decides to connect to one of the provided network suggestions, platform sends
      * a directed broadcast {@link #ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION} to the app if
-     * the network was created with {@link WifiNetworkConfigBuilder#setIsAppInteractionRequired()}
-     * flag set and the app holds
+     * the network was created with {@link WifiNetworkSuggestion.Builder
+     * #setIsAppInteractionRequired()} flag set and the app holds
      * {@link android.Manifest.permission#ACCESS_FINE_LOCATION ACCESS_FINE_LOCATION} permission.
      *<p>
      * NOTE:
@@ -1835,7 +1835,7 @@
      * @return {@code true} if the operation succeeded
      *
      * @deprecated
-     * a) See {@link WifiNetworkConfigBuilder#buildNetworkSpecifier()} for new
+     * a) See {@link WifiNetworkSpecifier.Builder#build()} for new
      * mechanism to trigger connection to a Wi-Fi network.
      * b) See {@link #addNetworkSuggestions(List)},
      * {@link #removeNetworkSuggestions(List)} for new API to add Wi-Fi networks for consideration
@@ -1879,7 +1879,7 @@
      * @return {@code true} if the operation succeeded
      *
      * @deprecated
-     * a) See {@link WifiNetworkConfigBuilder#buildNetworkSpecifier()} for new
+     * a) See {@link WifiNetworkSpecifier.Builder#build()} for new
      * mechanism to trigger connection to a Wi-Fi network.
      * b) See {@link #addNetworkSuggestions(List)},
      * {@link #removeNetworkSuggestions(List)} for new API to add Wi-Fi networks for consideration
@@ -1911,7 +1911,7 @@
      * @return {@code true} if the operation succeeded
      *
      * @deprecated
-     * a) See {@link WifiNetworkConfigBuilder#buildNetworkSpecifier()} for new
+     * a) See {@link WifiNetworkSpecifier.Builder#build()} for new
      * mechanism to trigger connection to a Wi-Fi network.
      * b) See {@link #addNetworkSuggestions(List)},
      * {@link #removeNetworkSuggestions(List)} for new API to add Wi-Fi networks for consideration
@@ -1934,7 +1934,7 @@
      * @return {@code true} if the operation succeeded
      *
      * @deprecated
-     * a) See {@link WifiNetworkConfigBuilder#buildNetworkSpecifier()} for new
+     * a) See {@link WifiNetworkSpecifier.Builder#build()} for new
      * mechanism to trigger connection to a Wi-Fi network.
      * b) See {@link #addNetworkSuggestions(List)},
      * {@link #removeNetworkSuggestions(List)} for new API to add Wi-Fi networks for consideration
@@ -1958,7 +1958,7 @@
      * @return {@code true} if the operation succeeded
      *
      * @deprecated
-     * a) See {@link WifiNetworkConfigBuilder#buildNetworkSpecifier()} for new
+     * a) See {@link WifiNetworkSpecifier.Builder#build()} for new
      * mechanism to trigger connection to a Wi-Fi network.
      * b) See {@link #addNetworkSuggestions(List)},
      * {@link #removeNetworkSuggestions(List)} for new API to add Wi-Fi networks for consideration
@@ -1982,7 +1982,7 @@
      * @return {@code true} if the operation succeeded
      *
      * @deprecated
-     * a) See {@link WifiNetworkConfigBuilder#buildNetworkSpecifier()} for new
+     * a) See {@link WifiNetworkSpecifier.Builder#build()} for new
      * mechanism to trigger connection to a Wi-Fi network.
      * b) See {@link #addNetworkSuggestions(List)},
      * {@link #removeNetworkSuggestions(List)} for new API to add Wi-Fi networks for consideration
diff --git a/wifi/java/android/net/wifi/WifiNetworkAgentSpecifier.java b/wifi/java/android/net/wifi/WifiNetworkAgentSpecifier.java
index 52ee742..9d87466 100644
--- a/wifi/java/android/net/wifi/WifiNetworkAgentSpecifier.java
+++ b/wifi/java/android/net/wifi/WifiNetworkAgentSpecifier.java
@@ -124,7 +124,7 @@
      */
     public boolean satisfiesNetworkSpecifier(@NonNull WifiNetworkSpecifier ns) {
         // None of these should be null by construction.
-        // {@link WifiNetworkConfigBuilder} enforces non-null in {@link WifiNetworkSpecifier}.
+        // {@link WifiNetworkSpecifier.Builder} enforces non-null in {@link WifiNetworkSpecifier}.
         // {@link WifiNetworkFactory} ensures non-null in {@link WifiNetworkAgentSpecifier}.
         checkNotNull(ns);
         checkNotNull(ns.ssidPatternMatcher);
diff --git a/wifi/java/android/net/wifi/WifiNetworkConfigBuilder.java b/wifi/java/android/net/wifi/WifiNetworkConfigBuilder.java
deleted file mode 100644
index 42d4393..0000000
--- a/wifi/java/android/net/wifi/WifiNetworkConfigBuilder.java
+++ /dev/null
@@ -1,657 +0,0 @@
-/*
- * Copyright (C) 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.net.wifi;
-
-import static com.android.internal.util.Preconditions.checkNotNull;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.app.ActivityThread;
-import android.net.MacAddress;
-import android.net.NetworkRequest;
-import android.net.NetworkSpecifier;
-import android.os.PatternMatcher;
-import android.os.Process;
-import android.text.TextUtils;
-import android.util.Pair;
-
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.StandardCharsets;
-import java.util.List;
-
-/**
- * WifiNetworkConfigBuilder to use for creating Wi-Fi network configuration.
- * <li>See {@link #buildNetworkSpecifier()} for creating a network specifier to use in
- * {@link NetworkRequest}.</li>
- * <li>See {@link #buildNetworkSuggestion()} for creating a network suggestion to use in
- * {@link WifiManager#addNetworkSuggestions(List)}.</li>
- */
-public class WifiNetworkConfigBuilder {
-    private static final String MATCH_ALL_SSID_PATTERN_PATH = ".*";
-    private static final String MATCH_EMPTY_SSID_PATTERN_PATH = "";
-    private static final Pair<MacAddress, MacAddress> MATCH_NO_BSSID_PATTERN1 =
-            new Pair(MacAddress.BROADCAST_ADDRESS, MacAddress.BROADCAST_ADDRESS);
-    private static final Pair<MacAddress, MacAddress> MATCH_NO_BSSID_PATTERN2 =
-            new Pair(MacAddress.ALL_ZEROS_ADDRESS, MacAddress.BROADCAST_ADDRESS);
-    private static final Pair<MacAddress, MacAddress> MATCH_ALL_BSSID_PATTERN =
-            new Pair(MacAddress.ALL_ZEROS_ADDRESS, MacAddress.ALL_ZEROS_ADDRESS);
-    private static final MacAddress MATCH_EXACT_BSSID_PATTERN_MASK =
-            MacAddress.BROADCAST_ADDRESS;
-    private static final int UNASSIGNED_PRIORITY = -1;
-
-    /**
-     * SSID pattern match specified by the app.
-     */
-    private @Nullable PatternMatcher mSsidPatternMatcher;
-    /**
-     * BSSID pattern match specified by the app.
-     * Pair of <BaseAddress, Mask>.
-     */
-    private @Nullable Pair<MacAddress, MacAddress> mBssidPatternMatcher;
-    /**
-     * Whether this is an OWE network or not.
-     */
-    private boolean mIsEnhancedOpen;
-    /**
-     * Pre-shared key for use with WPA-PSK networks.
-     */
-    private @Nullable String mWpa2PskPassphrase;
-    /**
-     * Pre-shared key for use with WPA3-SAE networks.
-     */
-    private @Nullable String mWpa3SaePassphrase;
-    /**
-     * The enterprise configuration details specifying the EAP method,
-     * certificates and other settings associated with the WPA-EAP networks.
-     */
-    private @Nullable WifiEnterpriseConfig mWpa2EnterpriseConfig;
-    /**
-     * The enterprise configuration details specifying the EAP method,
-     * certificates and other settings associated with the SuiteB networks.
-     */
-    private @Nullable WifiEnterpriseConfig mWpa3EnterpriseConfig;
-    /**
-     * This is a network that does not broadcast its SSID, so an
-     * SSID-specific probe request must be used for scans.
-     */
-    private boolean mIsHiddenSSID;
-    /**
-     * Whether app needs to log in to captive portal to obtain Internet access.
-     */
-    private boolean mIsAppInteractionRequired;
-    /**
-     * Whether user needs to log in to captive portal to obtain Internet access.
-     */
-    private boolean mIsUserInteractionRequired;
-    /**
-     * Whether this network is metered or not.
-     */
-    private boolean mIsMetered;
-    /**
-     * Priority of this network among other network suggestions provided by the app.
-     * The lower the number, the higher the priority (i.e value of 0 = highest priority).
-     */
-    private int mPriority;
-
-    public WifiNetworkConfigBuilder() {
-        mSsidPatternMatcher = null;
-        mBssidPatternMatcher = null;
-        mIsEnhancedOpen = false;
-        mWpa2PskPassphrase = null;
-        mWpa3SaePassphrase = null;
-        mWpa2EnterpriseConfig = null;
-        mWpa3EnterpriseConfig = null;
-        mIsHiddenSSID = false;
-        mIsAppInteractionRequired = false;
-        mIsUserInteractionRequired = false;
-        mIsMetered = false;
-        mPriority = UNASSIGNED_PRIORITY;
-    }
-
-    /**
-     * Set the unicode SSID match pattern to use for filtering networks from scan results.
-     * <p>
-     * <li>Only allowed for creating network specifier, i.e {@link #buildNetworkSpecifier()}. </li>
-     * <li>Overrides any previous value set using {@link #setSsid(String)} or
-     * {@link #setSsidPattern(PatternMatcher)}.</li>
-     *
-     * @param ssidPattern Instance of {@link PatternMatcher} containing the UTF-8 encoded
-     *                    string pattern to use for matching the network's SSID.
-     * @return Instance of {@link WifiNetworkConfigBuilder} to enable chaining of the builder
-     * method.
-     */
-    public WifiNetworkConfigBuilder setSsidPattern(@NonNull PatternMatcher ssidPattern) {
-        checkNotNull(ssidPattern);
-        mSsidPatternMatcher = ssidPattern;
-        return this;
-    }
-
-    /**
-     * Set the unicode SSID for the network.
-     * <p>
-     * <li>For network requests ({@link NetworkSpecifier}), built using
-     * {@link #buildNetworkSpecifier}, sets the SSID to use for filtering networks from scan
-     * results. Will only match networks whose SSID is identical to the UTF-8 encoding of the
-     * specified value.</li>
-     * <li>For network suggestions ({@link WifiNetworkSuggestion}), built using
-     * {@link #buildNetworkSuggestion()}, sets the SSID for the network.</li>
-     * <li>Overrides any previous value set using {@link #setSsid(String)} or
-     * {@link #setSsidPattern(PatternMatcher)}.</li>
-     *
-     * @param ssid The SSID of the network. It must be valid Unicode.
-     * @return Instance of {@link WifiNetworkConfigBuilder} to enable chaining of the builder
-     * method.
-     * @throws IllegalArgumentException if the SSID is not valid unicode.
-     */
-    public WifiNetworkConfigBuilder setSsid(@NonNull String ssid) {
-        checkNotNull(ssid);
-        final CharsetEncoder unicodeEncoder = StandardCharsets.UTF_8.newEncoder();
-        if (!unicodeEncoder.canEncode(ssid)) {
-            throw new IllegalArgumentException("SSID is not a valid unicode string");
-        }
-        mSsidPatternMatcher = new PatternMatcher(ssid, PatternMatcher.PATTERN_LITERAL);
-        return this;
-    }
-
-    /**
-     * Set the BSSID match pattern to use for filtering networks from scan results.
-     * Will match all networks with BSSID which satisfies the following:
-     * {@code BSSID & mask == baseAddress}.
-     * <p>
-     * <li>Only allowed for creating network specifier, i.e {@link #buildNetworkSpecifier()}. </li>
-     * <li>Overrides any previous value set using {@link #setBssid(MacAddress)} or
-     * {@link #setBssidPattern(MacAddress, MacAddress)}.</li>
-     *
-     * @param baseAddress Base address for BSSID pattern.
-     * @param mask Mask for BSSID pattern.
-     * @return Instance of {@link WifiNetworkConfigBuilder} to enable chaining of the builder
-     * method.
-     */
-    public WifiNetworkConfigBuilder setBssidPattern(
-            @NonNull MacAddress baseAddress, @NonNull MacAddress mask) {
-        checkNotNull(baseAddress, mask);
-        mBssidPatternMatcher = Pair.create(baseAddress, mask);
-        return this;
-    }
-
-    /**
-     * Set the BSSID to use for filtering networks from scan results. Will only match network whose
-     * BSSID is identical to the specified value.
-     * <p>
-     * <li>For network requests ({@link NetworkSpecifier}), built using
-     * {@link #buildNetworkSpecifier}, sets the BSSID to use for filtering networks from scan
-     * results. Will only match networks whose BSSID is identical to specified value.</li>
-     * <li>For network suggestions ({@link WifiNetworkSuggestion}), built using
-     * {@link #buildNetworkSuggestion()}, sets a specific BSSID for the network suggestion.
-     * If set, only the specified BSSID with the specified SSID will be considered for connection.
-     * If not set, all BSSIDs with the specified SSID will be considered for connection.</li>
-     * <li>Overrides any previous value set using {@link #setBssid(MacAddress)} or
-     * {@link #setBssidPattern(MacAddress, MacAddress)}.</li>
-     *
-     * @param bssid BSSID of the network.
-     * @return Instance of {@link WifiNetworkConfigBuilder} to enable chaining of the builder
-     * method.
-     */
-    public WifiNetworkConfigBuilder setBssid(@NonNull MacAddress bssid) {
-        checkNotNull(bssid);
-        mBssidPatternMatcher = Pair.create(bssid, MATCH_EXACT_BSSID_PATTERN_MASK);
-        return this;
-    }
-
-    /**
-     * Specifies whether this represents an Enhanced Open (OWE) network.
-     *
-     * @return Instance of {@link WifiNetworkConfigBuilder} to enable chaining of the builder
-     * method.
-     */
-    public WifiNetworkConfigBuilder setIsEnhancedOpen() {
-        mIsEnhancedOpen = true;
-        return this;
-    }
-
-    /**
-     * Set the ASCII WPA2 passphrase for this network. Needed for authenticating to
-     * WPA2-PSK networks.
-     *
-     * @param passphrase passphrase of the network.
-     * @return Instance of {@link WifiNetworkConfigBuilder} to enable chaining of the builder
-     * method.
-     * @throws IllegalArgumentException if the passphrase is not ASCII encodable.
-     */
-    public WifiNetworkConfigBuilder setWpa2Passphrase(@NonNull String passphrase) {
-        checkNotNull(passphrase);
-        final CharsetEncoder asciiEncoder = StandardCharsets.US_ASCII.newEncoder();
-        if (!asciiEncoder.canEncode(passphrase)) {
-            throw new IllegalArgumentException("passphrase not ASCII encodable");
-        }
-        mWpa2PskPassphrase = passphrase;
-        return this;
-    }
-
-    /**
-     * Set the ASCII WPA3 passphrase for this network. Needed for authenticating to
-     * WPA3-SAE networks.
-     *
-     * @param passphrase passphrase of the network.
-     * @return Instance of {@link WifiNetworkConfigBuilder} to enable chaining of the builder
-     * method.
-     * @throws IllegalArgumentException if the passphrase is not ASCII encodable.
-     */
-    public WifiNetworkConfigBuilder setWpa3Passphrase(@NonNull String passphrase) {
-        checkNotNull(passphrase);
-        final CharsetEncoder asciiEncoder = StandardCharsets.US_ASCII.newEncoder();
-        if (!asciiEncoder.canEncode(passphrase)) {
-            throw new IllegalArgumentException("passphrase not ASCII encodable");
-        }
-        mWpa3SaePassphrase = passphrase;
-        return this;
-    }
-
-    /**
-     * Set the associated enterprise configuration for this network. Needed for authenticating to
-     * WPA2-EAP networks. See {@link WifiEnterpriseConfig} for description.
-     *
-     * @param enterpriseConfig Instance of {@link WifiEnterpriseConfig}.
-     * @return Instance of {@link WifiNetworkConfigBuilder} to enable chaining of the builder
-     * method.
-     */
-    public WifiNetworkConfigBuilder setWpa2EnterpriseConfig(
-            @NonNull WifiEnterpriseConfig enterpriseConfig) {
-        checkNotNull(enterpriseConfig);
-        mWpa2EnterpriseConfig = new WifiEnterpriseConfig(enterpriseConfig);
-        return this;
-    }
-
-    /**
-     * Set the associated enterprise configuration for this network. Needed for authenticating to
-     * WPA3-SuiteB networks. See {@link WifiEnterpriseConfig} for description.
-     *
-     * @param enterpriseConfig Instance of {@link WifiEnterpriseConfig}.
-     * @return Instance of {@link WifiNetworkConfigBuilder} to enable chaining of the builder
-     * method.
-     */
-    public WifiNetworkConfigBuilder setWpa3EnterpriseConfig(
-            @NonNull WifiEnterpriseConfig enterpriseConfig) {
-        checkNotNull(enterpriseConfig);
-        mWpa3EnterpriseConfig = new WifiEnterpriseConfig(enterpriseConfig);
-        return this;
-    }
-
-    /**
-     * Specifies whether this represents a hidden network.
-     * <p>
-     * <li>For network requests (see {@link NetworkSpecifier}), built using
-     * {@link #buildNetworkSpecifier}, setting this disallows the usage of
-     * {@link #setSsidPattern(PatternMatcher)} since hidden networks need to be explicitly
-     * probed for.</li>
-     * <li>If not set, defaults to false (i.e not a hidden network).</li>
-     *
-     * @return Instance of {@link WifiNetworkConfigBuilder} to enable chaining of the builder
-     * method.
-     */
-    public WifiNetworkConfigBuilder setIsHiddenSsid() {
-        mIsHiddenSSID = true;
-        return this;
-    }
-
-    /**
-     * Specifies whether the app needs to log in to a captive portal to obtain Internet access.
-     * <p>
-     * This will dictate if the directed broadcast
-     * {@link WifiManager#ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION} will be sent to the app
-     * after successfully connecting to the network.
-     * Use this for captive portal type networks where the app needs to authenticate the user
-     * before the device can access the network.
-     * <p>
-     * <li>Only allowed for creating network suggestion, i.e {@link #buildNetworkSuggestion()}.</li>
-     * <li>If not set, defaults to false (i.e no app interaction required).</li>
-     *
-     * @return Instance of {@link WifiNetworkConfigBuilder} to enable chaining of the builder
-     * method.
-     */
-    public WifiNetworkConfigBuilder setIsAppInteractionRequired() {
-        mIsAppInteractionRequired = true;
-        return this;
-    }
-
-    /**
-     * Specifies whether the user needs to log in to a captive portal to obtain Internet access.
-     * <p>
-     * <li>Only allowed for creating network suggestion, i.e {@link #buildNetworkSuggestion()}.</li>
-     * <li>If not set, defaults to false (i.e no user interaction required).</li>
-     *
-     * @return Instance of {@link WifiNetworkConfigBuilder} to enable chaining of the builder
-     * method.
-     */
-    public WifiNetworkConfigBuilder setIsUserInteractionRequired() {
-        mIsUserInteractionRequired = true;
-        return this;
-    }
-
-    /**
-     * Specify the priority of this network among other network suggestions provided by the same app
-     * (priorities have no impact on suggestions by different apps). The lower the number, the
-     * higher the priority (i.e value of 0 = highest priority).
-     * <p>
-     * <li>Only allowed for creating network suggestion, i.e {@link #buildNetworkSuggestion()}.</li>
-     * <li>If not set, defaults to -1 (i.e unassigned priority).</li>
-     *
-     * @param priority Integer number representing the priority among suggestions by the app.
-     * @return Instance of {@link WifiNetworkConfigBuilder} to enable chaining of the builder
-     * method.
-     * @throws IllegalArgumentException if the priority value is negative.
-     */
-    public WifiNetworkConfigBuilder setPriority(int priority) {
-        if (priority < 0) {
-            throw new IllegalArgumentException("Invalid priority value " + priority);
-        }
-        mPriority = priority;
-        return this;
-    }
-
-    /**
-     * Specifies whether this network is metered.
-     * <p>
-     * <li>Only allowed for creating network suggestion, i.e {@link #buildNetworkSuggestion()}.</li>
-     * <li>If not set, defaults to false (i.e not metered).</li>
-     *
-     * @return Instance of {@link WifiNetworkConfigBuilder} to enable chaining of the builder
-     * method.
-     */
-    public WifiNetworkConfigBuilder setIsMetered() {
-        mIsMetered = true;
-        return this;
-    }
-
-    /**
-     * Set defaults for the various low level credential type fields in the newly created
-     * WifiConfiguration object.
-     *
-     * See {@link com.android.server.wifi.WifiConfigManager#setDefaultsInWifiConfiguration(
-     * WifiConfiguration)}.
-     *
-     * @param configuration provided WifiConfiguration object.
-     */
-    private static void setDefaultsInWifiConfiguration(@NonNull WifiConfiguration configuration) {
-        configuration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
-        configuration.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
-        configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
-        configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
-        configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
-    }
-
-    private void setSecurityParamsInWifiConfiguration(@NonNull WifiConfiguration configuration) {
-        if (!TextUtils.isEmpty(mWpa2PskPassphrase)) { // WPA-PSK network.
-            configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
-            // WifiConfiguration.preSharedKey needs quotes around ASCII password.
-            configuration.preSharedKey = "\"" + mWpa2PskPassphrase + "\"";
-        } else if (!TextUtils.isEmpty(mWpa3SaePassphrase)) { // WPA3-SAE network.
-            configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.SAE);
-            // PMF mandatory for SAE.
-            configuration.requirePMF = true;
-            // WifiConfiguration.preSharedKey needs quotes around ASCII password.
-            configuration.preSharedKey = "\"" + mWpa3SaePassphrase + "\"";
-        } else if (mWpa2EnterpriseConfig != null) { // WPA-EAP network
-            configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
-            configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
-            configuration.enterpriseConfig = mWpa2EnterpriseConfig;
-        } else if (mWpa3EnterpriseConfig != null) { // WPA3-SuiteB network
-            configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.SUITE_B_192);
-            configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.GCMP_256);
-            // TODO (b/113878056): Verify these params once we verify SuiteB configuration.
-            configuration.allowedGroupManagementCiphers.set(
-                    WifiConfiguration.GroupMgmtCipher.BIP_GMAC_256);
-            configuration.allowedSuiteBCiphers.set(
-                    WifiConfiguration.SuiteBCipher.ECDHE_ECDSA);
-            configuration.allowedSuiteBCiphers.set(
-                    WifiConfiguration.SuiteBCipher.ECDHE_RSA);
-            configuration.requirePMF = true;
-            configuration.enterpriseConfig = mWpa3EnterpriseConfig;
-        } else if (mIsEnhancedOpen) { // OWE network
-            configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.OWE);
-            // PMF mandatory.
-            configuration.requirePMF = true;
-        } else { // Open network
-            configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
-        }
-    }
-
-    /**
-     * Helper method to build WifiConfiguration object from the builder.
-     * @return Instance of {@link WifiConfiguration}.
-     */
-    private WifiConfiguration buildWifiConfiguration() {
-        final WifiConfiguration wifiConfiguration = new WifiConfiguration();
-        setDefaultsInWifiConfiguration(wifiConfiguration);
-        // WifiConfiguration.SSID needs quotes around unicode SSID.
-        if (mSsidPatternMatcher.getType() == PatternMatcher.PATTERN_LITERAL) {
-            wifiConfiguration.SSID = "\"" + mSsidPatternMatcher.getPath() + "\"";
-        }
-        if (mBssidPatternMatcher.second == MATCH_EXACT_BSSID_PATTERN_MASK) {
-            wifiConfiguration.BSSID = mBssidPatternMatcher.first.toString();
-        }
-        setSecurityParamsInWifiConfiguration(wifiConfiguration);
-        wifiConfiguration.hiddenSSID = mIsHiddenSSID;
-        wifiConfiguration.priority = mPriority;
-        wifiConfiguration.meteredOverride =
-                mIsMetered ? WifiConfiguration.METERED_OVERRIDE_METERED
-                           : WifiConfiguration.METERED_OVERRIDE_NONE;
-        return wifiConfiguration;
-    }
-
-    private boolean hasSetAnyPattern() {
-        return mSsidPatternMatcher != null || mBssidPatternMatcher != null;
-    }
-
-    private void setMatchAnyPatternIfUnset() {
-        if (mSsidPatternMatcher == null) {
-            mSsidPatternMatcher = new PatternMatcher(MATCH_ALL_SSID_PATTERN_PATH,
-                    PatternMatcher.PATTERN_SIMPLE_GLOB);
-        }
-        if (mBssidPatternMatcher == null) {
-            mBssidPatternMatcher = MATCH_ALL_BSSID_PATTERN;
-        }
-    }
-
-    private boolean hasSetMatchNonePattern() {
-        if (mSsidPatternMatcher.getType() != PatternMatcher.PATTERN_PREFIX
-                && mSsidPatternMatcher.getPath().equals(MATCH_EMPTY_SSID_PATTERN_PATH)) {
-            return true;
-        }
-        if (mBssidPatternMatcher.equals(MATCH_NO_BSSID_PATTERN1)) {
-            return true;
-        }
-        if (mBssidPatternMatcher.equals(MATCH_NO_BSSID_PATTERN2)) {
-            return true;
-        }
-        return false;
-    }
-
-    private boolean hasSetMatchAllPattern() {
-        if ((mSsidPatternMatcher.match(MATCH_EMPTY_SSID_PATTERN_PATH))
-                && mBssidPatternMatcher.equals(MATCH_ALL_BSSID_PATTERN)) {
-            return true;
-        }
-        return false;
-    }
-
-    private boolean hasSetMatchExactPattern() {
-        // exact ssid match with either match-all bssid or match-exact bssid.
-        if (mSsidPatternMatcher.getType() == PatternMatcher.PATTERN_LITERAL
-                && (mBssidPatternMatcher.equals(MATCH_ALL_BSSID_PATTERN)
-                || mBssidPatternMatcher.second.equals(MATCH_EXACT_BSSID_PATTERN_MASK))) {
-            return true;
-        }
-        return false;
-    }
-
-    private void validateSecurityParams() {
-        int numSecurityTypes = 0;
-        numSecurityTypes += mIsEnhancedOpen ? 1 : 0;
-        numSecurityTypes += !TextUtils.isEmpty(mWpa2PskPassphrase) ? 1 : 0;
-        numSecurityTypes += !TextUtils.isEmpty(mWpa3SaePassphrase) ? 1 : 0;
-        numSecurityTypes += mWpa2EnterpriseConfig != null ? 1 : 0;
-        numSecurityTypes += mWpa3EnterpriseConfig != null ? 1 : 0;
-        if (numSecurityTypes > 1) {
-            throw new IllegalStateException("only one of setIsEnhancedOpen, setWpa2Passphrase,"
-                    + "setWpa3Passphrase, setWpa2EnterpriseConfig or setWpa3EnterpriseConfig"
-                    + " can be invoked for network specifier");
-        }
-    }
-
-    /**
-     * Create a specifier object used to request a Wi-Fi network. The generated
-     * {@link NetworkSpecifier} should be used in
-     * {@link NetworkRequest.Builder#setNetworkSpecifier(NetworkSpecifier)} when building
-     * the {@link NetworkRequest}.
-     *<p>
-     * Note: Apps can set a combination of network match params:
-     * <li> SSID Pattern using {@link #setSsidPattern(PatternMatcher)} OR Specific SSID using
-     * {@link #setSsid(String)}. </li>
-     * AND/OR
-     * <li> BSSID Pattern using {@link #setBssidPattern(MacAddress, MacAddress)} OR Specific BSSID
-     * using {@link #setBssid(MacAddress)} </li>
-     * to trigger connection to a network that matches the set params.
-     * The system will find the set of networks matching the request and present the user
-     * with a system dialog which will allow the user to select a specific Wi-Fi network to connect
-     * to or to deny the request.
-     *</p>
-     *
-     * For example:
-     * To connect to an open network with a SSID prefix of "test" and a BSSID OUI of "10:03:23":
-     * {@code
-     * final NetworkSpecifier specifier =
-     *      new WifiNetworkConfigBuilder()
-     *      .setSsidPattern(new PatternMatcher("test", PatterMatcher.PATTERN_PREFIX))
-     *      .setBssidPattern(MacAddress.fromString("10:03:23:00:00:00"),
-     *                       MacAddress.fromString("ff:ff:ff:00:00:00"))
-     *      .buildNetworkSpecifier()
-     * final NetworkRequest request =
-     *      new NetworkRequest.Builder()
-     *      .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
-     *      .setNetworkSpecifier(specifier)
-     *      .build();
-     * final ConnectivityManager connectivityManager =
-     *      context.getSystemService(Context.CONNECTIVITY_SERVICE);
-     * final NetworkCallback networkCallback = new NetworkCallback() {
-     *      ...
-     *      {@literal @}Override
-     *      void onAvailable(...) {}
-     *      // etc.
-     * };
-     * connectivityManager.requestNetwork(request, networkCallback);
-     * }
-     *
-     * @return Instance of {@link NetworkSpecifier}.
-     * @throws IllegalStateException on invalid params set.
-     */
-    public NetworkSpecifier buildNetworkSpecifier() {
-        if (!hasSetAnyPattern()) {
-            throw new IllegalStateException("one of setSsidPattern/setSsid/setBssidPattern/setBssid"
-                    + " should be invoked for specifier");
-        }
-        setMatchAnyPatternIfUnset();
-        if (hasSetMatchNonePattern()) {
-            throw new IllegalStateException("cannot set match-none pattern for specifier");
-        }
-        if (hasSetMatchAllPattern()) {
-            throw new IllegalStateException("cannot set match-all pattern for specifier");
-        }
-        if (mIsHiddenSSID && mSsidPatternMatcher.getType() != PatternMatcher.PATTERN_LITERAL) {
-            throw new IllegalStateException("setSsid should also be invoked when "
-                    + "setIsHiddenSsid is invoked for network specifier");
-        }
-        if (mIsAppInteractionRequired || mIsUserInteractionRequired
-                || mPriority != -1 || mIsMetered) {
-            throw new IllegalStateException("none of setIsAppInteractionRequired/"
-                    + "setIsUserInteractionRequired/setPriority/setIsMetered are allowed for "
-                    + "specifier");
-        }
-        validateSecurityParams();
-
-        return new WifiNetworkSpecifier(
-                mSsidPatternMatcher,
-                mBssidPatternMatcher,
-                buildWifiConfiguration(),
-                Process.myUid(),
-                ActivityThread.currentApplication().getApplicationContext().getOpPackageName());
-    }
-
-    /**
-     * Create a network suggestion object use in {@link WifiManager#addNetworkSuggestions(List)}.
-     * See {@link WifiNetworkSuggestion}.
-     *<p>
-     * Note: Apps can set a combination of SSID using {@link #setSsid(String)} and BSSID
-     * using {@link #setBssid(MacAddress)} to provide more fine grained network suggestions to the
-     * platform.
-     * </p>
-     *
-     * For example:
-     * To provide credentials for one open, one WPA2 and one WPA3 network with their
-     * corresponding SSID's:
-     * {@code
-     * final WifiNetworkSuggestion suggestion1 =
-     *      new WifiNetworkConfigBuilder()
-     *      .setSsid("test111111")
-     *      .buildNetworkSuggestion()
-     * final WifiNetworkSuggestion suggestion2 =
-     *      new WifiNetworkConfigBuilder()
-     *      .setSsid("test222222")
-     *      .setWpa2Passphrase("test123456")
-     *      .buildNetworkSuggestion()
-     * final WifiNetworkSuggestion suggestion3 =
-     *      new WifiNetworkConfigBuilder()
-     *      .setSsid("test333333")
-     *      .setWpa3Passphrase("test6789")
-     *      .buildNetworkSuggestion()
-     * final List<WifiNetworkSuggestion> suggestionsList = new ArrayList<WifiNetworkSuggestion> {{
-     *          add(suggestion1);
-     *          add(suggestion2);
-     *          add(suggestion3);
-     *      }};
-     * final WifiManager wifiManager =
-     *      context.getSystemService(Context.WIFI_SERVICE);
-     * wifiManager.addNetworkSuggestions(suggestionsList);
-     * ...
-     * }
-     *
-     * @return Instance of {@link WifiNetworkSuggestion}.
-     * @throws IllegalStateException on invalid params set.
-     */
-    public WifiNetworkSuggestion buildNetworkSuggestion() {
-        if (mSsidPatternMatcher == null) {
-            throw new IllegalStateException("setSsid should be invoked for suggestion");
-        }
-        setMatchAnyPatternIfUnset();
-        if (!hasSetMatchExactPattern()) {
-            throw new IllegalStateException("none of setSsidPattern/setBssidPattern are"
-                    + " allowed for suggestion");
-        }
-        if (hasSetMatchNonePattern()) {
-            throw new IllegalStateException("cannot set match-none for suggestion");
-        }
-        validateSecurityParams();
-
-        return new WifiNetworkSuggestion(
-                buildWifiConfiguration(),
-                mIsAppInteractionRequired,
-                mIsUserInteractionRequired,
-                Process.myUid(),
-                ActivityThread.currentApplication().getApplicationContext().getOpPackageName());
-
-    }
-}
diff --git a/wifi/java/android/net/wifi/WifiNetworkSpecifier.java b/wifi/java/android/net/wifi/WifiNetworkSpecifier.java
index a5f4675..a69c7a5 100644
--- a/wifi/java/android/net/wifi/WifiNetworkSpecifier.java
+++ b/wifi/java/android/net/wifi/WifiNetworkSpecifier.java
@@ -19,31 +19,466 @@
 import static com.android.internal.util.Preconditions.checkNotNull;
 
 import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.app.ActivityThread;
 import android.net.MacAddress;
 import android.net.MatchAllNetworkSpecifier;
+import android.net.NetworkRequest;
 import android.net.NetworkSpecifier;
 import android.os.Parcel;
 import android.os.Parcelable;
 import android.os.PatternMatcher;
+import android.os.Process;
 import android.text.TextUtils;
 import android.util.Pair;
 
+import java.nio.charset.CharsetEncoder;
+import java.nio.charset.StandardCharsets;
 import java.util.Objects;
 
 /**
- * Network specifier object used to request a Wi-Fi network. Apps should use the
- * {@link WifiNetworkConfigBuilder} class to create an instance.
- * @hide
+ * Network specifier object used to request a local Wi-Fi network. Apps should use the
+ * {@link WifiNetworkSpecifier.Builder} class to create an instance.
  */
 public final class WifiNetworkSpecifier extends NetworkSpecifier implements Parcelable {
+
+    /**
+     * Builder used to create {@link WifiNetworkSpecifier} objects.
+     */
+    public static class Builder {
+        private static final String MATCH_ALL_SSID_PATTERN_PATH = ".*";
+        private static final String MATCH_EMPTY_SSID_PATTERN_PATH = "";
+        private static final Pair<MacAddress, MacAddress> MATCH_NO_BSSID_PATTERN1 =
+                new Pair(MacAddress.BROADCAST_ADDRESS, MacAddress.BROADCAST_ADDRESS);
+        private static final Pair<MacAddress, MacAddress> MATCH_NO_BSSID_PATTERN2 =
+                new Pair(MacAddress.ALL_ZEROS_ADDRESS, MacAddress.BROADCAST_ADDRESS);
+        private static final Pair<MacAddress, MacAddress> MATCH_ALL_BSSID_PATTERN =
+                new Pair(MacAddress.ALL_ZEROS_ADDRESS, MacAddress.ALL_ZEROS_ADDRESS);
+        private static final MacAddress MATCH_EXACT_BSSID_PATTERN_MASK =
+                MacAddress.BROADCAST_ADDRESS;
+
+        /**
+         * SSID pattern match specified by the app.
+         */
+        private @Nullable PatternMatcher mSsidPatternMatcher;
+        /**
+         * BSSID pattern match specified by the app.
+         * Pair of <BaseAddress, Mask>.
+         */
+        private @Nullable Pair<MacAddress, MacAddress> mBssidPatternMatcher;
+        /**
+         * Whether this is an OWE network or not.
+         */
+        private boolean mIsEnhancedOpen;
+        /**
+         * Pre-shared key for use with WPA-PSK networks.
+         */
+        private @Nullable String mWpa2PskPassphrase;
+        /**
+         * Pre-shared key for use with WPA3-SAE networks.
+         */
+        private @Nullable String mWpa3SaePassphrase;
+        /**
+         * The enterprise configuration details specifying the EAP method,
+         * certificates and other settings associated with the WPA-EAP networks.
+         */
+        private @Nullable WifiEnterpriseConfig mWpa2EnterpriseConfig;
+        /**
+         * The enterprise configuration details specifying the EAP method,
+         * certificates and other settings associated with the SuiteB networks.
+         */
+        private @Nullable WifiEnterpriseConfig mWpa3EnterpriseConfig;
+        /**
+         * This is a network that does not broadcast its SSID, so an
+         * SSID-specific probe request must be used for scans.
+         */
+        private boolean mIsHiddenSSID;
+
+        public Builder() {
+            mSsidPatternMatcher = null;
+            mBssidPatternMatcher = null;
+            mIsEnhancedOpen = false;
+            mWpa2PskPassphrase = null;
+            mWpa3SaePassphrase = null;
+            mWpa2EnterpriseConfig = null;
+            mWpa3EnterpriseConfig = null;
+            mIsHiddenSSID = false;
+        }
+
+        /**
+         * Set the unicode SSID match pattern to use for filtering networks from scan results.
+         * <p>
+         * <li>Overrides any previous value set using {@link #setSsid(String)} or
+         * {@link #setSsidPattern(PatternMatcher)}.</li>
+         *
+         * @param ssidPattern Instance of {@link PatternMatcher} containing the UTF-8 encoded
+         *                    string pattern to use for matching the network's SSID.
+         * @return Instance of {@link Builder} to enable chaining of the builder method.
+         */
+        public Builder setSsidPattern(@NonNull PatternMatcher ssidPattern) {
+            checkNotNull(ssidPattern);
+            mSsidPatternMatcher = ssidPattern;
+            return this;
+        }
+
+        /**
+         * Set the unicode SSID for the network.
+         * <p>
+         * <li>Sets the SSID to use for filtering networks from scan results. Will only match
+         * networks whose SSID is identical to the UTF-8 encoding of the specified value.</li>
+         * <li>Overrides any previous value set using {@link #setSsid(String)} or
+         * {@link #setSsidPattern(PatternMatcher)}.</li>
+         *
+         * @param ssid The SSID of the network. It must be valid Unicode.
+         * @return Instance of {@link Builder} to enable chaining of the builder method.
+         * @throws IllegalArgumentException if the SSID is not valid unicode.
+         */
+        public Builder setSsid(@NonNull String ssid) {
+            checkNotNull(ssid);
+            final CharsetEncoder unicodeEncoder = StandardCharsets.UTF_8.newEncoder();
+            if (!unicodeEncoder.canEncode(ssid)) {
+                throw new IllegalArgumentException("SSID is not a valid unicode string");
+            }
+            mSsidPatternMatcher = new PatternMatcher(ssid, PatternMatcher.PATTERN_LITERAL);
+            return this;
+        }
+
+        /**
+         * Set the BSSID match pattern to use for filtering networks from scan results.
+         * Will match all networks with BSSID which satisfies the following:
+         * {@code BSSID & mask == baseAddress}.
+         * <p>
+         * <li>Overrides any previous value set using {@link #setBssid(MacAddress)} or
+         * {@link #setBssidPattern(MacAddress, MacAddress)}.</li>
+         *
+         * @param baseAddress Base address for BSSID pattern.
+         * @param mask Mask for BSSID pattern.
+         * @return Instance of {@link Builder} to enable chaining of the builder method.
+         */
+        public Builder setBssidPattern(
+                @NonNull MacAddress baseAddress, @NonNull MacAddress mask) {
+            checkNotNull(baseAddress, mask);
+            mBssidPatternMatcher = Pair.create(baseAddress, mask);
+            return this;
+        }
+
+        /**
+         * Set the BSSID to use for filtering networks from scan results. Will only match network
+         * whose BSSID is identical to the specified value.
+         * <p>
+         * <li>Sets the BSSID to use for filtering networks from scan results. Will only match
+         * networks whose BSSID is identical to specified value.</li>
+         * <li>Overrides any previous value set using {@link #setBssid(MacAddress)} or
+         * {@link #setBssidPattern(MacAddress, MacAddress)}.</li>
+         *
+         * @param bssid BSSID of the network.
+         * @return Instance of {@link Builder} to enable chaining of the builder method.
+         */
+        public Builder setBssid(@NonNull MacAddress bssid) {
+            checkNotNull(bssid);
+            mBssidPatternMatcher = Pair.create(bssid, MATCH_EXACT_BSSID_PATTERN_MASK);
+            return this;
+        }
+
+        /**
+         * Specifies whether this represents an Enhanced Open (OWE) network.
+         *
+         * @return Instance of {@link Builder} to enable chaining of the builder method.
+         */
+        public Builder setIsEnhancedOpen() {
+            mIsEnhancedOpen = true;
+            return this;
+        }
+
+        /**
+         * Set the ASCII WPA2 passphrase for this network. Needed for authenticating to
+         * WPA2-PSK networks.
+         *
+         * @param passphrase passphrase of the network.
+         * @return Instance of {@link Builder} to enable chaining of the builder method.
+         * @throws IllegalArgumentException if the passphrase is not ASCII encodable.
+         */
+        public Builder setWpa2Passphrase(@NonNull String passphrase) {
+            checkNotNull(passphrase);
+            final CharsetEncoder asciiEncoder = StandardCharsets.US_ASCII.newEncoder();
+            if (!asciiEncoder.canEncode(passphrase)) {
+                throw new IllegalArgumentException("passphrase not ASCII encodable");
+            }
+            mWpa2PskPassphrase = passphrase;
+            return this;
+        }
+
+        /**
+         * Set the ASCII WPA3 passphrase for this network. Needed for authenticating to WPA3-SAE
+         * networks.
+         *
+         * @param passphrase passphrase of the network.
+         * @return Instance of {@link Builder} to enable chaining of the builder method.
+         * @throws IllegalArgumentException if the passphrase is not ASCII encodable.
+         */
+        public Builder setWpa3Passphrase(@NonNull String passphrase) {
+            checkNotNull(passphrase);
+            final CharsetEncoder asciiEncoder = StandardCharsets.US_ASCII.newEncoder();
+            if (!asciiEncoder.canEncode(passphrase)) {
+                throw new IllegalArgumentException("passphrase not ASCII encodable");
+            }
+            mWpa3SaePassphrase = passphrase;
+            return this;
+        }
+
+        /**
+         * Set the associated enterprise configuration for this network. Needed for authenticating
+         * to WPA2-EAP networks. See {@link WifiEnterpriseConfig} for description.
+         *
+         * @param enterpriseConfig Instance of {@link WifiEnterpriseConfig}.
+         * @return Instance of {@link Builder} to enable chaining of the builder method.
+         */
+        public Builder setWpa2EnterpriseConfig(
+                @NonNull WifiEnterpriseConfig enterpriseConfig) {
+            checkNotNull(enterpriseConfig);
+            mWpa2EnterpriseConfig = new WifiEnterpriseConfig(enterpriseConfig);
+            return this;
+        }
+
+        /**
+         * Set the associated enterprise configuration for this network. Needed for authenticating
+         * to WPA3-SuiteB networks. See {@link WifiEnterpriseConfig} for description.
+         *
+         * @param enterpriseConfig Instance of {@link WifiEnterpriseConfig}.
+         * @return Instance of {@link Builder} to enable chaining of the builder method.
+         */
+        public Builder setWpa3EnterpriseConfig(
+                @NonNull WifiEnterpriseConfig enterpriseConfig) {
+            checkNotNull(enterpriseConfig);
+            mWpa3EnterpriseConfig = new WifiEnterpriseConfig(enterpriseConfig);
+            return this;
+        }
+
+        /**
+         * Specifies whether this represents a hidden network.
+         * <p>
+         * <li>Setting this disallows the usage of {@link #setSsidPattern(PatternMatcher)} since
+         * hidden networks need to be explicitly probed for.</li>
+         * <li>If not set, defaults to false (i.e not a hidden network).</li>
+         *
+         * @return Instance of {@link Builder} to enable chaining of the builder method.
+         */
+        public Builder setIsHiddenSsid() {
+            mIsHiddenSSID = true;
+            return this;
+        }
+
+
+        /**
+         * Set defaults for the various low level credential type fields in the newly created
+         * WifiConfiguration object.
+         *
+         * See {@link com.android.server.wifi.WifiConfigManager#setDefaultsInWifiConfiguration(
+         * WifiConfiguration)}.
+         *
+         * @param configuration provided WifiConfiguration object.
+         */
+        private static void setDefaultsInWifiConfiguration(
+                @NonNull WifiConfiguration configuration) {
+            configuration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
+            configuration.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
+            configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
+            configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
+            configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
+        }
+
+        private void setSecurityParamsInWifiConfiguration(
+                @NonNull WifiConfiguration configuration) {
+            if (!TextUtils.isEmpty(mWpa2PskPassphrase)) { // WPA-PSK network.
+                configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
+                // WifiConfiguration.preSharedKey needs quotes around ASCII password.
+                configuration.preSharedKey = "\"" + mWpa2PskPassphrase + "\"";
+            } else if (!TextUtils.isEmpty(mWpa3SaePassphrase)) { // WPA3-SAE network.
+                configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.SAE);
+                // PMF mandatory for SAE.
+                configuration.requirePMF = true;
+                // WifiConfiguration.preSharedKey needs quotes around ASCII password.
+                configuration.preSharedKey = "\"" + mWpa3SaePassphrase + "\"";
+            } else if (mWpa2EnterpriseConfig != null) { // WPA-EAP network
+                configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
+                configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
+                configuration.enterpriseConfig = mWpa2EnterpriseConfig;
+            } else if (mWpa3EnterpriseConfig != null) { // WPA3-SuiteB network
+                configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.SUITE_B_192);
+                configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.GCMP_256);
+                // TODO (b/113878056): Verify these params once we verify SuiteB configuration.
+                configuration.allowedGroupManagementCiphers.set(
+                        WifiConfiguration.GroupMgmtCipher.BIP_GMAC_256);
+                configuration.allowedSuiteBCiphers.set(
+                        WifiConfiguration.SuiteBCipher.ECDHE_ECDSA);
+                configuration.allowedSuiteBCiphers.set(
+                        WifiConfiguration.SuiteBCipher.ECDHE_RSA);
+                configuration.requirePMF = true;
+                configuration.enterpriseConfig = mWpa3EnterpriseConfig;
+            } else if (mIsEnhancedOpen) { // OWE network
+                configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.OWE);
+                // PMF mandatory.
+                configuration.requirePMF = true;
+            } else { // Open network
+                configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
+            }
+        }
+
+        /**
+         * Helper method to build WifiConfiguration object from the builder.
+         * @return Instance of {@link WifiConfiguration}.
+         */
+        private WifiConfiguration buildWifiConfiguration() {
+            final WifiConfiguration wifiConfiguration = new WifiConfiguration();
+            setDefaultsInWifiConfiguration(wifiConfiguration);
+            // WifiConfiguration.SSID needs quotes around unicode SSID.
+            if (mSsidPatternMatcher.getType() == PatternMatcher.PATTERN_LITERAL) {
+                wifiConfiguration.SSID = "\"" + mSsidPatternMatcher.getPath() + "\"";
+            }
+            if (mBssidPatternMatcher.second == MATCH_EXACT_BSSID_PATTERN_MASK) {
+                wifiConfiguration.BSSID = mBssidPatternMatcher.first.toString();
+            }
+            setSecurityParamsInWifiConfiguration(wifiConfiguration);
+            wifiConfiguration.hiddenSSID = mIsHiddenSSID;
+            return wifiConfiguration;
+        }
+
+        private boolean hasSetAnyPattern() {
+            return mSsidPatternMatcher != null || mBssidPatternMatcher != null;
+        }
+
+        private void setMatchAnyPatternIfUnset() {
+            if (mSsidPatternMatcher == null) {
+                mSsidPatternMatcher = new PatternMatcher(MATCH_ALL_SSID_PATTERN_PATH,
+                        PatternMatcher.PATTERN_SIMPLE_GLOB);
+            }
+            if (mBssidPatternMatcher == null) {
+                mBssidPatternMatcher = MATCH_ALL_BSSID_PATTERN;
+            }
+        }
+
+        private boolean hasSetMatchNonePattern() {
+            if (mSsidPatternMatcher.getType() != PatternMatcher.PATTERN_PREFIX
+                    && mSsidPatternMatcher.getPath().equals(MATCH_EMPTY_SSID_PATTERN_PATH)) {
+                return true;
+            }
+            if (mBssidPatternMatcher.equals(MATCH_NO_BSSID_PATTERN1)) {
+                return true;
+            }
+            if (mBssidPatternMatcher.equals(MATCH_NO_BSSID_PATTERN2)) {
+                return true;
+            }
+            return false;
+        }
+
+        private boolean hasSetMatchAllPattern() {
+            if ((mSsidPatternMatcher.match(MATCH_EMPTY_SSID_PATTERN_PATH))
+                    && mBssidPatternMatcher.equals(MATCH_ALL_BSSID_PATTERN)) {
+                return true;
+            }
+            return false;
+        }
+
+        private void validateSecurityParams() {
+            int numSecurityTypes = 0;
+            numSecurityTypes += mIsEnhancedOpen ? 1 : 0;
+            numSecurityTypes += !TextUtils.isEmpty(mWpa2PskPassphrase) ? 1 : 0;
+            numSecurityTypes += !TextUtils.isEmpty(mWpa3SaePassphrase) ? 1 : 0;
+            numSecurityTypes += mWpa2EnterpriseConfig != null ? 1 : 0;
+            numSecurityTypes += mWpa3EnterpriseConfig != null ? 1 : 0;
+            if (numSecurityTypes > 1) {
+                throw new IllegalStateException("only one of setIsEnhancedOpen, setWpa2Passphrase,"
+                        + "setWpa3Passphrase, setWpa2EnterpriseConfig or setWpa3EnterpriseConfig"
+                        + " can be invoked for network specifier");
+            }
+        }
+
+        /**
+         * Create a specifier object used to request a local Wi-Fi network. The generated
+         * {@link NetworkSpecifier} should be used in
+         * {@link NetworkRequest.Builder#setNetworkSpecifier(NetworkSpecifier)} when building
+         * the {@link NetworkRequest}. These specifiers can only be used to request a local wifi
+         * network (i.e no internet capability). So, the device will not switch it's default route
+         * to wifi if there are other transports (cellular for example) available.
+         *<p>
+         * Note: Apps can set a combination of network match params:
+         * <li> SSID Pattern using {@link #setSsidPattern(PatternMatcher)} OR Specific SSID using
+         * {@link #setSsid(String)}. </li>
+         * AND/OR
+         * <li> BSSID Pattern using {@link #setBssidPattern(MacAddress, MacAddress)} OR Specific
+         * BSSID using {@link #setBssid(MacAddress)} </li>
+         * to trigger connection to a network that matches the set params.
+         * The system will find the set of networks matching the request and present the user
+         * with a system dialog which will allow the user to select a specific Wi-Fi network to
+         * connect to or to deny the request.
+         *</p>
+         *
+         * For example:
+         * To connect to an open network with a SSID prefix of "test" and a BSSID OUI of "10:03:23":
+         * {@code
+         * final NetworkSpecifier specifier =
+         *      new Builder()
+         *      .setSsidPattern(new PatternMatcher("test", PatterMatcher.PATTERN_PREFIX))
+         *      .setBssidPattern(MacAddress.fromString("10:03:23:00:00:00"),
+         *                       MacAddress.fromString("ff:ff:ff:00:00:00"))
+         *      .buildNetworkSpecifier()
+         * final NetworkRequest request =
+         *      new NetworkRequest.Builder()
+         *      .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
+         *      .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
+         *      .setNetworkSpecifier(specifier)
+         *      .build();
+         * final ConnectivityManager connectivityManager =
+         *      context.getSystemService(Context.CONNECTIVITY_SERVICE);
+         * final NetworkCallback networkCallback = new NetworkCallback() {
+         *      ...
+         *      {@literal @}Override
+         *      void onAvailable(...) {}
+         *      // etc.
+         * };
+         * connectivityManager.requestNetwork(request, networkCallback);
+         * }
+         *
+         * @return Instance of {@link NetworkSpecifier}.
+         * @throws IllegalStateException on invalid params set.
+         */
+        public NetworkSpecifier build() {
+            if (!hasSetAnyPattern()) {
+                throw new IllegalStateException("one of setSsidPattern/setSsid/setBssidPattern/"
+                        + "setBssid should be invoked for specifier");
+            }
+            setMatchAnyPatternIfUnset();
+            if (hasSetMatchNonePattern()) {
+                throw new IllegalStateException("cannot set match-none pattern for specifier");
+            }
+            if (hasSetMatchAllPattern()) {
+                throw new IllegalStateException("cannot set match-all pattern for specifier");
+            }
+            if (mIsHiddenSSID && mSsidPatternMatcher.getType() != PatternMatcher.PATTERN_LITERAL) {
+                throw new IllegalStateException("setSsid should also be invoked when "
+                        + "setIsHiddenSsid is invoked for network specifier");
+            }
+            validateSecurityParams();
+
+            return new WifiNetworkSpecifier(
+                    mSsidPatternMatcher,
+                    mBssidPatternMatcher,
+                    buildWifiConfiguration(),
+                    Process.myUid(),
+                    ActivityThread.currentApplication().getApplicationContext().getOpPackageName());
+        }
+    }
+
     /**
      * SSID pattern match specified by the app.
+     * @hide
      */
     public final PatternMatcher ssidPatternMatcher;
 
     /**
      * BSSID pattern match specified by the app.
      * Pair of <BaseAddress, Mask>.
+     * @hide
      */
     public final Pair<MacAddress, MacAddress> bssidPatternMatcher;
 
@@ -54,6 +489,7 @@
      * WifiConfiguration are not used. Instead we use the {@link #ssidPatternMatcher} &
      * {@link #bssidPatternMatcher} fields embedded directly
      * within {@link WifiNetworkSpecifier}.
+     * @hide
      */
     public final WifiConfiguration wifiConfiguration;
 
@@ -61,18 +497,26 @@
      * The UID of the process initializing this network specifier. Validated by receiver using
      * checkUidIfNecessary() and is used by satisfiedBy() to determine whether the specifier
      * matches the offered network.
+     * @hide
      */
     public final int requestorUid;
 
     /**
      * The package name of the app initializing this network specifier.
+     * @hide
      */
     public final String requestorPackageName;
 
+    /** @hide */
+    public WifiNetworkSpecifier() throws IllegalAccessException {
+        throw new IllegalAccessException("Use the builder to create an instance");
+    }
+
+    /** @hide */
     public WifiNetworkSpecifier(@NonNull PatternMatcher ssidPatternMatcher,
-                 @NonNull Pair<MacAddress, MacAddress> bssidPatternMatcher,
-                 @NonNull WifiConfiguration wifiConfiguration,
-                 int requestorUid, @NonNull String requestorPackageName) {
+                                @NonNull Pair<MacAddress, MacAddress> bssidPatternMatcher,
+                                @NonNull WifiConfiguration wifiConfiguration,
+                                int requestorUid, @NonNull String requestorPackageName) {
         checkNotNull(ssidPatternMatcher);
         checkNotNull(bssidPatternMatcher);
         checkNotNull(wifiConfiguration);
@@ -123,23 +567,6 @@
     }
 
     @Override
-    public boolean satisfiedBy(NetworkSpecifier other) {
-        if (this == other) {
-            return true;
-        }
-        // Any generic requests should be satisifed by a specific wifi network.
-        if (other == null || other instanceof MatchAllNetworkSpecifier) {
-            return true;
-        }
-        if (other instanceof WifiNetworkAgentSpecifier) {
-            return ((WifiNetworkAgentSpecifier) other).satisfiesNetworkSpecifier(this);
-        }
-        // Specific requests are checked for equality although testing for equality of 2 patterns do
-        // not make much sense!
-        return equals(other);
-    }
-
-    @Override
     public int hashCode() {
         return Objects.hash(
                 ssidPatternMatcher.getPath(),
@@ -184,6 +611,25 @@
                 .toString();
     }
 
+    /** @hide */
+    @Override
+    public boolean satisfiedBy(NetworkSpecifier other) {
+        if (this == other) {
+            return true;
+        }
+        // Any generic requests should be satisifed by a specific wifi network.
+        if (other == null || other instanceof MatchAllNetworkSpecifier) {
+            return true;
+        }
+        if (other instanceof WifiNetworkAgentSpecifier) {
+            return ((WifiNetworkAgentSpecifier) other).satisfiesNetworkSpecifier(this);
+        }
+        // Specific requests are checked for equality although testing for equality of 2 patterns do
+        // not make much sense!
+        return equals(other);
+    }
+
+    /** @hide */
     @Override
     public void assertValidFromUid(int requestorUid) {
         if (this.requestorUid != requestorUid) {
diff --git a/wifi/java/android/net/wifi/WifiNetworkSuggestion.java b/wifi/java/android/net/wifi/WifiNetworkSuggestion.java
index 6b05dfc..460c633 100644
--- a/wifi/java/android/net/wifi/WifiNetworkSuggestion.java
+++ b/wifi/java/android/net/wifi/WifiNetworkSuggestion.java
@@ -19,23 +19,449 @@
 import static com.android.internal.util.Preconditions.checkNotNull;
 
 import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.app.ActivityThread;
+import android.net.MacAddress;
 import android.os.Parcel;
 import android.os.Parcelable;
+import android.os.Process;
 import android.text.TextUtils;
 
+import java.nio.charset.CharsetEncoder;
+import java.nio.charset.StandardCharsets;
 import java.util.List;
 import java.util.Objects;
 
 /**
  * The Network Suggestion object is used to provide a Wi-Fi network for consideration when
  * auto-connecting to networks. Apps cannot directly create this object, they must use
- * {@link WifiNetworkConfigBuilder#buildNetworkSuggestion()} to obtain an instance
- * of this object.
+ * {@link WifiNetworkSuggestion.Builder#build()} to obtain an instance of this object.
  *<p>
  * Apps can provide a list of such networks to the platform using
  * {@link WifiManager#addNetworkSuggestions(List)}.
  */
 public final class WifiNetworkSuggestion implements Parcelable {
+
+    /**
+     * Builder used to create {@link WifiNetworkSuggestion} objects.
+     */
+    public static class Builder {
+        private static final int UNASSIGNED_PRIORITY = -1;
+
+        /**
+         * SSID of the network.
+         */
+        private String mSsid;
+        /**
+         * Optional BSSID within the network.
+         */
+        private MacAddress mBssid;
+        /**
+         * Whether this is an OWE network or not.
+         */
+        private boolean mIsEnhancedOpen;
+        /**
+         * Pre-shared key for use with WPA-PSK networks.
+         */
+        private @Nullable String mWpa2PskPassphrase;
+        /**
+         * Pre-shared key for use with WPA3-SAE networks.
+         */
+        private @Nullable String mWpa3SaePassphrase;
+        /**
+         * The enterprise configuration details specifying the EAP method,
+         * certificates and other settings associated with the WPA-EAP networks.
+         */
+        private @Nullable WifiEnterpriseConfig mWpa2EnterpriseConfig;
+        /**
+         * The enterprise configuration details specifying the EAP method,
+         * certificates and other settings associated with the SuiteB networks.
+         */
+        private @Nullable WifiEnterpriseConfig mWpa3EnterpriseConfig;
+        /**
+         * This is a network that does not broadcast its SSID, so an
+         * SSID-specific probe request must be used for scans.
+         */
+        private boolean mIsHiddenSSID;
+        /**
+         * Whether app needs to log in to captive portal to obtain Internet access.
+         */
+        private boolean mIsAppInteractionRequired;
+        /**
+         * Whether user needs to log in to captive portal to obtain Internet access.
+         */
+        private boolean mIsUserInteractionRequired;
+        /**
+         * Whether this network is metered or not.
+         */
+        private boolean mIsMetered;
+        /**
+         * Priority of this network among other network suggestions provided by the app.
+         * The lower the number, the higher the priority (i.e value of 0 = highest priority).
+         */
+        private int mPriority;
+
+        public Builder() {
+            mSsid = null;
+            mBssid =  null;
+            mIsEnhancedOpen = false;
+            mWpa2PskPassphrase = null;
+            mWpa3SaePassphrase = null;
+            mWpa2EnterpriseConfig = null;
+            mWpa3EnterpriseConfig = null;
+            mIsHiddenSSID = false;
+            mIsAppInteractionRequired = false;
+            mIsUserInteractionRequired = false;
+            mIsMetered = false;
+            mPriority = UNASSIGNED_PRIORITY;
+        }
+
+        /**
+         * Set the unicode SSID for the network.
+         * <p>
+         * <li>Overrides any previous value set using {@link #setSsid(String)}.</li>
+         *
+         * @param ssid The SSID of the network. It must be valid Unicode.
+         * @return Instance of {@link Builder} to enable chaining of the builder method.
+         * @throws IllegalArgumentException if the SSID is not valid unicode.
+         */
+        public Builder setSsid(@NonNull String ssid) {
+            checkNotNull(ssid);
+            final CharsetEncoder unicodeEncoder = StandardCharsets.UTF_8.newEncoder();
+            if (!unicodeEncoder.canEncode(ssid)) {
+                throw new IllegalArgumentException("SSID is not a valid unicode string");
+            }
+            mSsid = new String(ssid);
+            return this;
+        }
+
+        /**
+         * Set the BSSID to use for filtering networks from scan results. Will only match network
+         * whose BSSID is identical to the specified value.
+         * <p>
+         * <li Sets a specific BSSID for the network suggestion. If set, only the specified BSSID
+         * with the specified SSID will be considered for connection.
+         * <li>If set, only the specified BSSID with the specified SSID will be considered for
+         * connection.</li>
+         * <li>If not set, all BSSIDs with the specified SSID will be considered for connection.
+         * </li>
+         * <li>Overrides any previous value set using {@link #setBssid(MacAddress)}.</li>
+         *
+         * @param bssid BSSID of the network.
+         * @return Instance of {@link Builder} to enable chaining of the builder method.
+         */
+        public Builder setBssid(@NonNull MacAddress bssid) {
+            checkNotNull(bssid);
+            mBssid = MacAddress.fromBytes(bssid.toByteArray());
+            return this;
+        }
+
+        /**
+         * Specifies whether this represents an Enhanced Open (OWE) network.
+         *
+         * @return Instance of {@link Builder} to enable chaining of the builder method.
+         */
+        public Builder setIsEnhancedOpen() {
+            mIsEnhancedOpen = true;
+            return this;
+        }
+
+        /**
+         * Set the ASCII WPA2 passphrase for this network. Needed for authenticating to
+         * WPA2-PSK networks.
+         *
+         * @param passphrase passphrase of the network.
+         * @return Instance of {@link Builder} to enable chaining of the builder method.
+         * @throws IllegalArgumentException if the passphrase is not ASCII encodable.
+         */
+        public Builder setWpa2Passphrase(@NonNull String passphrase) {
+            checkNotNull(passphrase);
+            final CharsetEncoder asciiEncoder = StandardCharsets.US_ASCII.newEncoder();
+            if (!asciiEncoder.canEncode(passphrase)) {
+                throw new IllegalArgumentException("passphrase not ASCII encodable");
+            }
+            mWpa2PskPassphrase = passphrase;
+            return this;
+        }
+
+        /**
+         * Set the ASCII WPA3 passphrase for this network. Needed for authenticating to WPA3-SAE
+         * networks.
+         *
+         * @param passphrase passphrase of the network.
+         * @return Instance of {@link Builder} to enable chaining of the builder method.
+         * @throws IllegalArgumentException if the passphrase is not ASCII encodable.
+         */
+        public Builder setWpa3Passphrase(@NonNull String passphrase) {
+            checkNotNull(passphrase);
+            final CharsetEncoder asciiEncoder = StandardCharsets.US_ASCII.newEncoder();
+            if (!asciiEncoder.canEncode(passphrase)) {
+                throw new IllegalArgumentException("passphrase not ASCII encodable");
+            }
+            mWpa3SaePassphrase = passphrase;
+            return this;
+        }
+
+        /**
+         * Set the associated enterprise configuration for this network. Needed for authenticating
+         * to WPA2-EAP networks. See {@link WifiEnterpriseConfig} for description.
+         *
+         * @param enterpriseConfig Instance of {@link WifiEnterpriseConfig}.
+         * @return Instance of {@link Builder} to enable chaining of the builder method.
+         */
+        public Builder setWpa2EnterpriseConfig(
+                @NonNull WifiEnterpriseConfig enterpriseConfig) {
+            checkNotNull(enterpriseConfig);
+            mWpa2EnterpriseConfig = new WifiEnterpriseConfig(enterpriseConfig);
+            return this;
+        }
+
+        /**
+         * Set the associated enterprise configuration for this network. Needed for authenticating
+         * to WPA3-SuiteB networks. See {@link WifiEnterpriseConfig} for description.
+         *
+         * @param enterpriseConfig Instance of {@link WifiEnterpriseConfig}.
+         * @return Instance of {@link Builder} to enable chaining of the builder method.
+         */
+        public Builder setWpa3EnterpriseConfig(
+                @NonNull WifiEnterpriseConfig enterpriseConfig) {
+            checkNotNull(enterpriseConfig);
+            mWpa3EnterpriseConfig = new WifiEnterpriseConfig(enterpriseConfig);
+            return this;
+        }
+
+        /**
+         * Specifies whether this represents a hidden network.
+         * <p>
+         * <li>If not set, defaults to false (i.e not a hidden network).</li>
+         *
+         * @return Instance of {@link Builder} to enable chaining of the builder method.
+         */
+        public Builder setIsHiddenSsid() {
+            mIsHiddenSSID = true;
+            return this;
+        }
+
+        /**
+         * Specifies whether the app needs to log in to a captive portal to obtain Internet access.
+         * <p>
+         * This will dictate if the directed broadcast
+         * {@link WifiManager#ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION} will be sent to the
+         * app after successfully connecting to the network.
+         * Use this for captive portal type networks where the app needs to authenticate the user
+         * before the device can access the network.
+         * <p>
+         * <li>If not set, defaults to false (i.e no app interaction required).</li>
+         *
+         * @return Instance of {@link Builder} to enable chaining of the builder method.
+         */
+        public Builder setIsAppInteractionRequired() {
+            mIsAppInteractionRequired = true;
+            return this;
+        }
+
+        /**
+         * Specifies whether the user needs to log in to a captive portal to obtain Internet access.
+         * <p>
+         * <li>If not set, defaults to false (i.e no user interaction required).</li>
+         *
+         * @return Instance of {@link Builder} to enable chaining of the builder method.
+         */
+        public Builder setIsUserInteractionRequired() {
+            mIsUserInteractionRequired = true;
+            return this;
+        }
+
+        /**
+         * Specify the priority of this network among other network suggestions provided by the same
+         * app (priorities have no impact on suggestions by different apps). The lower the number,
+         * the higher the priority (i.e value of 0 = highest priority).
+         * <p>
+         * <li>If not set, defaults to -1 (i.e unassigned priority).</li>
+         *
+         * @param priority Integer number representing the priority among suggestions by the app.
+         * @return Instance of {@link Builder} to enable chaining of the builder method.
+         * @throws IllegalArgumentException if the priority value is negative.
+         */
+        public Builder setPriority(int priority) {
+            if (priority < 0) {
+                throw new IllegalArgumentException("Invalid priority value " + priority);
+            }
+            mPriority = priority;
+            return this;
+        }
+
+        /**
+         * Specifies whether this network is metered.
+         * <p>
+         * <li>If not set, defaults to false (i.e not metered).</li>
+         *
+         * @return Instance of {@link Builder} to enable chaining of the builder method.
+         */
+        public Builder setIsMetered() {
+            mIsMetered = true;
+            return this;
+        }
+
+        /**
+         * Set defaults for the various low level credential type fields in the newly created
+         * WifiConfiguration object.
+         *
+         * See {@link com.android.server.wifi.WifiConfigManager#setDefaultsInWifiConfiguration(
+         * WifiConfiguration)}.
+         *
+         * @param configuration provided WifiConfiguration object.
+         */
+        private static void setDefaultsInWifiConfiguration(
+                @NonNull WifiConfiguration configuration) {
+            configuration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
+            configuration.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
+            configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
+            configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
+            configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
+        }
+
+        private void setSecurityParamsInWifiConfiguration(
+                @NonNull WifiConfiguration configuration) {
+            if (!TextUtils.isEmpty(mWpa2PskPassphrase)) { // WPA-PSK network.
+                configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
+                // WifiConfiguration.preSharedKey needs quotes around ASCII password.
+                configuration.preSharedKey = "\"" + mWpa2PskPassphrase + "\"";
+            } else if (!TextUtils.isEmpty(mWpa3SaePassphrase)) { // WPA3-SAE network.
+                configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.SAE);
+                // PMF mandatory for SAE.
+                configuration.requirePMF = true;
+                // WifiConfiguration.preSharedKey needs quotes around ASCII password.
+                configuration.preSharedKey = "\"" + mWpa3SaePassphrase + "\"";
+            } else if (mWpa2EnterpriseConfig != null) { // WPA-EAP network
+                configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
+                configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
+                configuration.enterpriseConfig = mWpa2EnterpriseConfig;
+            } else if (mWpa3EnterpriseConfig != null) { // WPA3-SuiteB network
+                configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.SUITE_B_192);
+                configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.GCMP_256);
+                // TODO (b/113878056): Verify these params once we verify SuiteB configuration.
+                configuration.allowedGroupManagementCiphers.set(
+                        WifiConfiguration.GroupMgmtCipher.BIP_GMAC_256);
+                configuration.allowedSuiteBCiphers.set(
+                        WifiConfiguration.SuiteBCipher.ECDHE_ECDSA);
+                configuration.allowedSuiteBCiphers.set(
+                        WifiConfiguration.SuiteBCipher.ECDHE_RSA);
+                configuration.requirePMF = true;
+                configuration.enterpriseConfig = mWpa3EnterpriseConfig;
+            } else if (mIsEnhancedOpen) { // OWE network
+                configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.OWE);
+                // PMF mandatory.
+                configuration.requirePMF = true;
+            } else { // Open network
+                configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
+            }
+        }
+
+        /**
+         * Helper method to build WifiConfiguration object from the builder.
+         * @return Instance of {@link WifiConfiguration}.
+         */
+        private WifiConfiguration buildWifiConfiguration() {
+            final WifiConfiguration wifiConfiguration = new WifiConfiguration();
+            setDefaultsInWifiConfiguration(wifiConfiguration);
+            // WifiConfiguration.SSID needs quotes around unicode SSID.
+            wifiConfiguration.SSID = "\"" + mSsid + "\"";
+            if (mBssid != null) {
+                wifiConfiguration.BSSID = mBssid.toString();
+            }
+
+            setSecurityParamsInWifiConfiguration(wifiConfiguration);
+
+            wifiConfiguration.hiddenSSID = mIsHiddenSSID;
+            wifiConfiguration.priority = mPriority;
+            wifiConfiguration.meteredOverride =
+                    mIsMetered ? WifiConfiguration.METERED_OVERRIDE_METERED
+                            : WifiConfiguration.METERED_OVERRIDE_NONE;
+            return wifiConfiguration;
+        }
+
+        private void validateSecurityParams() {
+            int numSecurityTypes = 0;
+            numSecurityTypes += mIsEnhancedOpen ? 1 : 0;
+            numSecurityTypes += !TextUtils.isEmpty(mWpa2PskPassphrase) ? 1 : 0;
+            numSecurityTypes += !TextUtils.isEmpty(mWpa3SaePassphrase) ? 1 : 0;
+            numSecurityTypes += mWpa2EnterpriseConfig != null ? 1 : 0;
+            numSecurityTypes += mWpa3EnterpriseConfig != null ? 1 : 0;
+            if (numSecurityTypes > 1) {
+                throw new IllegalStateException("only one of setIsEnhancedOpen, setWpa2Passphrase,"
+                        + "setWpa3Passphrase, setWpa2EnterpriseConfig or setWpa3EnterpriseConfig"
+                        + " can be invoked for network specifier");
+            }
+        }
+
+        /**
+         * Create a network suggestion object use in
+         * {@link WifiManager#addNetworkSuggestions(List)}.
+         *
+         * See {@link WifiNetworkSuggestion}.
+         *<p>
+         * Note: Apps can set a combination of SSID using {@link #setSsid(String)} and BSSID
+         * using {@link #setBssid(MacAddress)} to provide more fine grained network suggestions to
+         * the platform.
+         * </p>
+         *
+         * For example:
+         * To provide credentials for one open, one WPA2 and one WPA3 network with their
+         * corresponding SSID's:
+         * {@code
+         * final WifiNetworkSuggestion suggestion1 =
+         *      new Builder()
+         *      .setSsid("test111111")
+         *      .buildNetworkSuggestion()
+         * final WifiNetworkSuggestion suggestion2 =
+         *      new Builder()
+         *      .setSsid("test222222")
+         *      .setWpa2Passphrase("test123456")
+         *      .buildNetworkSuggestion()
+         * final WifiNetworkSuggestion suggestion3 =
+         *      new Builder()
+         *      .setSsid("test333333")
+         *      .setWpa3Passphrase("test6789")
+         *      .buildNetworkSuggestion()
+         * final List<WifiNetworkSuggestion> suggestionsList =
+         *      new ArrayList<WifiNetworkSuggestion> {{
+         *          add(suggestion1);
+         *          add(suggestion2);
+         *          add(suggestion3);
+         *      }};
+         * final WifiManager wifiManager =
+         *      context.getSystemService(Context.WIFI_SERVICE);
+         * wifiManager.addNetworkSuggestions(suggestionsList);
+         * ...
+         * }
+         *
+         * @return Instance of {@link WifiNetworkSuggestion}.
+         * @throws IllegalStateException on invalid params set.
+         */
+        public WifiNetworkSuggestion build() {
+            if (mSsid == null) {
+                throw new IllegalStateException("setSsid should be invoked for suggestion");
+            }
+            if (TextUtils.isEmpty(mSsid)) {
+                throw new IllegalStateException("invalid ssid for suggestion");
+            }
+            if (mBssid != null
+                    && (mBssid.equals(MacAddress.BROADCAST_ADDRESS)
+                    || mBssid.equals(MacAddress.ALL_ZEROS_ADDRESS))) {
+                throw new IllegalStateException("invalid bssid for suggestion");
+            }
+            validateSecurityParams();
+
+            return new WifiNetworkSuggestion(
+                    buildWifiConfiguration(),
+                    mIsAppInteractionRequired,
+                    mIsUserInteractionRequired,
+                    Process.myUid(),
+                    ActivityThread.currentApplication().getApplicationContext().getOpPackageName());
+        }
+    }
+
     /**
      * Network configuration for the provided network.
      * @hide
@@ -67,6 +493,15 @@
     public final String suggestorPackageName;
 
     /** @hide */
+    public WifiNetworkSuggestion() {
+        this.wifiConfiguration = null;
+        this.isAppInteractionRequired = false;
+        this.isUserInteractionRequired = false;
+        this.suggestorUid = -1;
+        this.suggestorPackageName = null;
+    }
+
+    /** @hide */
     public WifiNetworkSuggestion(@NonNull WifiConfiguration wifiConfiguration,
                                  boolean isAppInteractionRequired,
                                  boolean isUserInteractionRequired,
diff --git a/wifi/java/android/net/wifi/hotspot2/pps/Credential.java b/wifi/java/android/net/wifi/hotspot2/pps/Credential.java
index 59a7290..28165e15 100644
--- a/wifi/java/android/net/wifi/hotspot2/pps/Credential.java
+++ b/wifi/java/android/net/wifi/hotspot2/pps/Credential.java
@@ -1216,7 +1216,15 @@
                 Arrays.equals(key1.getEncoded(), key2.getEncoded());
     }
 
-    private static boolean isX509CertificateEquals(X509Certificate cert1, X509Certificate cert2) {
+    /**
+     * Verify two X.509 certificates are identical.
+     *
+     * @param cert1 a certificate to compare
+     * @param cert2 a certificate to compare
+     * @return {@code true} if given certificates are the same each other, {@code false} otherwise.
+     * @hide
+     */
+    public static boolean isX509CertificateEquals(X509Certificate cert1, X509Certificate cert2) {
         if (cert1 == null && cert2 == null) {
             return true;
         }
diff --git a/wifi/java/android/net/wifi/hotspot2/pps/UpdateParameter.java b/wifi/java/android/net/wifi/hotspot2/pps/UpdateParameter.java
index 9eb6314..8d30ff1 100644
--- a/wifi/java/android/net/wifi/hotspot2/pps/UpdateParameter.java
+++ b/wifi/java/android/net/wifi/hotspot2/pps/UpdateParameter.java
@@ -16,6 +16,7 @@
 
 package android.net.wifi.hotspot2.pps;
 
+import android.net.wifi.ParcelUtil;
 import android.os.Parcel;
 import android.os.Parcelable;
 import android.text.TextUtils;
@@ -23,6 +24,7 @@
 import android.util.Log;
 
 import java.nio.charset.StandardCharsets;
+import java.security.cert.X509Certificate;
 import java.util.Arrays;
 import java.util.Objects;
 
@@ -167,7 +169,7 @@
     }
 
     /**
-     * SHA-256 fingerprint of the certificate located at {@link #trustRootCertUrl}
+     * SHA-256 fingerprint of the certificate located at {@code mTrustRootCertUrl}
      */
     private byte[] mTrustRootCertSha256Fingerprint = null;
     public void setTrustRootCertSha256Fingerprint(byte[] fingerprint) {
@@ -178,6 +180,31 @@
     }
 
     /**
+     * CA (Certificate Authority) X509 certificates.
+     */
+    private X509Certificate mCaCertificate;
+
+    /**
+     * Set the CA (Certification Authority) certificate associated with Policy/Subscription update.
+     *
+     * @param caCertificate The CA certificate to set
+     * @hide
+     */
+    public void setCaCertificate(X509Certificate caCertificate) {
+        mCaCertificate = caCertificate;
+    }
+
+    /**
+     * Get the CA (Certification Authority) certificate associated with Policy/Subscription update.
+     *
+     * @return CA certificate associated and {@code null} if certificate is not set.
+     * @hide
+     */
+    public X509Certificate getCaCertificate() {
+        return mCaCertificate;
+    }
+
+    /**
      * Constructor for creating Policy with default values.
      */
     public UpdateParameter() {}
@@ -202,6 +229,7 @@
             mTrustRootCertSha256Fingerprint = Arrays.copyOf(source.mTrustRootCertSha256Fingerprint,
                     source.mTrustRootCertSha256Fingerprint.length);
         }
+        mCaCertificate = source.mCaCertificate;
     }
 
     @Override
@@ -219,6 +247,7 @@
         dest.writeString(mBase64EncodedPassword);
         dest.writeString(mTrustRootCertUrl);
         dest.writeByteArray(mTrustRootCertSha256Fingerprint);
+        ParcelUtil.writeCertificate(dest, mCaCertificate);
     }
 
     @Override
@@ -239,14 +268,15 @@
                 && TextUtils.equals(mBase64EncodedPassword, that.mBase64EncodedPassword)
                 && TextUtils.equals(mTrustRootCertUrl, that.mTrustRootCertUrl)
                 && Arrays.equals(mTrustRootCertSha256Fingerprint,
-                        that.mTrustRootCertSha256Fingerprint);
+                that.mTrustRootCertSha256Fingerprint)
+                && Credential.isX509CertificateEquals(mCaCertificate, that.mCaCertificate);
     }
 
     @Override
     public int hashCode() {
         return Objects.hash(mUpdateIntervalInMinutes, mUpdateMethod, mRestriction, mServerUri,
                 mUsername, mBase64EncodedPassword, mTrustRootCertUrl,
-                mTrustRootCertSha256Fingerprint);
+                Arrays.hashCode(mTrustRootCertSha256Fingerprint), mCaCertificate);
     }
 
     @Override
@@ -361,6 +391,7 @@
                 updateParam.setBase64EncodedPassword(in.readString());
                 updateParam.setTrustRootCertUrl(in.readString());
                 updateParam.setTrustRootCertSha256Fingerprint(in.createByteArray());
+                updateParam.setCaCertificate(ParcelUtil.readCertificate(in));
                 return updateParam;
             }
 
diff --git a/wifi/tests/src/android/net/wifi/WifiNetworkConfigBuilderTest.java b/wifi/tests/src/android/net/wifi/WifiNetworkConfigBuilderTest.java
deleted file mode 100644
index dd6e2c9..0000000
--- a/wifi/tests/src/android/net/wifi/WifiNetworkConfigBuilderTest.java
+++ /dev/null
@@ -1,653 +0,0 @@
-/*
- * Copyright (C) 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.net.wifi;
-
-import static android.os.PatternMatcher.PATTERN_LITERAL;
-import static android.os.PatternMatcher.PATTERN_PREFIX;
-import static android.os.PatternMatcher.PATTERN_SIMPLE_GLOB;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
-import android.net.MacAddress;
-import android.net.NetworkSpecifier;
-import android.os.PatternMatcher;
-import android.os.Process;
-
-import androidx.test.filters.SmallTest;
-
-import org.junit.Test;
-
-/**
- * Unit tests for {@link android.net.wifi.WifiNetworkConfigBuilder}.
- */
-@SmallTest
-public class WifiNetworkConfigBuilderTest {
-    private static final String TEST_SSID = "Test123";
-    private static final String TEST_BSSID_OUI_BASE_ADDRESS = "12:12:12:00:00:00";
-    private static final String TEST_BSSID_OUI_MASK = "ff:ff:ff:00:00:00";
-    private static final String TEST_BSSID = "12:12:12:12:12:12";
-    private static final String TEST_PRESHARED_KEY = "Test123";
-
-    /**
-     * Validate correctness of WifiNetworkSpecifier object created by
-     * {@link WifiNetworkConfigBuilder#buildNetworkSpecifier()} for open network with SSID pattern.
-     */
-    @Test
-    public void testWifiNetworkSpecifierBuilderForOpenNetworkWithSsidPattern() {
-        NetworkSpecifier specifier = new WifiNetworkConfigBuilder()
-                .setSsidPattern(new PatternMatcher(TEST_SSID, PATTERN_PREFIX))
-                .buildNetworkSpecifier();
-
-        assertTrue(specifier instanceof WifiNetworkSpecifier);
-        WifiNetworkSpecifier wifiNetworkSpecifier = (WifiNetworkSpecifier) specifier;
-
-        assertEquals(Process.myUid(), wifiNetworkSpecifier.requestorUid);
-        assertEquals(TEST_SSID, wifiNetworkSpecifier.ssidPatternMatcher.getPath());
-        assertEquals(PATTERN_PREFIX, wifiNetworkSpecifier.ssidPatternMatcher.getType());
-        assertEquals(MacAddress.ALL_ZEROS_ADDRESS, wifiNetworkSpecifier.bssidPatternMatcher.first);
-        assertEquals(MacAddress.ALL_ZEROS_ADDRESS, wifiNetworkSpecifier.bssidPatternMatcher.second);
-        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedKeyManagement
-                .get(WifiConfiguration.KeyMgmt.NONE));
-        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedProtocols
-                .get(WifiConfiguration.Protocol.RSN));
-        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedAuthAlgorithms
-                .get(WifiConfiguration.AuthAlgorithm.OPEN));
-        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedPairwiseCiphers
-                .get(WifiConfiguration.PairwiseCipher.CCMP));
-        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedGroupCiphers
-                .get(WifiConfiguration.GroupCipher.CCMP));
-        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedGroupCiphers
-                .get(WifiConfiguration.GroupCipher.TKIP));
-    }
-
-    /**
-     * Validate correctness of WifiNetworkSpecifier object created by
-     * {@link WifiNetworkConfigBuilder#buildNetworkSpecifier()} for WPA_PSK network with BSSID
-     * pattern.
-     */
-    @Test
-    public void testWifiNetworkSpecifierBuilderForWpa2PskNetworkWithBssidPattern() {
-        NetworkSpecifier specifier = new WifiNetworkConfigBuilder()
-                .setBssidPattern(MacAddress.fromString(TEST_BSSID_OUI_BASE_ADDRESS),
-                        MacAddress.fromString(TEST_BSSID_OUI_MASK))
-                .setWpa2Passphrase(TEST_PRESHARED_KEY)
-                .buildNetworkSpecifier();
-
-        assertTrue(specifier instanceof WifiNetworkSpecifier);
-        WifiNetworkSpecifier wifiNetworkSpecifier = (WifiNetworkSpecifier) specifier;
-
-        assertEquals(".*", wifiNetworkSpecifier.ssidPatternMatcher.getPath());
-        assertEquals(PATTERN_SIMPLE_GLOB, wifiNetworkSpecifier.ssidPatternMatcher.getType());
-        assertEquals(MacAddress.fromString(TEST_BSSID_OUI_BASE_ADDRESS),
-                wifiNetworkSpecifier.bssidPatternMatcher.first);
-        assertEquals(MacAddress.fromString(TEST_BSSID_OUI_MASK),
-                wifiNetworkSpecifier.bssidPatternMatcher.second);
-        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedKeyManagement
-                .get(WifiConfiguration.KeyMgmt.WPA_PSK));
-        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedProtocols
-                .get(WifiConfiguration.Protocol.RSN));
-        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedAuthAlgorithms
-                .get(WifiConfiguration.AuthAlgorithm.OPEN));
-        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedPairwiseCiphers
-                .get(WifiConfiguration.PairwiseCipher.CCMP));
-        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedGroupCiphers
-                .get(WifiConfiguration.GroupCipher.CCMP));
-        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedGroupCiphers
-                .get(WifiConfiguration.GroupCipher.TKIP));
-        assertEquals("\"" + TEST_PRESHARED_KEY + "\"",
-                wifiNetworkSpecifier.wifiConfiguration.preSharedKey);
-    }
-
-    /**
-     * Validate correctness of WifiNetworkSpecifier object created by
-     * {@link WifiNetworkConfigBuilder#buildNetworkSpecifier()} for WPA_EAP network with
-     * SSID and BSSID pattern.
-     */
-    @Test
-    public void testWifiNetworkSpecifierBuilderForWpa2EapHiddenNetworkWithSsidAndBssid() {
-        WifiEnterpriseConfig enterpriseConfig = new WifiEnterpriseConfig();
-        enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.TLS);
-        enterpriseConfig.setPhase2Method(WifiEnterpriseConfig.Phase2.GTC);
-
-        NetworkSpecifier specifier = new WifiNetworkConfigBuilder()
-                .setSsid(TEST_SSID)
-                .setBssid(MacAddress.fromString(TEST_BSSID))
-                .setWpa2EnterpriseConfig(enterpriseConfig)
-                .setIsHiddenSsid()
-                .buildNetworkSpecifier();
-
-        assertTrue(specifier instanceof WifiNetworkSpecifier);
-        WifiNetworkSpecifier wifiNetworkSpecifier = (WifiNetworkSpecifier) specifier;
-
-        assertEquals(TEST_SSID, wifiNetworkSpecifier.ssidPatternMatcher.getPath());
-        assertEquals(PATTERN_LITERAL, wifiNetworkSpecifier.ssidPatternMatcher.getType());
-        assertEquals(MacAddress.fromString(TEST_BSSID),
-                wifiNetworkSpecifier.bssidPatternMatcher.first);
-        assertEquals(MacAddress.BROADCAST_ADDRESS,
-                wifiNetworkSpecifier.bssidPatternMatcher.second);
-        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedKeyManagement
-                .get(WifiConfiguration.KeyMgmt.WPA_EAP));
-        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedKeyManagement
-                .get(WifiConfiguration.KeyMgmt.IEEE8021X));
-        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedProtocols
-                .get(WifiConfiguration.Protocol.RSN));
-        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedAuthAlgorithms
-                .get(WifiConfiguration.AuthAlgorithm.OPEN));
-        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedPairwiseCiphers
-                .get(WifiConfiguration.PairwiseCipher.CCMP));
-        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedGroupCiphers
-                .get(WifiConfiguration.GroupCipher.CCMP));
-        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedGroupCiphers
-                .get(WifiConfiguration.GroupCipher.TKIP));
-        assertTrue(wifiNetworkSpecifier.wifiConfiguration.hiddenSSID);
-        assertEquals(enterpriseConfig.getEapMethod(),
-                wifiNetworkSpecifier.wifiConfiguration.enterpriseConfig.getEapMethod());
-        assertEquals(enterpriseConfig.getPhase2Method(),
-                wifiNetworkSpecifier.wifiConfiguration.enterpriseConfig.getPhase2Method());
-    }
-
-
-    /**
-     * Ensure {@link WifiNetworkConfigBuilder#setSsid(String)} throws an exception
-     * when the string is not Unicode.
-     */
-    @Test(expected = IllegalArgumentException.class)
-    public void testSetSsidWithNonUnicodeString() {
-        new WifiNetworkConfigBuilder()
-                .setSsid("\ud800")
-                .buildNetworkSpecifier();
-    }
-
-    /**
-     * Ensure {@link WifiNetworkConfigBuilder#setWpa2Passphrase(String)} throws an exception
-     * when the string is not ASCII encodable.
-     */
-    @Test(expected = IllegalArgumentException.class)
-    public void testSetWpa2PasphraseWithNonAsciiString() {
-        new WifiNetworkConfigBuilder()
-                .setSsid(TEST_SSID)
-                .setWpa2Passphrase("salvē")
-                .buildNetworkSpecifier();
-    }
-
-    /**
-     * Ensure {@link WifiNetworkConfigBuilder#buildNetworkSpecifier()} throws an exception
-     * when neither SSID nor BSSID patterns were set.
-     */
-    @Test(expected = IllegalStateException.class)
-    public void testWifiNetworkSpecifierBuilderWithNoSsidAndBssidPattern() {
-        new WifiNetworkConfigBuilder().buildNetworkSpecifier();
-    }
-
-    /**
-     * Ensure {@link WifiNetworkConfigBuilder#buildNetworkSpecifier()} throws an exception
-     * when match-all SSID pattern is set.
-     */
-    @Test(expected = IllegalStateException.class)
-    public void testWifiNetworkSpecifierBuilderWithMatchAllSsidPattern1() {
-        new WifiNetworkConfigBuilder()
-                .setSsidPattern(new PatternMatcher(".*", PatternMatcher.PATTERN_SIMPLE_GLOB))
-                .buildNetworkSpecifier();
-    }
-
-    /**
-     * Ensure {@link WifiNetworkConfigBuilder#buildNetworkSpecifier()} throws an exception
-     * when match-all SSID pattern is set.
-     */
-    @Test(expected = IllegalStateException.class)
-    public void testWifiNetworkSpecifierBuilderWithMatchAllSsidPattern2() {
-        new WifiNetworkConfigBuilder()
-                .setSsidPattern(new PatternMatcher(".*", PatternMatcher.PATTERN_ADVANCED_GLOB))
-                .buildNetworkSpecifier();
-    }
-
-    /**
-     * Ensure {@link WifiNetworkConfigBuilder#buildNetworkSpecifier()} throws an exception
-     * when match-all SSID pattern is set.
-     */
-    @Test(expected = IllegalStateException.class)
-    public void testWifiNetworkSpecifierBuilderWithMatchAllSsidPattern3() {
-        new WifiNetworkConfigBuilder()
-                .setSsidPattern(new PatternMatcher("", PatternMatcher.PATTERN_PREFIX))
-                .buildNetworkSpecifier();
-    }
-
-    /**
-     * Ensure {@link WifiNetworkConfigBuilder#buildNetworkSpecifier()} throws an exception
-     * when match-all BSSID pattern is set.
-     */
-    @Test(expected = IllegalStateException.class)
-    public void testWifiNetworkSpecifierBuilderWithMatchAllBssidPattern() {
-        new WifiNetworkConfigBuilder()
-                .setBssidPattern(MacAddress.ALL_ZEROS_ADDRESS, MacAddress.ALL_ZEROS_ADDRESS)
-                .buildNetworkSpecifier();
-    }
-
-    /**
-     * Ensure {@link WifiNetworkConfigBuilder#buildNetworkSpecifier()} throws an exception
-     * when match-none SSID pattern is set.
-     */
-    @Test(expected = IllegalStateException.class)
-    public void testWifiNetworkSpecifierBuilderWithMatchNoneSsidPattern1() {
-        new WifiNetworkConfigBuilder()
-                .setSsidPattern(new PatternMatcher("", PatternMatcher.PATTERN_LITERAL))
-                .buildNetworkSpecifier();
-    }
-
-    /**
-     * Ensure {@link WifiNetworkConfigBuilder#buildNetworkSpecifier()} throws an exception
-     * when match-none SSID pattern is set.
-     */
-    @Test(expected = IllegalStateException.class)
-    public void testWifiNetworkSpecifierBuilderWithMatchNoneSsidPattern2() {
-        new WifiNetworkConfigBuilder()
-                .setSsid("")
-                .buildNetworkSpecifier();
-    }
-
-    /**
-     * Ensure {@link WifiNetworkConfigBuilder#buildNetworkSpecifier()} throws an exception
-     * when match-none BSSID pattern is set.
-     */
-    @Test(expected = IllegalStateException.class)
-    public void testWifiNetworkSpecifierBuilderWithMatchNoneBssidPattern1() {
-        new WifiNetworkConfigBuilder()
-                .setBssidPattern(MacAddress.BROADCAST_ADDRESS, MacAddress.BROADCAST_ADDRESS)
-                .buildNetworkSpecifier();
-    }
-
-    /**
-     * Ensure {@link WifiNetworkConfigBuilder#buildNetworkSpecifier()} throws an exception
-     * when match-none BSSID pattern is set.
-     */
-    @Test(expected = IllegalStateException.class)
-    public void testWifiNetworkSpecifierBuilderWithMatchNoneBssidPattern2() {
-        new WifiNetworkConfigBuilder()
-                .setBssid(MacAddress.BROADCAST_ADDRESS)
-                .buildNetworkSpecifier();
-    }
-
-    /**
-     * Ensure {@link WifiNetworkConfigBuilder#buildNetworkSpecifier()} throws an exception
-     * when match-none BSSID pattern is set.
-     */
-    @Test(expected = IllegalStateException.class)
-    public void testWifiNetworkSpecifierBuilderWithMatchNoneBssidPattern3() {
-        new WifiNetworkConfigBuilder()
-                .setBssid(MacAddress.ALL_ZEROS_ADDRESS)
-                .buildNetworkSpecifier();
-    }
-
-    /**
-     * Ensure {@link WifiNetworkConfigBuilder#buildNetworkSpecifier()} throws an exception
-     * when SSID pattern is set for hidden network.
-     */
-    @Test(expected = IllegalStateException.class)
-    public void testWifiNetworkSpecifierBuilderWithBssidMatchPatternForHiddenNetwork() {
-        new WifiNetworkConfigBuilder()
-                .setBssidPattern(MacAddress.fromString(TEST_BSSID_OUI_BASE_ADDRESS),
-                        MacAddress.fromString(TEST_BSSID_OUI_MASK))
-                .setIsHiddenSsid()
-                .buildNetworkSpecifier();
-    }
-
-    /**
-     * Ensure {@link WifiNetworkConfigBuilder#buildNetworkSpecifier()} throws an exception
-     * when both {@link WifiNetworkConfigBuilder#setWpa2Passphrase(String)} and
-     * {@link WifiNetworkConfigBuilder#setWpa2EnterpriseConfig(WifiEnterpriseConfig)} are invoked.
-     */
-    @Test(expected = IllegalStateException.class)
-    public void testWifiNetworkSpecifierBuilderWithBothWpa2PasphraseAndEnterpriseConfig() {
-        new WifiNetworkConfigBuilder()
-                .setSsidPattern(new PatternMatcher(TEST_SSID, PATTERN_LITERAL))
-                .setWpa2Passphrase(TEST_PRESHARED_KEY)
-                .setWpa2EnterpriseConfig(new WifiEnterpriseConfig())
-                .buildNetworkSpecifier();
-    }
-
-    /**
-     * Ensure {@link WifiNetworkConfigBuilder#buildNetworkSpecifier()} throws an exception
-     * when SSID pattern is set for hidden network.
-     */
-    @Test(expected = IllegalStateException.class)
-    public void testWifiNetworkSpecifierBuilderWithSsidMatchPatternForHiddenNetwork() {
-        new WifiNetworkConfigBuilder()
-                .setSsidPattern(new PatternMatcher(TEST_SSID, PatternMatcher.PATTERN_PREFIX))
-                .setIsHiddenSsid()
-                .buildNetworkSpecifier();
-    }
-
-    /**
-     * Ensure {@link WifiNetworkConfigBuilder#buildNetworkSpecifier()} throws an exception
-     * when {@link WifiNetworkConfigBuilder#setIsAppInteractionRequired()} is set.
-     */
-    @Test(expected = IllegalStateException.class)
-    public void testWifiNetworkSpecifierBuilderWithRequiredAppInteraction() {
-        new WifiNetworkConfigBuilder()
-                .setSsidPattern(new PatternMatcher(TEST_SSID, PATTERN_LITERAL))
-                .setIsAppInteractionRequired()
-                .buildNetworkSpecifier();
-    }
-
-    /**
-     * Ensure {@link WifiNetworkConfigBuilder#buildNetworkSpecifier()} throws an exception
-     * when {@link WifiNetworkConfigBuilder#setIsUserInteractionRequired()} is set.
-     */
-    @Test(expected = IllegalStateException.class)
-    public void testWifiNetworkSpecifierBuilderWithRequiredUserInteraction() {
-        new WifiNetworkConfigBuilder()
-                .setSsidPattern(new PatternMatcher(TEST_SSID, PATTERN_LITERAL))
-                .setIsUserInteractionRequired()
-                .buildNetworkSpecifier();
-    }
-
-    /**
-     * Ensure {@link WifiNetworkConfigBuilder#buildNetworkSpecifier()} throws an exception
-     * when {@link WifiNetworkConfigBuilder#setPriority(int)} is set.
-     */
-    @Test(expected = IllegalStateException.class)
-    public void testWifiNetworkSpecifierBuilderWithSetPriority() {
-        new WifiNetworkConfigBuilder()
-                .setSsidPattern(new PatternMatcher(TEST_SSID, PATTERN_LITERAL))
-                .setPriority(4)
-                .buildNetworkSpecifier();
-    }
-
-    /**
-     * Ensure {@link WifiNetworkConfigBuilder#buildNetworkSpecifier()} throws an exception
-     * when {@link WifiNetworkConfigBuilder#setIsMetered()} is set.
-     */
-    @Test(expected = IllegalStateException.class)
-    public void testWifiNetworkSpecifierBuilderWithMetered() {
-        new WifiNetworkConfigBuilder()
-                .setSsidPattern(new PatternMatcher(TEST_SSID, PATTERN_LITERAL))
-                .setIsMetered()
-                .buildNetworkSpecifier();
-    }
-
-    /**
-     * Validate correctness of WifiNetworkSuggestion object created by
-     * {@link WifiNetworkConfigBuilder#buildNetworkSuggestion()} for Open network which requires
-     * app interaction.
-     */
-    @Test
-    public void testWifiNetworkSuggestionBuilderForOpenNetworkWithReqAppInteraction() {
-        WifiNetworkSuggestion suggestion = new WifiNetworkConfigBuilder()
-                .setSsid(TEST_SSID)
-                .setIsAppInteractionRequired()
-                .buildNetworkSuggestion();
-
-        assertEquals("\"" + TEST_SSID + "\"", suggestion.wifiConfiguration.SSID);
-        assertTrue(suggestion.wifiConfiguration.allowedKeyManagement
-                .get(WifiConfiguration.KeyMgmt.NONE));
-        assertTrue(suggestion.isAppInteractionRequired);
-        assertFalse(suggestion.isUserInteractionRequired);
-        assertEquals(WifiConfiguration.METERED_OVERRIDE_NONE,
-                suggestion.wifiConfiguration.meteredOverride);
-        assertEquals(-1, suggestion.wifiConfiguration.priority);
-    }
-
-    /**
-     * Validate correctness of WifiNetworkSuggestion object created by
-     * {@link WifiNetworkConfigBuilder#buildNetworkSuggestion()} for WPA_EAP network which requires
-     * app interaction and has a priority of zero set.
-     */
-    @Test
-    public void
-            testWifiNetworkSuggestionBuilderForWpa2EapNetworkWithPriorityAndReqAppInteraction() {
-        WifiNetworkSuggestion suggestion = new WifiNetworkConfigBuilder()
-                .setSsid(TEST_SSID)
-                .setWpa2Passphrase(TEST_PRESHARED_KEY)
-                .setIsAppInteractionRequired()
-                .setPriority(0)
-                .buildNetworkSuggestion();
-
-        assertEquals("\"" + TEST_SSID + "\"", suggestion.wifiConfiguration.SSID);
-        assertTrue(suggestion.wifiConfiguration.allowedKeyManagement
-                .get(WifiConfiguration.KeyMgmt.WPA_PSK));
-        assertEquals("\"" + TEST_PRESHARED_KEY + "\"",
-                suggestion.wifiConfiguration.preSharedKey);
-        assertTrue(suggestion.isAppInteractionRequired);
-        assertFalse(suggestion.isUserInteractionRequired);
-        assertEquals(WifiConfiguration.METERED_OVERRIDE_NONE,
-                suggestion.wifiConfiguration.meteredOverride);
-        assertEquals(0, suggestion.wifiConfiguration.priority);
-    }
-
-    /**
-     * Validate correctness of WifiNetworkSuggestion object created by
-     * {@link WifiNetworkConfigBuilder#buildNetworkSuggestion()} for WPA_PSK network which requires
-     * user interaction and is metered.
-     */
-    @Test
-    public void
-            testWifiNetworkSuggestionBuilderForWpa2PskNetworkWithMeteredAndReqUserInteraction() {
-        WifiNetworkSuggestion suggestion = new WifiNetworkConfigBuilder()
-                .setSsid(TEST_SSID)
-                .setWpa2Passphrase(TEST_PRESHARED_KEY)
-                .setIsUserInteractionRequired()
-                .setIsMetered()
-                .buildNetworkSuggestion();
-
-        assertEquals("\"" + TEST_SSID + "\"", suggestion.wifiConfiguration.SSID);
-        assertTrue(suggestion.wifiConfiguration.allowedKeyManagement
-                .get(WifiConfiguration.KeyMgmt.WPA_PSK));
-        assertEquals("\"" + TEST_PRESHARED_KEY + "\"",
-                suggestion.wifiConfiguration.preSharedKey);
-        assertFalse(suggestion.isAppInteractionRequired);
-        assertTrue(suggestion.isUserInteractionRequired);
-        assertEquals(WifiConfiguration.METERED_OVERRIDE_METERED,
-                suggestion.wifiConfiguration.meteredOverride);
-        assertEquals(-1, suggestion.wifiConfiguration.priority);
-    }
-
-    /**
-     * Validate correctness of WifiNetworkSuggestion object created by
-     * {@link WifiNetworkConfigBuilder#buildNetworkSuggestion()} for OWE network.
-     */
-    @Test
-    public void testWifiNetworkSuggestionBuilderForEnhancedOpenNetworkWithBssid() {
-        WifiNetworkSuggestion suggestion = new WifiNetworkConfigBuilder()
-                .setSsid(TEST_SSID)
-                .setBssid(MacAddress.fromString(TEST_BSSID))
-                .setIsEnhancedOpen()
-                .buildNetworkSuggestion();
-
-        assertEquals("\"" + TEST_SSID + "\"", suggestion.wifiConfiguration.SSID);
-        assertEquals(TEST_BSSID, suggestion.wifiConfiguration.BSSID);
-        assertTrue(suggestion.wifiConfiguration.allowedKeyManagement
-                .get(WifiConfiguration.KeyMgmt.OWE));
-        assertNull(suggestion.wifiConfiguration.preSharedKey);
-        assertTrue(suggestion.wifiConfiguration.requirePMF);
-    }
-
-    /**
-     * Validate correctness of WifiNetworkSuggestion object created by
-     * {@link WifiNetworkConfigBuilder#buildNetworkSuggestion()} for SAE network.
-     */
-    @Test
-    public void testWifiNetworkSuggestionBuilderForWpa3PskNetwork() {
-        WifiNetworkSuggestion suggestion = new WifiNetworkConfigBuilder()
-                .setSsid(TEST_SSID)
-                .setWpa3Passphrase(TEST_PRESHARED_KEY)
-                .buildNetworkSuggestion();
-
-        assertEquals("\"" + TEST_SSID + "\"", suggestion.wifiConfiguration.SSID);
-        assertTrue(suggestion.wifiConfiguration.allowedKeyManagement
-                .get(WifiConfiguration.KeyMgmt.SAE));
-        assertEquals("\"" + TEST_PRESHARED_KEY + "\"",
-                suggestion.wifiConfiguration.preSharedKey);
-        assertTrue(suggestion.wifiConfiguration.requirePMF);
-    }
-
-
-    /**
-     * Validate correctness of WifiNetworkSuggestion object created by
-     * {@link WifiNetworkConfigBuilder#buildNetworkSuggestion()} for SuiteB network.
-     */
-    @Test
-    public void testWifiNetworkSuggestionBuilderForWpa3EapNetwork() {
-        WifiEnterpriseConfig enterpriseConfig = new WifiEnterpriseConfig();
-        enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.TLS);
-        enterpriseConfig.setPhase2Method(WifiEnterpriseConfig.Phase2.GTC);
-
-        WifiNetworkSuggestion suggestion = new WifiNetworkConfigBuilder()
-                .setSsid(TEST_SSID)
-                .setWpa3EnterpriseConfig(enterpriseConfig)
-                .buildNetworkSuggestion();
-
-        assertEquals("\"" + TEST_SSID + "\"", suggestion.wifiConfiguration.SSID);
-        assertTrue(suggestion.wifiConfiguration.allowedKeyManagement
-                .get(WifiConfiguration.KeyMgmt.SUITE_B_192));
-        assertTrue(suggestion.wifiConfiguration.allowedGroupCiphers
-                .get(WifiConfiguration.GroupCipher.GCMP_256));
-        assertTrue(suggestion.wifiConfiguration.allowedGroupManagementCiphers
-                .get(WifiConfiguration.GroupMgmtCipher.BIP_GMAC_256));
-        assertTrue(suggestion.wifiConfiguration.allowedSuiteBCiphers
-                .get(WifiConfiguration.SuiteBCipher.ECDHE_ECDSA));
-        assertTrue(suggestion.wifiConfiguration.allowedSuiteBCiphers
-                .get(WifiConfiguration.SuiteBCipher.ECDHE_RSA));
-        assertTrue(suggestion.wifiConfiguration.requirePMF);
-        assertNull(suggestion.wifiConfiguration.preSharedKey);
-    }
-
-    /**
-     * Ensure {@link WifiNetworkConfigBuilder#buildNetworkSuggestion()} throws an exception
-     * when {@link WifiNetworkConfigBuilder#setSsidPattern(PatternMatcher)} is set.
-     */
-    @Test(expected = IllegalStateException.class)
-    public void testWifiNetworkSuggestionBuilderWithSsidPattern() {
-        new WifiNetworkConfigBuilder()
-                .setSsidPattern(new PatternMatcher(TEST_SSID, PATTERN_PREFIX))
-                .buildNetworkSuggestion();
-    }
-
-    /**
-     * Ensure {@link WifiNetworkConfigBuilder#buildNetworkSuggestion()} throws an exception
-     * when {@link WifiNetworkConfigBuilder#setBssidPattern(MacAddress, MacAddress)} is set.
-     */
-    @Test(expected = IllegalStateException.class)
-    public void testWifiNetworkSuggestionBuilderWithBssidPattern() {
-        new WifiNetworkConfigBuilder()
-                .setSsid(TEST_SSID)
-                .setBssidPattern(MacAddress.fromString(TEST_BSSID),
-                        MacAddress.fromString(TEST_BSSID))
-                .buildNetworkSuggestion();
-    }
-
-    /**
-     * Ensure {@link WifiNetworkConfigBuilder#buildNetworkSuggestion()} throws an exception
-     * when {@link WifiNetworkConfigBuilder#setSsid(String)} is not set.
-     */
-    @Test(expected = IllegalStateException.class)
-    public void testWifiNetworkSuggestionBuilderWithNoSsid() {
-        new WifiNetworkConfigBuilder()
-                .buildNetworkSuggestion();
-    }
-
-    /**
-     * Ensure {@link WifiNetworkConfigBuilder#buildNetworkSuggestion()} throws an exception
-     * when {@link WifiNetworkConfigBuilder#setSsid(String)} is invoked with an invalid value.
-     */
-    @Test(expected = IllegalStateException.class)
-    public void testWifiNetworkSuggestionBuilderWithInvalidSsid() {
-        new WifiNetworkConfigBuilder()
-                .setSsid("")
-                .buildNetworkSuggestion();
-    }
-
-    /**
-     * Ensure {@link WifiNetworkConfigBuilder#buildNetworkSuggestion()} throws an exception
-     * when {@link WifiNetworkConfigBuilder#setBssid(MacAddress)} is invoked with an invalid value.
-     */
-    @Test(expected = IllegalStateException.class)
-    public void testWifiNetworkSuggestionBuilderWithInvalidBroadcastBssid() {
-        new WifiNetworkConfigBuilder()
-                .setSsid(TEST_SSID)
-                .setBssid(MacAddress.BROADCAST_ADDRESS)
-                .buildNetworkSuggestion();
-    }
-
-    /**
-     * Ensure {@link WifiNetworkConfigBuilder#buildNetworkSuggestion()} throws an exception
-     * when {@link WifiNetworkConfigBuilder#setBssid(MacAddress)} is invoked with an invalid value.
-     */
-    @Test(expected = IllegalStateException.class)
-    public void testWifiNetworkSuggestionBuilderWithInvalidAllZeroBssid() {
-        new WifiNetworkConfigBuilder()
-                .setSsid(TEST_SSID)
-                .setBssid(MacAddress.ALL_ZEROS_ADDRESS)
-                .buildNetworkSuggestion();
-    }
-
-    /**
-     * Ensure {@link WifiNetworkConfigBuilder#setPriority(int)} throws an exception
-     * when the value is negative.
-     */
-    @Test(expected = IllegalArgumentException.class)
-    public void testWifiNetworkSuggestionBuilderWithInvalidPriority() {
-        new WifiNetworkConfigBuilder()
-                .setSsid(TEST_SSID)
-                .setPriority(-1)
-                .buildNetworkSuggestion();
-    }
-
-    /**
-     * Ensure {@link WifiNetworkConfigBuilder#buildNetworkSpecifier()} throws an exception
-     * when both {@link WifiNetworkConfigBuilder#setWpa2Passphrase(String)} and
-     * {@link WifiNetworkConfigBuilder#setWpa3Passphrase(String)} are invoked.
-     */
-    @Test(expected = IllegalStateException.class)
-    public void testWifiNetworkSpecifierBuilderWithBothWpa2PasphraseAndWpa3Passphrase() {
-        new WifiNetworkConfigBuilder()
-                .setSsidPattern(new PatternMatcher(TEST_SSID, PATTERN_LITERAL))
-                .setWpa2Passphrase(TEST_PRESHARED_KEY)
-                .setWpa3Passphrase(TEST_PRESHARED_KEY)
-                .buildNetworkSpecifier();
-    }
-
-    /**
-     * Ensure {@link WifiNetworkConfigBuilder#buildNetworkSpecifier()} throws an exception
-     * when both {@link WifiNetworkConfigBuilder#setWpa3Passphrase(String)} and
-     * {@link WifiNetworkConfigBuilder#setWpa3EnterpriseConfig(WifiEnterpriseConfig)} are invoked.
-     */
-    @Test(expected = IllegalStateException.class)
-    public void testWifiNetworkSpecifierBuilderWithBothWpa3PasphraseAndEnterprise() {
-        new WifiNetworkConfigBuilder()
-                .setSsidPattern(new PatternMatcher(TEST_SSID, PATTERN_LITERAL))
-                .setWpa3Passphrase(TEST_PRESHARED_KEY)
-                .setWpa3EnterpriseConfig(new WifiEnterpriseConfig())
-                .buildNetworkSpecifier();
-    }
-
-    /**
-     * Ensure {@link WifiNetworkConfigBuilder#buildNetworkSpecifier()} throws an exception
-     * when both {@link WifiNetworkConfigBuilder#setWpa3Passphrase(String)} and
-     * {@link WifiNetworkConfigBuilder#setIsEnhancedOpen(} are invoked.
-     */
-    @Test(expected = IllegalStateException.class)
-    public void testWifiNetworkSpecifierBuilderWithBothWpa3PasphraseAndEnhancedOpen() {
-        new WifiNetworkConfigBuilder()
-                .setSsidPattern(new PatternMatcher(TEST_SSID, PATTERN_LITERAL))
-                .setWpa3Passphrase(TEST_PRESHARED_KEY)
-                .setIsEnhancedOpen()
-                .buildNetworkSpecifier();
-    }
-}
diff --git a/wifi/tests/src/android/net/wifi/WifiNetworkSpecifierTest.java b/wifi/tests/src/android/net/wifi/WifiNetworkSpecifierTest.java
index fce247f..bef33b7 100644
--- a/wifi/tests/src/android/net/wifi/WifiNetworkSpecifierTest.java
+++ b/wifi/tests/src/android/net/wifi/WifiNetworkSpecifierTest.java
@@ -17,6 +17,8 @@
 package android.net.wifi;
 
 import static android.os.PatternMatcher.PATTERN_LITERAL;
+import static android.os.PatternMatcher.PATTERN_PREFIX;
+import static android.os.PatternMatcher.PATTERN_SIMPLE_GLOB;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
@@ -24,8 +26,10 @@
 
 import android.net.MacAddress;
 import android.net.MatchAllNetworkSpecifier;
+import android.net.NetworkSpecifier;
 import android.os.Parcel;
 import android.os.PatternMatcher;
+import android.os.Process;
 import android.util.Pair;
 
 import androidx.test.filters.SmallTest;
@@ -42,9 +46,343 @@
     private static final String TEST_SSID = "Test123";
     private static final String TEST_BSSID_OUI_BASE_ADDRESS = "12:12:12:00:00:00";
     private static final String TEST_BSSID_OUI_MASK = "ff:ff:ff:00:00:00";
+    private static final String TEST_BSSID = "12:12:12:12:12:12";
     private static final String TEST_PRESHARED_KEY = "\"Test123\"";
 
     /**
+     * Validate correctness of WifiNetworkSpecifier object created by
+     * {@link WifiNetworkSpecifier.Builder#build()} for open network with SSID pattern.
+     */
+    @Test
+    public void testWifiNetworkSpecifierBuilderForOpenNetworkWithSsidPattern() {
+        NetworkSpecifier specifier = new WifiNetworkSpecifier.Builder()
+                .setSsidPattern(new PatternMatcher(TEST_SSID, PATTERN_PREFIX))
+                .build();
+
+        assertTrue(specifier instanceof WifiNetworkSpecifier);
+        WifiNetworkSpecifier wifiNetworkSpecifier = (WifiNetworkSpecifier) specifier;
+
+        assertEquals(Process.myUid(), wifiNetworkSpecifier.requestorUid);
+        assertEquals(TEST_SSID, wifiNetworkSpecifier.ssidPatternMatcher.getPath());
+        assertEquals(PATTERN_PREFIX, wifiNetworkSpecifier.ssidPatternMatcher.getType());
+        assertEquals(MacAddress.ALL_ZEROS_ADDRESS, wifiNetworkSpecifier.bssidPatternMatcher.first);
+        assertEquals(MacAddress.ALL_ZEROS_ADDRESS, wifiNetworkSpecifier.bssidPatternMatcher.second);
+        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedKeyManagement
+                .get(WifiConfiguration.KeyMgmt.NONE));
+        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedProtocols
+                .get(WifiConfiguration.Protocol.RSN));
+        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedAuthAlgorithms
+                .get(WifiConfiguration.AuthAlgorithm.OPEN));
+        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedPairwiseCiphers
+                .get(WifiConfiguration.PairwiseCipher.CCMP));
+        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedGroupCiphers
+                .get(WifiConfiguration.GroupCipher.CCMP));
+        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedGroupCiphers
+                .get(WifiConfiguration.GroupCipher.TKIP));
+    }
+
+    /**
+     * Validate correctness of WifiNetworkSpecifier object created by
+     * {@link WifiNetworkSpecifier.Builder#build()} for WPA_PSK network with BSSID
+     * pattern.
+     */
+    @Test
+    public void testWifiNetworkSpecifierBuilderForWpa2PskNetworkWithBssidPattern() {
+        NetworkSpecifier specifier = new WifiNetworkSpecifier.Builder()
+                .setBssidPattern(MacAddress.fromString(TEST_BSSID_OUI_BASE_ADDRESS),
+                        MacAddress.fromString(TEST_BSSID_OUI_MASK))
+                .setWpa2Passphrase(TEST_PRESHARED_KEY)
+                .build();
+
+        assertTrue(specifier instanceof WifiNetworkSpecifier);
+        WifiNetworkSpecifier wifiNetworkSpecifier = (WifiNetworkSpecifier) specifier;
+
+        assertEquals(".*", wifiNetworkSpecifier.ssidPatternMatcher.getPath());
+        assertEquals(PATTERN_SIMPLE_GLOB, wifiNetworkSpecifier.ssidPatternMatcher.getType());
+        assertEquals(MacAddress.fromString(TEST_BSSID_OUI_BASE_ADDRESS),
+                wifiNetworkSpecifier.bssidPatternMatcher.first);
+        assertEquals(MacAddress.fromString(TEST_BSSID_OUI_MASK),
+                wifiNetworkSpecifier.bssidPatternMatcher.second);
+        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedKeyManagement
+                .get(WifiConfiguration.KeyMgmt.WPA_PSK));
+        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedProtocols
+                .get(WifiConfiguration.Protocol.RSN));
+        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedAuthAlgorithms
+                .get(WifiConfiguration.AuthAlgorithm.OPEN));
+        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedPairwiseCiphers
+                .get(WifiConfiguration.PairwiseCipher.CCMP));
+        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedGroupCiphers
+                .get(WifiConfiguration.GroupCipher.CCMP));
+        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedGroupCiphers
+                .get(WifiConfiguration.GroupCipher.TKIP));
+        assertEquals("\"" + TEST_PRESHARED_KEY + "\"",
+                wifiNetworkSpecifier.wifiConfiguration.preSharedKey);
+    }
+
+    /**
+     * Validate correctness of WifiNetworkSpecifier object created by
+     * {@link WifiNetworkSpecifier.Builder#build()} for WPA_EAP network with
+     * SSID and BSSID pattern.
+     */
+    @Test
+    public void testWifiNetworkSpecifierBuilderForWpa2EapHiddenNetworkWithSsidAndBssid() {
+        WifiEnterpriseConfig enterpriseConfig = new WifiEnterpriseConfig();
+        enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.TLS);
+        enterpriseConfig.setPhase2Method(WifiEnterpriseConfig.Phase2.GTC);
+
+        NetworkSpecifier specifier = new WifiNetworkSpecifier.Builder()
+                .setSsid(TEST_SSID)
+                .setBssid(MacAddress.fromString(TEST_BSSID))
+                .setWpa2EnterpriseConfig(enterpriseConfig)
+                .setIsHiddenSsid()
+                .build();
+
+        assertTrue(specifier instanceof WifiNetworkSpecifier);
+        WifiNetworkSpecifier wifiNetworkSpecifier = (WifiNetworkSpecifier) specifier;
+
+        assertEquals(TEST_SSID, wifiNetworkSpecifier.ssidPatternMatcher.getPath());
+        assertEquals(PATTERN_LITERAL, wifiNetworkSpecifier.ssidPatternMatcher.getType());
+        assertEquals(MacAddress.fromString(TEST_BSSID),
+                wifiNetworkSpecifier.bssidPatternMatcher.first);
+        assertEquals(MacAddress.BROADCAST_ADDRESS,
+                wifiNetworkSpecifier.bssidPatternMatcher.second);
+        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedKeyManagement
+                .get(WifiConfiguration.KeyMgmt.WPA_EAP));
+        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedKeyManagement
+                .get(WifiConfiguration.KeyMgmt.IEEE8021X));
+        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedProtocols
+                .get(WifiConfiguration.Protocol.RSN));
+        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedAuthAlgorithms
+                .get(WifiConfiguration.AuthAlgorithm.OPEN));
+        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedPairwiseCiphers
+                .get(WifiConfiguration.PairwiseCipher.CCMP));
+        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedGroupCiphers
+                .get(WifiConfiguration.GroupCipher.CCMP));
+        assertTrue(wifiNetworkSpecifier.wifiConfiguration.allowedGroupCiphers
+                .get(WifiConfiguration.GroupCipher.TKIP));
+        assertTrue(wifiNetworkSpecifier.wifiConfiguration.hiddenSSID);
+        assertEquals(enterpriseConfig.getEapMethod(),
+                wifiNetworkSpecifier.wifiConfiguration.enterpriseConfig.getEapMethod());
+        assertEquals(enterpriseConfig.getPhase2Method(),
+                wifiNetworkSpecifier.wifiConfiguration.enterpriseConfig.getPhase2Method());
+    }
+
+
+    /**
+     * Ensure {@link WifiNetworkSpecifier.Builder#setSsid(String)} throws an exception
+     * when the string is not Unicode.
+     */
+    @Test(expected = IllegalArgumentException.class)
+    public void testWifiNetworkSpecifierBuilderSetSsidWithNonUnicodeString() {
+        new WifiNetworkSpecifier.Builder()
+                .setSsid("\ud800")
+                .build();
+    }
+
+    /**
+     * Ensure {@link WifiNetworkSpecifier.Builder#setWpa2Passphrase(String)} throws an exception
+     * when the string is not ASCII encodable.
+     */
+    @Test(expected = IllegalArgumentException.class)
+    public void testWifiNetworkSpecifierSetWpa2PasphraseWithNonAsciiString() {
+        new WifiNetworkSpecifier.Builder()
+                .setSsid(TEST_SSID)
+                .setWpa2Passphrase("salvē")
+                .build();
+    }
+
+    /**
+     * Ensure {@link WifiNetworkSpecifier.Builder#build()} throws an exception
+     * when neither SSID nor BSSID patterns were set.
+     */
+    @Test(expected = IllegalStateException.class)
+    public void testWifiNetworkSpecifierBuilderWithNoSsidAndBssidPattern() {
+        new WifiNetworkSpecifier.Builder().build();
+    }
+
+    /**
+     * Ensure {@link WifiNetworkSpecifier.Builder#build()} throws an exception
+     * when match-all SSID pattern is set.
+     */
+    @Test(expected = IllegalStateException.class)
+    public void testWifiNetworkSpecifierBuilderWithMatchAllSsidPattern1() {
+        new WifiNetworkSpecifier.Builder()
+                .setSsidPattern(new PatternMatcher(".*", PATTERN_SIMPLE_GLOB))
+                .build();
+    }
+
+    /**
+     * Ensure {@link WifiNetworkSpecifier.Builder#build()} throws an exception
+     * when match-all SSID pattern is set.
+     */
+    @Test(expected = IllegalStateException.class)
+    public void testWifiNetworkSpecifierBuilderWithMatchAllSsidPattern2() {
+        new WifiNetworkSpecifier.Builder()
+                .setSsidPattern(new PatternMatcher(".*", PatternMatcher.PATTERN_ADVANCED_GLOB))
+                .build();
+    }
+
+    /**
+     * Ensure {@link WifiNetworkSpecifier.Builder#build()} throws an exception
+     * when match-all SSID pattern is set.
+     */
+    @Test(expected = IllegalStateException.class)
+    public void testWifiNetworkSpecifierBuilderWithMatchAllSsidPattern3() {
+        new WifiNetworkSpecifier.Builder()
+                .setSsidPattern(new PatternMatcher("", PATTERN_PREFIX))
+                .build();
+    }
+
+    /**
+     * Ensure {@link WifiNetworkSpecifier.Builder#build()} throws an exception
+     * when match-all BSSID pattern is set.
+     */
+    @Test(expected = IllegalStateException.class)
+    public void testWifiNetworkSpecifierBuilderWithMatchAllBssidPattern() {
+        new WifiNetworkSpecifier.Builder()
+                .setBssidPattern(MacAddress.ALL_ZEROS_ADDRESS, MacAddress.ALL_ZEROS_ADDRESS)
+                .build();
+    }
+
+    /**
+     * Ensure {@link WifiNetworkSpecifier.Builder#build()} throws an exception
+     * when match-none SSID pattern is set.
+     */
+    @Test(expected = IllegalStateException.class)
+    public void testWifiNetworkSpecifierBuilderWithMatchNoneSsidPattern1() {
+        new WifiNetworkSpecifier.Builder()
+                .setSsidPattern(new PatternMatcher("", PatternMatcher.PATTERN_LITERAL))
+                .build();
+    }
+
+    /**
+     * Ensure {@link WifiNetworkSpecifier.Builder#build()} throws an exception
+     * when match-none SSID pattern is set.
+     */
+    @Test(expected = IllegalStateException.class)
+    public void testWifiNetworkSpecifierBuilderWithMatchNoneSsidPattern2() {
+        new WifiNetworkSpecifier.Builder()
+                .setSsid("")
+                .build();
+    }
+
+    /**
+     * Ensure {@link WifiNetworkSpecifier.Builder#build()} throws an exception
+     * when match-none BSSID pattern is set.
+     */
+    @Test(expected = IllegalStateException.class)
+    public void testWifiNetworkSpecifierBuilderWithMatchNoneBssidPattern1() {
+        new WifiNetworkSpecifier.Builder()
+                .setBssidPattern(MacAddress.BROADCAST_ADDRESS, MacAddress.BROADCAST_ADDRESS)
+                .build();
+    }
+
+    /**
+     * Ensure {@link WifiNetworkSpecifier.Builder#build()} throws an exception
+     * when match-none BSSID pattern is set.
+     */
+    @Test(expected = IllegalStateException.class)
+    public void testWifiNetworkSpecifierBuilderWithMatchNoneBssidPattern2() {
+        new WifiNetworkSpecifier.Builder()
+                .setBssid(MacAddress.BROADCAST_ADDRESS)
+                .build();
+    }
+
+    /**
+     * Ensure {@link WifiNetworkSpecifier.Builder#build()} throws an exception
+     * when match-none BSSID pattern is set.
+     */
+    @Test(expected = IllegalStateException.class)
+    public void testWifiNetworkSpecifierBuilderWithMatchNoneBssidPattern3() {
+        new WifiNetworkSpecifier.Builder()
+                .setBssid(MacAddress.ALL_ZEROS_ADDRESS)
+                .build();
+    }
+
+    /**
+     * Ensure {@link WifiNetworkSpecifier.Builder#build()} throws an exception
+     * when SSID pattern is set for hidden network.
+     */
+    @Test(expected = IllegalStateException.class)
+    public void testWifiNetworkSpecifierBuilderWithBssidMatchPatternForHiddenNetwork() {
+        new WifiNetworkSpecifier.Builder()
+                .setBssidPattern(MacAddress.fromString(TEST_BSSID_OUI_BASE_ADDRESS),
+                        MacAddress.fromString(TEST_BSSID_OUI_MASK))
+                .setIsHiddenSsid()
+                .build();
+    }
+
+    /**
+     * Ensure {@link WifiNetworkSpecifier.Builder#build()} throws an exception
+     * when both {@link WifiNetworkSpecifier.Builder#setWpa2Passphrase(String)} and
+     * {@link WifiNetworkSpecifier.Builder#setWpa2EnterpriseConfig(WifiEnterpriseConfig)} are
+     * invoked.
+     */
+    @Test(expected = IllegalStateException.class)
+    public void testWifiNetworkSpecifierBuilderWithBothWpa2PasphraseAndEnterpriseConfig() {
+        new WifiNetworkSpecifier.Builder()
+                .setSsidPattern(new PatternMatcher(TEST_SSID, PATTERN_LITERAL))
+                .setWpa2Passphrase(TEST_PRESHARED_KEY)
+                .setWpa2EnterpriseConfig(new WifiEnterpriseConfig())
+                .build();
+    }
+
+    /**
+     * Ensure {@link WifiNetworkSpecifier.Builder#build()} throws an exception
+     * when SSID pattern is set for hidden network.
+     */
+    @Test(expected = IllegalStateException.class)
+    public void testWifiNetworkSpecifierBuilderWithSsidMatchPatternForHiddenNetwork() {
+        new WifiNetworkSpecifier.Builder()
+                .setSsidPattern(new PatternMatcher(TEST_SSID, PATTERN_PREFIX))
+                .setIsHiddenSsid()
+                .build();
+    }
+
+    /**
+     * Ensure {@link WifiNetworkSpecifier.Builder#build()} throws an exception
+     * when both {@link WifiNetworkSpecifier.Builder#setWpa2Passphrase(String)} and
+     * {@link WifiNetworkSpecifier.Builder#setWpa3Passphrase(String)} are invoked.
+     */
+    @Test(expected = IllegalStateException.class)
+    public void testWifiNetworkSpecifierBuilderWithBothWpa2PasphraseAndWpa3Passphrase() {
+        new WifiNetworkSpecifier.Builder()
+                .setSsidPattern(new PatternMatcher(TEST_SSID, PATTERN_LITERAL))
+                .setWpa2Passphrase(TEST_PRESHARED_KEY)
+                .setWpa3Passphrase(TEST_PRESHARED_KEY)
+                .build();
+    }
+
+    /**
+     * Ensure {@link WifiNetworkSpecifier.Builder#build()} throws an exception
+     * when both {@link WifiNetworkSpecifier.Builder#setWpa3Passphrase(String)} and
+     * {@link WifiNetworkSpecifier.Builder#setWpa3EnterpriseConfig(WifiEnterpriseConfig)} are
+     * invoked.
+     */
+    @Test(expected = IllegalStateException.class)
+    public void testWifiNetworkSpecifierBuilderWithBothWpa3PasphraseAndEnterprise() {
+        new WifiNetworkSpecifier.Builder()
+                .setSsidPattern(new PatternMatcher(TEST_SSID, PATTERN_LITERAL))
+                .setWpa3Passphrase(TEST_PRESHARED_KEY)
+                .setWpa3EnterpriseConfig(new WifiEnterpriseConfig())
+                .build();
+    }
+
+    /**
+     * Ensure {@link WifiNetworkSpecifier.Builder#build()} throws an exception
+     * when both {@link WifiNetworkSpecifier.Builder#setWpa3Passphrase(String)} and
+     * {@link WifiNetworkSpecifier.Builder#setIsEnhancedOpen()} are invoked.
+     */
+    @Test(expected = IllegalStateException.class)
+    public void testWifiNetworkSpecifierBuilderWithBothWpa3PasphraseAndEnhancedOpen() {
+        new WifiNetworkSpecifier.Builder()
+                .setSsidPattern(new PatternMatcher(TEST_SSID, PATTERN_LITERAL))
+                .setWpa3Passphrase(TEST_PRESHARED_KEY)
+                .setIsEnhancedOpen()
+                .build();
+    }
+
+    /**
      * Validate that parcel marshalling/unmarshalling works
      */
     @Test
diff --git a/wifi/tests/src/android/net/wifi/WifiNetworkSuggestionTest.java b/wifi/tests/src/android/net/wifi/WifiNetworkSuggestionTest.java
index 5f76055..05ee22c 100644
--- a/wifi/tests/src/android/net/wifi/WifiNetworkSuggestionTest.java
+++ b/wifi/tests/src/android/net/wifi/WifiNetworkSuggestionTest.java
@@ -18,7 +18,9 @@
 
 import static org.junit.Assert.*;
 
+import android.net.MacAddress;
 import android.os.Parcel;
+import android.os.Process;
 
 import androidx.test.filters.SmallTest;
 
@@ -36,6 +38,279 @@
     private static final String TEST_SSID = "\"Test123\"";
     private static final String TEST_BSSID = "12:12:12:12:12:12";
     private static final String TEST_SSID_1 = "\"Test1234\"";
+    private static final String TEST_PRESHARED_KEY = "Test123";
+
+    /**
+     * Validate correctness of WifiNetworkSuggestion object created by
+     * {@link WifiNetworkSuggestion.Builder#build()} for Open network which requires
+     * app interaction.
+     */
+    @Test
+    public void testWifiNetworkSuggestionBuilderForOpenNetworkWithReqAppInteraction() {
+        WifiNetworkSuggestion suggestion = new WifiNetworkSuggestion.Builder()
+                .setSsid(TEST_SSID)
+                .setIsAppInteractionRequired()
+                .build();
+
+        assertEquals(Process.myUid(), suggestion.suggestorUid);
+        assertEquals("\"" + TEST_SSID + "\"", suggestion.wifiConfiguration.SSID);
+        assertTrue(suggestion.wifiConfiguration.allowedKeyManagement
+                .get(WifiConfiguration.KeyMgmt.NONE));
+        assertTrue(suggestion.isAppInteractionRequired);
+        assertFalse(suggestion.isUserInteractionRequired);
+        assertEquals(WifiConfiguration.METERED_OVERRIDE_NONE,
+                suggestion.wifiConfiguration.meteredOverride);
+        assertEquals(-1, suggestion.wifiConfiguration.priority);
+    }
+
+    /**
+     * Validate correctness of WifiNetworkSuggestion object created by
+     * {@link WifiNetworkSuggestion.Builder#build()} for WPA_EAP network which requires
+     * app interaction and has a priority of zero set.
+     */
+    @Test
+    public void
+            testWifiNetworkSuggestionBuilderForWpa2EapNetworkWithPriorityAndReqAppInteraction() {
+        WifiNetworkSuggestion suggestion = new WifiNetworkSuggestion.Builder()
+                .setSsid(TEST_SSID)
+                .setWpa2Passphrase(TEST_PRESHARED_KEY)
+                .setIsAppInteractionRequired()
+                .setPriority(0)
+                .build();
+
+        assertEquals("\"" + TEST_SSID + "\"", suggestion.wifiConfiguration.SSID);
+        assertTrue(suggestion.wifiConfiguration.allowedKeyManagement
+                .get(WifiConfiguration.KeyMgmt.WPA_PSK));
+        assertEquals("\"" + TEST_PRESHARED_KEY + "\"",
+                suggestion.wifiConfiguration.preSharedKey);
+        assertTrue(suggestion.isAppInteractionRequired);
+        assertFalse(suggestion.isUserInteractionRequired);
+        assertEquals(WifiConfiguration.METERED_OVERRIDE_NONE,
+                suggestion.wifiConfiguration.meteredOverride);
+        assertEquals(0, suggestion.wifiConfiguration.priority);
+    }
+
+    /**
+     * Validate correctness of WifiNetworkSuggestion object created by
+     * {@link WifiNetworkSuggestion.Builder#build()} for WPA_PSK network which requires
+     * user interaction and is metered.
+     */
+    @Test
+    public void
+            testWifiNetworkSuggestionBuilderForWpa2PskNetworkWithMeteredAndReqUserInteraction() {
+        WifiNetworkSuggestion suggestion = new WifiNetworkSuggestion.Builder()
+                .setSsid(TEST_SSID)
+                .setWpa2Passphrase(TEST_PRESHARED_KEY)
+                .setIsUserInteractionRequired()
+                .setIsMetered()
+                .build();
+
+        assertEquals("\"" + TEST_SSID + "\"", suggestion.wifiConfiguration.SSID);
+        assertTrue(suggestion.wifiConfiguration.allowedKeyManagement
+                .get(WifiConfiguration.KeyMgmt.WPA_PSK));
+        assertEquals("\"" + TEST_PRESHARED_KEY + "\"",
+                suggestion.wifiConfiguration.preSharedKey);
+        assertFalse(suggestion.isAppInteractionRequired);
+        assertTrue(suggestion.isUserInteractionRequired);
+        assertEquals(WifiConfiguration.METERED_OVERRIDE_METERED,
+                suggestion.wifiConfiguration.meteredOverride);
+        assertEquals(-1, suggestion.wifiConfiguration.priority);
+    }
+
+    /**
+     * Validate correctness of WifiNetworkSuggestion object created by
+     * {@link WifiNetworkSuggestion.Builder#build()} for OWE network.
+     */
+    @Test
+    public void testWifiNetworkSuggestionBuilderForEnhancedOpenNetworkWithBssid() {
+        WifiNetworkSuggestion suggestion = new WifiNetworkSuggestion.Builder()
+                .setSsid(TEST_SSID)
+                .setBssid(MacAddress.fromString(TEST_BSSID))
+                .setIsEnhancedOpen()
+                .build();
+
+        assertEquals("\"" + TEST_SSID + "\"", suggestion.wifiConfiguration.SSID);
+        assertEquals(TEST_BSSID, suggestion.wifiConfiguration.BSSID);
+        assertTrue(suggestion.wifiConfiguration.allowedKeyManagement
+                .get(WifiConfiguration.KeyMgmt.OWE));
+        assertNull(suggestion.wifiConfiguration.preSharedKey);
+        assertTrue(suggestion.wifiConfiguration.requirePMF);
+    }
+
+    /**
+     * Validate correctness of WifiNetworkSuggestion object created by
+     * {@link WifiNetworkSuggestion.Builder#build()} for SAE network.
+     */
+    @Test
+    public void testWifiNetworkSuggestionBuilderForWpa3PskNetwork() {
+        WifiNetworkSuggestion suggestion = new WifiNetworkSuggestion.Builder()
+                .setSsid(TEST_SSID)
+                .setWpa3Passphrase(TEST_PRESHARED_KEY)
+                .build();
+
+        assertEquals("\"" + TEST_SSID + "\"", suggestion.wifiConfiguration.SSID);
+        assertTrue(suggestion.wifiConfiguration.allowedKeyManagement
+                .get(WifiConfiguration.KeyMgmt.SAE));
+        assertEquals("\"" + TEST_PRESHARED_KEY + "\"",
+                suggestion.wifiConfiguration.preSharedKey);
+        assertTrue(suggestion.wifiConfiguration.requirePMF);
+    }
+
+
+    /**
+     * Validate correctness of WifiNetworkSuggestion object created by
+     * {@link WifiNetworkSuggestion.Builder#build()} for SuiteB network.
+     */
+    @Test
+    public void testWifiNetworkSuggestionBuilderForWpa3EapNetwork() {
+        WifiEnterpriseConfig enterpriseConfig = new WifiEnterpriseConfig();
+        enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.TLS);
+        enterpriseConfig.setPhase2Method(WifiEnterpriseConfig.Phase2.GTC);
+
+        WifiNetworkSuggestion suggestion = new WifiNetworkSuggestion.Builder()
+                .setSsid(TEST_SSID)
+                .setWpa3EnterpriseConfig(enterpriseConfig)
+                .build();
+
+        assertEquals("\"" + TEST_SSID + "\"", suggestion.wifiConfiguration.SSID);
+        assertTrue(suggestion.wifiConfiguration.allowedKeyManagement
+                .get(WifiConfiguration.KeyMgmt.SUITE_B_192));
+        assertTrue(suggestion.wifiConfiguration.allowedGroupCiphers
+                .get(WifiConfiguration.GroupCipher.GCMP_256));
+        assertTrue(suggestion.wifiConfiguration.allowedGroupManagementCiphers
+                .get(WifiConfiguration.GroupMgmtCipher.BIP_GMAC_256));
+        assertTrue(suggestion.wifiConfiguration.allowedSuiteBCiphers
+                .get(WifiConfiguration.SuiteBCipher.ECDHE_ECDSA));
+        assertTrue(suggestion.wifiConfiguration.allowedSuiteBCiphers
+                .get(WifiConfiguration.SuiteBCipher.ECDHE_RSA));
+        assertTrue(suggestion.wifiConfiguration.requirePMF);
+        assertNull(suggestion.wifiConfiguration.preSharedKey);
+    }
+
+    /**
+     * Ensure {@link WifiNetworkSuggestion.Builder#setSsid(String)} throws an exception
+     * when the string is not Unicode.
+     */
+    @Test(expected = IllegalArgumentException.class)
+    public void testWifiNetworkSuggestionBuilderSetSsidWithNonUnicodeString() {
+        new WifiNetworkSuggestion.Builder()
+                .setSsid("\ud800")
+                .build();
+    }
+
+    /**
+     * Ensure {@link WifiNetworkSuggestion.Builder#setWpa2Passphrase(String)} throws an exception
+     * when the string is not ASCII encodable.
+     */
+    @Test(expected = IllegalArgumentException.class)
+    public void testWifiNetworkSuggestionBuilderSetWpa2PasphraseWithNonAsciiString() {
+        new WifiNetworkSuggestion.Builder()
+                .setSsid(TEST_SSID)
+                .setWpa2Passphrase("salvē")
+                .build();
+    }
+
+    /**
+     * Ensure {@link WifiNetworkSuggestion.Builder#build()} throws an exception
+     * when {@link WifiNetworkSuggestion.Builder#setSsid(String)} is not set.
+     */
+    @Test(expected = IllegalStateException.class)
+    public void testWifiNetworkSuggestionBuilderWithNoSsid() {
+        new WifiNetworkSuggestion.Builder()
+                .build();
+    }
+
+    /**
+     * Ensure {@link WifiNetworkSuggestion.Builder#build()} throws an exception
+     * when {@link WifiNetworkSuggestion.Builder#setSsid(String)} is invoked with an invalid value.
+     */
+    @Test(expected = IllegalStateException.class)
+    public void testWifiNetworkSuggestionBuilderWithInvalidSsid() {
+        new WifiNetworkSuggestion.Builder()
+                .setSsid("")
+                .build();
+    }
+
+    /**
+     * Ensure {@link WifiNetworkSuggestion.Builder#build()} throws an exception
+     * when {@link WifiNetworkSuggestion.Builder#setBssid(MacAddress)} is invoked with an invalid
+     * value.
+     */
+    @Test(expected = IllegalStateException.class)
+    public void testWifiNetworkSuggestionBuilderWithInvalidBroadcastBssid() {
+        new WifiNetworkSuggestion.Builder()
+                .setSsid(TEST_SSID)
+                .setBssid(MacAddress.BROADCAST_ADDRESS)
+                .build();
+    }
+
+    /**
+     * Ensure {@link WifiNetworkSuggestion.Builder#build()} throws an exception
+     * when {@link WifiNetworkSuggestion.Builder#setBssid(MacAddress)} is invoked with an invalid
+     * value.
+     */
+    @Test(expected = IllegalStateException.class)
+    public void testWifiNetworkSuggestionBuilderWithInvalidAllZeroBssid() {
+        new WifiNetworkSuggestion.Builder()
+                .setSsid(TEST_SSID)
+                .setBssid(MacAddress.ALL_ZEROS_ADDRESS)
+                .build();
+    }
+
+    /**
+     * Ensure {@link WifiNetworkSuggestion.Builder#setPriority(int)} throws an exception
+     * when the value is negative.
+     */
+    @Test(expected = IllegalArgumentException.class)
+    public void testWifiNetworkSuggestionBuilderWithInvalidPriority() {
+        new WifiNetworkSuggestion.Builder()
+                .setSsid(TEST_SSID)
+                .setPriority(-1)
+                .build();
+    }
+
+    /**
+     * Ensure {@link WifiNetworkSuggestion.Builder#build()} throws an exception
+     * when both {@link WifiNetworkSuggestion.Builder#setWpa2Passphrase(String)} and
+     * {@link WifiNetworkSuggestion.Builder#setWpa3Passphrase(String)} are invoked.
+     */
+    @Test(expected = IllegalStateException.class)
+    public void testWifiNetworkSuggestionBuilderWithBothWpa2PasphraseAndWpa3Passphrase() {
+        new WifiNetworkSuggestion.Builder()
+                .setSsid(TEST_SSID)
+                .setWpa2Passphrase(TEST_PRESHARED_KEY)
+                .setWpa3Passphrase(TEST_PRESHARED_KEY)
+                .build();
+    }
+
+    /**
+     * Ensure {@link WifiNetworkSuggestion.Builder#build()} throws an exception
+     * when both {@link WifiNetworkSuggestion.Builder#setWpa3Passphrase(String)} and
+     * {@link WifiNetworkSuggestion.Builder#setWpa3EnterpriseConfig(WifiEnterpriseConfig)} are
+     * invoked.
+     */
+    @Test(expected = IllegalStateException.class)
+    public void testWifiNetworkSuggestionBuilderWithBothWpa3PasphraseAndEnterprise() {
+        new WifiNetworkSuggestion.Builder()
+                .setSsid(TEST_SSID)
+                .setWpa3Passphrase(TEST_PRESHARED_KEY)
+                .setWpa3EnterpriseConfig(new WifiEnterpriseConfig())
+                .build();
+    }
+
+    /**
+     * Ensure {@link WifiNetworkSuggestion.Builder#build()} throws an exception
+     * when both {@link WifiNetworkSuggestion.Builder#setWpa3Passphrase(String)} and
+     * {@link WifiNetworkSuggestion.Builder#setIsEnhancedOpen()} are invoked.
+     */
+    @Test(expected = IllegalStateException.class)
+    public void testWifiNetworkSuggestionBuilderWithBothWpa3PasphraseAndEnhancedOpen() {
+        new WifiNetworkSuggestion.Builder()
+                .setSsid(TEST_SSID)
+                .setWpa3Passphrase(TEST_PRESHARED_KEY)
+                .setIsEnhancedOpen()
+                .build();
+    }
 
     /**
      * Check that parcel marshalling/unmarshalling works
diff --git a/wifi/tests/src/android/net/wifi/hotspot2/pps/CredentialTest.java b/wifi/tests/src/android/net/wifi/hotspot2/pps/CredentialTest.java
index 1ecc3fe..0a3e989 100644
--- a/wifi/tests/src/android/net/wifi/hotspot2/pps/CredentialTest.java
+++ b/wifi/tests/src/android/net/wifi/hotspot2/pps/CredentialTest.java
@@ -541,4 +541,20 @@
         Credential copyCred = new Credential(sourceCred);
         assertTrue(copyCred.equals(sourceCred));
     }
+
+    /**
+     * Verify that two certificates are identical.
+     */
+    @Test
+    public void validateTwoCertificateIdentical() {
+        assertTrue(Credential.isX509CertificateEquals(FakeKeys.CA_CERT1, FakeKeys.CA_CERT1));
+    }
+
+    /**
+     * Verify that two certificates are different.
+     */
+    @Test
+    public void validateTwoCertificateDifferent() {
+        assertFalse(Credential.isX509CertificateEquals(FakeKeys.CA_CERT0, FakeKeys.CA_CERT1));
+    }
 }
diff --git a/wifi/tests/src/android/net/wifi/hotspot2/pps/UpdateParameterTest.java b/wifi/tests/src/android/net/wifi/hotspot2/pps/UpdateParameterTest.java
index 0b8cd3d..07cb151 100644
--- a/wifi/tests/src/android/net/wifi/hotspot2/pps/UpdateParameterTest.java
+++ b/wifi/tests/src/android/net/wifi/hotspot2/pps/UpdateParameterTest.java
@@ -16,9 +16,11 @@
 
 package android.net.wifi.hotspot2.pps;
 
+import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
 
+import android.net.wifi.FakeKeys;
 import android.os.Parcel;
 import android.util.Base64;
 
@@ -56,6 +58,7 @@
                 Base64.encodeToString("password".getBytes(), Base64.DEFAULT));
         updateParam.setTrustRootCertUrl("trust.cert.com");
         updateParam.setTrustRootCertSha256Fingerprint(new byte[32]);
+        updateParam.setCaCertificate(FakeKeys.CA_CERT0);
         return updateParam;
     }
 
@@ -71,6 +74,7 @@
         parcel.setDataPosition(0);    // Rewind data position back to the beginning for read.
         UpdateParameter paramFromRead = UpdateParameter.CREATOR.createFromParcel(parcel);
         assertTrue(paramFromRead.equals(paramToWrite));
+        assertEquals(paramToWrite.hashCode(), paramFromRead.hashCode());
     }
 
     /**