Merge "Grumble, nobody likes kibibytes."
diff --git a/Android.mk b/Android.mk
index 6fc8fbf..0e5dfed 100644
--- a/Android.mk
+++ b/Android.mk
@@ -140,9 +140,11 @@
 	core/java/android/bluetooth/IBluetoothInputHost.aidl \
 	core/java/android/bluetooth/IBluetoothHidDeviceCallback.aidl \
 	core/java/android/bluetooth/IBluetoothGatt.aidl \
-	core/java/android/bluetooth/IBluetoothGattCallback.aidl \
-	core/java/android/bluetooth/IBluetoothGattServerCallback.aidl \
+	core/java/android/bluetooth/IBluetoothGattCallbackExt.aidl \
+	core/java/android/bluetooth/IBluetoothGattServerCallbackExt.aidl \
 	core/java/android/bluetooth/le/IAdvertiserCallback.aidl \
+	core/java/android/bluetooth/le/IAdvertisingSetCallback.aidl \
+	core/java/android/bluetooth/le/IPeriodicAdvertisingCallback.aidl \
 	core/java/android/bluetooth/le/IScannerCallback.aidl \
 	core/java/android/content/IClipboard.aidl \
 	core/java/android/content/IContentService.aidl \
@@ -942,6 +944,28 @@
 		-werror -hide 111 -hide 113 \
 		-overview $(LOCAL_PATH)/core/java/overview.html
 
+SUPPORT_API_DIR := ./frameworks/support/api
+
+# More API Level information for the Support Library, which is currently
+# included as part of the core framework docs build.
+framework_docs_LOCAL_DROIDDOC_OPTIONS += \
+    -since $(SUPPORT_API_DIR)/22.0.0.txt 22.0.0 \
+    -since $(SUPPORT_API_DIR)/22.0.0.txt 22.0.0 \
+    -since $(SUPPORT_API_DIR)/22.1.0.txt 22.1.0 \
+    -since $(SUPPORT_API_DIR)/22.2.0.txt 22.2.0 \
+    -since $(SUPPORT_API_DIR)/22.2.1.txt 22.2.1 \
+    -since $(SUPPORT_API_DIR)/23.0.0.txt 23.0.0 \
+    -since $(SUPPORT_API_DIR)/23.1.0.txt 23.1.0 \
+    -since $(SUPPORT_API_DIR)/23.1.1.txt 23.1.1 \
+    -since $(SUPPORT_API_DIR)/23.2.0.txt 23.2.0 \
+    -since $(SUPPORT_API_DIR)/23.2.1.txt 23.2.1 \
+    -since $(SUPPORT_API_DIR)/23.4.0.txt 23.4.0 \
+    -since $(SUPPORT_API_DIR)/24.0.0.txt 24.0.0 \
+    -since $(SUPPORT_API_DIR)/24.1.0.txt 24.1.0 \
+    -since $(SUPPORT_API_DIR)/24.2.0.txt 24.2.0 \
+    -since $(SUPPORT_API_DIR)/25.0.0.txt 25.0.0 \
+    -since $(SUPPORT_API_DIR)/25.1.0.txt 25.1.0
+
 framework_docs_LOCAL_API_CHECK_ADDITIONAL_JAVA_DIR:= \
 	$(call intermediates-dir-for,JAVA_LIBRARIES,framework,,COMMON)
 
diff --git a/api/current.txt b/api/current.txt
index 38a9be8..d68610e 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -607,6 +607,7 @@
     field public static final int fontFamily = 16843692; // 0x10103ac
     field public static final int fontFeatureSettings = 16843959; // 0x10104b7
     field public static final int fontProviderAuthority = 16844114; // 0x1010552
+    field public static final int fontProviderPackage = 16844122; // 0x101055a
     field public static final int fontProviderQuery = 16844115; // 0x1010553
     field public static final int fontStyle = 16844081; // 0x1010531
     field public static final int fontWeight = 16844083; // 0x1010533
@@ -7113,6 +7114,7 @@
     method public java.util.Set<android.bluetooth.BluetoothDevice> getBondedDevices();
     method public static synchronized android.bluetooth.BluetoothAdapter getDefaultAdapter();
     method public java.lang.String getName();
+    method public android.bluetooth.le.PeriodicAdvertisingManager getPeriodicAdvertisingManager();
     method public int getProfileConnectionState(int);
     method public boolean getProfileProxy(android.content.Context, android.bluetooth.BluetoothProfile.ServiceListener, int);
     method public android.bluetooth.BluetoothDevice getRemoteDevice(java.lang.String);
@@ -7121,6 +7123,10 @@
     method public int getState();
     method public boolean isDiscovering();
     method public boolean isEnabled();
+    method public boolean isLe2MPhySupported();
+    method public boolean isLeCodedPhySupported();
+    method public boolean isLeExtendedAdvertisingSupported();
+    method public boolean isLePeriodicAdvertisingSupported();
     method public boolean isMultipleAdvertisementSupported();
     method public boolean isOffloadedFilteringSupported();
     method public boolean isOffloadedScanBatchingSupported();
@@ -7489,6 +7495,9 @@
   public final class BluetoothDevice implements android.os.Parcelable {
     method public android.bluetooth.BluetoothGatt connectGatt(android.content.Context, boolean, android.bluetooth.BluetoothGattCallback);
     method public android.bluetooth.BluetoothGatt connectGatt(android.content.Context, boolean, android.bluetooth.BluetoothGattCallback, int);
+    method public android.bluetooth.BluetoothGatt connectGatt(android.content.Context, boolean, android.bluetooth.BluetoothGattCallbackExt);
+    method public android.bluetooth.BluetoothGatt connectGatt(android.content.Context, boolean, android.bluetooth.BluetoothGattCallbackExt, int);
+    method public android.bluetooth.BluetoothGatt connectGatt(android.content.Context, boolean, android.bluetooth.BluetoothGattCallbackExt, int, int);
     method public boolean createBond();
     method public android.bluetooth.BluetoothSocket createInsecureRfcommSocketToServiceRecord(java.util.UUID) throws java.io.IOException;
     method public android.bluetooth.BluetoothSocket createRfcommSocketToServiceRecord(java.util.UUID) throws java.io.IOException;
@@ -7532,6 +7541,13 @@
     field public static final java.lang.String EXTRA_UUID = "android.bluetooth.device.extra.UUID";
     field public static final int PAIRING_VARIANT_PASSKEY_CONFIRMATION = 2; // 0x2
     field public static final int PAIRING_VARIANT_PIN = 0; // 0x0
+    field public static final int PHY_LE_1M = 1; // 0x1
+    field public static final int PHY_LE_2M = 2; // 0x2
+    field public static final int PHY_LE_ANY = 7; // 0x7
+    field public static final int PHY_LE_CODED = 4; // 0x4
+    field public static final int PHY_OPTION_NO_PREFERRED = 0; // 0x0
+    field public static final int PHY_OPTION_S2 = 1; // 0x1
+    field public static final int PHY_OPTION_S8 = 2; // 0x2
     field public static final int TRANSPORT_AUTO = 0; // 0x0
     field public static final int TRANSPORT_BREDR = 1; // 0x1
     field public static final int TRANSPORT_LE = 2; // 0x2
@@ -7554,10 +7570,12 @@
     method public java.util.List<android.bluetooth.BluetoothGattService> getServices();
     method public boolean readCharacteristic(android.bluetooth.BluetoothGattCharacteristic);
     method public boolean readDescriptor(android.bluetooth.BluetoothGattDescriptor);
+    method public void readPhy();
     method public boolean readRemoteRssi();
     method public boolean requestConnectionPriority(int);
     method public boolean requestMtu(int);
     method public boolean setCharacteristicNotification(android.bluetooth.BluetoothGattCharacteristic, boolean);
+    method public void setPreferredPhy(int, int, int);
     method public boolean writeCharacteristic(android.bluetooth.BluetoothGattCharacteristic);
     method public boolean writeDescriptor(android.bluetooth.BluetoothGattDescriptor);
     field public static final int CONNECTION_PRIORITY_BALANCED = 0; // 0x0
@@ -7575,8 +7593,12 @@
     field public static final int GATT_WRITE_NOT_PERMITTED = 3; // 0x3
   }
 
-  public abstract class BluetoothGattCallback {
+  public abstract deprecated class BluetoothGattCallback extends android.bluetooth.BluetoothGattCallbackExt {
     ctor public BluetoothGattCallback();
+  }
+
+  public abstract class BluetoothGattCallbackExt {
+    ctor public BluetoothGattCallbackExt();
     method public void onCharacteristicChanged(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic);
     method public void onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int);
     method public void onCharacteristicWrite(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int);
@@ -7584,6 +7606,8 @@
     method public void onDescriptorRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattDescriptor, int);
     method public void onDescriptorWrite(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattDescriptor, int);
     method public void onMtuChanged(android.bluetooth.BluetoothGatt, int, int);
+    method public void onPhyRead(android.bluetooth.BluetoothGatt, int, int, int);
+    method public void onPhyUpdate(android.bluetooth.BluetoothGatt, int, int, int);
     method public void onReadRemoteRssi(android.bluetooth.BluetoothGatt, int, int);
     method public void onReliableWriteCompleted(android.bluetooth.BluetoothGatt, int);
     method public void onServicesDiscovered(android.bluetooth.BluetoothGatt, int);
@@ -7677,12 +7701,18 @@
     method public android.bluetooth.BluetoothGattService getService(java.util.UUID);
     method public java.util.List<android.bluetooth.BluetoothGattService> getServices();
     method public boolean notifyCharacteristicChanged(android.bluetooth.BluetoothDevice, android.bluetooth.BluetoothGattCharacteristic, boolean);
+    method public void readPhy(android.bluetooth.BluetoothDevice);
     method public boolean removeService(android.bluetooth.BluetoothGattService);
     method public boolean sendResponse(android.bluetooth.BluetoothDevice, int, int, int, byte[]);
+    method public void setPreferredPhy(android.bluetooth.BluetoothDevice, int, int, int);
   }
 
-  public abstract class BluetoothGattServerCallback {
+  public abstract deprecated class BluetoothGattServerCallback extends android.bluetooth.BluetoothGattServerCallbackExt {
     ctor public BluetoothGattServerCallback();
+  }
+
+  public abstract class BluetoothGattServerCallbackExt {
+    ctor public BluetoothGattServerCallbackExt();
     method public void onCharacteristicReadRequest(android.bluetooth.BluetoothDevice, int, int, android.bluetooth.BluetoothGattCharacteristic);
     method public void onCharacteristicWriteRequest(android.bluetooth.BluetoothDevice, int, android.bluetooth.BluetoothGattCharacteristic, boolean, boolean, int, byte[]);
     method public void onConnectionStateChange(android.bluetooth.BluetoothDevice, int, int);
@@ -7691,6 +7721,8 @@
     method public void onExecuteWrite(android.bluetooth.BluetoothDevice, int, boolean);
     method public void onMtuChanged(android.bluetooth.BluetoothDevice, int);
     method public void onNotificationSent(android.bluetooth.BluetoothDevice, int);
+    method public void onPhyRead(android.bluetooth.BluetoothDevice, int, int, int);
+    method public void onPhyUpdate(android.bluetooth.BluetoothDevice, int, int, int);
     method public void onServiceAdded(int, android.bluetooth.BluetoothGattService);
   }
 
@@ -7891,10 +7923,85 @@
     method public android.bluetooth.le.AdvertiseSettings.Builder setTxPowerLevel(int);
   }
 
+  public final class AdvertisingSet {
+    method public void enableAdvertising(boolean);
+    method public void periodicAdvertisingEnable(boolean);
+    method public void setAdvertisingData(android.bluetooth.le.AdvertiseData);
+    method public void setAdvertisingParameters(android.bluetooth.le.AdvertisingSetParameters);
+    method public void setPeriodicAdvertisingData(android.bluetooth.le.AdvertiseData);
+    method public void setPeriodicAdvertisingParameters(android.bluetooth.le.PeriodicAdvertisingParameters);
+    method public void setScanResponseData(android.bluetooth.le.AdvertiseData);
+  }
+
+  public abstract class AdvertisingSetCallback {
+    ctor public AdvertisingSetCallback();
+    method public void onAdvertisingDataSet(android.bluetooth.le.AdvertisingSet, int);
+    method public void onAdvertisingEnabled(android.bluetooth.le.AdvertisingSet, boolean, int);
+    method public void onAdvertisingParametersUpdated(android.bluetooth.le.AdvertisingSet, int);
+    method public void onAdvertisingSetStarted(android.bluetooth.le.AdvertisingSet, int);
+    method public void onAdvertisingSetStopped(android.bluetooth.le.AdvertisingSet);
+    method public void onPeriodicAdvertisingDataSet(android.bluetooth.le.AdvertisingSet, int);
+    method public void onPeriodicAdvertisingEnable(android.bluetooth.le.AdvertisingSet, boolean, int);
+    method public void onPeriodicAdvertisingParametersUpdated(android.bluetooth.le.AdvertisingSet, int);
+    method public void onScanResponseDataSet(android.bluetooth.le.AdvertisingSet, int);
+    field public static final int ADVERTISE_FAILED_ALREADY_STARTED = 3; // 0x3
+    field public static final int ADVERTISE_FAILED_DATA_TOO_LARGE = 1; // 0x1
+    field public static final int ADVERTISE_FAILED_FEATURE_UNSUPPORTED = 5; // 0x5
+    field public static final int ADVERTISE_FAILED_INTERNAL_ERROR = 4; // 0x4
+    field public static final int ADVERTISE_FAILED_TOO_MANY_ADVERTISERS = 2; // 0x2
+    field public static final int ADVERTISE_SUCCESS = 0; // 0x0
+  }
+
+  public final class AdvertisingSetParameters implements android.os.Parcelable {
+    method public int describeContents();
+    method public int getInterval();
+    method public int getPrimaryPhy();
+    method public int getSecondaryPhy();
+    method public int getTimeout();
+    method public int getTxPowerLevel();
+    method public boolean includeTxPower();
+    method public boolean isAnonymous();
+    method public boolean isConnectable();
+    method public boolean isLegacy();
+    method public void writeToParcel(android.os.Parcel, int);
+    field public static final android.os.Parcelable.Creator<android.bluetooth.le.AdvertisingSetParameters> CREATOR;
+    field public static final int INTERVAL_HIGH = 160; // 0xa0
+    field public static final int INTERVAL_LOW = 1600; // 0x640
+    field public static final int INTERVAL_MAX = 16777215; // 0xffffff
+    field public static final int INTERVAL_MEDIUM = 400; // 0x190
+    field public static final int INTERVAL_MIN = 160; // 0xa0
+    field public static final int PHY_LE_1M = 1; // 0x1
+    field public static final int PHY_LE_2M = 2; // 0x2
+    field public static final int PHY_LE_CODED = 3; // 0x3
+    field public static final int TX_POWER_HIGH = 1; // 0x1
+    field public static final int TX_POWER_LOW = -15; // 0xfffffff1
+    field public static final int TX_POWER_MAX = 1; // 0x1
+    field public static final int TX_POWER_MEDIUM = -7; // 0xfffffff9
+    field public static final int TX_POWER_MIN = -127; // 0xffffff81
+    field public static final int TX_POWER_ULTRA_LOW = -21; // 0xffffffeb
+  }
+
+  public static final class AdvertisingSetParameters.Builder {
+    ctor public AdvertisingSetParameters.Builder();
+    method public android.bluetooth.le.AdvertisingSetParameters build();
+    method public android.bluetooth.le.AdvertisingSetParameters.Builder setAnonymouus(boolean);
+    method public android.bluetooth.le.AdvertisingSetParameters.Builder setConnectable(boolean);
+    method public android.bluetooth.le.AdvertisingSetParameters.Builder setIncludeTxPower(boolean);
+    method public android.bluetooth.le.AdvertisingSetParameters.Builder setInterval(int);
+    method public android.bluetooth.le.AdvertisingSetParameters.Builder setLegacyMode(boolean);
+    method public android.bluetooth.le.AdvertisingSetParameters.Builder setPrimaryPhy(int);
+    method public android.bluetooth.le.AdvertisingSetParameters.Builder setSecondaryPhy(int);
+    method public android.bluetooth.le.AdvertisingSetParameters.Builder setTimeout(int);
+    method public android.bluetooth.le.AdvertisingSetParameters.Builder setTxPowerLevel(int);
+  }
+
   public final class BluetoothLeAdvertiser {
     method public void startAdvertising(android.bluetooth.le.AdvertiseSettings, android.bluetooth.le.AdvertiseData, android.bluetooth.le.AdvertiseCallback);
     method public void startAdvertising(android.bluetooth.le.AdvertiseSettings, android.bluetooth.le.AdvertiseData, android.bluetooth.le.AdvertiseData, android.bluetooth.le.AdvertiseCallback);
+    method public void startAdvertisingSet(android.bluetooth.le.AdvertisingSetParameters, android.bluetooth.le.AdvertiseData, android.bluetooth.le.AdvertiseData, android.bluetooth.le.PeriodicAdvertisingParameters, android.bluetooth.le.AdvertiseData, android.bluetooth.le.AdvertisingSetCallback);
+    method public void startAdvertisingSet(android.bluetooth.le.AdvertisingSetParameters, android.bluetooth.le.AdvertiseData, android.bluetooth.le.AdvertiseData, android.bluetooth.le.PeriodicAdvertisingParameters, android.bluetooth.le.AdvertiseData, android.bluetooth.le.AdvertisingSetCallback, android.os.Handler);
     method public void stopAdvertising(android.bluetooth.le.AdvertiseCallback);
+    method public void stopAdvertisingSet(android.bluetooth.le.AdvertisingSetCallback);
   }
 
   public final class BluetoothLeScanner {
@@ -7904,6 +8011,53 @@
     method public void stopScan(android.bluetooth.le.ScanCallback);
   }
 
+  public abstract class PeriodicAdvertisingCallback {
+    ctor public PeriodicAdvertisingCallback();
+    method public void onPeriodicAdvertisingReport(android.bluetooth.le.PeriodicAdvertisingReport);
+    method public void onSyncEstablished(int, android.bluetooth.BluetoothDevice, int, int, int, int);
+    method public void onSyncLost(int);
+    field public static final int SYNC_NO_RESOURCES = 2; // 0x2
+    field public static final int SYNC_NO_RESPONSE = 1; // 0x1
+  }
+
+  public final class PeriodicAdvertisingManager {
+    method public void registerSync(android.bluetooth.le.ScanResult, int, int, android.bluetooth.le.PeriodicAdvertisingCallback);
+    method public void registerSync(android.bluetooth.le.ScanResult, int, int, android.bluetooth.le.PeriodicAdvertisingCallback, android.os.Handler);
+    method public void unregisterSync(android.bluetooth.le.PeriodicAdvertisingCallback);
+  }
+
+  public final class PeriodicAdvertisingParameters implements android.os.Parcelable {
+    method public int describeContents();
+    method public boolean getEnable();
+    method public boolean getIncludeTxPower();
+    method public int getInterval();
+    method public void writeToParcel(android.os.Parcel, int);
+    field public static final android.os.Parcelable.Creator<android.bluetooth.le.PeriodicAdvertisingParameters> CREATOR;
+  }
+
+  public static final class PeriodicAdvertisingParameters.Builder {
+    ctor public PeriodicAdvertisingParameters.Builder();
+    method public android.bluetooth.le.PeriodicAdvertisingParameters build();
+    method public android.bluetooth.le.PeriodicAdvertisingParameters.Builder setEnable(boolean);
+    method public android.bluetooth.le.PeriodicAdvertisingParameters.Builder setIncludeTxPower(boolean);
+    method public android.bluetooth.le.PeriodicAdvertisingParameters.Builder setInterval(int);
+  }
+
+  public final class PeriodicAdvertisingReport implements android.os.Parcelable {
+    ctor public PeriodicAdvertisingReport(int, int, int, int, android.bluetooth.le.ScanRecord);
+    method public int describeContents();
+    method public android.bluetooth.le.ScanRecord getData();
+    method public int getDataStatus();
+    method public int getRssi();
+    method public int getSyncHandle();
+    method public long getTimestampNanos();
+    method public int getTxPower();
+    method public void writeToParcel(android.os.Parcel, int);
+    field public static final android.os.Parcelable.Creator<android.bluetooth.le.PeriodicAdvertisingReport> CREATOR;
+    field public static final int DATA_COMPLETE = 0; // 0x0
+    field public static final int DATA_INCOMPLETE_TRUNCATED = 2; // 0x2
+  }
+
   public abstract class ScanCallback {
     ctor public ScanCallback();
     method public void onBatchScanResults(java.util.List<android.bluetooth.le.ScanResult>);
@@ -7958,19 +8112,37 @@
   }
 
   public final class ScanResult implements android.os.Parcelable {
-    ctor public ScanResult(android.bluetooth.BluetoothDevice, android.bluetooth.le.ScanRecord, int, long);
+    ctor public deprecated ScanResult(android.bluetooth.BluetoothDevice, android.bluetooth.le.ScanRecord, int, long);
+    ctor public ScanResult(android.bluetooth.BluetoothDevice, int, int, int, int, int, int, int, android.bluetooth.le.ScanRecord, long);
     method public int describeContents();
+    method public int getAdvertisingSid();
+    method public int getDataStatus();
     method public android.bluetooth.BluetoothDevice getDevice();
+    method public int getPeriodicAdvertisingInterval();
+    method public int getPrimaryPhy();
     method public int getRssi();
     method public android.bluetooth.le.ScanRecord getScanRecord();
+    method public int getSecondaryPhy();
     method public long getTimestampNanos();
+    method public int getTxPower();
+    method public boolean isConnectable();
+    method public boolean isLegacy();
     method public void writeToParcel(android.os.Parcel, int);
     field public static final android.os.Parcelable.Creator<android.bluetooth.le.ScanResult> CREATOR;
+    field public static final int DATA_COMPLETE = 0; // 0x0
+    field public static final int DATA_TRUNCATED = 2; // 0x2
+    field public static final int PHY_LE_1M = 1; // 0x1
+    field public static final int PHY_LE_2M = 2; // 0x2
+    field public static final int PHY_LE_CODED = 3; // 0x3
+    field public static final int PHY_UNUSED = 0; // 0x0
+    field public static final int SID_NOT_PRESENT = 255; // 0xff
   }
 
   public final class ScanSettings implements android.os.Parcelable {
     method public int describeContents();
     method public int getCallbackType();
+    method public boolean getLegacy();
+    method public int getPhy();
     method public long getReportDelayMillis();
     method public int getScanMode();
     method public int getScanResultType();
@@ -7984,6 +8156,9 @@
     field public static final int MATCH_NUM_FEW_ADVERTISEMENT = 2; // 0x2
     field public static final int MATCH_NUM_MAX_ADVERTISEMENT = 3; // 0x3
     field public static final int MATCH_NUM_ONE_ADVERTISEMENT = 1; // 0x1
+    field public static final int PHY_LE_1M = 1; // 0x1
+    field public static final int PHY_LE_ALL_SUPPORTED = 255; // 0xff
+    field public static final int PHY_LE_CODED = 3; // 0x3
     field public static final int SCAN_MODE_BALANCED = 1; // 0x1
     field public static final int SCAN_MODE_LOW_LATENCY = 2; // 0x2
     field public static final int SCAN_MODE_LOW_POWER = 0; // 0x0
@@ -7994,8 +8169,10 @@
     ctor public ScanSettings.Builder();
     method public android.bluetooth.le.ScanSettings build();
     method public android.bluetooth.le.ScanSettings.Builder setCallbackType(int);
+    method public android.bluetooth.le.ScanSettings.Builder setLegacy(boolean);
     method public android.bluetooth.le.ScanSettings.Builder setMatchMode(int);
     method public android.bluetooth.le.ScanSettings.Builder setNumOfMatches(int);
+    method public android.bluetooth.le.ScanSettings.Builder setPhy(int);
     method public android.bluetooth.le.ScanSettings.Builder setReportDelay(long);
     method public android.bluetooth.le.ScanSettings.Builder setScanMode(int);
   }
@@ -8047,6 +8224,8 @@
 
   public final class CompanionDeviceManager {
     method public void associate(android.companion.AssociationRequest<?>, android.companion.CompanionDeviceManager.Callback, android.os.Handler);
+    method public void disassociate(java.lang.String);
+    method public java.util.List<java.lang.String> getAssociations();
     field public static final java.lang.String EXTRA_DEVICE = "android.companion.extra.DEVICE";
   }
 
@@ -12211,6 +12390,7 @@
     method public android.graphics.Bitmap extractAlpha(android.graphics.Paint, int[]);
     method public final int getAllocationByteCount();
     method public final int getByteCount();
+    method public final android.graphics.ColorSpace getColorSpace();
     method public final android.graphics.Bitmap.Config getConfig();
     method public int getDensity();
     method public int getGenerationId();
@@ -12593,6 +12773,7 @@
     method public java.lang.String getName();
     method public boolean isSrgb();
     method public abstract boolean isWideGamut();
+    method public static android.graphics.ColorSpace match(float[], android.graphics.ColorSpace.Rgb.TransferParameters);
     method public float[] toXyz(float, float, float);
     method public abstract float[] toXyz(float[]);
     field public static final float[] ILLUMINANT_A;
@@ -12677,6 +12858,10 @@
   public static class ColorSpace.Rgb extends android.graphics.ColorSpace {
     ctor public ColorSpace.Rgb(java.lang.String, float[], java.util.function.DoubleUnaryOperator, java.util.function.DoubleUnaryOperator);
     ctor public ColorSpace.Rgb(java.lang.String, float[], float[], java.util.function.DoubleUnaryOperator, java.util.function.DoubleUnaryOperator, float, float);
+    ctor public ColorSpace.Rgb(java.lang.String, float[], android.graphics.ColorSpace.Rgb.TransferParameters);
+    ctor public ColorSpace.Rgb(java.lang.String, float[], float[], android.graphics.ColorSpace.Rgb.TransferParameters);
+    ctor public ColorSpace.Rgb(java.lang.String, float[], double);
+    ctor public ColorSpace.Rgb(java.lang.String, float[], float[], double);
     method public float[] fromLinear(float, float, float);
     method public float[] fromLinear(float[]);
     method public float[] fromXyz(float[]);
@@ -12688,6 +12873,7 @@
     method public java.util.function.DoubleUnaryOperator getOetf();
     method public float[] getPrimaries(float[]);
     method public float[] getPrimaries();
+    method public android.graphics.ColorSpace.Rgb.TransferParameters getTransferParameters();
     method public float[] getTransform(float[]);
     method public float[] getTransform();
     method public float[] getWhitePoint(float[]);
@@ -12698,6 +12884,18 @@
     method public float[] toXyz(float[]);
   }
 
+  public static class ColorSpace.Rgb.TransferParameters {
+    ctor public ColorSpace.Rgb.TransferParameters(double, double, double, double, double);
+    ctor public ColorSpace.Rgb.TransferParameters(double, double, double, double, double, double, double);
+    field public final double a;
+    field public final double b;
+    field public final double c;
+    field public final double d;
+    field public final double e;
+    field public final double f;
+    field public final double g;
+  }
+
   public class ComposePathEffect extends android.graphics.PathEffect {
     ctor public ComposePathEffect(android.graphics.PathEffect, android.graphics.PathEffect);
   }
@@ -14089,9 +14287,12 @@
 package android.graphics.fonts {
 
   public final class FontRequest implements android.os.Parcelable {
-    ctor public FontRequest(java.lang.String, java.lang.String);
+    ctor public FontRequest(java.lang.String, java.lang.String, java.lang.String);
+    ctor public FontRequest(java.lang.String, java.lang.String, java.lang.String, java.util.List<java.util.List<byte[]>>);
     method public int describeContents();
+    method public java.util.List<java.util.List<byte[]>> getCertificates();
     method public java.lang.String getProviderAuthority();
+    method public java.lang.String getProviderPackage();
     method public java.lang.String getQuery();
     method public void writeToParcel(android.os.Parcel, int);
     field public static final android.os.Parcelable.Creator<android.graphics.fonts.FontRequest> CREATOR;
@@ -19635,6 +19836,8 @@
     field public static final int SHORT_COMMONLY_USED = 6; // 0x6
     field public static final int SHORT_GENERIC = 2; // 0x2
     field public static final int SHORT_GMT = 4; // 0x4
+    field public static final int TIMEZONE_ICU = 0; // 0x0
+    field public static final int TIMEZONE_JDK = 1; // 0x1
     field public static final android.icu.util.TimeZone UNKNOWN_ZONE;
     field public static final java.lang.String UNKNOWN_ZONE_ID = "Etc/Unknown";
   }
@@ -24949,6 +25152,7 @@
     method public void reportNetworkConnectivity(android.net.Network, boolean);
     method public boolean requestBandwidthUpdate(android.net.Network);
     method public void requestNetwork(android.net.NetworkRequest, android.net.ConnectivityManager.NetworkCallback);
+    method public void requestNetwork(android.net.NetworkRequest, int, android.net.ConnectivityManager.NetworkCallback);
     method public void requestNetwork(android.net.NetworkRequest, android.app.PendingIntent);
     method public deprecated void setNetworkPreference(int);
     method public static deprecated boolean setProcessDefaultNetwork(android.net.Network);
@@ -24996,6 +25200,7 @@
     method public void onLinkPropertiesChanged(android.net.Network, android.net.LinkProperties);
     method public void onLosing(android.net.Network, int);
     method public void onLost(android.net.Network);
+    method public void onUnavailable();
   }
 
   public static abstract interface ConnectivityManager.OnNetworkActiveListener {
@@ -30270,7 +30475,7 @@
     ctor public Bundle(android.os.Bundle);
     ctor public Bundle(android.os.PersistableBundle);
     method public java.lang.Object clone();
-    method public android.os.Bundle deepcopy();
+    method public android.os.Bundle deepCopy();
     method public int describeContents();
     method public android.os.IBinder getBinder(java.lang.String);
     method public android.os.Bundle getBundle(java.lang.String);
@@ -30995,6 +31200,7 @@
     method public boolean match(java.lang.String);
     method public void writeToParcel(android.os.Parcel, int);
     field public static final android.os.Parcelable.Creator<android.os.PatternMatcher> CREATOR;
+    field public static final int PATTERN_ADVANCED_GLOB = 3; // 0x3
     field public static final int PATTERN_LITERAL = 0; // 0x0
     field public static final int PATTERN_PREFIX = 1; // 0x1
     field public static final int PATTERN_SIMPLE_GLOB = 2; // 0x2
@@ -31005,7 +31211,7 @@
     ctor public PersistableBundle(int);
     ctor public PersistableBundle(android.os.PersistableBundle);
     method public java.lang.Object clone();
-    method public android.os.PersistableBundle deepcopy();
+    method public android.os.PersistableBundle deepCopy();
     method public int describeContents();
     method public android.os.PersistableBundle getPersistableBundle(java.lang.String);
     method public void putPersistableBundle(java.lang.String, android.os.PersistableBundle);
@@ -31113,6 +31319,7 @@
     method public E getBroadcastItem(int);
     method public java.lang.Object getRegisteredCallbackCookie(int);
     method public int getRegisteredCallbackCount();
+    method public E getRegisteredCallbackItem(int);
     method public void kill();
     method public void onCallbackDied(E);
     method public void onCallbackDied(E, java.lang.Object);
diff --git a/api/system-current.txt b/api/system-current.txt
index 6d6b321..cb0d7b1 100644
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -719,6 +719,7 @@
     field public static final int fontFamily = 16843692; // 0x10103ac
     field public static final int fontFeatureSettings = 16843959; // 0x10104b7
     field public static final int fontProviderAuthority = 16844114; // 0x1010552
+    field public static final int fontProviderPackage = 16844122; // 0x101055a
     field public static final int fontProviderQuery = 16844115; // 0x1010553
     field public static final int fontStyle = 16844081; // 0x1010531
     field public static final int fontWeight = 16844083; // 0x1010533
@@ -7585,6 +7586,7 @@
     method public java.util.Set<android.bluetooth.BluetoothDevice> getBondedDevices();
     method public static synchronized android.bluetooth.BluetoothAdapter getDefaultAdapter();
     method public java.lang.String getName();
+    method public android.bluetooth.le.PeriodicAdvertisingManager getPeriodicAdvertisingManager();
     method public int getProfileConnectionState(int);
     method public boolean getProfileProxy(android.content.Context, android.bluetooth.BluetoothProfile.ServiceListener, int);
     method public android.bluetooth.BluetoothDevice getRemoteDevice(java.lang.String);
@@ -7594,7 +7596,11 @@
     method public boolean isBleScanAlwaysAvailable();
     method public boolean isDiscovering();
     method public boolean isEnabled();
+    method public boolean isLe2MPhySupported();
+    method public boolean isLeCodedPhySupported();
     method public boolean isLeEnabled();
+    method public boolean isLeExtendedAdvertisingSupported();
+    method public boolean isLePeriodicAdvertisingSupported();
     method public boolean isMultipleAdvertisementSupported();
     method public boolean isOffloadedFilteringSupported();
     method public boolean isOffloadedScanBatchingSupported();
@@ -7965,6 +7971,9 @@
   public final class BluetoothDevice implements android.os.Parcelable {
     method public android.bluetooth.BluetoothGatt connectGatt(android.content.Context, boolean, android.bluetooth.BluetoothGattCallback);
     method public android.bluetooth.BluetoothGatt connectGatt(android.content.Context, boolean, android.bluetooth.BluetoothGattCallback, int);
+    method public android.bluetooth.BluetoothGatt connectGatt(android.content.Context, boolean, android.bluetooth.BluetoothGattCallbackExt);
+    method public android.bluetooth.BluetoothGatt connectGatt(android.content.Context, boolean, android.bluetooth.BluetoothGattCallbackExt, int);
+    method public android.bluetooth.BluetoothGatt connectGatt(android.content.Context, boolean, android.bluetooth.BluetoothGattCallbackExt, int, int);
     method public boolean createBond();
     method public android.bluetooth.BluetoothSocket createInsecureRfcommSocketToServiceRecord(java.util.UUID) throws java.io.IOException;
     method public android.bluetooth.BluetoothSocket createRfcommSocketToServiceRecord(java.util.UUID) throws java.io.IOException;
@@ -8010,6 +8019,13 @@
     field public static final java.lang.String EXTRA_UUID = "android.bluetooth.device.extra.UUID";
     field public static final int PAIRING_VARIANT_PASSKEY_CONFIRMATION = 2; // 0x2
     field public static final int PAIRING_VARIANT_PIN = 0; // 0x0
+    field public static final int PHY_LE_1M = 1; // 0x1
+    field public static final int PHY_LE_2M = 2; // 0x2
+    field public static final int PHY_LE_ANY = 7; // 0x7
+    field public static final int PHY_LE_CODED = 4; // 0x4
+    field public static final int PHY_OPTION_NO_PREFERRED = 0; // 0x0
+    field public static final int PHY_OPTION_S2 = 1; // 0x1
+    field public static final int PHY_OPTION_S8 = 2; // 0x2
     field public static final int TRANSPORT_AUTO = 0; // 0x0
     field public static final int TRANSPORT_BREDR = 1; // 0x1
     field public static final int TRANSPORT_LE = 2; // 0x2
@@ -8032,10 +8048,12 @@
     method public java.util.List<android.bluetooth.BluetoothGattService> getServices();
     method public boolean readCharacteristic(android.bluetooth.BluetoothGattCharacteristic);
     method public boolean readDescriptor(android.bluetooth.BluetoothGattDescriptor);
+    method public void readPhy();
     method public boolean readRemoteRssi();
     method public boolean requestConnectionPriority(int);
     method public boolean requestMtu(int);
     method public boolean setCharacteristicNotification(android.bluetooth.BluetoothGattCharacteristic, boolean);
+    method public void setPreferredPhy(int, int, int);
     method public boolean writeCharacteristic(android.bluetooth.BluetoothGattCharacteristic);
     method public boolean writeDescriptor(android.bluetooth.BluetoothGattDescriptor);
     field public static final int CONNECTION_PRIORITY_BALANCED = 0; // 0x0
@@ -8053,8 +8071,12 @@
     field public static final int GATT_WRITE_NOT_PERMITTED = 3; // 0x3
   }
 
-  public abstract class BluetoothGattCallback {
+  public abstract deprecated class BluetoothGattCallback extends android.bluetooth.BluetoothGattCallbackExt {
     ctor public BluetoothGattCallback();
+  }
+
+  public abstract class BluetoothGattCallbackExt {
+    ctor public BluetoothGattCallbackExt();
     method public void onCharacteristicChanged(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic);
     method public void onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int);
     method public void onCharacteristicWrite(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int);
@@ -8062,6 +8084,8 @@
     method public void onDescriptorRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattDescriptor, int);
     method public void onDescriptorWrite(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattDescriptor, int);
     method public void onMtuChanged(android.bluetooth.BluetoothGatt, int, int);
+    method public void onPhyRead(android.bluetooth.BluetoothGatt, int, int, int);
+    method public void onPhyUpdate(android.bluetooth.BluetoothGatt, int, int, int);
     method public void onReadRemoteRssi(android.bluetooth.BluetoothGatt, int, int);
     method public void onReliableWriteCompleted(android.bluetooth.BluetoothGatt, int);
     method public void onServicesDiscovered(android.bluetooth.BluetoothGatt, int);
@@ -8155,12 +8179,18 @@
     method public android.bluetooth.BluetoothGattService getService(java.util.UUID);
     method public java.util.List<android.bluetooth.BluetoothGattService> getServices();
     method public boolean notifyCharacteristicChanged(android.bluetooth.BluetoothDevice, android.bluetooth.BluetoothGattCharacteristic, boolean);
+    method public void readPhy(android.bluetooth.BluetoothDevice);
     method public boolean removeService(android.bluetooth.BluetoothGattService);
     method public boolean sendResponse(android.bluetooth.BluetoothDevice, int, int, int, byte[]);
+    method public void setPreferredPhy(android.bluetooth.BluetoothDevice, int, int, int);
   }
 
-  public abstract class BluetoothGattServerCallback {
+  public abstract deprecated class BluetoothGattServerCallback extends android.bluetooth.BluetoothGattServerCallbackExt {
     ctor public BluetoothGattServerCallback();
+  }
+
+  public abstract class BluetoothGattServerCallbackExt {
+    ctor public BluetoothGattServerCallbackExt();
     method public void onCharacteristicReadRequest(android.bluetooth.BluetoothDevice, int, int, android.bluetooth.BluetoothGattCharacteristic);
     method public void onCharacteristicWriteRequest(android.bluetooth.BluetoothDevice, int, android.bluetooth.BluetoothGattCharacteristic, boolean, boolean, int, byte[]);
     method public void onConnectionStateChange(android.bluetooth.BluetoothDevice, int, int);
@@ -8169,6 +8199,8 @@
     method public void onExecuteWrite(android.bluetooth.BluetoothDevice, int, boolean);
     method public void onMtuChanged(android.bluetooth.BluetoothDevice, int);
     method public void onNotificationSent(android.bluetooth.BluetoothDevice, int);
+    method public void onPhyRead(android.bluetooth.BluetoothDevice, int, int, int);
+    method public void onPhyUpdate(android.bluetooth.BluetoothDevice, int, int, int);
     method public void onServiceAdded(int, android.bluetooth.BluetoothGattService);
   }
 
@@ -8369,10 +8401,85 @@
     method public android.bluetooth.le.AdvertiseSettings.Builder setTxPowerLevel(int);
   }
 
+  public final class AdvertisingSet {
+    method public void enableAdvertising(boolean);
+    method public void periodicAdvertisingEnable(boolean);
+    method public void setAdvertisingData(android.bluetooth.le.AdvertiseData);
+    method public void setAdvertisingParameters(android.bluetooth.le.AdvertisingSetParameters);
+    method public void setPeriodicAdvertisingData(android.bluetooth.le.AdvertiseData);
+    method public void setPeriodicAdvertisingParameters(android.bluetooth.le.PeriodicAdvertisingParameters);
+    method public void setScanResponseData(android.bluetooth.le.AdvertiseData);
+  }
+
+  public abstract class AdvertisingSetCallback {
+    ctor public AdvertisingSetCallback();
+    method public void onAdvertisingDataSet(android.bluetooth.le.AdvertisingSet, int);
+    method public void onAdvertisingEnabled(android.bluetooth.le.AdvertisingSet, boolean, int);
+    method public void onAdvertisingParametersUpdated(android.bluetooth.le.AdvertisingSet, int);
+    method public void onAdvertisingSetStarted(android.bluetooth.le.AdvertisingSet, int);
+    method public void onAdvertisingSetStopped(android.bluetooth.le.AdvertisingSet);
+    method public void onPeriodicAdvertisingDataSet(android.bluetooth.le.AdvertisingSet, int);
+    method public void onPeriodicAdvertisingEnable(android.bluetooth.le.AdvertisingSet, boolean, int);
+    method public void onPeriodicAdvertisingParametersUpdated(android.bluetooth.le.AdvertisingSet, int);
+    method public void onScanResponseDataSet(android.bluetooth.le.AdvertisingSet, int);
+    field public static final int ADVERTISE_FAILED_ALREADY_STARTED = 3; // 0x3
+    field public static final int ADVERTISE_FAILED_DATA_TOO_LARGE = 1; // 0x1
+    field public static final int ADVERTISE_FAILED_FEATURE_UNSUPPORTED = 5; // 0x5
+    field public static final int ADVERTISE_FAILED_INTERNAL_ERROR = 4; // 0x4
+    field public static final int ADVERTISE_FAILED_TOO_MANY_ADVERTISERS = 2; // 0x2
+    field public static final int ADVERTISE_SUCCESS = 0; // 0x0
+  }
+
+  public final class AdvertisingSetParameters implements android.os.Parcelable {
+    method public int describeContents();
+    method public int getInterval();
+    method public int getPrimaryPhy();
+    method public int getSecondaryPhy();
+    method public int getTimeout();
+    method public int getTxPowerLevel();
+    method public boolean includeTxPower();
+    method public boolean isAnonymous();
+    method public boolean isConnectable();
+    method public boolean isLegacy();
+    method public void writeToParcel(android.os.Parcel, int);
+    field public static final android.os.Parcelable.Creator<android.bluetooth.le.AdvertisingSetParameters> CREATOR;
+    field public static final int INTERVAL_HIGH = 160; // 0xa0
+    field public static final int INTERVAL_LOW = 1600; // 0x640
+    field public static final int INTERVAL_MAX = 16777215; // 0xffffff
+    field public static final int INTERVAL_MEDIUM = 400; // 0x190
+    field public static final int INTERVAL_MIN = 160; // 0xa0
+    field public static final int PHY_LE_1M = 1; // 0x1
+    field public static final int PHY_LE_2M = 2; // 0x2
+    field public static final int PHY_LE_CODED = 3; // 0x3
+    field public static final int TX_POWER_HIGH = 1; // 0x1
+    field public static final int TX_POWER_LOW = -15; // 0xfffffff1
+    field public static final int TX_POWER_MAX = 1; // 0x1
+    field public static final int TX_POWER_MEDIUM = -7; // 0xfffffff9
+    field public static final int TX_POWER_MIN = -127; // 0xffffff81
+    field public static final int TX_POWER_ULTRA_LOW = -21; // 0xffffffeb
+  }
+
+  public static final class AdvertisingSetParameters.Builder {
+    ctor public AdvertisingSetParameters.Builder();
+    method public android.bluetooth.le.AdvertisingSetParameters build();
+    method public android.bluetooth.le.AdvertisingSetParameters.Builder setAnonymouus(boolean);
+    method public android.bluetooth.le.AdvertisingSetParameters.Builder setConnectable(boolean);
+    method public android.bluetooth.le.AdvertisingSetParameters.Builder setIncludeTxPower(boolean);
+    method public android.bluetooth.le.AdvertisingSetParameters.Builder setInterval(int);
+    method public android.bluetooth.le.AdvertisingSetParameters.Builder setLegacyMode(boolean);
+    method public android.bluetooth.le.AdvertisingSetParameters.Builder setPrimaryPhy(int);
+    method public android.bluetooth.le.AdvertisingSetParameters.Builder setSecondaryPhy(int);
+    method public android.bluetooth.le.AdvertisingSetParameters.Builder setTimeout(int);
+    method public android.bluetooth.le.AdvertisingSetParameters.Builder setTxPowerLevel(int);
+  }
+
   public final class BluetoothLeAdvertiser {
     method public void startAdvertising(android.bluetooth.le.AdvertiseSettings, android.bluetooth.le.AdvertiseData, android.bluetooth.le.AdvertiseCallback);
     method public void startAdvertising(android.bluetooth.le.AdvertiseSettings, android.bluetooth.le.AdvertiseData, android.bluetooth.le.AdvertiseData, android.bluetooth.le.AdvertiseCallback);
+    method public void startAdvertisingSet(android.bluetooth.le.AdvertisingSetParameters, android.bluetooth.le.AdvertiseData, android.bluetooth.le.AdvertiseData, android.bluetooth.le.PeriodicAdvertisingParameters, android.bluetooth.le.AdvertiseData, android.bluetooth.le.AdvertisingSetCallback);
+    method public void startAdvertisingSet(android.bluetooth.le.AdvertisingSetParameters, android.bluetooth.le.AdvertiseData, android.bluetooth.le.AdvertiseData, android.bluetooth.le.PeriodicAdvertisingParameters, android.bluetooth.le.AdvertiseData, android.bluetooth.le.AdvertisingSetCallback, android.os.Handler);
     method public void stopAdvertising(android.bluetooth.le.AdvertiseCallback);
+    method public void stopAdvertisingSet(android.bluetooth.le.AdvertisingSetCallback);
   }
 
   public final class BluetoothLeScanner {
@@ -8385,6 +8492,53 @@
     method public void stopScan(android.bluetooth.le.ScanCallback);
   }
 
+  public abstract class PeriodicAdvertisingCallback {
+    ctor public PeriodicAdvertisingCallback();
+    method public void onPeriodicAdvertisingReport(android.bluetooth.le.PeriodicAdvertisingReport);
+    method public void onSyncEstablished(int, android.bluetooth.BluetoothDevice, int, int, int, int);
+    method public void onSyncLost(int);
+    field public static final int SYNC_NO_RESOURCES = 2; // 0x2
+    field public static final int SYNC_NO_RESPONSE = 1; // 0x1
+  }
+
+  public final class PeriodicAdvertisingManager {
+    method public void registerSync(android.bluetooth.le.ScanResult, int, int, android.bluetooth.le.PeriodicAdvertisingCallback);
+    method public void registerSync(android.bluetooth.le.ScanResult, int, int, android.bluetooth.le.PeriodicAdvertisingCallback, android.os.Handler);
+    method public void unregisterSync(android.bluetooth.le.PeriodicAdvertisingCallback);
+  }
+
+  public final class PeriodicAdvertisingParameters implements android.os.Parcelable {
+    method public int describeContents();
+    method public boolean getEnable();
+    method public boolean getIncludeTxPower();
+    method public int getInterval();
+    method public void writeToParcel(android.os.Parcel, int);
+    field public static final android.os.Parcelable.Creator<android.bluetooth.le.PeriodicAdvertisingParameters> CREATOR;
+  }
+
+  public static final class PeriodicAdvertisingParameters.Builder {
+    ctor public PeriodicAdvertisingParameters.Builder();
+    method public android.bluetooth.le.PeriodicAdvertisingParameters build();
+    method public android.bluetooth.le.PeriodicAdvertisingParameters.Builder setEnable(boolean);
+    method public android.bluetooth.le.PeriodicAdvertisingParameters.Builder setIncludeTxPower(boolean);
+    method public android.bluetooth.le.PeriodicAdvertisingParameters.Builder setInterval(int);
+  }
+
+  public final class PeriodicAdvertisingReport implements android.os.Parcelable {
+    ctor public PeriodicAdvertisingReport(int, int, int, int, android.bluetooth.le.ScanRecord);
+    method public int describeContents();
+    method public android.bluetooth.le.ScanRecord getData();
+    method public int getDataStatus();
+    method public int getRssi();
+    method public int getSyncHandle();
+    method public long getTimestampNanos();
+    method public int getTxPower();
+    method public void writeToParcel(android.os.Parcel, int);
+    field public static final android.os.Parcelable.Creator<android.bluetooth.le.PeriodicAdvertisingReport> CREATOR;
+    field public static final int DATA_COMPLETE = 0; // 0x0
+    field public static final int DATA_INCOMPLETE_TRUNCATED = 2; // 0x2
+  }
+
   public final class ResultStorageDescriptor implements android.os.Parcelable {
     ctor public ResultStorageDescriptor(int, int, int);
     method public int describeContents();
@@ -8449,19 +8603,37 @@
   }
 
   public final class ScanResult implements android.os.Parcelable {
-    ctor public ScanResult(android.bluetooth.BluetoothDevice, android.bluetooth.le.ScanRecord, int, long);
+    ctor public deprecated ScanResult(android.bluetooth.BluetoothDevice, android.bluetooth.le.ScanRecord, int, long);
+    ctor public ScanResult(android.bluetooth.BluetoothDevice, int, int, int, int, int, int, int, android.bluetooth.le.ScanRecord, long);
     method public int describeContents();
+    method public int getAdvertisingSid();
+    method public int getDataStatus();
     method public android.bluetooth.BluetoothDevice getDevice();
+    method public int getPeriodicAdvertisingInterval();
+    method public int getPrimaryPhy();
     method public int getRssi();
     method public android.bluetooth.le.ScanRecord getScanRecord();
+    method public int getSecondaryPhy();
     method public long getTimestampNanos();
+    method public int getTxPower();
+    method public boolean isConnectable();
+    method public boolean isLegacy();
     method public void writeToParcel(android.os.Parcel, int);
     field public static final android.os.Parcelable.Creator<android.bluetooth.le.ScanResult> CREATOR;
+    field public static final int DATA_COMPLETE = 0; // 0x0
+    field public static final int DATA_TRUNCATED = 2; // 0x2
+    field public static final int PHY_LE_1M = 1; // 0x1
+    field public static final int PHY_LE_2M = 2; // 0x2
+    field public static final int PHY_LE_CODED = 3; // 0x3
+    field public static final int PHY_UNUSED = 0; // 0x0
+    field public static final int SID_NOT_PRESENT = 255; // 0xff
   }
 
   public final class ScanSettings implements android.os.Parcelable {
     method public int describeContents();
     method public int getCallbackType();
+    method public boolean getLegacy();
+    method public int getPhy();
     method public long getReportDelayMillis();
     method public int getScanMode();
     method public int getScanResultType();
@@ -8475,6 +8647,9 @@
     field public static final int MATCH_NUM_FEW_ADVERTISEMENT = 2; // 0x2
     field public static final int MATCH_NUM_MAX_ADVERTISEMENT = 3; // 0x3
     field public static final int MATCH_NUM_ONE_ADVERTISEMENT = 1; // 0x1
+    field public static final int PHY_LE_1M = 1; // 0x1
+    field public static final int PHY_LE_ALL_SUPPORTED = 255; // 0xff
+    field public static final int PHY_LE_CODED = 3; // 0x3
     field public static final int SCAN_MODE_BALANCED = 1; // 0x1
     field public static final int SCAN_MODE_LOW_LATENCY = 2; // 0x2
     field public static final int SCAN_MODE_LOW_POWER = 0; // 0x0
@@ -8487,8 +8662,10 @@
     ctor public ScanSettings.Builder();
     method public android.bluetooth.le.ScanSettings build();
     method public android.bluetooth.le.ScanSettings.Builder setCallbackType(int);
+    method public android.bluetooth.le.ScanSettings.Builder setLegacy(boolean);
     method public android.bluetooth.le.ScanSettings.Builder setMatchMode(int);
     method public android.bluetooth.le.ScanSettings.Builder setNumOfMatches(int);
+    method public android.bluetooth.le.ScanSettings.Builder setPhy(int);
     method public android.bluetooth.le.ScanSettings.Builder setReportDelay(long);
     method public android.bluetooth.le.ScanSettings.Builder setScanMode(int);
     method public android.bluetooth.le.ScanSettings.Builder setScanResultType(int);
@@ -8547,6 +8724,8 @@
 
   public final class CompanionDeviceManager {
     method public void associate(android.companion.AssociationRequest<?>, android.companion.CompanionDeviceManager.Callback, android.os.Handler);
+    method public void disassociate(java.lang.String);
+    method public java.util.List<java.lang.String> getAssociations();
     field public static final java.lang.String EXTRA_DEVICE = "android.companion.extra.DEVICE";
   }
 
@@ -9907,6 +10086,7 @@
     method public final java.lang.String getDataScheme(int);
     method public final android.os.PatternMatcher getDataSchemeSpecificPart(int);
     method public final java.lang.String getDataType(int);
+    method public final int getOrder();
     method public final int getPriority();
     method public final boolean hasAction(java.lang.String);
     method public final boolean hasCategory(java.lang.String);
@@ -9925,6 +10105,7 @@
     method public void readFromXml(org.xmlpull.v1.XmlPullParser) throws java.io.IOException, org.xmlpull.v1.XmlPullParserException;
     method public final java.util.Iterator<android.os.PatternMatcher> schemeSpecificPartsIterator();
     method public final java.util.Iterator<java.lang.String> schemesIterator();
+    method public final void setOrder(int);
     method public final void setPriority(int);
     method public final java.util.Iterator<java.lang.String> typesIterator();
     method public final void writeToParcel(android.os.Parcel, int);
@@ -10598,6 +10779,20 @@
     field public int version;
   }
 
+  public final class InstantAppInfo implements android.os.Parcelable {
+    ctor public InstantAppInfo(android.content.pm.ApplicationInfo, java.lang.String[], java.lang.String[]);
+    ctor public InstantAppInfo(java.lang.String, java.lang.CharSequence, java.lang.String[], java.lang.String[]);
+    method public int describeContents();
+    method public android.content.pm.ApplicationInfo getApplicationInfo();
+    method public java.lang.String[] getGrantedPermissions();
+    method public java.lang.String getPackageName();
+    method public java.lang.String[] getRequestedPermissions();
+    method public android.graphics.drawable.Drawable loadIcon(android.content.pm.PackageManager);
+    method public java.lang.CharSequence loadLabel(android.content.pm.PackageManager);
+    method public void writeToParcel(android.os.Parcel, int);
+    field public static final android.os.Parcelable.Creator<android.content.pm.InstantAppInfo> CREATOR;
+  }
+
   public final class InstantAppIntentFilter implements android.os.Parcelable {
     ctor public InstantAppIntentFilter(java.lang.String, java.util.List<android.content.IntentFilter>);
     method public int describeContents();
@@ -10953,6 +11148,8 @@
     method public abstract java.lang.String getInstallerPackageName(java.lang.String);
     method public abstract byte[] getInstantAppCookie();
     method public abstract int getInstantAppCookieMaxSize();
+    method public abstract android.graphics.drawable.Drawable getInstantAppIcon(java.lang.String);
+    method public abstract java.util.List<android.content.pm.InstantAppInfo> getInstantApps();
     method public abstract android.content.pm.InstrumentationInfo getInstrumentationInfo(android.content.ComponentName, int) throws android.content.pm.PackageManager.NameNotFoundException;
     method public abstract java.util.List<android.content.pm.IntentFilterVerificationInfo> getIntentFilterVerifications(java.lang.String);
     method public abstract int getIntentVerificationStatusAsUser(java.lang.String, int);
@@ -11197,6 +11394,7 @@
     field public static final int MATCH_DIRECT_BOOT_UNAWARE = 262144; // 0x40000
     field public static final int MATCH_DISABLED_COMPONENTS = 512; // 0x200
     field public static final int MATCH_DISABLED_UNTIL_USED_COMPONENTS = 32768; // 0x8000
+    field public static final int MATCH_INSTANT = 8388608; // 0x800000
     field public static final int MATCH_SYSTEM_ONLY = 1048576; // 0x100000
     field public static final int MATCH_UNINSTALLED_PACKAGES = 8192; // 0x2000
     field public static final long MAXIMUM_VERIFICATION_TIMEOUT = 3600000L; // 0x36ee80L
@@ -12928,6 +13126,7 @@
     method public android.graphics.Bitmap extractAlpha(android.graphics.Paint, int[]);
     method public final int getAllocationByteCount();
     method public final int getByteCount();
+    method public final android.graphics.ColorSpace getColorSpace();
     method public final android.graphics.Bitmap.Config getConfig();
     method public int getDensity();
     method public int getGenerationId();
@@ -13310,6 +13509,7 @@
     method public java.lang.String getName();
     method public boolean isSrgb();
     method public abstract boolean isWideGamut();
+    method public static android.graphics.ColorSpace match(float[], android.graphics.ColorSpace.Rgb.TransferParameters);
     method public float[] toXyz(float, float, float);
     method public abstract float[] toXyz(float[]);
     field public static final float[] ILLUMINANT_A;
@@ -13394,6 +13594,10 @@
   public static class ColorSpace.Rgb extends android.graphics.ColorSpace {
     ctor public ColorSpace.Rgb(java.lang.String, float[], java.util.function.DoubleUnaryOperator, java.util.function.DoubleUnaryOperator);
     ctor public ColorSpace.Rgb(java.lang.String, float[], float[], java.util.function.DoubleUnaryOperator, java.util.function.DoubleUnaryOperator, float, float);
+    ctor public ColorSpace.Rgb(java.lang.String, float[], android.graphics.ColorSpace.Rgb.TransferParameters);
+    ctor public ColorSpace.Rgb(java.lang.String, float[], float[], android.graphics.ColorSpace.Rgb.TransferParameters);
+    ctor public ColorSpace.Rgb(java.lang.String, float[], double);
+    ctor public ColorSpace.Rgb(java.lang.String, float[], float[], double);
     method public float[] fromLinear(float, float, float);
     method public float[] fromLinear(float[]);
     method public float[] fromXyz(float[]);
@@ -13405,6 +13609,7 @@
     method public java.util.function.DoubleUnaryOperator getOetf();
     method public float[] getPrimaries(float[]);
     method public float[] getPrimaries();
+    method public android.graphics.ColorSpace.Rgb.TransferParameters getTransferParameters();
     method public float[] getTransform(float[]);
     method public float[] getTransform();
     method public float[] getWhitePoint(float[]);
@@ -13415,6 +13620,18 @@
     method public float[] toXyz(float[]);
   }
 
+  public static class ColorSpace.Rgb.TransferParameters {
+    ctor public ColorSpace.Rgb.TransferParameters(double, double, double, double, double);
+    ctor public ColorSpace.Rgb.TransferParameters(double, double, double, double, double, double, double);
+    field public final double a;
+    field public final double b;
+    field public final double c;
+    field public final double d;
+    field public final double e;
+    field public final double f;
+    field public final double g;
+  }
+
   public class ComposePathEffect extends android.graphics.PathEffect {
     ctor public ComposePathEffect(android.graphics.PathEffect, android.graphics.PathEffect);
   }
@@ -14806,9 +15023,12 @@
 package android.graphics.fonts {
 
   public final class FontRequest implements android.os.Parcelable {
-    ctor public FontRequest(java.lang.String, java.lang.String);
+    ctor public FontRequest(java.lang.String, java.lang.String, java.lang.String);
+    ctor public FontRequest(java.lang.String, java.lang.String, java.lang.String, java.util.List<java.util.List<byte[]>>);
     method public int describeContents();
+    method public java.util.List<java.util.List<byte[]>> getCertificates();
     method public java.lang.String getProviderAuthority();
+    method public java.lang.String getProviderPackage();
     method public java.lang.String getQuery();
     method public void writeToParcel(android.os.Parcel, int);
     field public static final android.os.Parcelable.Creator<android.graphics.fonts.FontRequest> CREATOR;
@@ -15590,10 +15810,14 @@
     method public abstract void createCaptureSession(java.util.List<android.view.Surface>, android.hardware.camera2.CameraCaptureSession.StateCallback, android.os.Handler) throws android.hardware.camera2.CameraAccessException;
     method public abstract void createCaptureSessionByOutputConfigurations(java.util.List<android.hardware.camera2.params.OutputConfiguration>, android.hardware.camera2.CameraCaptureSession.StateCallback, android.os.Handler) throws android.hardware.camera2.CameraAccessException;
     method public abstract void createConstrainedHighSpeedCaptureSession(java.util.List<android.view.Surface>, android.hardware.camera2.CameraCaptureSession.StateCallback, android.os.Handler) throws android.hardware.camera2.CameraAccessException;
+    method public abstract void createCustomCaptureSession(android.hardware.camera2.params.InputConfiguration, java.util.List<android.hardware.camera2.params.OutputConfiguration>, int, android.hardware.camera2.CameraCaptureSession.StateCallback, android.os.Handler) throws android.hardware.camera2.CameraAccessException;
     method public abstract android.hardware.camera2.CaptureRequest.Builder createReprocessCaptureRequest(android.hardware.camera2.TotalCaptureResult) throws android.hardware.camera2.CameraAccessException;
     method public abstract void createReprocessableCaptureSession(android.hardware.camera2.params.InputConfiguration, java.util.List<android.view.Surface>, android.hardware.camera2.CameraCaptureSession.StateCallback, android.os.Handler) throws android.hardware.camera2.CameraAccessException;
     method public abstract void createReprocessableCaptureSessionByConfigurations(android.hardware.camera2.params.InputConfiguration, java.util.List<android.hardware.camera2.params.OutputConfiguration>, android.hardware.camera2.CameraCaptureSession.StateCallback, android.os.Handler) throws android.hardware.camera2.CameraAccessException;
     method public abstract java.lang.String getId();
+    field public static final int SESSION_OPERATION_MODE_CONSTRAINED_HIGH_SPEED = 1; // 0x1
+    field public static final int SESSION_OPERATION_MODE_NORMAL = 0; // 0x0
+    field public static final int SESSION_OPERATION_MODE_VENDOR_START = 32768; // 0x8000
     field public static final int TEMPLATE_MANUAL = 6; // 0x6
     field public static final int TEMPLATE_PREVIEW = 1; // 0x1
     field public static final int TEMPLATE_RECORD = 3; // 0x3
@@ -21074,6 +21298,8 @@
     field public static final int SHORT_COMMONLY_USED = 6; // 0x6
     field public static final int SHORT_GENERIC = 2; // 0x2
     field public static final int SHORT_GMT = 4; // 0x4
+    field public static final int TIMEZONE_ICU = 0; // 0x0
+    field public static final int TIMEZONE_JDK = 1; // 0x1
     field public static final android.icu.util.TimeZone UNKNOWN_ZONE;
     field public static final java.lang.String UNKNOWN_ZONE_ID = "Etc/Unknown";
   }
@@ -26723,7 +26949,12 @@
     ctor public LogMaker(int);
     ctor public LogMaker(java.lang.Object[]);
     method public android.metrics.LogMaker addTaggedData(int, java.lang.Object);
+    method public android.metrics.LogMaker clearCategory();
+    method public android.metrics.LogMaker clearPackageName();
+    method public android.metrics.LogMaker clearSubtype();
     method public android.metrics.LogMaker clearTaggedData(int);
+    method public android.metrics.LogMaker clearTimestamp();
+    method public android.metrics.LogMaker clearType();
     method public void deserialize(java.lang.Object[]);
     method public int getCategory();
     method public long getCounterBucket();
@@ -27042,6 +27273,7 @@
     method public void reportNetworkConnectivity(android.net.Network, boolean);
     method public boolean requestBandwidthUpdate(android.net.Network);
     method public void requestNetwork(android.net.NetworkRequest, android.net.ConnectivityManager.NetworkCallback);
+    method public void requestNetwork(android.net.NetworkRequest, int, android.net.ConnectivityManager.NetworkCallback);
     method public void requestNetwork(android.net.NetworkRequest, android.app.PendingIntent);
     method public deprecated void setNetworkPreference(int);
     method public static deprecated boolean setProcessDefaultNetwork(android.net.Network);
@@ -27095,6 +27327,7 @@
     method public void onLinkPropertiesChanged(android.net.Network, android.net.LinkProperties);
     method public void onLosing(android.net.Network, int);
     method public void onLost(android.net.Network);
+    method public void onUnavailable();
   }
 
   public static abstract interface ConnectivityManager.OnNetworkActiveListener {
@@ -32954,7 +33187,7 @@
     ctor public Bundle(android.os.Bundle);
     ctor public Bundle(android.os.PersistableBundle);
     method public java.lang.Object clone();
-    method public android.os.Bundle deepcopy();
+    method public android.os.Bundle deepCopy();
     method public int describeContents();
     method public android.os.IBinder getBinder(java.lang.String);
     method public android.os.Bundle getBundle(java.lang.String);
@@ -33700,6 +33933,7 @@
     method public boolean match(java.lang.String);
     method public void writeToParcel(android.os.Parcel, int);
     field public static final android.os.Parcelable.Creator<android.os.PatternMatcher> CREATOR;
+    field public static final int PATTERN_ADVANCED_GLOB = 3; // 0x3
     field public static final int PATTERN_LITERAL = 0; // 0x0
     field public static final int PATTERN_PREFIX = 1; // 0x1
     field public static final int PATTERN_SIMPLE_GLOB = 2; // 0x2
@@ -33710,7 +33944,7 @@
     ctor public PersistableBundle(int);
     ctor public PersistableBundle(android.os.PersistableBundle);
     method public java.lang.Object clone();
-    method public android.os.PersistableBundle deepcopy();
+    method public android.os.PersistableBundle deepCopy();
     method public int describeContents();
     method public android.os.PersistableBundle getPersistableBundle(java.lang.String);
     method public void putPersistableBundle(java.lang.String, android.os.PersistableBundle);
@@ -33846,6 +34080,7 @@
     method public E getBroadcastItem(int);
     method public java.lang.Object getRegisteredCallbackCookie(int);
     method public int getRegisteredCallbackCount();
+    method public E getRegisteredCallbackItem(int);
     method public void kill();
     method public void onCallbackDied(E);
     method public void onCallbackDied(E, java.lang.Object);
@@ -43793,6 +44028,8 @@
     method public java.lang.String getInstallerPackageName(java.lang.String);
     method public byte[] getInstantAppCookie();
     method public int getInstantAppCookieMaxSize();
+    method public android.graphics.drawable.Drawable getInstantAppIcon(java.lang.String);
+    method public java.util.List<android.content.pm.InstantAppInfo> getInstantApps();
     method public android.content.pm.InstrumentationInfo getInstrumentationInfo(android.content.ComponentName, int) throws android.content.pm.PackageManager.NameNotFoundException;
     method public java.util.List<android.content.pm.IntentFilterVerificationInfo> getIntentFilterVerifications(java.lang.String);
     method public int getIntentVerificationStatusAsUser(java.lang.String, int);
diff --git a/api/test-current.txt b/api/test-current.txt
index 70eecde..f8e6785 100644
--- a/api/test-current.txt
+++ b/api/test-current.txt
@@ -607,6 +607,7 @@
     field public static final int fontFamily = 16843692; // 0x10103ac
     field public static final int fontFeatureSettings = 16843959; // 0x10104b7
     field public static final int fontProviderAuthority = 16844114; // 0x1010552
+    field public static final int fontProviderPackage = 16844122; // 0x101055a
     field public static final int fontProviderQuery = 16844115; // 0x1010553
     field public static final int fontStyle = 16844081; // 0x1010531
     field public static final int fontWeight = 16844083; // 0x1010533
@@ -7140,6 +7141,7 @@
     method public java.util.Set<android.bluetooth.BluetoothDevice> getBondedDevices();
     method public static synchronized android.bluetooth.BluetoothAdapter getDefaultAdapter();
     method public java.lang.String getName();
+    method public android.bluetooth.le.PeriodicAdvertisingManager getPeriodicAdvertisingManager();
     method public int getProfileConnectionState(int);
     method public boolean getProfileProxy(android.content.Context, android.bluetooth.BluetoothProfile.ServiceListener, int);
     method public android.bluetooth.BluetoothDevice getRemoteDevice(java.lang.String);
@@ -7148,6 +7150,10 @@
     method public int getState();
     method public boolean isDiscovering();
     method public boolean isEnabled();
+    method public boolean isLe2MPhySupported();
+    method public boolean isLeCodedPhySupported();
+    method public boolean isLeExtendedAdvertisingSupported();
+    method public boolean isLePeriodicAdvertisingSupported();
     method public boolean isMultipleAdvertisementSupported();
     method public boolean isOffloadedFilteringSupported();
     method public boolean isOffloadedScanBatchingSupported();
@@ -7516,6 +7522,9 @@
   public final class BluetoothDevice implements android.os.Parcelable {
     method public android.bluetooth.BluetoothGatt connectGatt(android.content.Context, boolean, android.bluetooth.BluetoothGattCallback);
     method public android.bluetooth.BluetoothGatt connectGatt(android.content.Context, boolean, android.bluetooth.BluetoothGattCallback, int);
+    method public android.bluetooth.BluetoothGatt connectGatt(android.content.Context, boolean, android.bluetooth.BluetoothGattCallbackExt);
+    method public android.bluetooth.BluetoothGatt connectGatt(android.content.Context, boolean, android.bluetooth.BluetoothGattCallbackExt, int);
+    method public android.bluetooth.BluetoothGatt connectGatt(android.content.Context, boolean, android.bluetooth.BluetoothGattCallbackExt, int, int);
     method public boolean createBond();
     method public android.bluetooth.BluetoothSocket createInsecureRfcommSocketToServiceRecord(java.util.UUID) throws java.io.IOException;
     method public android.bluetooth.BluetoothSocket createRfcommSocketToServiceRecord(java.util.UUID) throws java.io.IOException;
@@ -7559,6 +7568,13 @@
     field public static final java.lang.String EXTRA_UUID = "android.bluetooth.device.extra.UUID";
     field public static final int PAIRING_VARIANT_PASSKEY_CONFIRMATION = 2; // 0x2
     field public static final int PAIRING_VARIANT_PIN = 0; // 0x0
+    field public static final int PHY_LE_1M = 1; // 0x1
+    field public static final int PHY_LE_2M = 2; // 0x2
+    field public static final int PHY_LE_ANY = 7; // 0x7
+    field public static final int PHY_LE_CODED = 4; // 0x4
+    field public static final int PHY_OPTION_NO_PREFERRED = 0; // 0x0
+    field public static final int PHY_OPTION_S2 = 1; // 0x1
+    field public static final int PHY_OPTION_S8 = 2; // 0x2
     field public static final int TRANSPORT_AUTO = 0; // 0x0
     field public static final int TRANSPORT_BREDR = 1; // 0x1
     field public static final int TRANSPORT_LE = 2; // 0x2
@@ -7581,10 +7597,12 @@
     method public java.util.List<android.bluetooth.BluetoothGattService> getServices();
     method public boolean readCharacteristic(android.bluetooth.BluetoothGattCharacteristic);
     method public boolean readDescriptor(android.bluetooth.BluetoothGattDescriptor);
+    method public void readPhy();
     method public boolean readRemoteRssi();
     method public boolean requestConnectionPriority(int);
     method public boolean requestMtu(int);
     method public boolean setCharacteristicNotification(android.bluetooth.BluetoothGattCharacteristic, boolean);
+    method public void setPreferredPhy(int, int, int);
     method public boolean writeCharacteristic(android.bluetooth.BluetoothGattCharacteristic);
     method public boolean writeDescriptor(android.bluetooth.BluetoothGattDescriptor);
     field public static final int CONNECTION_PRIORITY_BALANCED = 0; // 0x0
@@ -7602,8 +7620,12 @@
     field public static final int GATT_WRITE_NOT_PERMITTED = 3; // 0x3
   }
 
-  public abstract class BluetoothGattCallback {
+  public abstract deprecated class BluetoothGattCallback extends android.bluetooth.BluetoothGattCallbackExt {
     ctor public BluetoothGattCallback();
+  }
+
+  public abstract class BluetoothGattCallbackExt {
+    ctor public BluetoothGattCallbackExt();
     method public void onCharacteristicChanged(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic);
     method public void onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int);
     method public void onCharacteristicWrite(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int);
@@ -7611,6 +7633,8 @@
     method public void onDescriptorRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattDescriptor, int);
     method public void onDescriptorWrite(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattDescriptor, int);
     method public void onMtuChanged(android.bluetooth.BluetoothGatt, int, int);
+    method public void onPhyRead(android.bluetooth.BluetoothGatt, int, int, int);
+    method public void onPhyUpdate(android.bluetooth.BluetoothGatt, int, int, int);
     method public void onReadRemoteRssi(android.bluetooth.BluetoothGatt, int, int);
     method public void onReliableWriteCompleted(android.bluetooth.BluetoothGatt, int);
     method public void onServicesDiscovered(android.bluetooth.BluetoothGatt, int);
@@ -7704,12 +7728,18 @@
     method public android.bluetooth.BluetoothGattService getService(java.util.UUID);
     method public java.util.List<android.bluetooth.BluetoothGattService> getServices();
     method public boolean notifyCharacteristicChanged(android.bluetooth.BluetoothDevice, android.bluetooth.BluetoothGattCharacteristic, boolean);
+    method public void readPhy(android.bluetooth.BluetoothDevice);
     method public boolean removeService(android.bluetooth.BluetoothGattService);
     method public boolean sendResponse(android.bluetooth.BluetoothDevice, int, int, int, byte[]);
+    method public void setPreferredPhy(android.bluetooth.BluetoothDevice, int, int, int);
   }
 
-  public abstract class BluetoothGattServerCallback {
+  public abstract deprecated class BluetoothGattServerCallback extends android.bluetooth.BluetoothGattServerCallbackExt {
     ctor public BluetoothGattServerCallback();
+  }
+
+  public abstract class BluetoothGattServerCallbackExt {
+    ctor public BluetoothGattServerCallbackExt();
     method public void onCharacteristicReadRequest(android.bluetooth.BluetoothDevice, int, int, android.bluetooth.BluetoothGattCharacteristic);
     method public void onCharacteristicWriteRequest(android.bluetooth.BluetoothDevice, int, android.bluetooth.BluetoothGattCharacteristic, boolean, boolean, int, byte[]);
     method public void onConnectionStateChange(android.bluetooth.BluetoothDevice, int, int);
@@ -7718,6 +7748,8 @@
     method public void onExecuteWrite(android.bluetooth.BluetoothDevice, int, boolean);
     method public void onMtuChanged(android.bluetooth.BluetoothDevice, int);
     method public void onNotificationSent(android.bluetooth.BluetoothDevice, int);
+    method public void onPhyRead(android.bluetooth.BluetoothDevice, int, int, int);
+    method public void onPhyUpdate(android.bluetooth.BluetoothDevice, int, int, int);
     method public void onServiceAdded(int, android.bluetooth.BluetoothGattService);
   }
 
@@ -7918,10 +7950,85 @@
     method public android.bluetooth.le.AdvertiseSettings.Builder setTxPowerLevel(int);
   }
 
+  public final class AdvertisingSet {
+    method public void enableAdvertising(boolean);
+    method public void periodicAdvertisingEnable(boolean);
+    method public void setAdvertisingData(android.bluetooth.le.AdvertiseData);
+    method public void setAdvertisingParameters(android.bluetooth.le.AdvertisingSetParameters);
+    method public void setPeriodicAdvertisingData(android.bluetooth.le.AdvertiseData);
+    method public void setPeriodicAdvertisingParameters(android.bluetooth.le.PeriodicAdvertisingParameters);
+    method public void setScanResponseData(android.bluetooth.le.AdvertiseData);
+  }
+
+  public abstract class AdvertisingSetCallback {
+    ctor public AdvertisingSetCallback();
+    method public void onAdvertisingDataSet(android.bluetooth.le.AdvertisingSet, int);
+    method public void onAdvertisingEnabled(android.bluetooth.le.AdvertisingSet, boolean, int);
+    method public void onAdvertisingParametersUpdated(android.bluetooth.le.AdvertisingSet, int);
+    method public void onAdvertisingSetStarted(android.bluetooth.le.AdvertisingSet, int);
+    method public void onAdvertisingSetStopped(android.bluetooth.le.AdvertisingSet);
+    method public void onPeriodicAdvertisingDataSet(android.bluetooth.le.AdvertisingSet, int);
+    method public void onPeriodicAdvertisingEnable(android.bluetooth.le.AdvertisingSet, boolean, int);
+    method public void onPeriodicAdvertisingParametersUpdated(android.bluetooth.le.AdvertisingSet, int);
+    method public void onScanResponseDataSet(android.bluetooth.le.AdvertisingSet, int);
+    field public static final int ADVERTISE_FAILED_ALREADY_STARTED = 3; // 0x3
+    field public static final int ADVERTISE_FAILED_DATA_TOO_LARGE = 1; // 0x1
+    field public static final int ADVERTISE_FAILED_FEATURE_UNSUPPORTED = 5; // 0x5
+    field public static final int ADVERTISE_FAILED_INTERNAL_ERROR = 4; // 0x4
+    field public static final int ADVERTISE_FAILED_TOO_MANY_ADVERTISERS = 2; // 0x2
+    field public static final int ADVERTISE_SUCCESS = 0; // 0x0
+  }
+
+  public final class AdvertisingSetParameters implements android.os.Parcelable {
+    method public int describeContents();
+    method public int getInterval();
+    method public int getPrimaryPhy();
+    method public int getSecondaryPhy();
+    method public int getTimeout();
+    method public int getTxPowerLevel();
+    method public boolean includeTxPower();
+    method public boolean isAnonymous();
+    method public boolean isConnectable();
+    method public boolean isLegacy();
+    method public void writeToParcel(android.os.Parcel, int);
+    field public static final android.os.Parcelable.Creator<android.bluetooth.le.AdvertisingSetParameters> CREATOR;
+    field public static final int INTERVAL_HIGH = 160; // 0xa0
+    field public static final int INTERVAL_LOW = 1600; // 0x640
+    field public static final int INTERVAL_MAX = 16777215; // 0xffffff
+    field public static final int INTERVAL_MEDIUM = 400; // 0x190
+    field public static final int INTERVAL_MIN = 160; // 0xa0
+    field public static final int PHY_LE_1M = 1; // 0x1
+    field public static final int PHY_LE_2M = 2; // 0x2
+    field public static final int PHY_LE_CODED = 3; // 0x3
+    field public static final int TX_POWER_HIGH = 1; // 0x1
+    field public static final int TX_POWER_LOW = -15; // 0xfffffff1
+    field public static final int TX_POWER_MAX = 1; // 0x1
+    field public static final int TX_POWER_MEDIUM = -7; // 0xfffffff9
+    field public static final int TX_POWER_MIN = -127; // 0xffffff81
+    field public static final int TX_POWER_ULTRA_LOW = -21; // 0xffffffeb
+  }
+
+  public static final class AdvertisingSetParameters.Builder {
+    ctor public AdvertisingSetParameters.Builder();
+    method public android.bluetooth.le.AdvertisingSetParameters build();
+    method public android.bluetooth.le.AdvertisingSetParameters.Builder setAnonymouus(boolean);
+    method public android.bluetooth.le.AdvertisingSetParameters.Builder setConnectable(boolean);
+    method public android.bluetooth.le.AdvertisingSetParameters.Builder setIncludeTxPower(boolean);
+    method public android.bluetooth.le.AdvertisingSetParameters.Builder setInterval(int);
+    method public android.bluetooth.le.AdvertisingSetParameters.Builder setLegacyMode(boolean);
+    method public android.bluetooth.le.AdvertisingSetParameters.Builder setPrimaryPhy(int);
+    method public android.bluetooth.le.AdvertisingSetParameters.Builder setSecondaryPhy(int);
+    method public android.bluetooth.le.AdvertisingSetParameters.Builder setTimeout(int);
+    method public android.bluetooth.le.AdvertisingSetParameters.Builder setTxPowerLevel(int);
+  }
+
   public final class BluetoothLeAdvertiser {
     method public void startAdvertising(android.bluetooth.le.AdvertiseSettings, android.bluetooth.le.AdvertiseData, android.bluetooth.le.AdvertiseCallback);
     method public void startAdvertising(android.bluetooth.le.AdvertiseSettings, android.bluetooth.le.AdvertiseData, android.bluetooth.le.AdvertiseData, android.bluetooth.le.AdvertiseCallback);
+    method public void startAdvertisingSet(android.bluetooth.le.AdvertisingSetParameters, android.bluetooth.le.AdvertiseData, android.bluetooth.le.AdvertiseData, android.bluetooth.le.PeriodicAdvertisingParameters, android.bluetooth.le.AdvertiseData, android.bluetooth.le.AdvertisingSetCallback);
+    method public void startAdvertisingSet(android.bluetooth.le.AdvertisingSetParameters, android.bluetooth.le.AdvertiseData, android.bluetooth.le.AdvertiseData, android.bluetooth.le.PeriodicAdvertisingParameters, android.bluetooth.le.AdvertiseData, android.bluetooth.le.AdvertisingSetCallback, android.os.Handler);
     method public void stopAdvertising(android.bluetooth.le.AdvertiseCallback);
+    method public void stopAdvertisingSet(android.bluetooth.le.AdvertisingSetCallback);
   }
 
   public final class BluetoothLeScanner {
@@ -7931,6 +8038,53 @@
     method public void stopScan(android.bluetooth.le.ScanCallback);
   }
 
+  public abstract class PeriodicAdvertisingCallback {
+    ctor public PeriodicAdvertisingCallback();
+    method public void onPeriodicAdvertisingReport(android.bluetooth.le.PeriodicAdvertisingReport);
+    method public void onSyncEstablished(int, android.bluetooth.BluetoothDevice, int, int, int, int);
+    method public void onSyncLost(int);
+    field public static final int SYNC_NO_RESOURCES = 2; // 0x2
+    field public static final int SYNC_NO_RESPONSE = 1; // 0x1
+  }
+
+  public final class PeriodicAdvertisingManager {
+    method public void registerSync(android.bluetooth.le.ScanResult, int, int, android.bluetooth.le.PeriodicAdvertisingCallback);
+    method public void registerSync(android.bluetooth.le.ScanResult, int, int, android.bluetooth.le.PeriodicAdvertisingCallback, android.os.Handler);
+    method public void unregisterSync(android.bluetooth.le.PeriodicAdvertisingCallback);
+  }
+
+  public final class PeriodicAdvertisingParameters implements android.os.Parcelable {
+    method public int describeContents();
+    method public boolean getEnable();
+    method public boolean getIncludeTxPower();
+    method public int getInterval();
+    method public void writeToParcel(android.os.Parcel, int);
+    field public static final android.os.Parcelable.Creator<android.bluetooth.le.PeriodicAdvertisingParameters> CREATOR;
+  }
+
+  public static final class PeriodicAdvertisingParameters.Builder {
+    ctor public PeriodicAdvertisingParameters.Builder();
+    method public android.bluetooth.le.PeriodicAdvertisingParameters build();
+    method public android.bluetooth.le.PeriodicAdvertisingParameters.Builder setEnable(boolean);
+    method public android.bluetooth.le.PeriodicAdvertisingParameters.Builder setIncludeTxPower(boolean);
+    method public android.bluetooth.le.PeriodicAdvertisingParameters.Builder setInterval(int);
+  }
+
+  public final class PeriodicAdvertisingReport implements android.os.Parcelable {
+    ctor public PeriodicAdvertisingReport(int, int, int, int, android.bluetooth.le.ScanRecord);
+    method public int describeContents();
+    method public android.bluetooth.le.ScanRecord getData();
+    method public int getDataStatus();
+    method public int getRssi();
+    method public int getSyncHandle();
+    method public long getTimestampNanos();
+    method public int getTxPower();
+    method public void writeToParcel(android.os.Parcel, int);
+    field public static final android.os.Parcelable.Creator<android.bluetooth.le.PeriodicAdvertisingReport> CREATOR;
+    field public static final int DATA_COMPLETE = 0; // 0x0
+    field public static final int DATA_INCOMPLETE_TRUNCATED = 2; // 0x2
+  }
+
   public abstract class ScanCallback {
     ctor public ScanCallback();
     method public void onBatchScanResults(java.util.List<android.bluetooth.le.ScanResult>);
@@ -7985,19 +8139,37 @@
   }
 
   public final class ScanResult implements android.os.Parcelable {
-    ctor public ScanResult(android.bluetooth.BluetoothDevice, android.bluetooth.le.ScanRecord, int, long);
+    ctor public deprecated ScanResult(android.bluetooth.BluetoothDevice, android.bluetooth.le.ScanRecord, int, long);
+    ctor public ScanResult(android.bluetooth.BluetoothDevice, int, int, int, int, int, int, int, android.bluetooth.le.ScanRecord, long);
     method public int describeContents();
+    method public int getAdvertisingSid();
+    method public int getDataStatus();
     method public android.bluetooth.BluetoothDevice getDevice();
+    method public int getPeriodicAdvertisingInterval();
+    method public int getPrimaryPhy();
     method public int getRssi();
     method public android.bluetooth.le.ScanRecord getScanRecord();
+    method public int getSecondaryPhy();
     method public long getTimestampNanos();
+    method public int getTxPower();
+    method public boolean isConnectable();
+    method public boolean isLegacy();
     method public void writeToParcel(android.os.Parcel, int);
     field public static final android.os.Parcelable.Creator<android.bluetooth.le.ScanResult> CREATOR;
+    field public static final int DATA_COMPLETE = 0; // 0x0
+    field public static final int DATA_TRUNCATED = 2; // 0x2
+    field public static final int PHY_LE_1M = 1; // 0x1
+    field public static final int PHY_LE_2M = 2; // 0x2
+    field public static final int PHY_LE_CODED = 3; // 0x3
+    field public static final int PHY_UNUSED = 0; // 0x0
+    field public static final int SID_NOT_PRESENT = 255; // 0xff
   }
 
   public final class ScanSettings implements android.os.Parcelable {
     method public int describeContents();
     method public int getCallbackType();
+    method public boolean getLegacy();
+    method public int getPhy();
     method public long getReportDelayMillis();
     method public int getScanMode();
     method public int getScanResultType();
@@ -8011,6 +8183,9 @@
     field public static final int MATCH_NUM_FEW_ADVERTISEMENT = 2; // 0x2
     field public static final int MATCH_NUM_MAX_ADVERTISEMENT = 3; // 0x3
     field public static final int MATCH_NUM_ONE_ADVERTISEMENT = 1; // 0x1
+    field public static final int PHY_LE_1M = 1; // 0x1
+    field public static final int PHY_LE_ALL_SUPPORTED = 255; // 0xff
+    field public static final int PHY_LE_CODED = 3; // 0x3
     field public static final int SCAN_MODE_BALANCED = 1; // 0x1
     field public static final int SCAN_MODE_LOW_LATENCY = 2; // 0x2
     field public static final int SCAN_MODE_LOW_POWER = 0; // 0x0
@@ -8021,8 +8196,10 @@
     ctor public ScanSettings.Builder();
     method public android.bluetooth.le.ScanSettings build();
     method public android.bluetooth.le.ScanSettings.Builder setCallbackType(int);
+    method public android.bluetooth.le.ScanSettings.Builder setLegacy(boolean);
     method public android.bluetooth.le.ScanSettings.Builder setMatchMode(int);
     method public android.bluetooth.le.ScanSettings.Builder setNumOfMatches(int);
+    method public android.bluetooth.le.ScanSettings.Builder setPhy(int);
     method public android.bluetooth.le.ScanSettings.Builder setReportDelay(long);
     method public android.bluetooth.le.ScanSettings.Builder setScanMode(int);
   }
@@ -8074,6 +8251,8 @@
 
   public final class CompanionDeviceManager {
     method public void associate(android.companion.AssociationRequest<?>, android.companion.CompanionDeviceManager.Callback, android.os.Handler);
+    method public void disassociate(java.lang.String);
+    method public java.util.List<java.lang.String> getAssociations();
     field public static final java.lang.String EXTRA_DEVICE = "android.companion.extra.DEVICE";
   }
 
@@ -12249,6 +12428,7 @@
     method public android.graphics.Bitmap extractAlpha(android.graphics.Paint, int[]);
     method public final int getAllocationByteCount();
     method public final int getByteCount();
+    method public final android.graphics.ColorSpace getColorSpace();
     method public final android.graphics.Bitmap.Config getConfig();
     method public int getDensity();
     method public int getGenerationId();
@@ -12631,6 +12811,7 @@
     method public java.lang.String getName();
     method public boolean isSrgb();
     method public abstract boolean isWideGamut();
+    method public static android.graphics.ColorSpace match(float[], android.graphics.ColorSpace.Rgb.TransferParameters);
     method public float[] toXyz(float, float, float);
     method public abstract float[] toXyz(float[]);
     field public static final float[] ILLUMINANT_A;
@@ -12715,6 +12896,10 @@
   public static class ColorSpace.Rgb extends android.graphics.ColorSpace {
     ctor public ColorSpace.Rgb(java.lang.String, float[], java.util.function.DoubleUnaryOperator, java.util.function.DoubleUnaryOperator);
     ctor public ColorSpace.Rgb(java.lang.String, float[], float[], java.util.function.DoubleUnaryOperator, java.util.function.DoubleUnaryOperator, float, float);
+    ctor public ColorSpace.Rgb(java.lang.String, float[], android.graphics.ColorSpace.Rgb.TransferParameters);
+    ctor public ColorSpace.Rgb(java.lang.String, float[], float[], android.graphics.ColorSpace.Rgb.TransferParameters);
+    ctor public ColorSpace.Rgb(java.lang.String, float[], double);
+    ctor public ColorSpace.Rgb(java.lang.String, float[], float[], double);
     method public float[] fromLinear(float, float, float);
     method public float[] fromLinear(float[]);
     method public float[] fromXyz(float[]);
@@ -12726,6 +12911,7 @@
     method public java.util.function.DoubleUnaryOperator getOetf();
     method public float[] getPrimaries(float[]);
     method public float[] getPrimaries();
+    method public android.graphics.ColorSpace.Rgb.TransferParameters getTransferParameters();
     method public float[] getTransform(float[]);
     method public float[] getTransform();
     method public float[] getWhitePoint(float[]);
@@ -12736,6 +12922,18 @@
     method public float[] toXyz(float[]);
   }
 
+  public static class ColorSpace.Rgb.TransferParameters {
+    ctor public ColorSpace.Rgb.TransferParameters(double, double, double, double, double);
+    ctor public ColorSpace.Rgb.TransferParameters(double, double, double, double, double, double, double);
+    field public final double a;
+    field public final double b;
+    field public final double c;
+    field public final double d;
+    field public final double e;
+    field public final double f;
+    field public final double g;
+  }
+
   public class ComposePathEffect extends android.graphics.PathEffect {
     ctor public ComposePathEffect(android.graphics.PathEffect, android.graphics.PathEffect);
   }
@@ -14128,9 +14326,12 @@
 package android.graphics.fonts {
 
   public final class FontRequest implements android.os.Parcelable {
-    ctor public FontRequest(java.lang.String, java.lang.String);
+    ctor public FontRequest(java.lang.String, java.lang.String, java.lang.String);
+    ctor public FontRequest(java.lang.String, java.lang.String, java.lang.String, java.util.List<java.util.List<byte[]>>);
     method public int describeContents();
+    method public java.util.List<java.util.List<byte[]>> getCertificates();
     method public java.lang.String getProviderAuthority();
+    method public java.lang.String getProviderPackage();
     method public java.lang.String getQuery();
     method public void writeToParcel(android.os.Parcel, int);
     field public static final android.os.Parcelable.Creator<android.graphics.fonts.FontRequest> CREATOR;
@@ -14904,10 +15105,14 @@
     method public abstract void createCaptureSession(java.util.List<android.view.Surface>, android.hardware.camera2.CameraCaptureSession.StateCallback, android.os.Handler) throws android.hardware.camera2.CameraAccessException;
     method public abstract void createCaptureSessionByOutputConfigurations(java.util.List<android.hardware.camera2.params.OutputConfiguration>, android.hardware.camera2.CameraCaptureSession.StateCallback, android.os.Handler) throws android.hardware.camera2.CameraAccessException;
     method public abstract void createConstrainedHighSpeedCaptureSession(java.util.List<android.view.Surface>, android.hardware.camera2.CameraCaptureSession.StateCallback, android.os.Handler) throws android.hardware.camera2.CameraAccessException;
+    method public abstract void createCustomCaptureSession(android.hardware.camera2.params.InputConfiguration, java.util.List<android.hardware.camera2.params.OutputConfiguration>, int, android.hardware.camera2.CameraCaptureSession.StateCallback, android.os.Handler) throws android.hardware.camera2.CameraAccessException;
     method public abstract android.hardware.camera2.CaptureRequest.Builder createReprocessCaptureRequest(android.hardware.camera2.TotalCaptureResult) throws android.hardware.camera2.CameraAccessException;
     method public abstract void createReprocessableCaptureSession(android.hardware.camera2.params.InputConfiguration, java.util.List<android.view.Surface>, android.hardware.camera2.CameraCaptureSession.StateCallback, android.os.Handler) throws android.hardware.camera2.CameraAccessException;
     method public abstract void createReprocessableCaptureSessionByConfigurations(android.hardware.camera2.params.InputConfiguration, java.util.List<android.hardware.camera2.params.OutputConfiguration>, android.hardware.camera2.CameraCaptureSession.StateCallback, android.os.Handler) throws android.hardware.camera2.CameraAccessException;
     method public abstract java.lang.String getId();
+    field public static final int SESSION_OPERATION_MODE_CONSTRAINED_HIGH_SPEED = 1; // 0x1
+    field public static final int SESSION_OPERATION_MODE_NORMAL = 0; // 0x0
+    field public static final int SESSION_OPERATION_MODE_VENDOR_START = 32768; // 0x8000
     field public static final int TEMPLATE_MANUAL = 6; // 0x6
     field public static final int TEMPLATE_PREVIEW = 1; // 0x1
     field public static final int TEMPLATE_RECORD = 3; // 0x3
@@ -19674,6 +19879,8 @@
     field public static final int SHORT_COMMONLY_USED = 6; // 0x6
     field public static final int SHORT_GENERIC = 2; // 0x2
     field public static final int SHORT_GMT = 4; // 0x4
+    field public static final int TIMEZONE_ICU = 0; // 0x0
+    field public static final int TIMEZONE_JDK = 1; // 0x1
     field public static final android.icu.util.TimeZone UNKNOWN_ZONE;
     field public static final java.lang.String UNKNOWN_ZONE_ID = "Etc/Unknown";
   }
@@ -25046,6 +25253,7 @@
     method public void reportNetworkConnectivity(android.net.Network, boolean);
     method public boolean requestBandwidthUpdate(android.net.Network);
     method public void requestNetwork(android.net.NetworkRequest, android.net.ConnectivityManager.NetworkCallback);
+    method public void requestNetwork(android.net.NetworkRequest, int, android.net.ConnectivityManager.NetworkCallback);
     method public void requestNetwork(android.net.NetworkRequest, android.app.PendingIntent);
     method public deprecated void setNetworkPreference(int);
     method public static deprecated boolean setProcessDefaultNetwork(android.net.Network);
@@ -25093,6 +25301,7 @@
     method public void onLinkPropertiesChanged(android.net.Network, android.net.LinkProperties);
     method public void onLosing(android.net.Network, int);
     method public void onLost(android.net.Network);
+    method public void onUnavailable();
   }
 
   public static abstract interface ConnectivityManager.OnNetworkActiveListener {
@@ -30367,7 +30576,7 @@
     ctor public Bundle(android.os.Bundle);
     ctor public Bundle(android.os.PersistableBundle);
     method public java.lang.Object clone();
-    method public android.os.Bundle deepcopy();
+    method public android.os.Bundle deepCopy();
     method public int describeContents();
     method public android.os.IBinder getBinder(java.lang.String);
     method public android.os.Bundle getBundle(java.lang.String);
@@ -31113,6 +31322,7 @@
     method public boolean match(java.lang.String);
     method public void writeToParcel(android.os.Parcel, int);
     field public static final android.os.Parcelable.Creator<android.os.PatternMatcher> CREATOR;
+    field public static final int PATTERN_ADVANCED_GLOB = 3; // 0x3
     field public static final int PATTERN_LITERAL = 0; // 0x0
     field public static final int PATTERN_PREFIX = 1; // 0x1
     field public static final int PATTERN_SIMPLE_GLOB = 2; // 0x2
@@ -31123,7 +31333,7 @@
     ctor public PersistableBundle(int);
     ctor public PersistableBundle(android.os.PersistableBundle);
     method public java.lang.Object clone();
-    method public android.os.PersistableBundle deepcopy();
+    method public android.os.PersistableBundle deepCopy();
     method public int describeContents();
     method public android.os.PersistableBundle getPersistableBundle(java.lang.String);
     method public void putPersistableBundle(java.lang.String, android.os.PersistableBundle);
@@ -31232,6 +31442,7 @@
     method public E getBroadcastItem(int);
     method public java.lang.Object getRegisteredCallbackCookie(int);
     method public int getRegisteredCallbackCount();
+    method public E getRegisteredCallbackItem(int);
     method public void kill();
     method public void onCallbackDied(E);
     method public void onCallbackDied(E, java.lang.Object);
diff --git a/cmds/idmap/Android.mk b/cmds/idmap/Android.mk
index eb6da18..50ccb07 100644
--- a/cmds/idmap/Android.mk
+++ b/cmds/idmap/Android.mk
@@ -15,7 +15,7 @@
 LOCAL_PATH:= $(call my-dir)
 include $(CLEAR_VARS)
 
-LOCAL_SRC_FILES := idmap.cpp create.cpp inspect.cpp
+LOCAL_SRC_FILES := idmap.cpp create.cpp scan.cpp inspect.cpp
 
 LOCAL_SHARED_LIBRARIES := liblog libutils libandroidfw
 
diff --git a/cmds/idmap/idmap.cpp b/cmds/idmap/idmap.cpp
index d388977..3ab1915 100644
--- a/cmds/idmap/idmap.cpp
+++ b/cmds/idmap/idmap.cpp
@@ -13,6 +13,8 @@
       idmap --help \n\
       idmap --fd target overlay fd \n\
       idmap --path target overlay idmap \n\
+      idmap --scan target-package-name-to-look-for path-to-target-apk dir-to-hold-idmaps \\\
+                   dir-to-scan [additional-dir-to-scan [additional-dir-to-scan [...]]]\n\
       idmap --inspect idmap \n\
 \n\
 DESCRIPTION \n\
@@ -47,6 +49,11 @@
       --path: create idmap for target package 'target' (path to apk) and overlay package \n\
               'overlay' (path to apk); write results to 'idmap' (path). \n\
 \n\
+      --scan: non-recursively search directory 'dir-to-scan' (path) for overlay packages with \n\
+              target package 'target-package-name-to-look-for' (package name) present at\n\
+              'path-to-target-apk' (path to apk). For each overlay package found, create an\n\
+              idmap file in 'dir-to-hold-idmaps' (path). \n\
+\n\
       --inspect: decode the binary format of 'idmap' (path) and display the contents in a \n\
                  debug-friendly format. \n\
 \n\
@@ -90,6 +97,16 @@
 NOTES \n\
       This tool and its expected invocation from installd is modelled on dexopt.";
 
+    bool verify_directory_readable(const char *path)
+    {
+        return access(path, R_OK | X_OK) == 0;
+    }
+
+    bool verify_directory_writable(const char *path)
+    {
+        return access(path, W_OK) == 0;
+    }
+
     bool verify_file_readable(const char *path)
     {
         return access(path, R_OK) == 0;
@@ -150,6 +167,36 @@
         return idmap_create_path(target_apk_path, overlay_apk_path, idmap_path);
     }
 
+    int maybe_scan(const char *target_package_name, const char *target_apk_path,
+            const char *idmap_dir, const android::Vector<const char *> *overlay_dirs)
+    {
+        if (!verify_root_or_system()) {
+            fprintf(stderr, "error: permission denied: not user root or user system\n");
+            return -1;
+        }
+
+        if (!verify_file_readable(target_apk_path)) {
+            ALOGD("error: failed to read apk %s: %s\n", target_apk_path, strerror(errno));
+            return -1;
+        }
+
+        if (!verify_directory_writable(idmap_dir)) {
+            ALOGD("error: no write access to %s: %s\n", idmap_dir, strerror(errno));
+            return -1;
+        }
+
+        const size_t N = overlay_dirs->size();
+        for (size_t i = 0; i < N; i++) {
+            const char *dir = overlay_dirs->itemAt(i);
+            if (!verify_directory_readable(dir)) {
+                ALOGD("error: no read access to %s: %s\n", dir, strerror(errno));
+                return -1;
+            }
+        }
+
+        return idmap_scan(target_package_name, target_apk_path, idmap_dir, overlay_dirs);
+    }
+
     int maybe_inspect(const char *idmap_path)
     {
         // anyone (not just root or system) may do --inspect
@@ -188,6 +235,14 @@
         return maybe_create_path(argv[2], argv[3], argv[4]);
     }
 
+    if (argc >= 6 && !strcmp(argv[1], "--scan")) {
+        android::Vector<const char *> v;
+        for (int i = 5; i < argc; i++) {
+            v.push(argv[i]);
+        }
+        return maybe_scan(argv[2], argv[3], argv[4], &v);
+    }
+
     if (argc == 3 && !strcmp(argv[1], "--inspect")) {
         return maybe_inspect(argv[2]);
     }
diff --git a/cmds/idmap/idmap.h b/cmds/idmap/idmap.h
index 5914de9..8d4210b 100644
--- a/cmds/idmap/idmap.h
+++ b/cmds/idmap/idmap.h
@@ -25,6 +25,12 @@
 
 int idmap_create_fd(const char *target_apk_path, const char *overlay_apk_path, int fd);
 
+// Regarding target_package_name: the idmap_scan implementation should
+// be able to extract this from the manifest in target_apk_path,
+// simplifying the external API.
+int idmap_scan(const char *target_package_name, const char *target_apk_path,
+        const char *idmap_dir, const android::Vector<const char *> *overlay_dirs);
+
 int idmap_inspect(const char *idmap_path);
 
 #endif // _IDMAP_H_
diff --git a/cmds/idmap/scan.cpp b/cmds/idmap/scan.cpp
new file mode 100644
index 0000000..8122395
--- /dev/null
+++ b/cmds/idmap/scan.cpp
@@ -0,0 +1,240 @@
+#include <dirent.h>
+#include <inttypes.h>
+#include <sys/file.h>
+#include <sys/stat.h>
+
+#include "idmap.h"
+
+#include <memory>
+#include <androidfw/ResourceTypes.h>
+#include <androidfw/StreamingZipInflater.h>
+#include <androidfw/ZipFileRO.h>
+#include <private/android_filesystem_config.h> // for AID_SYSTEM
+#include <utils/SortedVector.h>
+#include <utils/String16.h>
+#include <utils/String8.h>
+
+#define NO_OVERLAY_TAG (-1000)
+
+using namespace android;
+
+namespace {
+    struct Overlay {
+        Overlay() {}
+        Overlay(const String8& a, const String8& i, int p) :
+            apk_path(a), idmap_path(i), priority(p) {}
+
+        bool operator<(Overlay const& rhs) const
+        {
+            return rhs.priority > priority;
+        }
+
+        String8 apk_path;
+        String8 idmap_path;
+        int priority;
+    };
+
+    bool writePackagesList(const char *filename, const SortedVector<Overlay>& overlayVector)
+    {
+        // the file is opened for appending so that it doesn't get truncated
+        // before we can guarantee mutual exclusion via the flock
+        FILE* fout = fopen(filename, "a");
+        if (fout == NULL) {
+            return false;
+        }
+
+        if (TEMP_FAILURE_RETRY(flock(fileno(fout), LOCK_EX)) != 0) {
+            fclose(fout);
+            return false;
+        }
+
+        if (TEMP_FAILURE_RETRY(ftruncate(fileno(fout), 0)) != 0) {
+            TEMP_FAILURE_RETRY(flock(fileno(fout), LOCK_UN));
+            fclose(fout);
+            return false;
+        }
+
+        for (size_t i = 0; i < overlayVector.size(); ++i) {
+            const Overlay& overlay = overlayVector[i];
+            fprintf(fout, "%s %s\n", overlay.apk_path.string(), overlay.idmap_path.string());
+        }
+
+        TEMP_FAILURE_RETRY(fflush(fout));
+        TEMP_FAILURE_RETRY(flock(fileno(fout), LOCK_UN));
+        fclose(fout);
+
+        // Make file world readable since Zygote (running as root) will read
+        // it when creating the initial AssetManger object
+        const mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; // 0644
+        if (chmod(filename, mode) == -1) {
+            unlink(filename);
+            return false;
+        }
+
+        return true;
+    }
+
+    String8 flatten_path(const char *path)
+    {
+        String16 tmp(path);
+        tmp.replaceAll('/', '@');
+        return String8(tmp);
+    }
+
+    int parse_overlay_tag(const ResXMLTree& parser, const char *target_package_name)
+    {
+        const size_t N = parser.getAttributeCount();
+        String16 target;
+        int priority = -1;
+        for (size_t i = 0; i < N; ++i) {
+            size_t len;
+            String16 key(parser.getAttributeName(i, &len));
+            if (key == String16("targetPackage")) {
+                const char16_t *p = parser.getAttributeStringValue(i, &len);
+                if (p != NULL) {
+                    target = String16(p, len);
+                }
+            } else if (key == String16("priority")) {
+                Res_value v;
+                if (parser.getAttributeValue(i, &v) == sizeof(Res_value)) {
+                    priority = v.data;
+                    if (priority < 0 || priority > 9999) {
+                        return -1;
+                    }
+                }
+            }
+        }
+        if (target == String16(target_package_name)) {
+            return priority;
+        }
+        return NO_OVERLAY_TAG;
+    }
+
+    int parse_manifest(const void *data, size_t size, const char *target_package_name)
+    {
+        ResXMLTree parser;
+        parser.setTo(data, size);
+        if (parser.getError() != NO_ERROR) {
+            ALOGD("%s failed to init xml parser, error=0x%08x\n", __FUNCTION__, parser.getError());
+            return -1;
+        }
+
+        ResXMLParser::event_code_t type;
+        do {
+            type = parser.next();
+            if (type == ResXMLParser::START_TAG) {
+                size_t len;
+                String16 tag(parser.getElementName(&len));
+                if (tag == String16("overlay")) {
+                    return parse_overlay_tag(parser, target_package_name);
+                }
+            }
+        } while (type != ResXMLParser::BAD_DOCUMENT && type != ResXMLParser::END_DOCUMENT);
+
+        return NO_OVERLAY_TAG;
+    }
+
+    int parse_apk(const char *path, const char *target_package_name)
+    {
+        std::unique_ptr<ZipFileRO> zip(ZipFileRO::open(path));
+        if (zip.get() == NULL) {
+            ALOGW("%s: failed to open zip %s\n", __FUNCTION__, path);
+            return -1;
+        }
+        ZipEntryRO entry;
+        if ((entry = zip->findEntryByName("AndroidManifest.xml")) == NULL) {
+            ALOGW("%s: failed to find entry AndroidManifest.xml\n", __FUNCTION__);
+            return -1;
+        }
+        uint32_t uncompLen = 0;
+        uint16_t method;
+        if (!zip->getEntryInfo(entry, &method, &uncompLen, NULL, NULL, NULL, NULL)) {
+            ALOGW("%s: failed to read entry info\n", __FUNCTION__);
+            return -1;
+        }
+        if (method != ZipFileRO::kCompressDeflated) {
+            ALOGW("%s: cannot handle zip compression method %" PRIu16 "\n", __FUNCTION__, method);
+            return -1;
+        }
+        FileMap *dataMap = zip->createEntryFileMap(entry);
+        if (dataMap == NULL) {
+            ALOGW("%s: failed to create FileMap\n", __FUNCTION__);
+            return -1;
+        }
+        char *buf = new char[uncompLen];
+        if (NULL == buf) {
+            ALOGW("%s: failed to allocate %" PRIu32 " byte\n", __FUNCTION__, uncompLen);
+            delete dataMap;
+            return -1;
+        }
+        StreamingZipInflater inflater(dataMap, uncompLen);
+        if (inflater.read(buf, uncompLen) < 0) {
+            ALOGW("%s: failed to inflate %" PRIu32 " byte\n", __FUNCTION__, uncompLen);
+            delete[] buf;
+            delete dataMap;
+            return -1;
+        }
+
+        int priority = parse_manifest(buf, static_cast<size_t>(uncompLen), target_package_name);
+        delete[] buf;
+        delete dataMap;
+        return priority;
+    }
+}
+
+int idmap_scan(const char *target_package_name, const char *target_apk_path,
+        const char *idmap_dir, const android::Vector<const char *> *overlay_dirs)
+{
+    String8 filename = String8(idmap_dir);
+    filename.appendPath("overlays.list");
+
+    SortedVector<Overlay> overlayVector;
+    const size_t N = overlay_dirs->size();
+    for (size_t i = 0; i < N; ++i) {
+        const char *overlay_dir = overlay_dirs->itemAt(i);
+        DIR *dir = opendir(overlay_dir);
+        if (dir == NULL) {
+            return EXIT_FAILURE;
+        }
+
+        struct dirent *dirent;
+        while ((dirent = readdir(dir)) != NULL) {
+            struct stat st;
+            char overlay_apk_path[PATH_MAX + 1];
+            snprintf(overlay_apk_path, PATH_MAX, "%s/%s", overlay_dir, dirent->d_name);
+            if (stat(overlay_apk_path, &st) < 0) {
+                continue;
+            }
+            if (!S_ISREG(st.st_mode)) {
+                continue;
+            }
+
+            int priority = parse_apk(overlay_apk_path, target_package_name);
+            if (priority < 0) {
+                continue;
+            }
+
+            String8 idmap_path(idmap_dir);
+            idmap_path.appendPath(flatten_path(overlay_apk_path + 1));
+            idmap_path.append("@idmap");
+
+            if (idmap_create_path(target_apk_path, overlay_apk_path, idmap_path.string()) != 0) {
+                ALOGE("error: failed to create idmap for target=%s overlay=%s idmap=%s\n",
+                        target_apk_path, overlay_apk_path, idmap_path.string());
+                continue;
+            }
+
+            Overlay overlay(String8(overlay_apk_path), idmap_path, priority);
+            overlayVector.add(overlay);
+        }
+
+        closedir(dir);
+    }
+
+    if (!writePackagesList(filename.string(), overlayVector)) {
+        return EXIT_FAILURE;
+    }
+
+    return EXIT_SUCCESS;
+}
+
diff --git a/core/java/android/animation/AnimatorSet.java b/core/java/android/animation/AnimatorSet.java
index fca26f8..86adbb0 100644
--- a/core/java/android/animation/AnimatorSet.java
+++ b/core/java/android/animation/AnimatorSet.java
@@ -714,8 +714,8 @@
         mReversing = inReverse;
 
         // Now that all dependencies are set up, start the animations that should be started.
-        boolean isZeroDuration = ValueAnimator.getDurationScale() == 0f || isEmptySet(this);
-        if (!isZeroDuration) {
+        boolean isEmptySet = isEmptySet(this);
+        if (!isEmptySet) {
             startAnimation();
         }
 
@@ -727,7 +727,7 @@
                 tmpListeners.get(i).onAnimationStart(this, inReverse);
             }
         }
-        if (isZeroDuration) {
+        if (isEmptySet) {
             // In the case of empty AnimatorSet, or 0 duration scale, we will trigger the
             // onAnimationEnd() right away.
             forceToEnd();
@@ -979,7 +979,7 @@
     public boolean doAnimationFrame(long frameTime) {
         float durationScale = ValueAnimator.getDurationScale();
         if (durationScale == 0f) {
-            // Duration scale changed to 0 amid animation, end the animation right away.
+            // Duration scale is 0, end the animation right away.
             forceToEnd();
             return true;
         }
diff --git a/core/java/android/app/ApplicationPackageManager.java b/core/java/android/app/ApplicationPackageManager.java
index 64e2d49..97992ca 100644
--- a/core/java/android/app/ApplicationPackageManager.java
+++ b/core/java/android/app/ApplicationPackageManager.java
@@ -65,6 +65,7 @@
 import android.graphics.drawable.Drawable;
 import android.graphics.drawable.LayerDrawable;
 import android.net.Uri;
+import android.os.Build;
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.Looper;
@@ -2129,10 +2130,15 @@
     @Override
     public void getPackageSizeInfoAsUser(String packageName, int userHandle,
             IPackageStatsObserver observer) {
-        try {
-            mPM.getPackageSizeInfo(packageName, userHandle, observer);
-        } catch (RemoteException e) {
-            throw e.rethrowFromSystemServer();
+        if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.O) {
+            throw new UnsupportedOperationException(
+                    "Shame on you for calling a hidden API. Shame!");
+        } else if (observer != null) {
+            Log.d(TAG, "Shame on you for calling a hidden API. Shame!");
+            try {
+                observer.onGetStatsCompleted(null, false);
+            } catch (RemoteException ignored) {
+            }
         }
     }
 
diff --git a/core/java/android/app/LoadedApk.java b/core/java/android/app/LoadedApk.java
index 7cdd45f..be38f42 100644
--- a/core/java/android/app/LoadedApk.java
+++ b/core/java/android/app/LoadedApk.java
@@ -749,19 +749,17 @@
         }
 
         final File profileFile = getPrimaryProfileFile(mPackageName);
-        final File foreignDexProfilesFile =
-                Environment.getDataProfilesDeForeignDexDirectory(UserHandle.myUserId());
 
-        VMRuntime.registerAppInfo(profileFile.getPath(), mApplicationInfo.dataDir,
-                codePaths.toArray(new String[codePaths.size()]), foreignDexProfilesFile.getPath());
+        VMRuntime.registerAppInfo(profileFile.getPath(),
+                codePaths.toArray(new String[codePaths.size()]));
 
         // Setup the reporter to notify package manager of any relevant dex loads.
         // At this point the primary apk is loaded and will not be reported.
         // Anything loaded from now on will be tracked as a potential secondary
         // or foreign dex file. The goal is to enable:
         //    1) monitoring and compilation of secondary dex file
-        //    2) track foreign dex file usage (used to determined the
-        //       compilation filter of apks).
+        //    2) track whether or not a dex file is used by other apps (used to
+        //       determined the compilation filter of apks).
         if (BaseDexClassLoader.getReporter() != DexLoadReporter.INSTANCE) {
             // Set the dex load reporter if not already set.
             // Note that during the app's life cycle different LoadedApks may be
diff --git a/core/java/android/app/Notification.java b/core/java/android/app/Notification.java
index 3fc459e..a098591 100644
--- a/core/java/android/app/Notification.java
+++ b/core/java/android/app/Notification.java
@@ -72,6 +72,7 @@
 import com.android.internal.R;
 import com.android.internal.util.ArrayUtils;
 import com.android.internal.util.NotificationColorUtil;
+import com.android.internal.util.Preconditions;
 
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
@@ -4068,7 +4069,7 @@
         public RemoteViews makeAmbientNotification() {
             RemoteViews ambient = applyStandardTemplateWithActions(
                     R.layout.notification_template_material_ambient,
-                    mParams.reset().fillTextsFrom(this).hasProgress(false).ambient(true));
+                    mParams.reset().ambient(true).fillTextsFrom(this).hasProgress(false));
             return ambient;
         }
 
@@ -4381,7 +4382,13 @@
         }
 
         private CharSequence processLegacyText(CharSequence charSequence) {
-            if (isLegacy() || textColorsNeedInversion()) {
+            return processLegacyText(charSequence, false /* ambient */);
+        }
+
+        private CharSequence processLegacyText(CharSequence charSequence, boolean ambient) {
+            boolean isAlreadyLightText = isLegacy() || textColorsNeedInversion();
+            boolean wantLightText = ambient;
+            if (isAlreadyLightText != wantLightText) {
                 return getColorUtil().invertCharSequenceColors(charSequence);
             } else {
                 return charSequence;
@@ -7853,14 +7860,15 @@
         }
 
         final StandardTemplateParams ambient(boolean ambient) {
+            Preconditions.checkState(title == null && text == null, "must set ambient before text");
             this.ambient = ambient;
             return this;
         }
 
         final StandardTemplateParams fillTextsFrom(Builder b) {
             Bundle extras = b.mN.extras;
-            title = b.processLegacyText(extras.getCharSequence(EXTRA_TITLE));
-            text = b.processLegacyText(extras.getCharSequence(EXTRA_TEXT));
+            title = b.processLegacyText(extras.getCharSequence(EXTRA_TITLE), ambient);
+            text = b.processLegacyText(extras.getCharSequence(EXTRA_TEXT), ambient);
             return this;
         }
     }
diff --git a/core/java/android/app/NotificationChannel.java b/core/java/android/app/NotificationChannel.java
index 85e6b85..16c85f5 100644
--- a/core/java/android/app/NotificationChannel.java
+++ b/core/java/android/app/NotificationChannel.java
@@ -275,6 +275,13 @@
         mDeleted = deleted;
     }
 
+    /**
+     * @hide
+     */
+    public void setNameResId(@StringRes int nameResId) {
+        this.mNameResId = nameResId;
+    }
+
     // Modifiable by a notification ranker.
 
     /**
diff --git a/core/java/android/app/QueuedWork.java b/core/java/android/app/QueuedWork.java
index a38fd43..56338f5 100644
--- a/core/java/android/app/QueuedWork.java
+++ b/core/java/android/app/QueuedWork.java
@@ -21,9 +21,11 @@
 import android.os.Looper;
 import android.os.Message;
 import android.os.Process;
+import android.os.StrictMode;
 import android.util.Log;
 
 import com.android.internal.annotations.GuardedBy;
+import com.android.internal.util.ExponentiallyBucketedHistogram;
 
 import java.util.LinkedList;
 
@@ -46,11 +48,14 @@
  */
 public class QueuedWork {
     private static final String LOG_TAG = QueuedWork.class.getSimpleName();
-    private static final boolean DEBUG = true;
+    private static final boolean DEBUG = false;
 
     /** Delay for delayed runnables, as big as possible but low enough to be barely perceivable */
     private static final long DELAY = 100;
 
+    /** If a {@link #waitToFinish()} takes more than {@value #MAX_WAIT_TIME_MILLIS} ms, warn */
+    private static final long MAX_WAIT_TIME_MILLIS = 512;
+
     /** Lock for this class */
     private static final Object sLock = new Object();
 
@@ -79,6 +84,13 @@
     @GuardedBy("sLock")
     private static boolean sCanDelay = true;
 
+    /** Time (and number of instances) waited for work to get processed */
+    @GuardedBy("sLock")
+    private final static ExponentiallyBucketedHistogram
+            mWaitTimes = new ExponentiallyBucketedHistogram(
+            16);
+    private static int mNumWaits = 0;
+
     /**
      * Lazily create a handler on a separate thread.
      *
@@ -135,13 +147,9 @@
      * after Service command handling, etc. (so async work is never lost)
      */
     public static void waitToFinish() {
-        long startTime = 0;
+        long startTime = System.currentTimeMillis();
         boolean hadMessages = false;
 
-        if (DEBUG) {
-            startTime = System.currentTimeMillis();
-        }
-
         Handler handler = getHandler();
 
         synchronized (sLock) {
@@ -159,7 +167,12 @@
             sCanDelay = false;
         }
 
-        processPendingWork();
+        StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
+        try {
+            processPendingWork();
+        } finally {
+            StrictMode.setThreadPolicy(oldPolicy);
+        }
 
         try {
             while (true) {
@@ -179,11 +192,16 @@
             sCanDelay = true;
         }
 
-        if (DEBUG) {
+        synchronized (sLock) {
             long waitTime = System.currentTimeMillis() - startTime;
 
             if (waitTime > 0 || hadMessages) {
-                Log.d(LOG_TAG, "waited " + waitTime + " ms");
+                mWaitTimes.add(Long.valueOf(waitTime).intValue());
+                mNumWaits++;
+
+                if (DEBUG || mNumWaits % 1024 == 0 || waitTime > MAX_WAIT_TIME_MILLIS) {
+                    mWaitTimes.log(LOG_TAG, "waited: ");
+                }
             }
         }
     }
diff --git a/core/java/android/app/SharedPreferencesImpl.java b/core/java/android/app/SharedPreferencesImpl.java
index 11ba7ee..063ad24 100644
--- a/core/java/android/app/SharedPreferencesImpl.java
+++ b/core/java/android/app/SharedPreferencesImpl.java
@@ -28,6 +28,7 @@
 import com.google.android.collect.Maps;
 
 import com.android.internal.annotations.GuardedBy;
+import com.android.internal.util.ExponentiallyBucketedHistogram;
 import com.android.internal.util.XmlUtils;
 
 import dalvik.system.BlockGuard;
@@ -53,9 +54,12 @@
 
 final class SharedPreferencesImpl implements SharedPreferences {
     private static final String TAG = "SharedPreferencesImpl";
-    private static final boolean DEBUG = true;
+    private static final boolean DEBUG = false;
     private static final Object CONTENT = new Object();
 
+    /** If a fsync takes more than {@value #MAX_FSYNC_DURATION_MILLIS} ms, warn */
+    private static final long MAX_FSYNC_DURATION_MILLIS = 256;
+
     // Lock ordering rules:
     //  - acquire SharedPreferencesImpl.mLock before EditorImpl.mLock
     //  - acquire mWritingToDiskLock before EditorImpl.mLock
@@ -93,6 +97,11 @@
     @GuardedBy("mWritingToDiskLock")
     private long mDiskStateGeneration;
 
+    /** Time (and number of instances) of file-system sync requests */
+    @GuardedBy("mWritingToDiskLock")
+    private final ExponentiallyBucketedHistogram mSyncTimes = new ExponentiallyBucketedHistogram(16);
+    private int mNumSync = 0;
+
     SharedPreferencesImpl(File file, int mode) {
         mFile = file;
         mBackupFile = makeBackupFile(file);
@@ -139,8 +148,8 @@
                     str = new BufferedInputStream(
                             new FileInputStream(mFile), 16*1024);
                     map = XmlUtils.readMapXml(str);
-                } catch (XmlPullParserException | IOException e) {
-                    Log.w(TAG, "getSharedPreferences", e);
+                } catch (Exception e) {
+                    Log.w(TAG, "Cannot read " + mFile.getAbsolutePath(), e);
                 } finally {
                     IoUtils.closeQuietly(str);
                 }
@@ -719,15 +728,11 @@
             }
             XmlUtils.writeMapXml(mcr.mapToWriteToDisk, str);
 
-            if (DEBUG) {
-                writeTime = System.currentTimeMillis();
-            }
+            writeTime = System.currentTimeMillis();
 
             FileUtils.sync(str);
 
-            if (DEBUG) {
-                fsyncTime = System.currentTimeMillis();
-            }
+            fsyncTime = System.currentTimeMillis();
 
             str.close();
             ContextImpl.setFilePermissionsFromMode(mFile.getPath(), mMode, 0);
@@ -761,14 +766,24 @@
 
             mcr.setDiskWriteResult(true, true);
 
-            Log.d(TAG, "write: " + (existsTime - startTime) + "/"
-                    + (backupExistsTime - startTime) + "/"
-                    + (outputStreamCreateTime - startTime) + "/"
-                    + (writeTime - startTime) + "/"
-                    + (fsyncTime - startTime) + "/"
-                    + (setPermTime - startTime) + "/"
-                    + (fstatTime - startTime) + "/"
-                    + (deleteTime - startTime));
+            if (DEBUG) {
+                Log.d(TAG, "write: " + (existsTime - startTime) + "/"
+                        + (backupExistsTime - startTime) + "/"
+                        + (outputStreamCreateTime - startTime) + "/"
+                        + (writeTime - startTime) + "/"
+                        + (fsyncTime - startTime) + "/"
+                        + (setPermTime - startTime) + "/"
+                        + (fstatTime - startTime) + "/"
+                        + (deleteTime - startTime));
+            }
+
+            long fsyncDuration = fsyncTime - writeTime;
+            mSyncTimes.add(Long.valueOf(fsyncDuration).intValue());
+            mNumSync++;
+
+            if (DEBUG || mNumSync % 1024 == 0 || fsyncDuration > MAX_FSYNC_DURATION_MILLIS) {
+                mSyncTimes.log(TAG, "Time required to fsync " + mFile + ": ");
+            }
 
             return;
         } catch (XmlPullParserException e) {
diff --git a/core/java/android/app/admin/DeviceAdminReceiver.java b/core/java/android/app/admin/DeviceAdminReceiver.java
index 34a0c30..0fb5966 100644
--- a/core/java/android/app/admin/DeviceAdminReceiver.java
+++ b/core/java/android/app/admin/DeviceAdminReceiver.java
@@ -779,6 +779,8 @@
      * become affiliated again (even if security logging is enabled).
      * See {@link DevicePolicyManager#setAffiliationIds}
      *
+     * <p>This callback will be re-triggered if the logs are not retrieved.
+     *
      * <p>This callback is only applicable to device owners.
      *
      * @param context The running context as per {@link #onReceive}.
diff --git a/core/java/android/app/job/JobInfo.java b/core/java/android/app/job/JobInfo.java
index 3887556..6652eee 100644
--- a/core/java/android/app/job/JobInfo.java
+++ b/core/java/android/app/job/JobInfo.java
@@ -425,8 +425,8 @@
 
     private JobInfo(JobInfo.Builder b) {
         jobId = b.mJobId;
-        extras = b.mExtras.deepcopy();
-        transientExtras = b.mTransientExtras.deepcopy();
+        extras = b.mExtras.deepCopy();
+        transientExtras = b.mTransientExtras.deepCopy();
         service = b.mJobService;
         constraintFlags = b.mConstraintFlags;
         triggerContentUris = b.mTriggerContentUris != null
diff --git a/core/java/android/bluetooth/BluetoothAdapter.java b/core/java/android/bluetooth/BluetoothAdapter.java
index 4534767..d36692a 100644
--- a/core/java/android/bluetooth/BluetoothAdapter.java
+++ b/core/java/android/bluetooth/BluetoothAdapter.java
@@ -26,6 +26,7 @@
 import android.app.ActivityThread;
 import android.bluetooth.le.BluetoothLeAdvertiser;
 import android.bluetooth.le.BluetoothLeScanner;
+import android.bluetooth.le.PeriodicAdvertisingManager;
 import android.bluetooth.le.ScanCallback;
 import android.bluetooth.le.ScanFilter;
 import android.bluetooth.le.ScanRecord;
@@ -525,6 +526,7 @@
 
     private static BluetoothLeScanner sBluetoothLeScanner;
     private static BluetoothLeAdvertiser sBluetoothLeAdvertiser;
+    private static PeriodicAdvertisingManager sPeriodicAdvertisingManager;
 
     private final IBluetoothManager mManagerService;
     private IBluetooth mService;
@@ -630,6 +632,30 @@
     }
 
     /**
+     * Returns a {@link PeriodicAdvertisingManager} object for Bluetooth LE Periodic Advertising
+     * operations. Will return null if Bluetooth is turned off or if Bluetooth LE Periodic
+     * Advertising is not supported on this device.
+     * <p>
+     * Use {@link #isLePeriodicAdvertisingSupported()} to check whether LE Periodic Advertising is
+     * supported on this device before calling this method.
+     */
+    public PeriodicAdvertisingManager getPeriodicAdvertisingManager() {
+      if (!getLeAccess())
+        return null;
+
+      if (!isLePeriodicAdvertisingSupported())
+        return null;
+
+      synchronized (mLock) {
+        if (sPeriodicAdvertisingManager == null) {
+          sPeriodicAdvertisingManager =
+              new PeriodicAdvertisingManager(mManagerService);
+        }
+      }
+      return sPeriodicAdvertisingManager;
+    }
+
+    /**
      * Returns a {@link BluetoothLeScanner} object for Bluetooth LE scan operations.
      */
     public BluetoothLeScanner getBluetoothLeScanner() {
@@ -1385,6 +1411,78 @@
     }
 
     /**
+     * Return true if LE 2M PHY feature is supported.
+     *
+     * @return true if chipset supports LE 2M PHY feature
+     */
+    public boolean isLe2MPhySupported() {
+        if (!getLeAccess()) return false;
+        try {
+            mServiceLock.readLock().lock();
+            if (mService != null) return mService.isLe2MPhySupported();
+        } catch (RemoteException e) {
+            Log.e(TAG, "failed to get isExtendedAdvertisingSupported, error: ", e);
+        } finally {
+            mServiceLock.readLock().unlock();
+        }
+        return false;
+    }
+
+    /**
+     * Return true if LE Coded PHY feature is supported.
+     *
+     * @return true if chipset supports LE Coded PHY feature
+     */
+    public boolean isLeCodedPhySupported() {
+        if (!getLeAccess()) return false;
+        try {
+            mServiceLock.readLock().lock();
+            if (mService != null) return mService.isLeCodedPhySupported();
+        } catch (RemoteException e) {
+            Log.e(TAG, "failed to get isLeCodedPhySupported, error: ", e);
+        } finally {
+            mServiceLock.readLock().unlock();
+        }
+        return false;
+    }
+
+    /**
+     * Return true if LE Periodic Advertising feature is supported.
+     *
+     * @return true if chipset supports LE Periodic Advertising feature
+     */
+    public boolean isLeExtendedAdvertisingSupported() {
+        if (!getLeAccess()) return false;
+        try {
+            mServiceLock.readLock().lock();
+            if (mService != null) return mService.isLeExtendedAdvertisingSupported();
+        } catch (RemoteException e) {
+            Log.e(TAG, "failed to get isLeExtendedAdvertisingSupported, error: ", e);
+        } finally {
+            mServiceLock.readLock().unlock();
+        }
+        return false;
+    }
+
+    /**
+     * Return true if LE Periodic Advertising feature is supported.
+     *
+     * @return true if chipset supports LE Periodic Advertising feature
+     */
+    public boolean isLePeriodicAdvertisingSupported() {
+        if (!getLeAccess()) return false;
+        try {
+            mServiceLock.readLock().lock();
+            if (mService != null) return mService.isLePeriodicAdvertisingSupported();
+        } catch (RemoteException e) {
+            Log.e(TAG, "failed to get isLePeriodicAdvertisingSupported, error: ", e);
+        } finally {
+            mServiceLock.readLock().unlock();
+        }
+        return false;
+    }
+
+    /**
      * Return true if hardware has entries available for matching beacons
      *
      * @return true if there are hw entries available for matching beacons
@@ -1858,6 +1956,35 @@
         return listenUsingL2capOn(port, false, false);
     }
 
+
+    /**
+     * Construct an insecure L2CAP server socket.
+     * Call #accept to retrieve connections to this socket.
+     * <p>To auto assign a port without creating a SDP record use
+     * {@link SOCKET_CHANNEL_AUTO_STATIC_NO_SDP} as port number.
+     * @param port    the PSM to listen on
+     * @return An L2CAP BluetoothServerSocket
+     * @throws IOException On error, for example Bluetooth not available, or
+     *                     insufficient permissions.
+     * @hide
+     */
+    public BluetoothServerSocket listenUsingInsecureL2capOn(int port) throws IOException {
+        BluetoothServerSocket socket = new BluetoothServerSocket(
+                BluetoothSocket.TYPE_L2CAP, false, false, port, false, false);
+        int errno = socket.mSocket.bindListen();
+        if(port == SOCKET_CHANNEL_AUTO_STATIC_NO_SDP) {
+            socket.setChannel(socket.mSocket.getPort());
+        }
+        if (errno != 0) {
+            //TODO(BT): Throw the same exception error code
+            // that the previous code was using.
+            //socket.mSocket.throwErrnoNative(errno);
+            throw new IOException("Error: " + errno);
+        }
+        return socket;
+
+    }
+
     /**
      * Read the local Out of Band Pairing Data
      * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
diff --git a/core/java/android/bluetooth/BluetoothDevice.java b/core/java/android/bluetooth/BluetoothDevice.java
index 5c9e2ee..31fc294 100644
--- a/core/java/android/bluetooth/BluetoothDevice.java
+++ b/core/java/android/bluetooth/BluetoothDevice.java
@@ -592,6 +592,42 @@
      */
     public static final int TRANSPORT_LE = 2;
 
+    /**
+     * 1M initiating PHY.
+     */
+    public static final int PHY_LE_1M = 1;
+
+    /**
+     * 2M initiating PHY.
+     */
+    public static final int PHY_LE_2M = 2;
+
+    /**
+     * LE Coded initiating PHY.
+     */
+    public static final int PHY_LE_CODED = 4;
+
+    /**
+     * Any LE PHY.
+     */
+    public static final int PHY_LE_ANY = PHY_LE_1M | PHY_LE_2M | PHY_LE_CODED;
+
+    /**
+     * No preferred coding when transmitting on the LE Coded PHY.
+     */
+    public static final int PHY_OPTION_NO_PREFERRED = 0;
+
+    /**
+     * Prefer the S=2 coding to be used when transmitting on the LE Coded PHY.
+     */
+    public static final int PHY_OPTION_S2 = 1;
+
+    /**
+     * Prefer the S=8 coding to be used when transmitting on the LE Coded PHY.
+     */
+    public static final int PHY_OPTION_S8 = 2;
+
+
     /** @hide */
     public static final String EXTRA_MAS_INSTANCE =
         "android.bluetooth.device.extra.MAS_INSTANCE";
@@ -1412,6 +1448,27 @@
     }
 
     /**
+     * Create an L2cap {@link BluetoothSocket} ready to start an insecure
+     * outgoing connection to this remote device on given channel.
+     * <p>The remote device will be not authenticated and communication on this
+     * socket will not be encrypted.
+     * <p>Use {@link BluetoothSocket#connect} to initiate the outgoing
+     * connection.
+     * <p>Valid L2CAP PSM channels are in range 1 to 2^16.
+     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
+     *
+     * @param channel L2cap PSM/channel to connect to
+     * @return a RFCOMM BluetoothServerSocket ready for an outgoing connection
+     * @throws IOException on error, for example Bluetooth not available, or
+     *                     insufficient permissions
+     * @hide
+     */
+    public BluetoothSocket createInsecureL2capSocket(int channel) throws IOException {
+        return new BluetoothSocket(BluetoothSocket.TYPE_L2CAP, -1, false, false, this, channel,
+                null);
+    }
+
+    /**
      * Create an RFCOMM {@link BluetoothSocket} ready to start a secure
      * outgoing connection to this remote device using SDP lookup of uuid.
      * <p>This is designed to be used with {@link
@@ -1594,6 +1651,67 @@
      */
     public BluetoothGatt connectGatt(Context context, boolean autoConnect,
                                      BluetoothGattCallback callback, int transport) {
+        return (connectGatt(context, autoConnect,callback, TRANSPORT_AUTO, PHY_LE_1M));
+    }
+
+    /**
+     * Connect to GATT Server hosted by this device. Caller acts as GATT client.
+     * The callback is used to deliver results to Caller, such as connection status as well
+     * as any further GATT client operations.
+     * The method returns a BluetoothGatt instance. You can use BluetoothGatt to conduct
+     * GATT client operations.
+     * @param callback GATT callback handler that will receive asynchronous callbacks.
+     * @param autoConnect Whether to directly connect to the remote device (false)
+     *                    or to automatically connect as soon as the remote
+     *                    device becomes available (true).
+     * @throws IllegalArgumentException if callback is null
+     */
+    public BluetoothGatt connectGatt(Context context, boolean autoConnect,
+                                     BluetoothGattCallbackExt callback) {
+        return (connectGatt(context, autoConnect,callback, TRANSPORT_AUTO));
+    }
+
+    /**
+     * Connect to GATT Server hosted by this device. Caller acts as GATT client.
+     * The callback is used to deliver results to Caller, such as connection status as well
+     * as any further GATT client operations.
+     * The method returns a BluetoothGatt instance. You can use BluetoothGatt to conduct
+     * GATT client operations.
+     * @param callback GATT callback handler that will receive asynchronous callbacks.
+     * @param autoConnect Whether to directly connect to the remote device (false)
+     *                    or to automatically connect as soon as the remote
+     *                    device becomes available (true).
+     * @param transport preferred transport for GATT connections to remote dual-mode devices
+     *             {@link BluetoothDevice#TRANSPORT_AUTO} or
+     *             {@link BluetoothDevice#TRANSPORT_BREDR} or {@link BluetoothDevice#TRANSPORT_LE}
+     * @throws IllegalArgumentException if callback is null
+     */
+    public BluetoothGatt connectGatt(Context context, boolean autoConnect,
+                                     BluetoothGattCallbackExt callback, int transport) {
+        return (connectGatt(context, autoConnect,callback, TRANSPORT_AUTO, PHY_LE_1M));
+    }
+
+    /**
+     * Connect to GATT Server hosted by this device. Caller acts as GATT client.
+     * The callback is used to deliver results to Caller, such as connection status as well
+     * as any further GATT client operations.
+     * The method returns a BluetoothGatt instance. You can use BluetoothGatt to conduct
+     * GATT client operations.
+     * @param callback GATT callback handler that will receive asynchronous callbacks.
+     * @param autoConnect Whether to directly connect to the remote device (false)
+     *                    or to automatically connect as soon as the remote
+     *                    device becomes available (true).
+     * @param transport preferred transport for GATT connections to remote dual-mode devices
+     *             {@link BluetoothDevice#TRANSPORT_AUTO} or
+     *             {@link BluetoothDevice#TRANSPORT_BREDR} or {@link BluetoothDevice#TRANSPORT_LE}
+     * @param phy preferred PHY for connections to remote LE device. Bitwise OR of any of
+     *             {@link BluetoothDevice#PHY_LE_1M}, {@link BluetoothDevice#PHY_LE_2M},
+     *             and {@link BluetoothDevice#PHY_LE_CODED}. This option does not take effect if
+     *             {@code autoConnect} is set to true.
+     * @throws IllegalArgumentException if callback is null
+     */
+    public BluetoothGatt connectGatt(Context context, boolean autoConnect,
+                                     BluetoothGattCallbackExt callback, int transport, int phy) {
         // TODO(Bluetooth) check whether platform support BLE
         //     Do the check here or in GattServer?
         BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
@@ -1604,7 +1722,7 @@
                 // BLE is not supported
                 return null;
             }
-            BluetoothGatt gatt = new BluetoothGatt(iGatt, this, transport);
+            BluetoothGatt gatt = new BluetoothGatt(iGatt, this, transport, phy);
             gatt.connect(autoConnect, callback);
             return gatt;
         } catch (RemoteException e) {Log.e(TAG, "", e);}
diff --git a/core/java/android/bluetooth/BluetoothGatt.java b/core/java/android/bluetooth/BluetoothGatt.java
index 12ebdac..11dbf70 100644
--- a/core/java/android/bluetooth/BluetoothGatt.java
+++ b/core/java/android/bluetooth/BluetoothGatt.java
@@ -31,7 +31,7 @@
  * <p>This class provides Bluetooth GATT functionality to enable communication
  * with Bluetooth Smart or Smart Ready devices.
  *
- * <p>To connect to a remote peripheral device, create a {@link BluetoothGattCallback}
+ * <p>To connect to a remote peripheral device, create a {@link BluetoothGattCallbackExt}
  * and call {@link BluetoothDevice#connectGatt} to get a instance of this class.
  * GATT capable devices can be discovered using the Bluetooth device discovery or BLE
  * scan process.
@@ -42,7 +42,7 @@
     private static final boolean VDBG = false;
 
     private IBluetoothGatt mService;
-    private BluetoothGattCallback mCallback;
+    private BluetoothGattCallbackExt mCallback;
     private int mClientIf;
     private BluetoothDevice mDevice;
     private boolean mAutoConnect;
@@ -51,6 +51,7 @@
     private final Object mStateLock = new Object();
     private Boolean mDeviceBusy = false;
     private int mTransport;
+    private int mPhy;
 
     private static final int AUTH_RETRY_STATE_IDLE = 0;
     private static final int AUTH_RETRY_STATE_NO_MITM = 1;
@@ -132,10 +133,10 @@
     /*package*/ static final int AUTHENTICATION_MITM = 2;
 
     /**
-     * Bluetooth GATT callbacks. Overrides the default BluetoothGattCallback implementation.
+     * Bluetooth GATT callbacks. Overrides the default BluetoothGattCallbackExt implementation.
      */
-    private final IBluetoothGattCallback mBluetoothGattCallback =
-        new IBluetoothGattCallback.Stub() {
+    private final IBluetoothGattCallbackExt mBluetoothGattCallbackExt =
+        new IBluetoothGattCallbackExt.Stub() {
             /**
              * Application interface registered - app is ready to go
              * @hide
@@ -161,13 +162,51 @@
                 }
                 try {
                     mService.clientConnect(mClientIf, mDevice.getAddress(),
-                                           !mAutoConnect, mTransport); // autoConnect is inverse of "isDirect"
+                                           !mAutoConnect, mTransport, mPhy); // autoConnect is inverse of "isDirect"
                 } catch (RemoteException e) {
                     Log.e(TAG,"",e);
                 }
             }
 
             /**
+             * Phy update callback
+             * @hide
+             */
+            @Override
+            public void onPhyUpdate(String address, int txPhy, int rxPhy, int status) {
+                if (DBG) Log.d(TAG, "onPhyUpdate() - status=" + status
+                                 + " address=" + address + " txPhy=" + txPhy + " rxPhy=" + rxPhy);
+                if (!address.equals(mDevice.getAddress())) {
+                    return;
+                }
+
+                try {
+                    mCallback.onPhyUpdate(BluetoothGatt.this, txPhy, rxPhy, status);
+                } catch (Exception ex) {
+                    Log.w(TAG, "Unhandled exception in callback", ex);
+                }
+            }
+
+            /**
+             * Phy read callback
+             * @hide
+             */
+            @Override
+            public void onPhyRead(String address, int txPhy, int rxPhy, int status) {
+                if (DBG) Log.d(TAG, "onPhyRead() - status=" + status
+                                 + " address=" + address + " txPhy=" + txPhy + " rxPhy=" + rxPhy);
+                if (!address.equals(mDevice.getAddress())) {
+                    return;
+                }
+
+                try {
+                    mCallback.onPhyRead(BluetoothGatt.this, txPhy, rxPhy, status);
+                } catch (Exception ex) {
+                    Log.w(TAG, "Unhandled exception in callback", ex);
+                }
+            }
+
+            /**
              * Client connection state changed
              * @hide
              */
@@ -503,10 +542,11 @@
         };
 
     /*package*/ BluetoothGatt(IBluetoothGatt iGatt, BluetoothDevice device,
-                                int transport) {
+                                int transport, int phy) {
         mService = iGatt;
         mDevice = device;
         mTransport = transport;
+        mPhy = phy;
         mServices = new ArrayList<BluetoothGattService>();
 
         mConnState = CONN_STATE_IDLE;
@@ -578,7 +618,7 @@
     /**
      * Register an application callback to start using GATT.
      *
-     * <p>This is an asynchronous call. The callback {@link BluetoothGattCallback#onAppRegistered}
+     * <p>This is an asynchronous call. The callback {@link BluetoothGattCallbackExt#onAppRegistered}
      * is used to notify success or failure if the function returns true.
      *
      * <p>Requires {@link android.Manifest.permission#BLUETOOTH} permission.
@@ -587,7 +627,7 @@
      * @return If true, the callback will be called to notify success or failure,
      *         false on immediate error
      */
-    private boolean registerApp(BluetoothGattCallback callback) {
+    private boolean registerApp(BluetoothGattCallbackExt callback) {
         if (DBG) Log.d(TAG, "registerApp()");
         if (mService == null) return false;
 
@@ -596,7 +636,7 @@
         if (DBG) Log.d(TAG, "registerApp() - UUID=" + uuid);
 
         try {
-            mService.registerClient(new ParcelUuid(uuid), mBluetoothGattCallback);
+            mService.registerClient(new ParcelUuid(uuid), mBluetoothGattCallbackExt);
         } catch (RemoteException e) {
             Log.e(TAG,"",e);
             return false;
@@ -626,7 +666,7 @@
      *
      * <p>The connection may not be established right away, but will be
      * completed when the remote device is available. A
-     * {@link BluetoothGattCallback#onConnectionStateChange} callback will be
+     * {@link BluetoothGattCallbackExt#onConnectionStateChange} callback will be
      * invoked when the connection state changes as a result of this function.
      *
      * <p>The autoConnect parameter determines whether to actively connect to
@@ -644,7 +684,7 @@
      *                    device becomes available (true).
      * @return true, if the connection attempt was initiated successfully
      */
-    /*package*/ boolean connect(Boolean autoConnect, BluetoothGattCallback callback) {
+    /*package*/ boolean connect(Boolean autoConnect, BluetoothGattCallbackExt callback) {
         if (DBG) Log.d(TAG, "connect() - device: " + mDevice.getAddress() + ", auto: " + autoConnect);
         synchronized(mStateLock) {
             if (mConnState != CONN_STATE_IDLE) {
@@ -696,7 +736,7 @@
     public boolean connect() {
         try {
             mService.clientConnect(mClientIf, mDevice.getAddress(),
-                                   false, mTransport); // autoConnect is inverse of "isDirect"
+                                   false, mTransport, mPhy); // autoConnect is inverse of "isDirect"
             return true;
         } catch (RemoteException e) {
             Log.e(TAG,"",e);
@@ -705,6 +745,45 @@
     }
 
     /**
+     * Set the preferred connection PHY for this app. Please note that this is just a
+     * recommendation, wether the PHY change will happen depends on other applications peferences,
+     * local and remote controller capabilities. Controller can override these settings.
+     * <p>
+     * {@link BluetoothGattCallbackExt#onPhyUpdate} will be triggered as a result of this call, even
+     * if no PHY change happens. It is also triggered when remote device updates the PHY.
+     *
+     * @param txPhy preferred transmitter PHY. Bitwise OR of any of
+     *             {@link BluetoothDevice#PHY_LE_1M}, {@link BluetoothDevice#PHY_LE_2M}, and
+     *             {@link BluetoothDevice#PHY_LE_CODED}.
+     * @param rxPhy preferred receiver PHY. Bitwise OR of any of
+     *             {@link BluetoothDevice#PHY_LE_1M}, {@link BluetoothDevice#PHY_LE_2M}, and
+     *             {@link BluetoothDevice#PHY_LE_CODED}.
+     * @param phyOptions preferred coding to use when transmitting on the LE Coded PHY. Can be one
+     *             of {@link BluetoothDevice#PHY_OPTION_NO_PREFERRED},
+     *             {@link BluetoothDevice#PHY_OPTION_S2} or {@link BluetoothDevice#PHY_OPTION_S8}
+     */
+    public void setPreferredPhy(int txPhy, int rxPhy, int phyOptions) {
+        try {
+            mService.clientSetPreferredPhy(mClientIf, mDevice.getAddress(), txPhy, rxPhy,
+                                           phyOptions);
+        } catch (RemoteException e) {
+            Log.e(TAG,"",e);
+        }
+    }
+
+    /**
+     * Read the current transmitter PHY and receiver PHY of the connection. The values are returned
+     * in {@link BluetoothGattCallbackExt#onPhyRead}
+     */
+    public void readPhy() {
+        try {
+            mService.clientReadPhy(mClientIf, mDevice.getAddress());
+        } catch (RemoteException e) {
+            Log.e(TAG,"",e);
+        }
+    }
+
+    /**
      * Return the remote bluetooth device this GATT client targets to
      *
      * @return remote bluetooth device
@@ -718,7 +797,7 @@
      * characteristics and descriptors.
      *
      * <p>This is an asynchronous operation. Once service discovery is completed,
-     * the {@link BluetoothGattCallback#onServicesDiscovered} callback is
+     * the {@link BluetoothGattCallbackExt#onServicesDiscovered} callback is
      * triggered. If the discovery was successful, the remote services can be
      * retrieved using the {@link #getServices} function.
      *
@@ -797,7 +876,7 @@
      * Reads the requested characteristic from the associated remote device.
      *
      * <p>This is an asynchronous operation. The result of the read operation
-     * is reported by the {@link BluetoothGattCallback#onCharacteristicRead}
+     * is reported by the {@link BluetoothGattCallbackExt#onCharacteristicRead}
      * callback.
      *
      * <p>Requires {@link android.Manifest.permission#BLUETOOTH} permission.
@@ -839,7 +918,7 @@
      * Writes a given characteristic and its values to the associated remote device.
      *
      * <p>Once the write operation has been completed, the
-     * {@link BluetoothGattCallback#onCharacteristicWrite} callback is invoked,
+     * {@link BluetoothGattCallbackExt#onCharacteristicWrite} callback is invoked,
      * reporting the result of the operation.
      *
      * <p>Requires {@link android.Manifest.permission#BLUETOOTH} permission.
@@ -883,7 +962,7 @@
      * Reads the value for a given descriptor from the associated remote device.
      *
      * <p>Once the read operation has been completed, the
-     * {@link BluetoothGattCallback#onDescriptorRead} callback is
+     * {@link BluetoothGattCallbackExt#onDescriptorRead} callback is
      * triggered, signaling the result of the operation.
      *
      * <p>Requires {@link android.Manifest.permission#BLUETOOTH} permission.
@@ -924,7 +1003,7 @@
     /**
      * Write the value of a given descriptor to the associated remote device.
      *
-     * <p>A {@link BluetoothGattCallback#onDescriptorWrite} callback is
+     * <p>A {@link BluetoothGattCallbackExt#onDescriptorWrite} callback is
      * triggered to report the result of the write operation.
      *
      * <p>Requires {@link android.Manifest.permission#BLUETOOTH} permission.
@@ -968,7 +1047,7 @@
      * <p>Once a reliable write transaction has been initiated, all calls
      * to {@link #writeCharacteristic} are sent to the remote device for
      * verification and queued up for atomic execution. The application will
-     * receive an {@link BluetoothGattCallback#onCharacteristicWrite} callback
+     * receive an {@link BluetoothGattCallbackExt#onCharacteristicWrite} callback
      * in response to every {@link #writeCharacteristic} call and is responsible
      * for verifying if the value has been transmitted accurately.
      *
@@ -1002,7 +1081,7 @@
      * <p>This function will commit all queued up characteristic write
      * operations for a given remote device.
      *
-     * <p>A {@link BluetoothGattCallback#onReliableWriteCompleted} callback is
+     * <p>A {@link BluetoothGattCallbackExt#onReliableWriteCompleted} callback is
      * invoked to indicate whether the transaction has been executed correctly.
      *
      * <p>Requires {@link android.Manifest.permission#BLUETOOTH} permission.
@@ -1060,7 +1139,7 @@
      * Enable or disable notifications/indications for a given characteristic.
      *
      * <p>Once notifications are enabled for a characteristic, a
-     * {@link BluetoothGattCallback#onCharacteristicChanged} callback will be
+     * {@link BluetoothGattCallbackExt#onCharacteristicChanged} callback will be
      * triggered if the remote device indicates that the given characteristic
      * has changed.
      *
@@ -1115,7 +1194,7 @@
     /**
      * Read the RSSI for a connected remote device.
      *
-     * <p>The {@link BluetoothGattCallback#onReadRemoteRssi} callback will be
+     * <p>The {@link BluetoothGattCallbackExt#onReadRemoteRssi} callback will be
      * invoked when the RSSI value has been read.
      *
      * <p>Requires {@link android.Manifest.permission#BLUETOOTH} permission.
@@ -1143,7 +1222,7 @@
      * the data sent is truncated to the MTU size. This function may be used
      * to request a larger MTU size to be able to send more data at once.
      *
-     * <p>A {@link BluetoothGattCallback#onMtuChanged} callback will indicate
+     * <p>A {@link BluetoothGattCallbackExt#onMtuChanged} callback will indicate
      * whether this operation was successful.
      *
      * <p>Requires {@link android.Manifest.permission#BLUETOOTH} permission.
diff --git a/core/java/android/bluetooth/BluetoothGattCallback.java b/core/java/android/bluetooth/BluetoothGattCallback.java
index a915620..4da106d 100644
--- a/core/java/android/bluetooth/BluetoothGattCallback.java
+++ b/core/java/android/bluetooth/BluetoothGattCallback.java
@@ -18,138 +18,22 @@
 
 /**
  * This abstract class is used to implement {@link BluetoothGatt} callbacks.
+ * @deprecated use {@link BluetoothGattCallbackExt}
  */
-public abstract class BluetoothGattCallback {
+public abstract class BluetoothGattCallback extends BluetoothGattCallbackExt {
 
     /**
-     * Callback indicating when GATT client has connected/disconnected to/from a remote
-     * GATT server.
-     *
-     * @param gatt GATT client
-     * @param status Status of the connect or disconnect operation.
-     *               {@link BluetoothGatt#GATT_SUCCESS} if the operation succeeds.
-     * @param newState Returns the new connection state. Can be one of
-     *                  {@link BluetoothProfile#STATE_DISCONNECTED} or
-     *                  {@link BluetoothProfile#STATE_CONNECTED}
+     * @hide
      */
-    public void onConnectionStateChange(BluetoothGatt gatt, int status,
-                                        int newState) {
+    @Override
+    public void onPhyUpdate(BluetoothGatt gatt, int txPhy, int rxPhy, int status) {
     }
 
     /**
-     * Callback invoked when the list of remote services, characteristics and descriptors
-     * for the remote device have been updated, ie new services have been discovered.
-     *
-     * @param gatt GATT client invoked {@link BluetoothGatt#discoverServices}
-     * @param status {@link BluetoothGatt#GATT_SUCCESS} if the remote device
-     *               has been explored successfully.
+     * @hide
      */
-    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
+    @Override
+    public void onPhyRead(BluetoothGatt gatt, int txPhy, int rxPhy, int status) {
     }
 
-    /**
-     * Callback reporting the result of a characteristic read operation.
-     *
-     * @param gatt GATT client invoked {@link BluetoothGatt#readCharacteristic}
-     * @param characteristic Characteristic that was read from the associated
-     *                       remote device.
-     * @param status {@link BluetoothGatt#GATT_SUCCESS} if the read operation
-     *               was completed successfully.
-     */
-    public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,
-                                     int status) {
-    }
-
-    /**
-     * Callback indicating the result of a characteristic write operation.
-     *
-     * <p>If this callback is invoked while a reliable write transaction is
-     * in progress, the value of the characteristic represents the value
-     * reported by the remote device. An application should compare this
-     * value to the desired value to be written. If the values don't match,
-     * the application must abort the reliable write transaction.
-     *
-     * @param gatt GATT client invoked {@link BluetoothGatt#writeCharacteristic}
-     * @param characteristic Characteristic that was written to the associated
-     *                       remote device.
-     * @param status The result of the write operation
-     *               {@link BluetoothGatt#GATT_SUCCESS} if the operation succeeds.
-     */
-    public void onCharacteristicWrite(BluetoothGatt gatt,
-                                      BluetoothGattCharacteristic characteristic, int status) {
-    }
-
-    /**
-     * Callback triggered as a result of a remote characteristic notification.
-     *
-     * @param gatt GATT client the characteristic is associated with
-     * @param characteristic Characteristic that has been updated as a result
-     *                       of a remote notification event.
-     */
-    public void onCharacteristicChanged(BluetoothGatt gatt,
-                                        BluetoothGattCharacteristic characteristic) {
-    }
-
-    /**
-     * Callback reporting the result of a descriptor read operation.
-     *
-     * @param gatt GATT client invoked {@link BluetoothGatt#readDescriptor}
-     * @param descriptor Descriptor that was read from the associated
-     *                   remote device.
-     * @param status {@link BluetoothGatt#GATT_SUCCESS} if the read operation
-     *               was completed successfully
-     */
-    public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor,
-                                 int status) {
-    }
-
-    /**
-     * Callback indicating the result of a descriptor write operation.
-     *
-     * @param gatt GATT client invoked {@link BluetoothGatt#writeDescriptor}
-     * @param descriptor Descriptor that was writte to the associated
-     *                   remote device.
-     * @param status The result of the write operation
-     *               {@link BluetoothGatt#GATT_SUCCESS} if the operation succeeds.
-     */
-    public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor,
-                                  int status) {
-    }
-
-    /**
-     * Callback invoked when a reliable write transaction has been completed.
-     *
-     * @param gatt GATT client invoked {@link BluetoothGatt#executeReliableWrite}
-     * @param status {@link BluetoothGatt#GATT_SUCCESS} if the reliable write
-     *               transaction was executed successfully
-     */
-    public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
-    }
-
-    /**
-     * Callback reporting the RSSI for a remote device connection.
-     *
-     * This callback is triggered in response to the
-     * {@link BluetoothGatt#readRemoteRssi} function.
-     *
-     * @param gatt GATT client invoked {@link BluetoothGatt#readRemoteRssi}
-     * @param rssi The RSSI value for the remote device
-     * @param status {@link BluetoothGatt#GATT_SUCCESS} if the RSSI was read successfully
-     */
-    public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
-    }
-
-    /**
-     * Callback indicating the MTU for a given device connection has changed.
-     *
-     * This callback is triggered in response to the
-     * {@link BluetoothGatt#requestMtu} function, or in response to a connection
-     * event.
-     *
-     * @param gatt GATT client invoked {@link BluetoothGatt#requestMtu}
-     * @param mtu The new MTU size
-     * @param status {@link BluetoothGatt#GATT_SUCCESS} if the MTU has been changed successfully
-     */
-    public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
-    }
 }
diff --git a/core/java/android/bluetooth/BluetoothGattCallbackExt.java b/core/java/android/bluetooth/BluetoothGattCallbackExt.java
new file mode 100644
index 0000000..63774c8
--- /dev/null
+++ b/core/java/android/bluetooth/BluetoothGattCallbackExt.java
@@ -0,0 +1,182 @@
+/*
+ * 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.
+ */
+
+package android.bluetooth;
+
+/**
+ * This abstract class is used to implement {@link BluetoothGatt} callbacks.
+ */
+public abstract class BluetoothGattCallbackExt {
+
+    /**
+     * Callback triggered as result of {@link BluetoothGatt#setPreferredPhy}, or as a result of
+     * remote device changing the PHY.
+     *
+     * @param gatt GATT client
+     * @param txPhy the transmitter PHY in use. One of {@link BluetoothDevice#PHY_LE_1M},
+     *             {@link BluetoothDevice#PHY_LE_2M}, and {@link BluetoothDevice#PHY_LE_CODED}.
+     * @param rxPhy the receiver PHY in use. One of {@link BluetoothDevice#PHY_LE_1M},
+     *             {@link BluetoothDevice#PHY_LE_2M}, and {@link BluetoothDevice#PHY_LE_CODED}.
+     * @param status status of the operation
+     */
+    public void onPhyUpdate(BluetoothGatt gatt, int txPhy, int rxPhy, int status) {
+    }
+
+    /**
+     * Callback triggered as result of {@link BluetoothGatt#readPhy}
+     *
+     * @param gatt GATT client
+     * @param txPhy the transmitter PHY in use. One of {@link BluetoothDevice#PHY_LE_1M},
+     *             {@link BluetoothDevice#PHY_LE_2M}, and {@link BluetoothDevice#PHY_LE_CODED}.
+     * @param rxPhy the receiver PHY in use. One of {@link BluetoothDevice#PHY_LE_1M},
+     *             {@link BluetoothDevice#PHY_LE_2M}, and {@link BluetoothDevice#PHY_LE_CODED}.
+     * @param status status of the operation
+     */
+    public void onPhyRead(BluetoothGatt gatt, int txPhy, int rxPhy, int status) {
+    }
+
+    /**
+     * Callback indicating when GATT client has connected/disconnected to/from a remote
+     * GATT server.
+     *
+     * @param gatt GATT client
+     * @param status Status of the connect or disconnect operation.
+     *               {@link BluetoothGatt#GATT_SUCCESS} if the operation succeeds.
+     * @param newState Returns the new connection state. Can be one of
+     *                  {@link BluetoothProfile#STATE_DISCONNECTED} or
+     *                  {@link BluetoothProfile#STATE_CONNECTED}
+     */
+    public void onConnectionStateChange(BluetoothGatt gatt, int status,
+                                        int newState) {
+    }
+
+    /**
+     * Callback invoked when the list of remote services, characteristics and descriptors
+     * for the remote device have been updated, ie new services have been discovered.
+     *
+     * @param gatt GATT client invoked {@link BluetoothGatt#discoverServices}
+     * @param status {@link BluetoothGatt#GATT_SUCCESS} if the remote device
+     *               has been explored successfully.
+     */
+    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
+    }
+
+    /**
+     * Callback reporting the result of a characteristic read operation.
+     *
+     * @param gatt GATT client invoked {@link BluetoothGatt#readCharacteristic}
+     * @param characteristic Characteristic that was read from the associated
+     *                       remote device.
+     * @param status {@link BluetoothGatt#GATT_SUCCESS} if the read operation
+     *               was completed successfully.
+     */
+    public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,
+                                     int status) {
+    }
+
+    /**
+     * Callback indicating the result of a characteristic write operation.
+     *
+     * <p>If this callback is invoked while a reliable write transaction is
+     * in progress, the value of the characteristic represents the value
+     * reported by the remote device. An application should compare this
+     * value to the desired value to be written. If the values don't match,
+     * the application must abort the reliable write transaction.
+     *
+     * @param gatt GATT client invoked {@link BluetoothGatt#writeCharacteristic}
+     * @param characteristic Characteristic that was written to the associated
+     *                       remote device.
+     * @param status The result of the write operation
+     *               {@link BluetoothGatt#GATT_SUCCESS} if the operation succeeds.
+     */
+    public void onCharacteristicWrite(BluetoothGatt gatt,
+                                      BluetoothGattCharacteristic characteristic, int status) {
+    }
+
+    /**
+     * Callback triggered as a result of a remote characteristic notification.
+     *
+     * @param gatt GATT client the characteristic is associated with
+     * @param characteristic Characteristic that has been updated as a result
+     *                       of a remote notification event.
+     */
+    public void onCharacteristicChanged(BluetoothGatt gatt,
+                                        BluetoothGattCharacteristic characteristic) {
+    }
+
+    /**
+     * Callback reporting the result of a descriptor read operation.
+     *
+     * @param gatt GATT client invoked {@link BluetoothGatt#readDescriptor}
+     * @param descriptor Descriptor that was read from the associated
+     *                   remote device.
+     * @param status {@link BluetoothGatt#GATT_SUCCESS} if the read operation
+     *               was completed successfully
+     */
+    public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor,
+                                 int status) {
+    }
+
+    /**
+     * Callback indicating the result of a descriptor write operation.
+     *
+     * @param gatt GATT client invoked {@link BluetoothGatt#writeDescriptor}
+     * @param descriptor Descriptor that was writte to the associated
+     *                   remote device.
+     * @param status The result of the write operation
+     *               {@link BluetoothGatt#GATT_SUCCESS} if the operation succeeds.
+     */
+    public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor,
+                                  int status) {
+    }
+
+    /**
+     * Callback invoked when a reliable write transaction has been completed.
+     *
+     * @param gatt GATT client invoked {@link BluetoothGatt#executeReliableWrite}
+     * @param status {@link BluetoothGatt#GATT_SUCCESS} if the reliable write
+     *               transaction was executed successfully
+     */
+    public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
+    }
+
+    /**
+     * Callback reporting the RSSI for a remote device connection.
+     *
+     * This callback is triggered in response to the
+     * {@link BluetoothGatt#readRemoteRssi} function.
+     *
+     * @param gatt GATT client invoked {@link BluetoothGatt#readRemoteRssi}
+     * @param rssi The RSSI value for the remote device
+     * @param status {@link BluetoothGatt#GATT_SUCCESS} if the RSSI was read successfully
+     */
+    public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
+    }
+
+    /**
+     * Callback indicating the MTU for a given device connection has changed.
+     *
+     * This callback is triggered in response to the
+     * {@link BluetoothGatt#requestMtu} function, or in response to a connection
+     * event.
+     *
+     * @param gatt GATT client invoked {@link BluetoothGatt#requestMtu}
+     * @param mtu The new MTU size
+     * @param status {@link BluetoothGatt#GATT_SUCCESS} if the MTU has been changed successfully
+     */
+    public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
+    }
+}
diff --git a/core/java/android/bluetooth/BluetoothGattServer.java b/core/java/android/bluetooth/BluetoothGattServer.java
index 5ffceba..9ee739f 100644
--- a/core/java/android/bluetooth/BluetoothGattServer.java
+++ b/core/java/android/bluetooth/BluetoothGattServer.java
@@ -46,7 +46,7 @@
 
     private BluetoothAdapter mAdapter;
     private IBluetoothGatt mService;
-    private BluetoothGattServerCallback mCallback;
+    private BluetoothGattServerCallbackExt mCallback;
 
     private Object mServerIfLock = new Object();
     private int mServerIf;
@@ -59,8 +59,8 @@
     /**
      * Bluetooth GATT interface callbacks
      */
-    private final IBluetoothGattServerCallback mBluetoothGattServerCallback =
-        new IBluetoothGattServerCallback.Stub() {
+    private final IBluetoothGattServerCallbackExt mBluetoothGattServerCallback =
+        new IBluetoothGattServerCallbackExt.Stub() {
             /**
              * Application interface registered - app is ready to go
              * @hide
@@ -292,6 +292,42 @@
                     Log.w(TAG, "Unhandled exception: " + ex);
                 }
             }
+
+            /**
+             * The PHY for a connection was updated
+             * @hide
+             */
+            public void onPhyUpdate(String address, int txPhy, int rxPhy, int status) {
+                if (DBG) Log.d(TAG, "onPhyUpdate() - " + "device=" + address + ", txPHy=" + txPhy
+                    + ", rxPHy=" + rxPhy);
+
+                BluetoothDevice device = mAdapter.getRemoteDevice(address);
+                if (device == null) return;
+
+                try {
+                    mCallback.onPhyUpdate(device, txPhy, rxPhy, status);
+                } catch (Exception ex) {
+                    Log.w(TAG, "Unhandled exception: " + ex);
+                }
+            }
+
+            /**
+             * The PHY for a connection was read
+             * @hide
+             */
+            public void onPhyRead(String address, int txPhy, int rxPhy, int status) {
+                if (DBG) Log.d(TAG, "onPhyUpdate() - " + "device=" + address + ", txPHy=" + txPhy
+                    + ", rxPHy=" + rxPhy);
+
+                BluetoothDevice device = mAdapter.getRemoteDevice(address);
+                if (device == null) return;
+
+                try {
+                    mCallback.onPhyRead(device, txPhy, rxPhy, status);
+                } catch (Exception ex) {
+                    Log.w(TAG, "Unhandled exception: " + ex);
+                }
+            }
         };
 
     /**
@@ -360,7 +396,7 @@
      * @return true, the callback will be called to notify success or failure,
      *         false on immediate error
      */
-    /*package*/ boolean registerCallback(BluetoothGattServerCallback callback) {
+    /*package*/ boolean registerCallback(BluetoothGattServerCallbackExt callback) {
         if (DBG) Log.d(TAG, "registerCallback()");
         if (mService == null) {
             Log.e(TAG, "GATT service not available");
@@ -436,7 +472,7 @@
      *
      * <p>The connection may not be established right away, but will be
      * completed when the remote device is available. A
-     * {@link BluetoothGattServerCallback#onConnectionStateChange} callback will be
+     * {@link BluetoothGattServerCallbackExt#onConnectionStateChange} callback will be
      * invoked when the connection state changes as a result of this function.
      *
      * <p>The autoConnect paramter determines whether to actively connect to
@@ -488,16 +524,58 @@
     }
 
     /**
+     * Set the preferred connection PHY for this app. Please note that this is just a
+     * recommendation, wether the PHY change will happen depends on other applications peferences,
+     * local and remote controller capabilities. Controller can override these settings.
+     * <p>
+     * {@link BluetoothGattServerCallbackExt#onPhyUpdate} will be triggered as a result of this call, even
+     * if no PHY change happens. It is also triggered when remote device updates the PHY.
+     *
+     * @param device The remote device to send this response to
+     * @param txPhy preferred transmitter PHY. Bitwise OR of any of
+     *             {@link BluetoothDevice#PHY_LE_1M}, {@link BluetoothDevice#PHY_LE_2M}, and
+     *             {@link BluetoothDevice#PHY_LE_CODED}.
+     * @param rxPhy preferred receiver PHY. Bitwise OR of any of
+     *             {@link BluetoothDevice#PHY_LE_1M}, {@link BluetoothDevice#PHY_LE_2M}, and
+     *             {@link BluetoothDevice#PHY_LE_CODED}.
+     * @param phyOptions preferred coding to use when transmitting on the LE Coded PHY. Can be one
+     *             of {@link BluetoothDevice#PHY_OPTION_NO_PREFERRED},
+     *             {@link BluetoothDevice#PHY_OPTION_S2} or {@link BluetoothDevice#PHY_OPTION_S8}
+     */
+    public void setPreferredPhy(BluetoothDevice device, int txPhy, int rxPhy, int phyOptions) {
+        try {
+            mService.serverSetPreferredPhy(mServerIf, device.getAddress(), txPhy, rxPhy,
+                                           phyOptions);
+        } catch (RemoteException e) {
+            Log.e(TAG,"",e);
+        }
+    }
+
+    /**
+     * Read the current transmitter PHY and receiver PHY of the connection. The values are returned
+     * in {@link BluetoothGattServerCallbackExt#onPhyRead}
+     *
+     * @param device The remote device to send this response to
+     */
+    public void readPhy(BluetoothDevice device) {
+        try {
+            mService.serverReadPhy(mServerIf, device.getAddress());
+        } catch (RemoteException e) {
+            Log.e(TAG,"",e);
+        }
+    }
+
+    /**
      * Send a response to a read or write request to a remote device.
      *
      * <p>This function must be invoked in when a remote read/write request
      * is received by one of these callback methods:
      *
      * <ul>
-     *      <li>{@link BluetoothGattServerCallback#onCharacteristicReadRequest}
-     *      <li>{@link BluetoothGattServerCallback#onCharacteristicWriteRequest}
-     *      <li>{@link BluetoothGattServerCallback#onDescriptorReadRequest}
-     *      <li>{@link BluetoothGattServerCallback#onDescriptorWriteRequest}
+     *      <li>{@link BluetoothGattServerCallbackExt#onCharacteristicReadRequest}
+     *      <li>{@link BluetoothGattServerCallbackExt#onCharacteristicWriteRequest}
+     *      <li>{@link BluetoothGattServerCallbackExt#onDescriptorReadRequest}
+     *      <li>{@link BluetoothGattServerCallbackExt#onDescriptorWriteRequest}
      * </ul>
      *
      * <p>Requires {@link android.Manifest.permission#BLUETOOTH} permission.
diff --git a/core/java/android/bluetooth/BluetoothGattServerCallback.java b/core/java/android/bluetooth/BluetoothGattServerCallback.java
index 2afcf9a..75ceb52 100644
--- a/core/java/android/bluetooth/BluetoothGattServerCallback.java
+++ b/core/java/android/bluetooth/BluetoothGattServerCallback.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2013 The Android Open Source Project
+ * 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.
@@ -20,141 +20,21 @@
 
 /**
  * This abstract class is used to implement {@link BluetoothGattServer} callbacks.
+ * @deprecated please use {@link BluetoothGattServerCallbackExt}
  */
-public abstract class BluetoothGattServerCallback {
+public abstract class BluetoothGattServerCallback extends BluetoothGattServerCallbackExt {
 
     /**
-     * Callback indicating when a remote device has been connected or disconnected.
-     *
-     * @param device Remote device that has been connected or disconnected.
-     * @param status Status of the connect or disconnect operation.
-     * @param newState Returns the new connection state. Can be one of
-     *                  {@link BluetoothProfile#STATE_DISCONNECTED} or
-     *                  {@link BluetoothProfile#STATE_CONNECTED}
+     * @hide
      */
-    public void onConnectionStateChange(BluetoothDevice device, int status,
-                                        int newState) {
+    @Override
+    public void onPhyUpdate(BluetoothDevice device, int txPhy, int rxPhy, int status) {
     }
 
     /**
-     * Indicates whether a local service has been added successfully.
-     *
-     * @param status Returns {@link BluetoothGatt#GATT_SUCCESS} if the service
-     *               was added successfully.
-     * @param service The service that has been added
+     * @hide
      */
-    public void onServiceAdded(int status, BluetoothGattService service) {
-    }
-
-    /**
-     * A remote client has requested to read a local characteristic.
-     *
-     * <p>An application must call {@link BluetoothGattServer#sendResponse}
-     * to complete the request.
-     *
-     * @param device The remote device that has requested the read operation
-     * @param requestId The Id of the request
-     * @param offset Offset into the value of the characteristic
-     * @param characteristic Characteristic to be read
-     */
-    public void onCharacteristicReadRequest(BluetoothDevice device, int requestId,
-                        int offset, BluetoothGattCharacteristic characteristic) {
-    }
-
-    /**
-     * A remote client has requested to write to a local characteristic.
-     *
-     * <p>An application must call {@link BluetoothGattServer#sendResponse}
-     * to complete the request.
-     *
-     * @param device The remote device that has requested the write operation
-     * @param requestId The Id of the request
-     * @param characteristic Characteristic to be written to.
-     * @param preparedWrite true, if this write operation should be queued for
-     *                      later execution.
-     * @param responseNeeded true, if the remote device requires a response
-     * @param offset The offset given for the value
-     * @param value The value the client wants to assign to the characteristic
-     */
-    public void onCharacteristicWriteRequest(BluetoothDevice device, int requestId,
-                                             BluetoothGattCharacteristic characteristic,
-                                             boolean preparedWrite, boolean responseNeeded,
-                                             int offset, byte[] value) {
-    }
-
-    /**
-     * A remote client has requested to read a local descriptor.
-     *
-     * <p>An application must call {@link BluetoothGattServer#sendResponse}
-     * to complete the request.
-     *
-     * @param device The remote device that has requested the read operation
-     * @param requestId The Id of the request
-     * @param offset Offset into the value of the characteristic
-     * @param descriptor Descriptor to be read
-     */
-    public void onDescriptorReadRequest(BluetoothDevice device, int requestId,
-                                        int offset, BluetoothGattDescriptor descriptor) {
-    }
-
-    /**
-     * A remote client has requested to write to a local descriptor.
-     *
-     * <p>An application must call {@link BluetoothGattServer#sendResponse}
-     * to complete the request.
-     *
-     * @param device The remote device that has requested the write operation
-     * @param requestId The Id of the request
-     * @param descriptor Descriptor to be written to.
-     * @param preparedWrite true, if this write operation should be queued for
-     *                      later execution.
-     * @param responseNeeded true, if the remote device requires a response
-     * @param offset The offset given for the value
-     * @param value The value the client wants to assign to the descriptor
-     */
-    public void onDescriptorWriteRequest(BluetoothDevice device, int requestId,
-                                         BluetoothGattDescriptor descriptor,
-                                         boolean preparedWrite, boolean responseNeeded,
-                                         int offset,  byte[] value) {
-    }
-
-    /**
-     * Execute all pending write operations for this device.
-     *
-     * <p>An application must call {@link BluetoothGattServer#sendResponse}
-     * to complete the request.
-     *
-     * @param device The remote device that has requested the write operations
-     * @param requestId The Id of the request
-     * @param execute Whether the pending writes should be executed (true) or
-     *                cancelled (false)
-     */
-    public void onExecuteWrite(BluetoothDevice device, int requestId, boolean execute) {
-    }
-
-    /**
-     * Callback invoked when a notification or indication has been sent to
-     * a remote device.
-     *
-     * <p>When multiple notifications are to be sent, an application must
-     * wait for this callback to be received before sending additional
-     * notifications.
-     *
-     * @param device The remote device the notification has been sent to
-     * @param status {@link BluetoothGatt#GATT_SUCCESS} if the operation was successful
-     */
-    public void onNotificationSent(BluetoothDevice device, int status) {
-    }
-
-    /**
-     * Callback indicating the MTU for a given device connection has changed.
-     *
-     * <p>This callback will be invoked if a remote client has requested to change
-     * the MTU for a given connection.
-     *
-     * @param device The remote device that requested the MTU change
-     * @param mtu The new MTU size
-     */
-    public void onMtuChanged(BluetoothDevice device, int mtu) {
+    @Override
+    public void onPhyRead(BluetoothDevice device, int txPhy, int rxPhy, int status) {
     }
 }
diff --git a/core/java/android/bluetooth/BluetoothGattServerCallbackExt.java b/core/java/android/bluetooth/BluetoothGattServerCallbackExt.java
new file mode 100644
index 0000000..455cce0
--- /dev/null
+++ b/core/java/android/bluetooth/BluetoothGattServerCallbackExt.java
@@ -0,0 +1,187 @@
+/*
+ * Copyright (C) 2013 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.bluetooth;
+
+import android.bluetooth.BluetoothDevice;
+
+/**
+ * This abstract class is used to implement {@link BluetoothGattServer} callbacks.
+ */
+public abstract class BluetoothGattServerCallbackExt {
+
+    /**
+     * Callback indicating when a remote device has been connected or disconnected.
+     *
+     * @param device Remote device that has been connected or disconnected.
+     * @param status Status of the connect or disconnect operation.
+     * @param newState Returns the new connection state. Can be one of
+     *                  {@link BluetoothProfile#STATE_DISCONNECTED} or
+     *                  {@link BluetoothProfile#STATE_CONNECTED}
+     */
+    public void onConnectionStateChange(BluetoothDevice device, int status,
+                                        int newState) {
+    }
+
+    /**
+     * Indicates whether a local service has been added successfully.
+     *
+     * @param status Returns {@link BluetoothGatt#GATT_SUCCESS} if the service
+     *               was added successfully.
+     * @param service The service that has been added
+     */
+    public void onServiceAdded(int status, BluetoothGattService service) {
+    }
+
+    /**
+     * A remote client has requested to read a local characteristic.
+     *
+     * <p>An application must call {@link BluetoothGattServer#sendResponse}
+     * to complete the request.
+     *
+     * @param device The remote device that has requested the read operation
+     * @param requestId The Id of the request
+     * @param offset Offset into the value of the characteristic
+     * @param characteristic Characteristic to be read
+     */
+    public void onCharacteristicReadRequest(BluetoothDevice device, int requestId,
+                        int offset, BluetoothGattCharacteristic characteristic) {
+    }
+
+    /**
+     * A remote client has requested to write to a local characteristic.
+     *
+     * <p>An application must call {@link BluetoothGattServer#sendResponse}
+     * to complete the request.
+     *
+     * @param device The remote device that has requested the write operation
+     * @param requestId The Id of the request
+     * @param characteristic Characteristic to be written to.
+     * @param preparedWrite true, if this write operation should be queued for
+     *                      later execution.
+     * @param responseNeeded true, if the remote device requires a response
+     * @param offset The offset given for the value
+     * @param value The value the client wants to assign to the characteristic
+     */
+    public void onCharacteristicWriteRequest(BluetoothDevice device, int requestId,
+                                             BluetoothGattCharacteristic characteristic,
+                                             boolean preparedWrite, boolean responseNeeded,
+                                             int offset, byte[] value) {
+    }
+
+    /**
+     * A remote client has requested to read a local descriptor.
+     *
+     * <p>An application must call {@link BluetoothGattServer#sendResponse}
+     * to complete the request.
+     *
+     * @param device The remote device that has requested the read operation
+     * @param requestId The Id of the request
+     * @param offset Offset into the value of the characteristic
+     * @param descriptor Descriptor to be read
+     */
+    public void onDescriptorReadRequest(BluetoothDevice device, int requestId,
+                                        int offset, BluetoothGattDescriptor descriptor) {
+    }
+
+    /**
+     * A remote client has requested to write to a local descriptor.
+     *
+     * <p>An application must call {@link BluetoothGattServer#sendResponse}
+     * to complete the request.
+     *
+     * @param device The remote device that has requested the write operation
+     * @param requestId The Id of the request
+     * @param descriptor Descriptor to be written to.
+     * @param preparedWrite true, if this write operation should be queued for
+     *                      later execution.
+     * @param responseNeeded true, if the remote device requires a response
+     * @param offset The offset given for the value
+     * @param value The value the client wants to assign to the descriptor
+     */
+    public void onDescriptorWriteRequest(BluetoothDevice device, int requestId,
+                                         BluetoothGattDescriptor descriptor,
+                                         boolean preparedWrite, boolean responseNeeded,
+                                         int offset,  byte[] value) {
+    }
+
+    /**
+     * Execute all pending write operations for this device.
+     *
+     * <p>An application must call {@link BluetoothGattServer#sendResponse}
+     * to complete the request.
+     *
+     * @param device The remote device that has requested the write operations
+     * @param requestId The Id of the request
+     * @param execute Whether the pending writes should be executed (true) or
+     *                cancelled (false)
+     */
+    public void onExecuteWrite(BluetoothDevice device, int requestId, boolean execute) {
+    }
+
+    /**
+     * Callback invoked when a notification or indication has been sent to
+     * a remote device.
+     *
+     * <p>When multiple notifications are to be sent, an application must
+     * wait for this callback to be received before sending additional
+     * notifications.
+     *
+     * @param device The remote device the notification has been sent to
+     * @param status {@link BluetoothGatt#GATT_SUCCESS} if the operation was successful
+     */
+    public void onNotificationSent(BluetoothDevice device, int status) {
+    }
+
+    /**
+     * Callback indicating the MTU for a given device connection has changed.
+     *
+     * <p>This callback will be invoked if a remote client has requested to change
+     * the MTU for a given connection.
+     *
+     * @param device The remote device that requested the MTU change
+     * @param mtu The new MTU size
+     */
+    public void onMtuChanged(BluetoothDevice device, int mtu) {
+    }
+
+    /**
+     * Callback triggered as result of {@link BluetoothGattServer#setPreferredPhy}, or as a result
+     * of remote device changing the PHY.
+     *
+     * @param device The remote device
+     * @param txPhy the transmitter PHY in use. One of {@link BluetoothDevice#PHY_LE_1M},
+     *             {@link BluetoothDevice#PHY_LE_2M}, and {@link BluetoothDevice#PHY_LE_CODED}
+     * @param rxPhy the receiver PHY in use. One of {@link BluetoothDevice#PHY_LE_1M},
+     *             {@link BluetoothDevice#PHY_LE_2M}, and {@link BluetoothDevice#PHY_LE_CODED}
+     * @param status status of the operation
+     */
+    public void onPhyUpdate(BluetoothDevice device, int txPhy, int rxPhy, int status) {
+    }
+
+    /**
+     * Callback triggered as result of {@link BluetoothGattServer#readPhy}
+     *
+     * @param device The remote device that requested the PHY read
+     * @param txPhy the transmitter PHY in use. One of {@link BluetoothDevice#PHY_LE_1M},
+     *             {@link BluetoothDevice#PHY_LE_2M}, and {@link BluetoothDevice#PHY_LE_CODED}
+     * @param rxPhy the receiver PHY in use. One of {@link BluetoothDevice#PHY_LE_1M},
+     *             {@link BluetoothDevice#PHY_LE_2M}, and {@link BluetoothDevice#PHY_LE_CODED}
+     * @param status status of the operation
+     */
+    public void onPhyRead(BluetoothDevice device, int txPhy, int rxPhy, int status) {
+    }
+}
diff --git a/core/java/android/bluetooth/BluetoothMapClient.java b/core/java/android/bluetooth/BluetoothMapClient.java
index 7d8459c..ccab3cd 100644
--- a/core/java/android/bluetooth/BluetoothMapClient.java
+++ b/core/java/android/bluetooth/BluetoothMapClient.java
@@ -50,7 +50,10 @@
     public static final String ACTION_MESSAGE_DELIVERED_SUCCESSFULLY =
             "android.bluetooth.mapmce.profile.action.MESSAGE_DELIVERED_SUCCESSFULLY";
 
-    /* Extras used in ACTION_MESSAGE_RECEIVED intent */
+    /* Extras used in ACTION_MESSAGE_RECEIVED intent.
+     * NOTE: HANDLE is only valid for a single session with the device. */
+    public static final String EXTRA_MESSAGE_HANDLE =
+            "android.bluetooth.mapmce.profile.extra.MESSAGE_HANDLE";
     public static final String EXTRA_SENDER_CONTACT_URI =
             "android.bluetooth.mapmce.profile.extra.SENDER_CONTACT_URI";
     public static final String EXTRA_SENDER_CONTACT_NAME =
diff --git a/core/java/android/bluetooth/IBluetooth.aidl b/core/java/android/bluetooth/IBluetooth.aidl
index 53fef2a..76ca554 100644
--- a/core/java/android/bluetooth/IBluetooth.aidl
+++ b/core/java/android/bluetooth/IBluetooth.aidl
@@ -104,6 +104,10 @@
     boolean isOffloadedFilteringSupported();
     boolean isOffloadedScanBatchingSupported();
     boolean isActivityAndEnergyReportingSupported();
+    boolean isLe2MPhySupported();
+    boolean isLeCodedPhySupported();
+    boolean isLeExtendedAdvertisingSupported();
+    boolean isLePeriodicAdvertisingSupported();
     BluetoothActivityEnergyInfo reportActivityInfo();
 
     /**
diff --git a/core/java/android/bluetooth/IBluetoothGatt.aidl b/core/java/android/bluetooth/IBluetoothGatt.aidl
index aa2291e..33fedc7 100644
--- a/core/java/android/bluetooth/IBluetoothGatt.aidl
+++ b/core/java/android/bluetooth/IBluetoothGatt.aidl
@@ -20,15 +20,20 @@
 import android.bluetooth.BluetoothGattService;
 import android.bluetooth.le.AdvertiseSettings;
 import android.bluetooth.le.AdvertiseData;
+import android.bluetooth.le.AdvertisingSetParameters;
+import android.bluetooth.le.PeriodicAdvertisingParameters;
 import android.bluetooth.le.ScanFilter;
+import android.bluetooth.le.ScanResult;
 import android.bluetooth.le.ScanSettings;
 import android.bluetooth.le.ResultStorageDescriptor;
 import android.os.ParcelUuid;
 import android.os.WorkSource;
 
-import android.bluetooth.IBluetoothGattCallback;
-import android.bluetooth.IBluetoothGattServerCallback;
+import android.bluetooth.IBluetoothGattCallbackExt;
+import android.bluetooth.IBluetoothGattServerCallbackExt;
 import android.bluetooth.le.IAdvertiserCallback;
+import android.bluetooth.le.IAdvertisingSetCallback;
+import android.bluetooth.le.IPeriodicAdvertisingCallback;
 import android.bluetooth.le.IScannerCallback;
 
 /**
@@ -53,10 +58,29 @@
                                in AdvertiseSettings settings);
     void stopMultiAdvertising(in int advertiserId);
 
-    void registerClient(in ParcelUuid appId, in IBluetoothGattCallback callback);
+    void startAdvertisingSet(in AdvertisingSetParameters parameters, in AdvertiseData advertiseData,
+                                in AdvertiseData scanResponse, in PeriodicAdvertisingParameters periodicParameters,
+                                in AdvertiseData periodicData, in IAdvertisingSetCallback callback);
+    void stopAdvertisingSet(in IAdvertisingSetCallback callback);
+
+    void enableAdverisingSet(in int advertiserId, in boolean enable);
+    void setAdvertisingData(in int advertiserId, in AdvertiseData data);
+    void setScanResponseData(in int advertiserId, in AdvertiseData data);
+    void setAdvertisingParameters(in int advertiserId, in AdvertisingSetParameters parameters);
+    void setPeriodicAdvertisingParameters(in int advertiserId, in PeriodicAdvertisingParameters parameters);
+    void setPeriodicAdvertisingData(in int advertiserId, in AdvertiseData data);
+    void periodicAdvertisingEnable(in int advertiserId, in boolean enable);
+
+    void registerSync(in ScanResult scanResult, in int skip, in int timeout, in IPeriodicAdvertisingCallback callback);
+    void unregisterSync(in IPeriodicAdvertisingCallback callback);
+
+    void registerClient(in ParcelUuid appId, in IBluetoothGattCallbackExt callback);
+
     void unregisterClient(in int clientIf);
-    void clientConnect(in int clientIf, in String address, in boolean isDirect, in int transport);
+    void clientConnect(in int clientIf, in String address, in boolean isDirect, in int transport, in int phy);
     void clientDisconnect(in int clientIf, in String address);
+    void clientSetPreferredPhy(in int clientIf, in String address, in int txPhy, in int rxPhy, in int phyOptions);
+    void clientReadPhy(in int clientIf, in String address);
     void refreshDevice(in int clientIf, in String address);
     void discoverServices(in int clientIf, in String address);
     void readCharacteristic(in int clientIf, in String address, in int handle, in int authReq);
@@ -72,10 +96,12 @@
     void configureMTU(in int clientIf, in String address, in int mtu);
     void connectionParameterUpdate(in int clientIf, in String address, in int connectionPriority);
 
-    void registerServer(in ParcelUuid appId, in IBluetoothGattServerCallback callback);
+    void registerServer(in ParcelUuid appId, in IBluetoothGattServerCallbackExt callback);
     void unregisterServer(in int serverIf);
     void serverConnect(in int serverIf, in String address, in boolean isDirect, in int transport);
     void serverDisconnect(in int serverIf, in String address);
+    void serverSetPreferredPhy(in int clientIf, in String address, in int txPhy, in int rxPhy, in int phyOptions);
+    void serverReadPhy(in int clientIf, in String address);
     void addService(in int serverIf, in BluetoothGattService service);
     void removeService(in int serverIf, in int handle);
     void clearServices(in int serverIf);
diff --git a/core/java/android/bluetooth/IBluetoothGattCallback.aidl b/core/java/android/bluetooth/IBluetoothGattCallbackExt.aidl
similarity index 88%
rename from core/java/android/bluetooth/IBluetoothGattCallback.aidl
rename to core/java/android/bluetooth/IBluetoothGattCallbackExt.aidl
index 72cb618..736f4b2 100644
--- a/core/java/android/bluetooth/IBluetoothGattCallback.aidl
+++ b/core/java/android/bluetooth/IBluetoothGattCallbackExt.aidl
@@ -22,10 +22,12 @@
  * Callback definitions for interacting with BLE / GATT
  * @hide
  */
-oneway interface IBluetoothGattCallback {
+oneway interface IBluetoothGattCallbackExt {
     void onClientRegistered(in int status, in int clientIf);
     void onClientConnectionState(in int status, in int clientIf,
                                  in boolean connected, in String address);
+    void onPhyUpdate(in String address, in int txPhy, in int rxPhy, in int status);
+    void onPhyRead(in String address, in int txPhy, in int rxPhy, in int status);
     void onSearchComplete(in String address, in List<BluetoothGattService> services, in int status);
     void onCharacteristicRead(in String address, in int status, in int handle, in byte[] value);
     void onCharacteristicWrite(in String address, in int status, in int handle);
diff --git a/core/java/android/bluetooth/IBluetoothGattServerCallback.aidl b/core/java/android/bluetooth/IBluetoothGattServerCallbackExt.aidl
similarity index 87%
rename from core/java/android/bluetooth/IBluetoothGattServerCallback.aidl
rename to core/java/android/bluetooth/IBluetoothGattServerCallbackExt.aidl
index 1a924fb..091ffb3 100644
--- a/core/java/android/bluetooth/IBluetoothGattServerCallback.aidl
+++ b/core/java/android/bluetooth/IBluetoothGattServerCallbackExt.aidl
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2013 The Android Open Source Project
+ * 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.
@@ -21,7 +21,7 @@
  * Callback definitions for interacting with BLE / GATT
  * @hide
  */
-oneway interface IBluetoothGattServerCallback {
+oneway interface IBluetoothGattServerCallbackExt {
     void onServerRegistered(in int status, in int serverIf);
     void onServerConnectionState(in int status, in int serverIf,
                                  in boolean connected, in String address);
@@ -40,4 +40,6 @@
     void onExecuteWrite(in String address, in int transId, in boolean execWrite);
     void onNotificationSent(in String address, in int status);
     void onMtuChanged(in String address, in int mtu);
+    void onPhyUpdate(in String address, in int txPhy, in int rxPhy, in int status);
+    void onPhyRead(in String address, in int txPhy, in int rxPhy, in int status);
 }
diff --git a/core/java/android/bluetooth/le/AdvertisingSet.java b/core/java/android/bluetooth/le/AdvertisingSet.java
new file mode 100644
index 0000000..1524022
--- /dev/null
+++ b/core/java/android/bluetooth/le/AdvertisingSet.java
@@ -0,0 +1,162 @@
+/*
+ * 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.
+ */
+
+package android.bluetooth.le;
+
+import android.bluetooth.IBluetoothGatt;
+import android.bluetooth.IBluetoothManager;
+import android.bluetooth.le.IAdvertisingSetCallback;
+import android.os.RemoteException;
+import android.util.Log;
+
+/**
+ * This class provides a way to control single Bluetooth LE advertising instance.
+ * <p>
+ * To get an instance of {@link AdvertisingSet}, call the
+ * {@link BluetoothLeAdvertiser#startAdvertisingSet} method.
+ * <p>
+ * <b>Note:</b> Most of the methods here require {@link android.Manifest.permission#BLUETOOTH_ADMIN}
+ * permission.
+ *
+ * @see AdvertiseData
+ */
+public final class AdvertisingSet {
+    private static final String TAG = "AdvertisingSet";
+
+    private final IBluetoothGatt gatt;
+    private int advertiserId;
+
+    /* package */ AdvertisingSet(int advertiserId,
+                                 IBluetoothManager bluetoothManager) {
+        this.advertiserId = advertiserId;
+
+        try {
+          this.gatt = bluetoothManager.getBluetoothGatt();
+        } catch (RemoteException e) {
+          Log.e(TAG, "Failed to get Bluetooth gatt - ", e);
+          throw new IllegalStateException("Failed to get Bluetooth");
+        }
+    }
+
+    /* package */ void setAdvertiserId(int advertiserId) {
+      this.advertiserId = advertiserId;
+    }
+
+    /**
+     * Enables Advertising. This method returns immediately, the operation status is
+     * delivered
+     * through {@code callback.onAdvertisingEnabled()}.
+     * <p>
+     * Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}
+     *
+     */
+    public void enableAdvertising(boolean enable) {
+        try {
+            gatt.enableAdverisingSet(this.advertiserId, enable);
+        } catch (RemoteException e) {
+            Log.e(TAG, "remote exception - ", e);
+        }
+    }
+
+    /**
+     * Set/update data being Advertised. Make sure that data doesn't exceed the size limit for
+     * specified AdvertisingSetParameters. This method returns immediately, the operation status is
+     * delivered through {@code callback.onAdvertisingDataSet()}.
+     * <p>
+     * Advertising data must be empty if non-legacy scannable advertising is used.
+     */
+    public void setAdvertisingData(AdvertiseData data) {
+        try {
+            gatt.setAdvertisingData(this.advertiserId, data);
+        } catch (RemoteException e) {
+            Log.e(TAG, "remote exception - ", e);
+        }
+    }
+
+    /**
+     * Set/update scan response data. Make sure that data doesn't exceed the size limit for
+     * specified AdvertisingSetParameters. This method returns immediately, the operation status
+     * is delivered through {@code callback.onScanResponseDataSet()}.
+     */
+    public void setScanResponseData(AdvertiseData data) {
+        try {
+            gatt.setScanResponseData(this.advertiserId, data);
+        } catch (RemoteException e) {
+            Log.e(TAG, "remote exception - ", e);
+        }
+    }
+
+    /**
+     * Update advertising parameters associated with this AdvertisingSet. Must be called when
+     * advertising is not active. This method returns immediately, the operation status is delivered
+     * through {@code callback.onAdvertisingParametersUpdated}.
+     */
+    public void setAdvertisingParameters(AdvertisingSetParameters parameters) {
+        try {
+            gatt.setAdvertisingParameters(this.advertiserId, parameters);
+        } catch (RemoteException e) {
+            Log.e(TAG, "remote exception - ", e);
+        }
+    }
+
+    /**
+     * Update periodic advertising parameters associated with this set. Must be called when
+     * periodic advertising is not enabled. This method returns immediately, the operation
+     * status is delivered through {@code callback.onPeriodicAdvertisingParametersUpdated()}.
+     */
+    public void setPeriodicAdvertisingParameters(PeriodicAdvertisingParameters parameters) {
+        try {
+            gatt.setPeriodicAdvertisingParameters(this.advertiserId, parameters);
+        } catch (RemoteException e) {
+            Log.e(TAG, "remote exception - ", e);
+        }
+    }
+
+    /**
+     * Used to set periodic advertising data, must be called after setPeriodicAdvertisingParameters,
+     * or after advertising was started with periodic advertising data set. This method returns
+     * immediately, the operation status is delivered through
+     * {@code callback.onPeriodicAdvertisingDataSet()}.
+     */
+    public void setPeriodicAdvertisingData(AdvertiseData data) {
+        try {
+            gatt.setPeriodicAdvertisingData(this.advertiserId, data);
+        } catch (RemoteException e) {
+            Log.e(TAG, "remote exception - ", e);
+        }
+    }
+
+    /**
+     * Used to enable/disable periodic advertising. This method returns immediately, the operation
+     * status is delivered through {@code callback.onPeriodicAdvertisingEnable()}.
+     */
+    public void periodicAdvertisingEnable(boolean enable) {
+        try {
+            gatt.periodicAdvertisingEnable(this.advertiserId, enable);
+        } catch (RemoteException e) {
+            Log.e(TAG, "remote exception - ", e);
+        }
+    }
+
+    /**
+     * Returns advertiserId associated with thsi advertising set.
+     *
+     * @hide
+     */
+    public int getAdvertiserId(){
+      return advertiserId;
+    }
+}
\ No newline at end of file
diff --git a/core/java/android/bluetooth/le/AdvertisingSetCallback.java b/core/java/android/bluetooth/le/AdvertisingSetCallback.java
new file mode 100644
index 0000000..ceed8d9
--- /dev/null
+++ b/core/java/android/bluetooth/le/AdvertisingSetCallback.java
@@ -0,0 +1,144 @@
+/*
+ * 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.
+ */
+
+package android.bluetooth.le;
+
+import android.bluetooth.BluetoothDevice;
+
+/**
+ * Bluetooth LE advertising set callbacks, used to deliver advertising operation
+ * status.
+ */
+public abstract class AdvertisingSetCallback {
+
+    /**
+     * The requested operation was successful.
+     */
+    public static final int ADVERTISE_SUCCESS = 0;
+
+    /**
+     * Failed to start advertising as the advertise data to be broadcasted is too
+     * large.
+     */
+    public static final int ADVERTISE_FAILED_DATA_TOO_LARGE = 1;
+
+    /**
+     * Failed to start advertising because no advertising instance is available.
+     */
+    public static final int ADVERTISE_FAILED_TOO_MANY_ADVERTISERS = 2;
+
+    /**
+     * Failed to start advertising as the advertising is already started.
+     */
+    public static final int ADVERTISE_FAILED_ALREADY_STARTED = 3;
+
+    /**
+     * Operation failed due to an internal error.
+     */
+    public static final int ADVERTISE_FAILED_INTERNAL_ERROR = 4;
+
+    /**
+     * This feature is not supported on this platform.
+     */
+    public static final int ADVERTISE_FAILED_FEATURE_UNSUPPORTED = 5;
+
+    /**
+     * Callback triggered in response to {@link BluetoothLeAdvertiser#startAdvertisingSet}
+     * indicating result of the operation. If status is ADVERTISE_SUCCESS, then advertisingSet
+     * contains the started set and it is advertising. If error occured, advertisingSet is
+     * null, and status will be set to proper error code.
+     *
+     * @param advertisingSet The advertising set that was started or null if error.
+     * @param status Status of the operation.
+     */
+    public void onAdvertisingSetStarted(AdvertisingSet advertisingSet, int status) {}
+
+    /**
+     * Callback triggered in response to {@link BluetoothLeAdvertiser#stopAdvertisingSet}
+     * indicating advertising set is stopped.
+     *
+     * @param advertisingSet The advertising set.
+     */
+    public void onAdvertisingSetStopped(AdvertisingSet advertisingSet) {}
+
+    /**
+     * Callback triggered in response to {@link BluetoothLeAdvertiser#startAdvertisingSet} indicating
+     * result of the operation. If status is ADVERTISE_SUCCESS, then advertising set is advertising.
+     *
+     * @param advertisingSet The advertising set.
+     * @param status Status of the operation.
+     */
+    public void onAdvertisingEnabled(AdvertisingSet advertisingSet, boolean enable, int status) {}
+
+    /**
+     * Callback triggered in response to {@link AdvertisingSet#setAdvertisingData} indicating
+     * result of the operation. If status is ADVERTISE_SUCCESS, then data was changed.
+     *
+     * @param advertisingSet The advertising set.
+     * @param status Status of the operation.
+     */
+    public void onAdvertisingDataSet(AdvertisingSet advertisingSet, int status) {}
+
+    /**
+     * Callback triggered in response to {@link AdvertisingSet#setAdvertisingData} indicating
+     * result of the operation.
+     *
+     * @param advertisingSet The advertising set.
+     * @param status Status of the operation.
+     */
+    public void onScanResponseDataSet(AdvertisingSet advertisingSet, int status) {}
+
+    /**
+     * Callback triggered in response to {@link AdvertisingSet#setAdvertisingParameters}
+     * indicating result of the operation.
+     *
+     * @param advertisingSet The advertising set.
+     * @param status Status of the operation.
+     */
+    public void onAdvertisingParametersUpdated(AdvertisingSet advertisingSet,
+                                               int status) {}
+
+    /**
+     * Callback triggered in response to {@link AdvertisingSet#setPeriodicAdvertisingParameters}
+     * indicating result of the operation.
+     *
+     * @param advertisingSet The advertising set.
+     * @param status Status of the operation.
+     */
+    public void
+    onPeriodicAdvertisingParametersUpdated(AdvertisingSet advertisingSet,
+                                           int status) {}
+
+    /**
+     * Callback triggered in response to {@link AdvertisingSet#setPeriodicAdvertisingData}
+     * indicating result of the operation.
+     *
+     * @param advertisingSet The advertising set.
+     * @param status Status of the operation.
+     */
+    public void onPeriodicAdvertisingDataSet(AdvertisingSet advertisingSet,
+                                             int status) {}
+
+    /**
+     * Callback triggered in response to {@link AdvertisingSet#periodicAdvertisingEnable}
+     * indicating result of the operation.
+     *
+     * @param advertisingSet The advertising set.
+     * @param status Status of the operation.
+     */
+    public void onPeriodicAdvertisingEnable(AdvertisingSet advertisingSet, boolean enable,
+                                            int status) {}
+}
\ No newline at end of file
diff --git a/core/java/com/android/internal/logging/legacy/Util.java b/core/java/android/bluetooth/le/AdvertisingSetParameters.aidl
similarity index 77%
rename from core/java/com/android/internal/logging/legacy/Util.java
rename to core/java/android/bluetooth/le/AdvertisingSetParameters.aidl
index 99f71ca..39034a0 100644
--- a/core/java/com/android/internal/logging/legacy/Util.java
+++ b/core/java/android/bluetooth/le/AdvertisingSetParameters.aidl
@@ -13,13 +13,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package com.android.internal.logging.legacy;
 
-/**
- * Created by cwren on 11/21/16.
- */
-public class Util {
-    public static boolean debug() {
-        return false;
-    }
-}
+package android.bluetooth.le;
+
+parcelable AdvertisingSetParameters;
diff --git a/core/java/android/bluetooth/le/AdvertisingSetParameters.java b/core/java/android/bluetooth/le/AdvertisingSetParameters.java
new file mode 100644
index 0000000..03a01e1
--- /dev/null
+++ b/core/java/android/bluetooth/le/AdvertisingSetParameters.java
@@ -0,0 +1,409 @@
+/*
+ * 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.
+ */
+
+package android.bluetooth.le;
+
+import android.os.Parcel;
+import android.os.Parcelable;
+
+/**
+ * The {@link AdvertisingSetParameters} provide a way to adjust advertising
+ * preferences for each
+ * Bluetooth LE advertising set. Use {@link AdvertisingSetParameters.Builder} to
+ * create an
+ * instance of this class.
+ */
+public final class AdvertisingSetParameters implements Parcelable {
+
+    /**
+     * 1M advertiser PHY.
+     */
+    public static final int PHY_LE_1M = 1;
+
+    /**
+     * 2M advertiser PHY.
+     */
+    public static final int PHY_LE_2M = 2;
+
+    /**
+     * LE Coded advertiser PHY.
+     */
+    public static final int PHY_LE_CODED = 3;
+
+    /**
+    * Advertise on low frequency, around every 1000ms. This is the default and
+    * preferred advertising mode as it consumes the least power.
+    */
+    public static final int INTERVAL_LOW = 1600;
+
+    /**
+     * Advertise on medium frequency, around every 250ms. This is balanced
+     * between advertising frequency and power consumption.
+     */
+    public static final int INTERVAL_MEDIUM = 400;
+
+    /**
+     * Perform high frequency, low latency advertising, around every 100ms. This
+     * has the highest power consumption and should not be used for continuous
+     * background advertising.
+     */
+    public static final int INTERVAL_HIGH = 160;
+
+    /**
+     * Minimum value for advertising interval.
+     */
+    public static final int INTERVAL_MIN = 160;
+
+    /**
+     * Maximum value for advertising interval.
+     */
+    public static final int INTERVAL_MAX = 16777215;
+
+    /**
+     * Advertise using the lowest transmission (TX) power level. Low transmission
+     * power can be used to restrict the visibility range of advertising packets.
+     */
+    public static final int TX_POWER_ULTRA_LOW = -21;
+
+    /**
+     * Advertise using low TX power level.
+     */
+    public static final int TX_POWER_LOW = -15;
+
+    /**
+     * Advertise using medium TX power level.
+     */
+    public static final int TX_POWER_MEDIUM = -7;
+
+    /**
+     * Advertise using high TX power level. This corresponds to largest visibility
+     * range of the advertising packet.
+     */
+    public static final int TX_POWER_HIGH = 1;
+
+    /**
+     * Minimum value for TX power.
+     */
+    public static final int TX_POWER_MIN = -127;
+
+    /**
+     * Maximum value for TX power.
+     */
+    public static final int TX_POWER_MAX = 1;
+
+    /**
+     * The maximum limited advertisement duration as specified by the Bluetooth
+     * SIG
+     */
+    private static final int LIMITED_ADVERTISING_MAX_MILLIS = 180 * 1000;
+
+    private final boolean isLegacy;
+    private final boolean isAnonymous;
+    private final boolean includeTxPower;
+    private final int primaryPhy;
+    private final int secondaryPhy;
+    private final boolean connectable;
+    private final int interval;
+    private final int txPowerLevel;
+    private final int timeoutMillis;
+
+    private AdvertisingSetParameters(boolean connectable, boolean isLegacy,
+                                     boolean isAnonymous, boolean includeTxPower,
+                                     int primaryPhy, int secondaryPhy,
+                                     int interval, int txPowerLevel,
+                                     int timeoutMillis) {
+        this.connectable = connectable;
+        this.isLegacy = isLegacy;
+        this.isAnonymous = isAnonymous;
+        this.includeTxPower = includeTxPower;
+        this.primaryPhy = primaryPhy;
+        this.secondaryPhy = secondaryPhy;
+        this.interval = interval;
+        this.txPowerLevel = txPowerLevel;
+        this.timeoutMillis = timeoutMillis;
+    }
+
+    private AdvertisingSetParameters(Parcel in) {
+        connectable = in.readInt() != 0 ? true : false;
+        isLegacy = in.readInt() != 0 ? true : false;
+        isAnonymous = in.readInt() != 0 ? true : false;
+        includeTxPower = in.readInt() != 0 ? true : false;
+        primaryPhy = in.readInt();
+        secondaryPhy = in.readInt();
+        interval = in.readInt();
+        txPowerLevel = in.readInt();
+        timeoutMillis = in.readInt();
+    }
+
+    /**
+     * Returns whether the advertisement will be connectable.
+     */
+    public boolean isConnectable() { return connectable; }
+
+    /**
+     * Returns whether the legacy advertisement will be used.
+     */
+    public boolean isLegacy() { return isLegacy; }
+
+    /**
+     * Returns whether the advertisement will be anonymous.
+     */
+    public boolean isAnonymous() { return isAnonymous; }
+
+    /**
+     * Returns whether the TX Power will be included.
+     */
+    public boolean includeTxPower() { return includeTxPower; }
+
+    /**
+     * Returns the primary advertising phy.
+     */
+    public int getPrimaryPhy() { return primaryPhy; }
+
+    /**
+     * Returns the secondary advertising phy.
+     */
+    public int getSecondaryPhy() { return secondaryPhy; }
+
+    /**
+     * Returns the advertising interval.
+     */
+    public int getInterval() { return interval; }
+
+    /**
+     * Returns the TX power level for advertising.
+     */
+    public int getTxPowerLevel() { return txPowerLevel; }
+
+    /**
+     * Returns the advertising time limit in milliseconds.
+     */
+    public int getTimeout() { return timeoutMillis; }
+
+    @Override
+    public String toString() {
+        return "AdvertisingSetParameters [connectable=" + connectable
+             + ", isLegacy=" + isLegacy
+             + ", isAnonymous=" + isAnonymous
+             + ", includeTxPower=" + includeTxPower
+             + ", primaryPhy=" + primaryPhy
+             + ", secondaryPhy=" + secondaryPhy
+             + ", interval=" + interval
+             + ", txPowerLevel=" + txPowerLevel
+             + ", timeoutMillis=" + timeoutMillis + "]";
+    }
+
+    @Override
+    public int describeContents() {
+       return 0;
+    }
+
+    @Override
+    public void writeToParcel(Parcel dest, int flags) {
+        dest.writeInt(connectable ? 1 : 0);
+        dest.writeInt(isLegacy ? 1 : 0);
+        dest.writeInt(isAnonymous ? 1 : 0);
+        dest.writeInt(includeTxPower ? 1 : 0);
+        dest.writeInt(primaryPhy);
+        dest.writeInt(secondaryPhy);
+        dest.writeInt(interval);
+        dest.writeInt(txPowerLevel);
+        dest.writeInt(timeoutMillis);
+    }
+
+    public static final Parcelable.Creator<AdvertisingSetParameters> CREATOR =
+        new Creator<AdvertisingSetParameters>() {
+          @Override
+          public AdvertisingSetParameters[] newArray(int size) {
+            return new AdvertisingSetParameters[size];
+          }
+
+          @Override
+          public AdvertisingSetParameters createFromParcel(Parcel in) {
+            return new AdvertisingSetParameters(in);
+          }
+        };
+
+    /**
+     * Builder class for {@link AdvertisingSetParameters}.
+     */
+    public static final class Builder {
+
+        private boolean connectable = true;
+        private boolean isLegacy = false;
+        private boolean isAnonymous = false;
+        private boolean includeTxPower = false;
+        private int primaryPhy = PHY_LE_1M;
+        private int secondaryPhy = PHY_LE_1M;
+        private int interval = INTERVAL_LOW;
+        private int txPowerLevel = TX_POWER_MEDIUM;
+        private int timeoutMillis = 0;
+
+        /**
+         * Set whether the advertisement type should be connectable or
+         * non-connectable.
+         * Legacy advertisements can be both connectable and scannable. Other
+         * advertisements can be connectable only if not scannable.
+         * @param connectable Controls whether the advertisment type will be
+         * connectable (true) or non-connectable (false).
+         */
+        public Builder setConnectable(boolean connectable) {
+            this.connectable = connectable;
+            return this;
+        }
+
+        /**
+         * When set to true, advertising set will advertise 4.x Spec compliant
+         * advertisements.
+         *
+         * @param isLegacy wether legacy advertising mode should be used.
+         */
+        public Builder setLegacyMode(boolean isLegacy) {
+            this.isLegacy = isLegacy;
+            return this;
+        }
+
+        /**
+         * Set wether advertiser address should be ommited from all packets. If this
+         * mode is used, periodic advertising can't be enabled for this set.
+         *
+         * This is used only if legacy mode is not used.
+         *
+         * @param isAnonymous wether anonymous advertising should be used.
+         */
+        public Builder setAnonymouus(boolean isAnonymous) {
+            this.isAnonymous = isAnonymous;
+            return this;
+        }
+
+        /**
+         * Set wether TX power should be included in the extended header.
+         *
+         * This is used only if legacy mode is not used.
+         *
+         * @param includeTxPower wether TX power should be included in extended
+         * header
+         */
+        public Builder setIncludeTxPower(boolean includeTxPower) {
+            this.includeTxPower = includeTxPower;
+            return this;
+        }
+
+        /**
+         * Set the primary physical channel used for this advertising set.
+         *
+         * This is used only if legacy mode is not used.
+         *
+         * @param primaryPhy Primary advertising physical channel, can only be
+         *            {@link AdvertisingSetParameters#PHY_LE_1M} or
+         *            {@link AdvertisingSetParameters#PHY_LE_CODED}.
+         * @throws IllegalArgumentException If the primaryPhy is invalid.
+         */
+        public Builder setPrimaryPhy(int primaryPhy) {
+            if (primaryPhy != PHY_LE_1M && primaryPhy != PHY_LE_CODED) {
+               throw new IllegalArgumentException("bad primaryPhy " + primaryPhy);
+            }
+            this.primaryPhy = primaryPhy;
+            return this;
+        }
+
+        /**
+         * Set the secondary physical channel used for this advertising set.
+         *
+         * This is used only if legacy mode is not used.
+         *
+         * @param secondaryPhy Secondary advertising physical channel, can only be
+         *            one of {@link AdvertisingSetParameters#PHY_LE_1M},
+         *            {@link AdvertisingSetParameters#PHY_LE_2M} or
+         *            {@link AdvertisingSetParameters#PHY_LE_CODED}.
+         * @throws IllegalArgumentException If the secondaryPhy is invalid.
+         */
+        public Builder setSecondaryPhy(int secondaryPhy) {
+            if (secondaryPhy != PHY_LE_1M && secondaryPhy !=PHY_LE_2M &&
+                secondaryPhy != PHY_LE_CODED) {
+               throw new IllegalArgumentException("bad secondaryPhy " + secondaryPhy);
+            }
+            this.secondaryPhy = secondaryPhy;
+            return this;
+        }
+
+        /**
+         * Set advertising interval.
+         *
+         * @param interval Bluetooth LE Advertising interval, in 0.625ms unit. Valid
+         *            range is from 160 (100ms) to 16777215 (10,485.759375 s).
+         *            Recommended values are:
+         *            {@link AdvertisingSetParameters#INTERVAL_LOW},
+         *            {@link AdvertisingSetParameters#INTERVAL_MEDIUM}, or
+         *            {@link AdvertisingSetParameters#INTERVAL_HIGH}.
+         * @throws IllegalArgumentException If the interval is invalid.
+         */
+        public Builder setInterval(int interval) {
+            if (interval < INTERVAL_MIN || interval > INTERVAL_MAX) {
+               throw new IllegalArgumentException("unknown interval " + interval);
+            }
+            this.interval = interval;
+            return this;
+        }
+
+        /**
+         * Set the transmission power level for the advertising.
+         * @param txPowerLevel Transmission power of Bluetooth LE Advertising, in
+         *             dBm. The valid range is [-127, 1] Recommended values are:
+         *             {@link AdvertisingSetParameters#TX_POWER_ULTRA_LOW},
+         *             {@link AdvertisingSetParameters#TX_POWER_LOW},
+         *             {@link AdvertisingSetParameters#TX_POWER_MEDIUM}, or
+         *             {@link AdvertisingSetParameters#TX_POWER_HIGH}.
+         *
+         * @throws IllegalArgumentException If the {@code txPowerLevel} is invalid.
+         */
+        public Builder setTxPowerLevel(int txPowerLevel) {
+            if (txPowerLevel < TX_POWER_MIN || txPowerLevel > TX_POWER_MAX) {
+                throw new IllegalArgumentException("unknown txPowerLevel " +
+                                                   txPowerLevel);
+            }
+            this.txPowerLevel = txPowerLevel;
+            return this;
+        }
+
+        /**
+         * Limit advertising to a given amount of time.
+         * @param timeoutMillis Advertising time limit. May not exceed 180000
+         * milliseconds. A value of 0 will disable the time limit.
+         * @throws IllegalArgumentException If the provided timeout is over 180000
+         * ms.
+         */
+        public Builder setTimeout(int timeoutMillis) {
+            if (timeoutMillis < 0 || timeoutMillis > LIMITED_ADVERTISING_MAX_MILLIS) {
+                throw new IllegalArgumentException("timeoutMillis invalid (must be 0-" +
+                                                   LIMITED_ADVERTISING_MAX_MILLIS +
+                                                   " milliseconds)");
+            }
+            this.timeoutMillis = timeoutMillis;
+            return this;
+        }
+
+        /**
+         * Build the {@link AdvertisingSetParameters} object.
+         */
+        public AdvertisingSetParameters build() {
+            return new AdvertisingSetParameters(connectable, isLegacy, isAnonymous,
+                                                includeTxPower, primaryPhy,
+                                                secondaryPhy, interval, txPowerLevel,
+                                                timeoutMillis);
+        }
+    }
+}
\ No newline at end of file
diff --git a/core/java/android/bluetooth/le/BluetoothLeAdvertiser.java b/core/java/android/bluetooth/le/BluetoothLeAdvertiser.java
index 94d03e5..e03c947 100644
--- a/core/java/android/bluetooth/le/BluetoothLeAdvertiser.java
+++ b/core/java/android/bluetooth/le/BluetoothLeAdvertiser.java
@@ -62,6 +62,9 @@
     private BluetoothAdapter mBluetoothAdapter;
     private final Map<AdvertiseCallback, AdvertiseCallbackWrapper>
             mLeAdvertisers = new HashMap<AdvertiseCallback, AdvertiseCallbackWrapper>();
+    private final Map<AdvertisingSetCallback, IAdvertisingSetCallback>
+            advertisingSetCallbackWrappers = new HashMap<>();
+    private final Map<Integer, AdvertisingSet> advertisingSets = new HashMap<>();
 
     /**
      * Use BluetoothAdapter.getLeAdvertiser() instead.
@@ -156,6 +159,93 @@
     }
 
     /**
+    * Creates a new advertising set. If operation succeed, device will start advertising. This
+    * method returns immediately, the operation status is delivered through
+    * {@code callback.onNewAdvertisingSet()}.
+    * <p>
+    * @param parameters advertising set parameters.
+    * @param advertiseData Advertisement data to be broadcasted.
+    * @param scanResponse Scan response associated with the advertisement data.
+    * @param periodicData Periodic advertising data.
+    * @param callback Callback for advertising set.
+    */
+    public void startAdvertisingSet(AdvertisingSetParameters parameters,
+                                    AdvertiseData advertiseData, AdvertiseData scanResponse,
+                                    PeriodicAdvertisingParameters periodicParameters,
+                                    AdvertiseData periodicData, AdvertisingSetCallback callback) {
+        startAdvertisingSet(parameters, advertiseData, scanResponse, periodicParameters,
+                            periodicData, callback, new Handler(Looper.getMainLooper()));
+    }
+
+    /**
+    * Creates a new advertising set. If operation succeed, device will start advertising. This
+    * method returns immediately, the operation status is delivered through
+    * {@code callback.onNewAdvertisingSet()}.
+    * <p>
+    * @param parameters advertising set parameters.
+    * @param advertiseData Advertisement data to be broadcasted.
+    * @param scanResponse Scan response associated with the advertisement data.
+    * @param periodicData Periodic advertising data.
+    * @param callback Callback for advertising set.
+    * @param handler thread upon which the callbacks will be invoked.
+    */
+    public void startAdvertisingSet(AdvertisingSetParameters parameters,
+                                    AdvertiseData advertiseData, AdvertiseData scanResponse,
+                                    PeriodicAdvertisingParameters periodicParameters,
+                                    AdvertiseData periodicData, AdvertisingSetCallback callback,
+                                    Handler handler) {
+        BluetoothLeUtils.checkAdapterStateOn(mBluetoothAdapter);
+
+        if (callback == null) {
+          throw new IllegalArgumentException("callback cannot be null");
+        }
+
+        IBluetoothGatt gatt;
+        try {
+          gatt = mBluetoothManager.getBluetoothGatt();
+        } catch (RemoteException e) {
+          Log.e(TAG, "Failed to get Bluetooth gatt - ", e);
+          throw new IllegalStateException("Failed to get Bluetooth");
+        }
+
+        IAdvertisingSetCallback wrapped = wrap(callback, handler);
+        advertisingSetCallbackWrappers.put(callback, wrapped);
+
+        try {
+            gatt.startAdvertisingSet(parameters, advertiseData, scanResponse, periodicParameters,
+                                     periodicData, wrapped);
+        } catch (RemoteException e) {
+          Log.e(TAG, "Failed to start advertising set - ", e);
+          throw new IllegalStateException("Failed to start advertising set");
+        }
+    }
+
+    /**
+     * Used to dispose of a {@link AdvertisingSet} object, obtained with {@link
+     * BluetoothLeAdvertiser#startAdvertisingSet}.
+     */
+    public void stopAdvertisingSet(AdvertisingSetCallback callback) {
+        if (callback == null) {
+          throw new IllegalArgumentException("callback cannot be null");
+        }
+
+        IAdvertisingSetCallback wrapped = advertisingSetCallbackWrappers.remove(callback);
+        if (wrapped == null) {
+            throw new IllegalArgumentException(
+                "callback does not represent valid registered callback.");
+        }
+
+        IBluetoothGatt gatt;
+        try {
+            gatt = mBluetoothManager.getBluetoothGatt();
+            gatt.stopAdvertisingSet(wrapped);
+       } catch (RemoteException e) {
+            Log.e(TAG, "Failed to stop advertising - ", e);
+            throw new IllegalStateException("Failed to stop advertising");
+        }
+    }
+
+    /**
      * Cleans up advertisers. Should be called when bluetooth is down.
      *
      * @hide
@@ -219,6 +309,110 @@
         return array == null ? 0 : array.length;
     }
 
+    IAdvertisingSetCallback wrap(AdvertisingSetCallback callback, Handler handler) {
+        return new IAdvertisingSetCallback.Stub() {
+            public void onAdvertisingSetStarted(int advertiserId, int status) {
+                handler.post(new Runnable() {
+                    @Override
+                    public void run() {
+                        if (status != AdvertisingSetCallback.ADVERTISE_SUCCESS) {
+                            callback.onAdvertisingSetStarted(null, status);
+                            advertisingSetCallbackWrappers.remove(callback);
+                            return;
+                        }
+
+                        AdvertisingSet advertisingSet =
+                            new AdvertisingSet(advertiserId, mBluetoothManager);
+                        advertisingSets.put(advertiserId, advertisingSet);
+                        callback.onAdvertisingSetStarted(advertisingSet, status);
+                    }
+                });
+            }
+
+            public void onAdvertisingSetStopped(int advertiserId) {
+                handler.post(new Runnable() {
+                    @Override
+                    public void run() {
+                        AdvertisingSet advertisingSet = advertisingSets.get(advertiserId);
+                        callback.onAdvertisingSetStopped(advertisingSet);
+                        advertisingSets.remove(advertiserId);
+                        advertisingSetCallbackWrappers.remove(callback);
+                    }
+                });
+            }
+
+            public void onAdvertisingEnabled(int advertiserId, boolean enabled, int status) {
+                handler.post(new Runnable() {
+                    @Override
+                    public void run() {
+                        AdvertisingSet advertisingSet = advertisingSets.get(advertiserId);
+                        callback.onAdvertisingEnabled(advertisingSet, enabled, status);
+                    }
+                });
+            }
+
+            public void onAdvertisingDataSet(int advertiserId, int status) {
+                handler.post(new Runnable() {
+                    @Override
+                    public void run() {
+                        AdvertisingSet advertisingSet = advertisingSets.get(advertiserId);
+                        callback.onAdvertisingDataSet(advertisingSet, status);
+                    }
+                });
+            }
+
+            public void onScanResponseDataSet(int advertiserId, int status) {
+                handler.post(new Runnable() {
+                    @Override
+                    public void run() {
+                        AdvertisingSet advertisingSet = advertisingSets.get(advertiserId);
+                        callback.onScanResponseDataSet(advertisingSet, status);
+                    }
+                });
+            }
+
+            public void onAdvertisingParametersUpdated(int advertiserId, int status) {
+                handler.post(new Runnable() {
+                    @Override
+                    public void run() {
+                        AdvertisingSet advertisingSet = advertisingSets.get(advertiserId);
+                        callback.onAdvertisingParametersUpdated(advertisingSet, status);
+                    }
+                });
+            }
+
+            public void onPeriodicAdvertisingParametersUpdated(int advertiserId, int status) {
+                handler.post(new Runnable() {
+                    @Override
+                    public void run() {
+                        AdvertisingSet advertisingSet = advertisingSets.get(advertiserId);
+                        callback.onPeriodicAdvertisingParametersUpdated(advertisingSet, status);
+                    }
+                });
+            }
+
+            public void onPeriodicAdvertisingDataSet(int advertiserId, int status) {
+                handler.post(new Runnable() {
+                    @Override
+                    public void run() {
+                        AdvertisingSet advertisingSet = advertisingSets.get(advertiserId);
+                        callback.onPeriodicAdvertisingDataSet(advertisingSet, status);
+                    }
+                });
+            }
+
+            public void onPeriodicAdvertisingEnable(int advertiserId, boolean enable, int status) {
+                handler.post(new Runnable() {
+                    @Override
+                    public void run() {
+                        AdvertisingSet advertisingSet = advertisingSets.get(advertiserId);
+                        callback.onPeriodicAdvertisingEnable(advertisingSet, enable, status);
+                    }
+                });
+            }
+        };
+    }
+
     /**
      * Bluetooth GATT interface callbacks for advertising.
      */
diff --git a/core/java/android/bluetooth/le/IAdvertisingSetCallback.aidl b/core/java/android/bluetooth/le/IAdvertisingSetCallback.aidl
new file mode 100644
index 0000000..4b0a111
--- /dev/null
+++ b/core/java/android/bluetooth/le/IAdvertisingSetCallback.aidl
@@ -0,0 +1,32 @@
+/*
+ * 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.
+ */
+package android.bluetooth.le;
+
+/**
+ * Callback definitions for interacting with Advertiser
+ * @hide
+ */
+oneway interface IAdvertisingSetCallback {
+  void onAdvertisingSetStarted(in int advertiserId, in int status);
+  void onAdvertisingSetStopped(in int advertiserId);
+  void onAdvertisingEnabled(in int advertiserId, in boolean enable, in int status);
+  void onAdvertisingDataSet(in int advertiserId, in int status);
+  void onScanResponseDataSet(in int advertiserId, in int status);
+  void onAdvertisingParametersUpdated(in int advertiserId, in int status);
+  void onPeriodicAdvertisingParametersUpdated(in int advertiserId, in int status);
+  void onPeriodicAdvertisingDataSet(in int advertiserId, in int status);
+  void onPeriodicAdvertisingEnable(in int advertiserId, in boolean enable, in int status);
+}
diff --git a/core/java/android/bluetooth/le/IPeriodicAdvertisingCallback.aidl b/core/java/android/bluetooth/le/IPeriodicAdvertisingCallback.aidl
new file mode 100644
index 0000000..a76c54d
--- /dev/null
+++ b/core/java/android/bluetooth/le/IPeriodicAdvertisingCallback.aidl
@@ -0,0 +1,31 @@
+/*
+ * 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.
+ */
+package android.bluetooth.le;
+
+import android.bluetooth.BluetoothDevice;
+import android.bluetooth.le.PeriodicAdvertisingReport;
+
+/**
+ * Callback definitions for interacting with Periodic Advertising
+ * @hide
+ */
+oneway interface IPeriodicAdvertisingCallback {
+
+  void onSyncEstablished(in int syncHandle, in BluetoothDevice device, in int advertisingSid,
+                         in int skip, in int timeout, in int status);
+  void onPeriodicAdvertisingReport(in PeriodicAdvertisingReport report);
+  void onSyncLost(in int syncHandle);
+}
diff --git a/core/java/android/bluetooth/le/PeriodicAdvertisingCallback.java b/core/java/android/bluetooth/le/PeriodicAdvertisingCallback.java
new file mode 100644
index 0000000..6616231
--- /dev/null
+++ b/core/java/android/bluetooth/le/PeriodicAdvertisingCallback.java
@@ -0,0 +1,77 @@
+/*
+ * 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.
+ */
+
+package android.bluetooth.le;
+
+import android.bluetooth.BluetoothDevice;
+
+/**
+ * Bluetooth LE periodic advertising callbacks, used to deliver periodic
+ * advertising operation status.
+ *
+ * @see PeriodicAdvertisingManager#createSync
+ */
+public abstract class PeriodicAdvertisingCallback {
+
+    /**
+     * The requested operation was successful.
+     *
+     * @hide
+     */
+    public static final int SYNC_SUCCESS = 0;
+
+    /**
+     * Sync failed to be established because remote device did not respond.
+     */
+    public static final int SYNC_NO_RESPONSE = 1;
+
+    /**
+     *  Sync failed to be established because controller can't support more syncs.
+     */
+    public static final int SYNC_NO_RESOURCES = 2;
+
+
+    /**
+     * Callback when synchronization was established.
+     *
+     * @param syncHandle handle used to identify this synchronization.
+     * @param device remote device.
+     * @param advertisingSid synchronized advertising set id.
+     * @param skip  The number of periodic advertising packets that can be skipped
+     * after a successful receive in force. @see PeriodicAdvertisingManager#createSync
+     * @param timeout Synchronization timeout for the periodic advertising in force. One
+     * unit is 10ms. @see PeriodicAdvertisingManager#createSync
+     * @param timeout
+     * @param status operation status.
+     */
+    public void onSyncEstablished(int syncHandle, BluetoothDevice device,
+                                  int advertisingSid, int skip, int timeout,
+                                  int status) {}
+
+    /**
+     * Callback when periodic advertising report is received.
+     *
+     * @param report periodic advertising report.
+     */
+    public void onPeriodicAdvertisingReport(PeriodicAdvertisingReport report) {}
+
+    /**
+     * Callback when periodic advertising synchronization was lost.
+     *
+     * @param syncHandle handle used to identify this synchronization.
+     */
+    public void onSyncLost(int syncHandle) {}
+}
diff --git a/core/java/android/bluetooth/le/PeriodicAdvertisingManager.java b/core/java/android/bluetooth/le/PeriodicAdvertisingManager.java
new file mode 100644
index 0000000..12c8a8c
--- /dev/null
+++ b/core/java/android/bluetooth/le/PeriodicAdvertisingManager.java
@@ -0,0 +1,237 @@
+/*
+ * 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.
+ */
+
+package android.bluetooth.le;
+
+import android.bluetooth.BluetoothAdapter;
+import android.bluetooth.BluetoothDevice;
+import android.bluetooth.IBluetoothGatt;
+import android.bluetooth.IBluetoothManager;
+import android.os.Handler;
+import android.os.Looper;
+import android.os.RemoteException;
+import android.util.Log;
+import java.util.IdentityHashMap;
+import java.util.Map;
+
+/**
+ * This class provides methods to perform periodic advertising related
+ * operations. An application can register for periodic advertisements using
+ * {@link PeriodicAdvertisingManager#registerSync}.
+ * <p>
+ * Use {@link BluetoothAdapter#getPeriodicAdvertisingManager()} to get an
+ * instance of {@link PeriodicAdvertisingManager}.
+ * <p>
+ * <b>Note:</b> Most of the methods here require
+ * {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission.
+ */
+public final class PeriodicAdvertisingManager {
+
+  private static final String TAG = "PeriodicAdvertisingManager";
+
+  private static final int SKIP_MIN = 0;
+  private static final int SKIP_MAX = 499;
+  private static final int TIMEOUT_MIN = 10;
+  private static final int TIMEOUT_MAX = 16384;
+
+  private static final int SYNC_STARTING = -1;
+
+  private final IBluetoothManager mBluetoothManager;
+  private BluetoothAdapter mBluetoothAdapter;
+
+  /* maps callback, to callback wrapper and sync handle */
+  Map<PeriodicAdvertisingCallback,
+      IPeriodicAdvertisingCallback /* callbackWrapper */> callbackWrappers;
+
+  /**
+   * Use {@link BluetoothAdapter#getBluetoothLeScanner()} instead.
+   *
+   * @param bluetoothManager BluetoothManager that conducts overall Bluetooth Management.
+   * @hide
+   */
+  public PeriodicAdvertisingManager(IBluetoothManager bluetoothManager) {
+    mBluetoothManager = bluetoothManager;
+    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
+    callbackWrappers = new IdentityHashMap<>();
+  }
+
+  /**
+   * Synchronize with periodic advertising pointed to by the {@code scanResult}.
+   * The {@code scanResult} used must contain a valid advertisingSid. First
+   * call to registerSync will use the {@code skip} and {@code timeout} provided.
+   * Subsequent calls from other apps, trying to sync with same set will reuse
+   * existing sync, thus {@code skip} and {@code timeout} values will not take
+   * effect. The values in effect will be returned in
+   * {@link PeriodicAdvertisingCallback#onSyncEstablished}.
+   *
+   * @param scanResult Scan result containing advertisingSid.
+   * @param skip The number of periodic advertising packets that can be skipped
+   * after a successful receive. Must be between 0 and 499.
+   * @param timeout Synchronization timeout for the periodic advertising. One
+   * unit is 10ms. Must be between 10 (100ms) and 16384 (163.84s).
+   * @param callback Callback used to deliver all operations status.
+   * @throws IllegalArgumentException if {@code scanResult} is null or {@code
+   * skip} is invalid or {@code timeout} is invalid or {@code callback} is null.
+   */
+  public void registerSync(ScanResult scanResult, int skip, int timeout,
+                         PeriodicAdvertisingCallback callback) {
+    registerSync(scanResult, skip, timeout, callback, null);
+  }
+
+  /**
+   * Synchronize with periodic advertising pointed to by the {@code scanResult}.
+   * The {@code scanResult} used must contain a valid advertisingSid. First
+   * call to registerSync will use the {@code skip} and {@code timeout} provided.
+   * Subsequent calls from other apps, trying to sync with same set will reuse
+   * existing sync, thus {@code skip} and {@code timeout} values will not take
+   * effect. The values in effect will be returned in
+   * {@link PeriodicAdvertisingCallback#onSyncEstablished}.
+   *
+   * @param scanResult Scan result containing advertisingSid.
+   * @param skip The number of periodic advertising packets that can be skipped
+   * after a successful receive. Must be between 0 and 499.
+   * @param timeout Synchronization timeout for the periodic advertising. One
+   * unit is 10ms. Must be between 10 (100ms) and 16384 (163.84s).
+   * @param callback Callback used to deliver all operations status.
+   * @param handler thread upon which the callbacks will be invoked.
+   * @throws IllegalArgumentException if {@code scanResult} is null or {@code
+   * skip} is invalid or {@code timeout} is invalid or {@code callback} is null.
+   */
+  public void registerSync(ScanResult scanResult, int skip, int timeout,
+                         PeriodicAdvertisingCallback callback, Handler handler) {
+    if (callback == null) {
+      throw new IllegalArgumentException("callback can't be null");
+    }
+
+    if (scanResult == null) {
+      throw new IllegalArgumentException("scanResult can't be null");
+    }
+
+    if (scanResult.getAdvertisingSid() == ScanResult.SID_NOT_PRESENT) {
+      throw new IllegalArgumentException("scanResult must contain a valid sid");
+    }
+
+    if (skip < SKIP_MIN || skip > SKIP_MAX) {
+      throw new IllegalArgumentException(
+          "timeout must be between " + TIMEOUT_MIN + " and " + TIMEOUT_MAX);
+    }
+
+    if (timeout < TIMEOUT_MIN || timeout > TIMEOUT_MAX) {
+      throw new IllegalArgumentException(
+          "timeout must be between " + TIMEOUT_MIN + " and " + TIMEOUT_MAX);
+    }
+
+    IBluetoothGatt gatt;
+    try {
+        gatt = mBluetoothManager.getBluetoothGatt();
+    } catch (RemoteException e) {
+        Log.e(TAG, "Failed to get Bluetooth gatt - ", e);
+        callback.onSyncEstablished(0, scanResult.getDevice(), scanResult.getAdvertisingSid(),
+                                   skip, timeout,
+                                   PeriodicAdvertisingCallback.SYNC_NO_RESOURCES);
+        return;
+    }
+
+    if (handler == null)
+      handler = new Handler(Looper.getMainLooper());
+
+    IPeriodicAdvertisingCallback wrapped = wrap(callback, handler);
+    callbackWrappers.put(callback, wrapped);
+
+    try {
+      gatt.registerSync(scanResult, skip, timeout, wrapped);
+    } catch (RemoteException e) {
+      Log.e(TAG, "Failed to register sync - ", e);
+      return;
+    }
+  }
+
+  /**
+   * Cancel pending attempt to create sync, or terminate existing sync.
+   *
+   * @param callback Callback used to deliver all operations status.
+   * @throws IllegalArgumentException if {@code callback} is null, or not a properly
+   * registered callback.
+   */
+  public void unregisterSync(PeriodicAdvertisingCallback callback) {
+    if (callback == null) {
+      throw new IllegalArgumentException("callback can't be null");
+    }
+
+    IBluetoothGatt gatt;
+    try {
+        gatt = mBluetoothManager.getBluetoothGatt();
+    } catch (RemoteException e) {
+        Log.e(TAG, "Failed to get Bluetooth gatt - ", e);
+        return;
+    }
+
+    IPeriodicAdvertisingCallback wrapper = callbackWrappers.remove(callback);
+    if (wrapper == null) {
+      throw new IllegalArgumentException("callback was not properly registered");
+    }
+
+    try {
+      gatt.unregisterSync(wrapper);
+    } catch (RemoteException e) {
+        Log.e(TAG, "Failed to cancel sync creation - ", e);
+        return;
+    }
+  }
+
+  private IPeriodicAdvertisingCallback wrap(PeriodicAdvertisingCallback callback, Handler handler) {
+    return new IPeriodicAdvertisingCallback.Stub() {
+      public void onSyncEstablished(int syncHandle, BluetoothDevice device,
+                                    int advertisingSid, int skip, int timeout, int status) {
+
+          handler.post(new Runnable() {
+              @Override
+              public void run() {
+                  callback.onSyncEstablished(syncHandle, device, advertisingSid, skip, timeout,
+                                             status);
+
+                  if (status != PeriodicAdvertisingCallback.SYNC_SUCCESS) {
+                      // App can still unregister the sync until notified it failed. Remove callback
+                      // after app was notifed.
+                      callbackWrappers.remove(callback);
+                  }
+              }
+          });
+      }
+
+      public void onPeriodicAdvertisingReport(PeriodicAdvertisingReport report) {
+          handler.post(new Runnable() {
+              @Override
+              public void run() {
+                callback.onPeriodicAdvertisingReport(report);
+              }
+          });
+      }
+
+      public void onSyncLost(int syncHandle) {
+          handler.post(new Runnable() {
+              @Override
+              public void run() {
+                callback.onSyncLost(syncHandle);
+                // App can still unregister the sync until notified it's lost. Remove callback after
+                // app was notifed.
+                callbackWrappers.remove(callback);
+              }
+          });
+      }
+    };
+  }
+}
diff --git a/core/java/com/android/internal/logging/legacy/Util.java b/core/java/android/bluetooth/le/PeriodicAdvertisingParameters.aidl
similarity index 77%
copy from core/java/com/android/internal/logging/legacy/Util.java
copy to core/java/android/bluetooth/le/PeriodicAdvertisingParameters.aidl
index 99f71ca..f4bea22 100644
--- a/core/java/com/android/internal/logging/legacy/Util.java
+++ b/core/java/android/bluetooth/le/PeriodicAdvertisingParameters.aidl
@@ -13,13 +13,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package com.android.internal.logging.legacy;
 
-/**
- * Created by cwren on 11/21/16.
- */
-public class Util {
-    public static boolean debug() {
-        return false;
-    }
-}
+package android.bluetooth.le;
+
+parcelable PeriodicAdvertisingParameters;
diff --git a/core/java/android/bluetooth/le/PeriodicAdvertisingParameters.java b/core/java/android/bluetooth/le/PeriodicAdvertisingParameters.java
new file mode 100644
index 0000000..ebc92bd
--- /dev/null
+++ b/core/java/android/bluetooth/le/PeriodicAdvertisingParameters.java
@@ -0,0 +1,134 @@
+/*
+ * 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.
+ */
+
+package android.bluetooth.le;
+
+import android.os.Parcel;
+import android.os.Parcelable;
+
+/**
+ * The {@link PeriodicAdvertisingParameters} provide a way to adjust periodic
+ * advertising preferences for each Bluetooth LE advertising set. Use {@link
+ * AdvertisingSetParameters.Builder} to create an instance of this class.
+ */
+public final class PeriodicAdvertisingParameters implements Parcelable {
+
+    private static final int INTERVAL_MAX = 80;
+    private static final int INTERVAL_MIN = 65519;
+
+    private final boolean enable;
+    private final boolean includeTxPower;
+    private final int interval;
+
+    private PeriodicAdvertisingParameters(boolean enable, boolean includeTxPower, int interval) {
+        this.enable = enable;
+        this.includeTxPower = includeTxPower;
+        this.interval = interval;
+    }
+
+    private PeriodicAdvertisingParameters(Parcel in) {
+        enable = in.readInt() != 0 ? true : false;
+        includeTxPower = in.readInt() != 0 ? true : false;
+        interval = in.readInt();
+    }
+
+    /**
+     * Returns whether the periodic advertising shall be enabled.
+     */
+    public boolean getEnable() { return enable; }
+
+    /**
+     * Returns whether the TX Power will be included.
+     */
+    public boolean getIncludeTxPower() { return includeTxPower; }
+
+    /**
+     * Returns the periodic advertising interval, in 1.25ms unit.
+     * Valid values are from 80 (100ms) to 65519 (81.89875s).
+     */
+    public int getInterval() { return interval; }
+
+    @Override
+    public int describeContents() {
+        return 0;
+    }
+
+    @Override
+    public void writeToParcel(Parcel dest, int flags) {
+        dest.writeInt(enable ? 1 : 0);
+        dest.writeInt(includeTxPower ? 1 : 0);
+        dest.writeInt(interval);
+    }
+
+    public static final Parcelable
+        .Creator<PeriodicAdvertisingParameters> CREATOR =
+        new Creator<PeriodicAdvertisingParameters>() {
+            @Override
+            public PeriodicAdvertisingParameters[] newArray(int size) {
+                return new PeriodicAdvertisingParameters[size];
+            }
+
+            @Override
+            public PeriodicAdvertisingParameters createFromParcel(Parcel in) {
+                return new PeriodicAdvertisingParameters(in);
+            }
+        };
+
+    public static final class Builder {
+        private boolean includeTxPower = false;
+        private boolean enable = false;
+        private int interval = INTERVAL_MAX;
+
+        /**
+         * Set wether the Periodic Advertising should be enabled for this set.
+         */
+        public Builder setEnable(boolean enable) {
+            this.enable = enable;
+            return this;
+        }
+
+        /**
+         * Whether the transmission power level should be included in the periodic
+         * packet.
+         */
+        public Builder setIncludeTxPower(boolean includeTxPower) {
+            this.includeTxPower = includeTxPower;
+            return this;
+        }
+
+        /**
+         * Set advertising interval for periodic advertising, in 1.25ms unit.
+         * Valid values are from 80 (100ms) to 65519 (81.89875s).
+         * Value from range [interval, interval+20ms] will be picked as the actual value.
+         * @throws IllegalArgumentException If the interval is invalid.
+         */
+        public Builder setInterval(int interval) {
+            if (interval < INTERVAL_MIN || interval > INTERVAL_MAX) {
+                throw new IllegalArgumentException("Invalid interval (must be " + INTERVAL_MIN +
+                                                   "-" + INTERVAL_MAX + ")");
+            }
+            this.interval = interval;
+            return this;
+        }
+
+        /**
+         * Build the {@link AdvertisingSetParameters} object.
+         */
+        public PeriodicAdvertisingParameters build() {
+            return new PeriodicAdvertisingParameters(enable, includeTxPower, interval);
+        }
+    }
+}
diff --git a/core/java/com/android/internal/logging/legacy/Util.java b/core/java/android/bluetooth/le/PeriodicAdvertisingReport.aidl
similarity index 77%
copy from core/java/com/android/internal/logging/legacy/Util.java
copy to core/java/android/bluetooth/le/PeriodicAdvertisingReport.aidl
index 99f71ca..547d096 100644
--- a/core/java/com/android/internal/logging/legacy/Util.java
+++ b/core/java/android/bluetooth/le/PeriodicAdvertisingReport.aidl
@@ -13,13 +13,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package com.android.internal.logging.legacy;
 
-/**
- * Created by cwren on 11/21/16.
- */
-public class Util {
-    public static boolean debug() {
-        return false;
-    }
-}
+package android.bluetooth.le;
+
+parcelable PeriodicAdvertisingReport;
diff --git a/core/java/android/bluetooth/le/PeriodicAdvertisingReport.java b/core/java/android/bluetooth/le/PeriodicAdvertisingReport.java
new file mode 100644
index 0000000..3ff4ca5
--- /dev/null
+++ b/core/java/android/bluetooth/le/PeriodicAdvertisingReport.java
@@ -0,0 +1,184 @@
+/*
+ * 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.
+ */
+
+package android.bluetooth.le;
+
+import android.annotation.Nullable;
+import android.os.Parcel;
+import android.os.Parcelable;
+
+import java.util.Objects;
+
+/**
+ * PeriodicAdvertisingReport for Bluetooth LE synchronized advertising.
+ */
+public final class PeriodicAdvertisingReport implements Parcelable {
+
+    /**
+     * The data returned is complete
+     */
+    public static final int DATA_COMPLETE = 0;
+
+    /**
+     * The data returned is incomplete. The controller was unsuccessfull to
+     * receive all chained packets, returning only partial data.
+     */
+    public static final int DATA_INCOMPLETE_TRUNCATED = 2;
+
+    private int syncHandle;
+    private int txPower;
+    private int rssi;
+    private int dataStatus;
+
+    // periodic advertising data.
+    @Nullable
+    private ScanRecord data;
+
+    // Device timestamp when the result was last seen.
+    private long timestampNanos;
+
+    /**
+     * Constructor of periodic advertising result.
+     *
+     */
+    public PeriodicAdvertisingReport(int syncHandle, int txPower, int rssi,
+                                     int dataStatus, ScanRecord data) {
+        this.syncHandle = syncHandle;
+        this.txPower = txPower;
+        this.rssi = rssi;
+        this.dataStatus = dataStatus;
+        this.data = data;
+    }
+
+    private PeriodicAdvertisingReport(Parcel in) {
+        readFromParcel(in);
+    }
+
+    @Override
+    public void writeToParcel(Parcel dest, int flags) {
+        dest.writeInt(syncHandle);
+        dest.writeLong(txPower);
+        dest.writeInt(rssi);
+        dest.writeInt(dataStatus);
+        if (data != null) {
+            dest.writeInt(1);
+            dest.writeByteArray(data.getBytes());
+        } else {
+            dest.writeInt(0);
+        }
+    }
+
+    private void readFromParcel(Parcel in) {
+        syncHandle = in.readInt();
+        txPower = in.readInt();
+        rssi = in.readInt();
+        dataStatus = in.readInt();
+        if (in.readInt() == 1) {
+            data = ScanRecord.parseFromBytes(in.createByteArray());
+        }
+    }
+
+    @Override
+    public int describeContents() {
+        return 0;
+    }
+
+    /**
+     * Returns the synchronization handle.
+     */
+    public int getSyncHandle() {
+        return syncHandle;
+    }
+
+    /**
+     * Returns the transmit power in dBm. The valid range is [-127, 126]. Value
+     * of 127 means information was not available.
+     */
+    public int getTxPower() {
+        return txPower;
+    }
+
+    /**
+     * Returns the received signal strength in dBm. The valid range is [-127, 20].
+     */
+    public int getRssi() {
+        return rssi;
+    }
+
+    /**
+     * Returns the data status. Can be one of {@link PeriodicAdvertisingReport#DATA_COMPLETE}
+     * or {@link PeriodicAdvertisingReport#DATA_INCOMPLETE_TRUNCATED}.
+     */
+    public int getDataStatus() {
+        return dataStatus;
+    }
+
+    /**
+     * Returns the data contained in this periodic advertising report.
+     */
+    @Nullable
+    public ScanRecord getData() {
+        return data;
+    }
+
+    /**
+     * Returns timestamp since boot when the scan record was observed.
+     */
+    public long getTimestampNanos() {
+        return timestampNanos;
+    }
+
+    @Override
+    public int hashCode() {
+        return Objects.hash(syncHandle, txPower, rssi, dataStatus, data, timestampNanos);
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+        if (obj == null || getClass() != obj.getClass()) {
+            return false;
+        }
+        PeriodicAdvertisingReport other = (PeriodicAdvertisingReport) obj;
+        return (syncHandle == other.syncHandle) &&
+            (txPower == other.txPower) &&
+            (rssi == other.rssi) &&
+            (dataStatus == other.dataStatus) &&
+            Objects.equals(data, other.data) &&
+            (timestampNanos == other.timestampNanos);
+    }
+
+    @Override
+    public String toString() {
+      return "PeriodicAdvertisingReport{syncHandle=" + syncHandle +
+          ", txPower=" + txPower + ", rssi=" + rssi + ", dataStatus=" + dataStatus +
+          ", data=" + Objects.toString(data) + ", timestampNanos=" + timestampNanos + '}';
+    }
+
+    public static final Parcelable.Creator<PeriodicAdvertisingReport> CREATOR = new Creator<PeriodicAdvertisingReport>() {
+            @Override
+        public PeriodicAdvertisingReport createFromParcel(Parcel source) {
+            return new PeriodicAdvertisingReport(source);
+        }
+
+            @Override
+        public PeriodicAdvertisingReport[] newArray(int size) {
+            return new PeriodicAdvertisingReport[size];
+        }
+    };
+}
diff --git a/core/java/android/bluetooth/le/ScanResult.java b/core/java/android/bluetooth/le/ScanResult.java
index 2fdfe7f..583ddd2 100644
--- a/core/java/android/bluetooth/le/ScanResult.java
+++ b/core/java/android/bluetooth/le/ScanResult.java
@@ -27,7 +27,56 @@
  * ScanResult for Bluetooth LE scan.
  */
 public final class ScanResult implements Parcelable {
-    // Remote bluetooth device.
+
+    /**
+     * For chained advertisements, inidcates tha the data contained in this
+     * scan result is complete.
+     */
+    public static final int DATA_COMPLETE = 0x00;
+
+    /**
+     * For chained advertisements, indicates that the controller was
+     * unable to receive all chained packets and the scan result contains
+     * incomplete truncated data.
+     */
+    public static final int DATA_TRUNCATED = 0x02;
+
+    /**
+     * Indicates that the secondary physical layer was not used.
+     */
+    public static final int PHY_UNUSED = 0x00;
+
+    /**
+     * Bluetooth LE 1Mbit advertiser PHY.
+     */
+    public static final int PHY_LE_1M = 0x01;
+
+    /**
+     * Bluetooth LE 2Mbit advertiser PHY.
+     */
+    public static final int PHY_LE_2M = 0x02;
+
+    /**
+     * Bluetooth LE Coded advertiser PHY.
+     */
+    public static final int PHY_LE_CODED = 0x03;
+
+    /**
+     * Advertising Set ID is not present in the packet.
+     */
+    public static final int SID_NOT_PRESENT = 0xFF;
+
+    /**
+     * Mask for checking wether event type represents legacy advertisement.
+     */
+    private static final int ET_LEGACY_MASK = 0x10;
+
+    /**
+     * Mask for checking wether event type represents connectable advertisement.
+     */
+    private static final int ET_CONNECTABLE_MASK = 0x01;
+
+    // Remote Bluetooth device.
     private BluetoothDevice mDevice;
 
     // Scan record, including advertising data and scan response data.
@@ -40,13 +89,21 @@
     // Device timestamp when the result was last seen.
     private long mTimestampNanos;
 
+    private int mEventType;
+    private int mPrimaryPhy;
+    private int mSecondaryPhy;
+    private int mAdvertisingSid;
+    private int mTxPower;
+    private int mPeriodicAdvertisingInterval;
+
     /**
-     * Constructor of scan result.
+     * Constructs a new ScanResult.
      *
-     * @param device Remote bluetooth device that is found.
+     * @param device Remote Bluetooth device found.
      * @param scanRecord Scan record including both advertising data and scan response data.
      * @param rssi Received signal strength.
-     * @param timestampNanos Device timestamp when the scan result was observed.
+     * @param timestampNanos Timestamp at which the scan result was observed.
+     * @deprecated use {@link #ScanResult(BluetoothDevice, int, int, int, int, int, int, int, ScanRecord, long)}
      */
     public ScanResult(BluetoothDevice device, ScanRecord scanRecord, int rssi,
             long timestampNanos) {
@@ -54,6 +111,41 @@
         mScanRecord = scanRecord;
         mRssi = rssi;
         mTimestampNanos = timestampNanos;
+        mEventType = (DATA_COMPLETE << 5) | ET_LEGACY_MASK | ET_CONNECTABLE_MASK;
+        mPrimaryPhy = PHY_LE_1M;
+        mSecondaryPhy = PHY_UNUSED;
+        mAdvertisingSid = SID_NOT_PRESENT;
+        mTxPower = 127;
+        mPeriodicAdvertisingInterval = 0;
+    }
+
+    /**
+     * Constructs a new ScanResult.
+     *
+     * @param device Remote Bluetooth device found.
+     * @param eventType Event type.
+     * @param primaryPhy Primary advertising phy.
+     * @param secondaryPhy Secondary advertising phy.
+     * @param advertisingSid Advertising set ID.
+     * @param txPower Transmit power.
+     * @param rssi Received signal strength.
+     * @param periodicAdvertisingInterval Periodic advertising interval.
+     * @param scanRecord Scan record including both advertising data and scan response data.
+     * @param timestampNanos Timestamp at which the scan result was observed.
+     */
+    public ScanResult(BluetoothDevice device, int eventType, int primaryPhy, int secondaryPhy,
+                      int advertisingSid, int txPower, int rssi, int periodicAdvertisingInterval,
+                      ScanRecord scanRecord, long timestampNanos) {
+        mDevice = device;
+        mEventType = eventType;
+        mPrimaryPhy = primaryPhy;
+        mSecondaryPhy = secondaryPhy;
+        mAdvertisingSid = advertisingSid;
+        mTxPower = txPower;
+        mRssi = rssi;
+        mPeriodicAdvertisingInterval = periodicAdvertisingInterval;
+        mScanRecord = scanRecord;
+        mTimestampNanos = timestampNanos;
     }
 
     private ScanResult(Parcel in) {
@@ -76,6 +168,12 @@
         }
         dest.writeInt(mRssi);
         dest.writeLong(mTimestampNanos);
+        dest.writeInt(mEventType);
+        dest.writeInt(mPrimaryPhy);
+        dest.writeInt(mSecondaryPhy);
+        dest.writeInt(mAdvertisingSid);
+        dest.writeInt(mTxPower);
+        dest.writeInt(mPeriodicAdvertisingInterval);
     }
 
     private void readFromParcel(Parcel in) {
@@ -87,6 +185,12 @@
         }
         mRssi = in.readInt();
         mTimestampNanos = in.readLong();
+        mEventType = in.readInt();
+        mPrimaryPhy = in.readInt();
+        mSecondaryPhy = in.readInt();
+        mAdvertisingSid = in.readInt();
+        mTxPower = in.readInt();
+        mPeriodicAdvertisingInterval = in.readInt();
     }
 
     @Override
@@ -95,7 +199,7 @@
     }
 
     /**
-     * Returns the remote bluetooth device identified by the bluetooth device address.
+     * Returns the remote Bluetooth device identified by the Bluetooth device address.
      */
     public BluetoothDevice getDevice() {
         return mDevice;
@@ -110,7 +214,7 @@
     }
 
     /**
-     * Returns the received signal strength in dBm. The valid range is [-127, 127].
+     * Returns the received signal strength in dBm. The valid range is [-127, 126].
      */
     public int getRssi() {
         return mRssi;
@@ -123,9 +227,79 @@
         return mTimestampNanos;
     }
 
+    /**
+     * Returns true if this object represents legacy scan result.
+     * Legacy scan results do not contain advanced advertising information
+     * as specified in the Bluetooth Core Specification v5.
+     */
+    public boolean isLegacy() {
+        return (mEventType & ET_LEGACY_MASK) != 0;
+    }
+
+    /**
+     * Returns true if this object represents connectable scan result.
+     */
+    public boolean isConnectable() {
+        return (mEventType & ET_CONNECTABLE_MASK) != 0;
+    }
+
+    /**
+     * Returns the data status.
+     * Can be one of {@link ScanResult#DATA_COMPLETE} or
+     * {@link ScanResult#DATA_TRUNCATED}.
+     */
+    public int getDataStatus() {
+        // return bit 5 and 6
+        return (mEventType >> 5) & 0x03;
+    }
+
+    /**
+     * Returns the primary Physical Layer
+     * on which this advertisment was received.
+     * Can be one of {@link ScanResult#PHY_LE_1M} or
+     * {@link ScanResult#PHY_LE_CODED}.
+     */
+    public int getPrimaryPhy() { return mPrimaryPhy; }
+
+    /**
+     * Returns the secondary Physical Layer
+     * on which this advertisment was received.
+     * Can be one of {@link ScanResult#PHY_LE_1M},
+     * {@link ScanResult#PHY_LE_2M}, {@link ScanResult#PHY_LE_CODED}
+     * or {@link ScanResult#PHY_UNUSED} - if the advertisement
+     * was not received on a secondary physical channel.
+     */
+    public int getSecondaryPhy() { return mSecondaryPhy; }
+
+    /**
+     * Returns the advertising set id.
+     * May return {@link ScanResult#SID_NOT_PRESENT} if
+     * no set id was is present.
+     */
+    public int getAdvertisingSid() { return mAdvertisingSid; }
+
+    /**
+     * Returns the transmit power in dBm.
+     * Valid range is [-127, 126]. A value of 127 indicates that the
+     * advertisement did not indicate TX power.
+     */
+    public int getTxPower() { return mTxPower; }
+
+    /**
+     * Returns the periodic advertising interval in units of 1.25ms.
+     * Valid range is 6 (7.5ms) to 65536 (81918.75ms). A value of 0 means
+     * periodic advertising is not used for this scan result.
+     */
+    public int getPeriodicAdvertisingInterval() {
+        return mPeriodicAdvertisingInterval;
+    }
+
     @Override
     public int hashCode() {
-        return Objects.hash(mDevice, mRssi, mScanRecord, mTimestampNanos);
+        return Objects.hash(mDevice, mRssi, mScanRecord, mTimestampNanos,
+                            mEventType, mPrimaryPhy, mSecondaryPhy,
+                            mAdvertisingSid, mTxPower,
+                            mPeriodicAdvertisingInterval);
     }
 
     @Override
@@ -138,15 +312,24 @@
         }
         ScanResult other = (ScanResult) obj;
         return Objects.equals(mDevice, other.mDevice) && (mRssi == other.mRssi) &&
-                Objects.equals(mScanRecord, other.mScanRecord)
-                && (mTimestampNanos == other.mTimestampNanos);
+            Objects.equals(mScanRecord, other.mScanRecord) &&
+            (mTimestampNanos == other.mTimestampNanos) &&
+            mEventType == other.mEventType &&
+            mPrimaryPhy == other.mPrimaryPhy &&
+            mSecondaryPhy == other.mSecondaryPhy &&
+            mAdvertisingSid == other.mAdvertisingSid &&
+            mTxPower == other.mTxPower &&
+            mPeriodicAdvertisingInterval == other.mPeriodicAdvertisingInterval;
     }
 
     @Override
     public String toString() {
-        return "ScanResult{" + "mDevice=" + mDevice + ", mScanRecord="
-                + Objects.toString(mScanRecord) + ", mRssi=" + mRssi + ", mTimestampNanos="
-                + mTimestampNanos + '}';
+      return "ScanResult{" + "device=" + mDevice + ", scanRecord=" +
+          Objects.toString(mScanRecord) + ", rssi=" + mRssi +
+          ", timestampNanos=" + mTimestampNanos + ", eventType=" + mEventType +
+          ", primaryPhy=" + mPrimaryPhy + ", secondaryPhy=" + mSecondaryPhy +
+          ", advertisingSid=" + mAdvertisingSid + ", txPower=" + mTxPower +
+          ", periodicAdvertisingInterval=" + mPeriodicAdvertisingInterval + '}';
     }
 
     public static final Parcelable.Creator<ScanResult> CREATOR = new Creator<ScanResult>() {
diff --git a/core/java/android/bluetooth/le/ScanSettings.java b/core/java/android/bluetooth/le/ScanSettings.java
index d616624..69c9a8c 100644
--- a/core/java/android/bluetooth/le/ScanSettings.java
+++ b/core/java/android/bluetooth/le/ScanSettings.java
@@ -122,6 +122,24 @@
     @SystemApi
     public static final int SCAN_RESULT_TYPE_ABBREVIATED = 1;
 
+    /**
+     * Use the Bluetooth LE 1Mbit PHY for scanning.
+     */
+    public static final int PHY_LE_1M = 1;
+
+    /**
+     * Use Bluetooth LE Coded PHY for scanning.
+     */
+    public static final int PHY_LE_CODED = 3;
+
+    /**
+     * Use all supported PHYs for scanning.
+     * This will check the controller capabilities, and start
+     * the scan on 1Mbit and LE Coded PHYs if supported, or on
+     * the 1Mbit PHY only.
+     */
+    public static final int PHY_LE_ALL_SUPPORTED = 255;
+
     // Bluetooth LE scan mode.
     private int mScanMode;
 
@@ -138,6 +156,11 @@
 
     private int mNumOfMatchesPerFilter;
 
+    // Include only legacy advertising results
+    private boolean mLegacy;
+
+    private int mPhy;
+
     public int getScanMode() {
         return mScanMode;
     }
@@ -165,6 +188,22 @@
     }
 
     /**
+     * Returns whether only legacy advertisements will be returned.
+     * Legacy advertisements include advertisements as specified
+     * by the Bluetooth core specification 4.2 and below.
+     */
+    public boolean getLegacy() {
+        return mLegacy;
+    }
+
+    /**
+     * Returns the physical layer used during a scan.
+     */
+    public int getPhy() {
+        return mPhy;
+    }
+
+    /**
      * Returns report delay timestamp based on the device clock.
      */
     public long getReportDelayMillis() {
@@ -172,13 +211,16 @@
     }
 
     private ScanSettings(int scanMode, int callbackType, int scanResultType,
-            long reportDelayMillis, int matchMode, int numOfMatchesPerFilter) {
+                         long reportDelayMillis, int matchMode,
+                         int numOfMatchesPerFilter, boolean legacy, int phy) {
         mScanMode = scanMode;
         mCallbackType = callbackType;
         mScanResultType = scanResultType;
         mReportDelayMillis = reportDelayMillis;
         mNumOfMatchesPerFilter = numOfMatchesPerFilter;
         mMatchMode = matchMode;
+        mLegacy = legacy;
+        mPhy = phy;
     }
 
     private ScanSettings(Parcel in) {
@@ -188,6 +230,8 @@
         mReportDelayMillis = in.readLong();
         mMatchMode = in.readInt();
         mNumOfMatchesPerFilter = in.readInt();
+        mLegacy = in.readInt() != 0 ? true : false;
+        mPhy = in.readInt();
     }
 
     @Override
@@ -198,6 +242,8 @@
         dest.writeLong(mReportDelayMillis);
         dest.writeInt(mMatchMode);
         dest.writeInt(mNumOfMatchesPerFilter);
+        dest.writeInt(mLegacy ? 1 : 0);
+        dest.writeInt(mPhy);
     }
 
     @Override
@@ -228,6 +274,9 @@
         private long mReportDelayMillis = 0;
         private int mMatchMode = MATCH_MODE_AGGRESSIVE;
         private int mNumOfMatchesPerFilter  = MATCH_NUM_MAX_ADVERTISEMENT;
+        private boolean mLegacy = true;
+        private int mPhy = PHY_LE_ALL_SUPPORTED;
+
         /**
          * Set scan mode for Bluetooth LE scan.
          *
@@ -341,11 +390,44 @@
         }
 
         /**
+         * Set whether only legacy advertisments should be returned in scan results.
+         * Legacy advertisements include advertisements as specified by the
+         * Bluetooth core specification 4.2 and below. This is true by default
+         * for compatibility with older apps.
+         *
+         * @param legacy true if only legacy advertisements will be returned
+         */
+        public Builder setLegacy(boolean legacy) {
+            mLegacy = legacy;
+            return this;
+        }
+
+        /**
+         * Set the Physical Layer to use during this scan.
+         * This is used only if {@link ScanSettings.Builder#setLegacy}
+         * is set to false.
+         * {@link android.bluetooth.BluetoothAdapter#isLeCodedPhySupported}
+         * may be used to check whether LE Coded phy is supported by calling
+         * {@link android.bluetooth.BluetoothAdapter#isLeCodedPhySupported}.
+         * Selecting an unsupported phy will result in failure to start scan.
+         *
+         * @param phy Can be one of
+         *   {@link ScanSettings#PHY_LE_1M},
+         *   {@link ScanSettings#PHY_LE_CODED} or
+         *   {@link ScanSettings#PHY_LE_ALL_SUPPORTED}
+         */
+        public Builder setPhy(int phy) {
+            mPhy = phy;
+            return this;
+        }
+
+        /**
          * Build {@link ScanSettings}.
          */
         public ScanSettings build() {
             return new ScanSettings(mScanMode, mCallbackType, mScanResultType,
-                    mReportDelayMillis, mMatchMode, mNumOfMatchesPerFilter);
+                                    mReportDelayMillis, mMatchMode,
+                                    mNumOfMatchesPerFilter, mLegacy, mPhy);
         }
     }
 }
diff --git a/core/java/android/companion/CompanionDeviceManager.java b/core/java/android/companion/CompanionDeviceManager.java
index c0c1a4d..6fa32b4 100644
--- a/core/java/android/companion/CompanionDeviceManager.java
+++ b/core/java/android/companion/CompanionDeviceManager.java
@@ -26,6 +26,8 @@
 import android.os.Looper;
 import android.os.RemoteException;
 
+import java.util.List;
+
 /**
  * System level service for managing companion devices
  *
@@ -102,6 +104,11 @@
      * special capabilities have a negative effect on the device's battery and user's data
      * usage, therefore you should requested them when absolutely necessary.</p>
      *
+     * <p>You can call {@link #getAssociations} to get the list of currently associated
+     * devices, and {@link #disassociate} to remove an association. Consider doing so when the
+     * association is no longer relevant to avoid unnecessary battery and/or data drain resulting
+     * from special privileges that the association provides</p>
+     *
      * @param request specific details about this request
      * @param callback will be called once there's at least one device found for user to choose from
      * @param handler A handler to control which thread the callback will be delivered on, or null,
@@ -119,6 +126,8 @@
         try {
             mService.associate(
                     request,
+                    //TODO implicit pointer to outer class -> =null onDestroy
+                    //TODO onStop if isFinishing -> stopScan
                     new IFindDeviceCallback.Stub() {
                         @Override
                         public void onSuccess(PendingIntent launcher) {
@@ -138,6 +147,38 @@
         }
     }
 
+    /**
+     * @return a list of MAC addresses of devices that have been previously associated with the
+     * current app. You can use these with {@link #disassociate}
+     */
+    @NonNull
+    public List<String> getAssociations() {
+        try {
+            return mService.getAssociations(mContext.getPackageName());
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Remove the association between this app and the device with the given mac address.
+     *
+     * <p>Any privileges provided via being associated with a given device will be revoked</p>
+     *
+     * <p>Consider doing so when the
+     * association is no longer relevant to avoid unnecessary battery and/or data drain resulting
+     * from special privileges that the association provides</p>
+     *
+     * @param deviceMacAddress the MAC address of device to disassociate from this app
+     */
+    public void disassociate(@NonNull String deviceMacAddress) {
+        try {
+            mService.disassociate(deviceMacAddress, mContext.getPackageName());
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
     /** @hide */
     public void requestNotificationAccess() {
         //TODO implement
diff --git a/core/java/android/companion/ICompanionDeviceDiscoveryService.aidl b/core/java/android/companion/ICompanionDeviceDiscoveryService.aidl
index 4d77963..5398c3c 100644
--- a/core/java/android/companion/ICompanionDeviceDiscoveryService.aidl
+++ b/core/java/android/companion/ICompanionDeviceDiscoveryService.aidl
@@ -20,6 +20,7 @@
 import android.companion.ICompanionDeviceDiscoveryServiceCallback;
 import android.companion.IFindDeviceCallback;
 
+
 /** @hide */
 interface ICompanionDeviceDiscoveryService {
     void startDiscovery(
diff --git a/core/java/android/companion/ICompanionDeviceDiscoveryServiceCallback.aidl b/core/java/android/companion/ICompanionDeviceDiscoveryServiceCallback.aidl
index 7af708e..6bbb58da 100644
--- a/core/java/android/companion/ICompanionDeviceDiscoveryServiceCallback.aidl
+++ b/core/java/android/companion/ICompanionDeviceDiscoveryServiceCallback.aidl
@@ -18,5 +18,5 @@
 
 /** @hide */
 interface ICompanionDeviceDiscoveryServiceCallback {
-    void onDeviceSelected(String packageName, int userId);
+    oneway void onDeviceSelected(String packageName, int userId, String deviceAddress);
 }
diff --git a/core/java/android/companion/ICompanionDeviceManager.aidl b/core/java/android/companion/ICompanionDeviceManager.aidl
index 1d30ada..495141d 100644
--- a/core/java/android/companion/ICompanionDeviceManager.aidl
+++ b/core/java/android/companion/ICompanionDeviceManager.aidl
@@ -29,6 +29,9 @@
         in IFindDeviceCallback callback,
         in String callingPackage);
 
+    List<String> getAssociations(String callingPackage);
+    void disassociate(String deviceMacAddress, String callingPackage);
+
     //TODO add these
 //    boolean haveNotificationAccess(String packageName);
 //    oneway void requestNotificationAccess(String packageName);
diff --git a/core/java/android/content/IntentFilter.java b/core/java/android/content/IntentFilter.java
index 56609eb..93204d1 100644
--- a/core/java/android/content/IntentFilter.java
+++ b/core/java/android/content/IntentFilter.java
@@ -16,6 +16,7 @@
 
 package android.content;
 
+import android.annotation.SystemApi;
 import android.net.Uri;
 import android.os.Parcel;
 import android.os.Parcelable;
@@ -138,6 +139,7 @@
  * will only match an Intent that does not have any categories.
  */
 public class IntentFilter implements Parcelable {
+    private static final String AGLOB_STR = "aglob";
     private static final String SGLOB_STR = "sglob";
     private static final String PREFIX_STR = "prefix";
     private static final String LITERAL_STR = "literal";
@@ -482,11 +484,13 @@
     }
 
     /** @hide */
+    @SystemApi
     public final void setOrder(int order) {
         mOrder = order;
     }
 
     /** @hide */
+    @SystemApi
     public final int getOrder() {
         return mOrder;
     }
@@ -1594,6 +1598,9 @@
                 case PatternMatcher.PATTERN_SIMPLE_GLOB:
                     serializer.attribute(null, SGLOB_STR, pe.getPath());
                     break;
+                case PatternMatcher.PATTERN_ADVANCED_GLOB:
+                    serializer.attribute(null, AGLOB_STR, pe.getPath());
+                    break;
             }
             serializer.endTag(null, SSP_STR);
         }
@@ -1621,6 +1628,9 @@
                 case PatternMatcher.PATTERN_SIMPLE_GLOB:
                     serializer.attribute(null, SGLOB_STR, pe.getPath());
                     break;
+                case PatternMatcher.PATTERN_ADVANCED_GLOB:
+                    serializer.attribute(null, AGLOB_STR, pe.getPath());
+                    break;
             }
             serializer.endTag(null, PATH_STR);
         }
@@ -1673,6 +1683,8 @@
                     addDataSchemeSpecificPart(ssp, PatternMatcher.PATTERN_PREFIX);
                 } else if ((ssp=parser.getAttributeValue(null, SGLOB_STR)) != null) {
                     addDataSchemeSpecificPart(ssp, PatternMatcher.PATTERN_SIMPLE_GLOB);
+                } else if ((ssp=parser.getAttributeValue(null, AGLOB_STR)) != null) {
+                    addDataSchemeSpecificPart(ssp, PatternMatcher.PATTERN_ADVANCED_GLOB);
                 }
             } else if (tagName.equals(AUTH_STR)) {
                 String host = parser.getAttributeValue(null, HOST_STR);
@@ -1688,6 +1700,8 @@
                     addDataPath(path, PatternMatcher.PATTERN_PREFIX);
                 } else if ((path=parser.getAttributeValue(null, SGLOB_STR)) != null) {
                     addDataPath(path, PatternMatcher.PATTERN_SIMPLE_GLOB);
+                } else if ((path=parser.getAttributeValue(null, AGLOB_STR)) != null) {
+                    addDataPath(path, PatternMatcher.PATTERN_ADVANCED_GLOB);
                 }
             } else {
                 Log.w("IntentFilter", "Unknown tag parsing IntentFilter: " + tagName);
diff --git a/core/java/android/content/pm/PackageManager.java b/core/java/android/content/pm/PackageManager.java
index b3b5bcf..664e76b 100644
--- a/core/java/android/content/pm/PackageManager.java
+++ b/core/java/android/content/pm/PackageManager.java
@@ -133,6 +133,7 @@
             MATCH_SYSTEM_ONLY,
             MATCH_FACTORY_ONLY,
             MATCH_DEBUG_TRIAGED_MISSING,
+            MATCH_INSTANT,
             GET_DISABLED_COMPONENTS,
             GET_DISABLED_UNTIL_USED_COMPONENTS,
             GET_UNINSTALLED_PACKAGES,
@@ -148,6 +149,7 @@
             MATCH_SYSTEM_ONLY,
             MATCH_DEBUG_TRIAGED_MISSING,
             MATCH_DISABLED_UNTIL_USED_COMPONENTS,
+            MATCH_INSTANT,
             GET_DISABLED_UNTIL_USED_COMPONENTS,
             GET_UNINSTALLED_PACKAGES,
     })
@@ -167,6 +169,7 @@
             MATCH_DIRECT_BOOT_UNAWARE,
             MATCH_SYSTEM_ONLY,
             MATCH_UNINSTALLED_PACKAGES,
+            MATCH_INSTANT,
             GET_DISABLED_COMPONENTS,
             GET_DISABLED_UNTIL_USED_COMPONENTS,
             GET_UNINSTALLED_PACKAGES,
@@ -188,6 +191,7 @@
             MATCH_DIRECT_BOOT_UNAWARE,
             MATCH_SYSTEM_ONLY,
             MATCH_UNINSTALLED_PACKAGES,
+            MATCH_INSTANT,
             GET_DISABLED_COMPONENTS,
             GET_DISABLED_UNTIL_USED_COMPONENTS,
             GET_UNINSTALLED_PACKAGES,
@@ -444,6 +448,7 @@
      * instant app. By default, instant app components are not matched.
      * @hide
      */
+    @SystemApi
     public static final int MATCH_INSTANT = 0x00800000;
 
     /**
@@ -3739,6 +3744,7 @@
      *
      * @hide
      */
+    @SystemApi
     @RequiresPermission(Manifest.permission.ACCESS_INSTANT_APPS)
     public abstract @NonNull List<InstantAppInfo> getInstantApps();
 
@@ -3749,6 +3755,7 @@
      *
      * @hide
      */
+    @SystemApi
     @RequiresPermission(Manifest.permission.ACCESS_INSTANT_APPS)
     public abstract @Nullable Drawable getInstantAppIcon(String packageName);
 
diff --git a/core/java/android/content/pm/PackageParser.java b/core/java/android/content/pm/PackageParser.java
index 60cc6b0..a1c325a 100644
--- a/core/java/android/content/pm/PackageParser.java
+++ b/core/java/android/content/pm/PackageParser.java
@@ -4867,6 +4867,13 @@
                             PatternMatcher.PATTERN_SIMPLE_GLOB, readPermission, writePermission);
                 }
 
+                path = sa.getNonConfigurationString(
+                        com.android.internal.R.styleable.AndroidManifestPathPermission_pathAdvancedPattern, 0);
+                if (path != null) {
+                    pa = new PathPermission(path,
+                            PatternMatcher.PATTERN_ADVANCED_GLOB, readPermission, writePermission);
+                }
+
                 sa.recycle();
 
                 if (pa != null) {
@@ -5389,6 +5396,16 @@
                     outInfo.addDataPath(str, PatternMatcher.PATTERN_SIMPLE_GLOB);
                 }
 
+                str = sa.getNonConfigurationString(
+                        com.android.internal.R.styleable.AndroidManifestData_pathAdvancedPattern, 0);
+                if (str != null) {
+                    if (!allowGlobs) {
+                        outError[0] = "pathAdvancedPattern not allowed here; path must be literal";
+                        return false;
+                    }
+                    outInfo.addDataPath(str, PatternMatcher.PATTERN_ADVANCED_GLOB);
+                }
+
                 sa.recycle();
                 XmlUtils.skipCurrentTag(parser);
             } else if (!RIGID_PARSER) {
diff --git a/core/java/android/content/pm/PackageStats.java b/core/java/android/content/pm/PackageStats.java
index cb9039b..c746af4 100644
--- a/core/java/android/content/pm/PackageStats.java
+++ b/core/java/android/content/pm/PackageStats.java
@@ -19,6 +19,9 @@
 import android.os.Parcel;
 import android.os.Parcelable;
 import android.os.UserHandle;
+import android.text.TextUtils;
+
+import java.util.Objects;
 
 /**
  * implementation of PackageStats associated with a
@@ -173,4 +176,31 @@
         dest.writeLong(externalMediaSize);
         dest.writeLong(externalObbSize);
     }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (!(obj instanceof PackageStats)) {
+            return false;
+        }
+
+        final PackageStats otherStats = (PackageStats) obj;
+        return ((TextUtils.equals(packageName, otherStats.packageName))
+                && userHandle == otherStats.userHandle
+                && codeSize == otherStats.codeSize
+                && dataSize == otherStats.dataSize
+                && cacheSize == otherStats.cacheSize
+                && externalCodeSize == otherStats.externalCodeSize
+                && externalDataSize == otherStats.externalDataSize
+                && externalCacheSize == otherStats.externalCacheSize
+                && externalMediaSize == otherStats.externalMediaSize
+                && externalObbSize == otherStats.externalObbSize);
+    }
+
+    @Override
+    public int hashCode() {
+        return Objects.hash(packageName, userHandle, codeSize, dataSize,
+                cacheSize, externalCodeSize, externalDataSize, externalCacheSize, externalMediaSize,
+                externalObbSize);
+    }
+
 }
diff --git a/core/java/android/content/res/FontResourcesParser.java b/core/java/android/content/res/FontResourcesParser.java
index 3f8f90e..50fc344 100644
--- a/core/java/android/content/res/FontResourcesParser.java
+++ b/core/java/android/content/res/FontResourcesParser.java
@@ -67,13 +67,14 @@
         AttributeSet attrs = Xml.asAttributeSet(parser);
         TypedArray array = resources.obtainAttributes(attrs, R.styleable.FontFamily);
         String authority = array.getString(R.styleable.FontFamily_fontProviderAuthority);
+        String providerPackage = array.getString(R.styleable.FontFamily_fontProviderPackage);
         String query = array.getString(R.styleable.FontFamily_fontProviderQuery);
         array.recycle();
-        if (authority != null && query != null) {
+        if (authority != null && providerPackage != null && query != null) {
             while (parser.next() != XmlPullParser.END_TAG) {
                 skip(parser);
             }
-            return new FontConfig.Family(authority, query);
+            return new FontConfig.Family(authority, providerPackage, query);
         }
         List<FontConfig.Font> fonts = new ArrayList<>();
         while (parser.next() != XmlPullParser.END_TAG) {
diff --git a/core/java/android/hardware/SensorDirectChannel.java b/core/java/android/hardware/SensorDirectChannel.java
index 0efd62b..a65d57d 100644
--- a/core/java/android/hardware/SensorDirectChannel.java
+++ b/core/java/android/hardware/SensorDirectChannel.java
@@ -135,8 +135,8 @@
     }
 
     /**
-     * This function encode handle information in {@link android.os.Memory} into a long array to be
-     * passed down to native methods.
+     * This function encode handle information in {@link android.os.MemoryFile} into a long array to
+     * be passed down to native methods.
      *
      * @hide */
     static long[] encodeData(MemoryFile ashmem) {
diff --git a/core/java/android/hardware/SensorManager.java b/core/java/android/hardware/SensorManager.java
index cfda2f4..a6930b0 100644
--- a/core/java/android/hardware/SensorManager.java
+++ b/core/java/android/hardware/SensorManager.java
@@ -895,7 +895,7 @@
      * @see #configureDirectChannel(SensorDirectChannel, Sensor, int)
      */
     public SensorDirectChannel createDirectChannel(MemoryFile mem) {
-        return createDirectChannelImpl(mem.length(), mem, null);
+        return createDirectChannelImpl(mem, null);
     }
 
     /**
@@ -913,12 +913,12 @@
      * @see #configureDirectChannel(SensorDirectChannel, Sensor, int)
      */
     public SensorDirectChannel createDirectChannel(HardwareBuffer mem) {
-        return null;
+        return createDirectChannelImpl(null, mem);
     }
 
     /** @hide */
-    protected abstract SensorDirectChannel createDirectChannelImpl(long size,
-            MemoryFile ashmemFile, HardwareBuffer hardwareBuffer);
+    protected abstract SensorDirectChannel createDirectChannelImpl(
+            MemoryFile memoryFile, HardwareBuffer hardwareBuffer);
 
     /** @hide */
     void destroyDirectChannel(SensorDirectChannel channel) {
diff --git a/core/java/android/hardware/SystemSensorManager.java b/core/java/android/hardware/SystemSensorManager.java
index 4992def..7029847 100644
--- a/core/java/android/hardware/SystemSensorManager.java
+++ b/core/java/android/hardware/SystemSensorManager.java
@@ -34,6 +34,7 @@
 
 import com.android.internal.annotations.GuardedBy;
 
+import java.io.IOException;
 import java.lang.ref.WeakReference;
 import java.util.ArrayList;
 import java.util.HashMap;
@@ -50,6 +51,7 @@
 public class SystemSensorManager extends SensorManager {
     //TODO: disable extra logging before release
     private static boolean DEBUG_DYNAMIC_SENSOR = true;
+    private static int MIN_DIRECT_CHANNEL_BUFFER_SIZE = 104;
 
     private static native void nativeClassInit();
     private static native long nativeCreate(String opPackageName);
@@ -59,7 +61,7 @@
     private static native boolean nativeIsDataInjectionEnabled(long nativeInstance);
 
     private static native int nativeCreateDirectChannel(
-            long nativeInstance, long size, int channelType, long [] channelData);
+            long nativeInstance, long size, int channelType, int fd, HardwareBuffer buffer);
     private static native void nativeDestroyDirectChannel(
             long nativeInstance, int channelHandle);
     private static native int nativeConfigDirectChannel(
@@ -525,24 +527,54 @@
     }
 
     /** @hide */
-    protected SensorDirectChannel createDirectChannelImpl(long size,
-            MemoryFile ashmemFile, HardwareBuffer grallocMemObject) {
+    protected SensorDirectChannel createDirectChannelImpl(
+            MemoryFile memoryFile, HardwareBuffer hardwareBuffer) {
         SensorDirectChannel ch = null;
-
-        if (size <= 0) throw new IllegalArgumentException("size has to be greater than 0");
-
-        if (ashmemFile != null) {
-            if (size != ashmemFile.length()) {
-                throw new IllegalArgumentException("size has to match MemoryFile.length()");
+        long size;
+        if (memoryFile != null) {
+            int fd;
+            try {
+                fd = memoryFile.getFileDescriptor().getInt$();
+            } catch (IOException e) {
+                throw new IllegalArgumentException("MemoryFile object is not valid");
             }
+
+            if (memoryFile.length() < MIN_DIRECT_CHANNEL_BUFFER_SIZE) {
+                throw new IllegalArgumentException(
+                        "Size of MemoryFile has to be greater than "
+                        + MIN_DIRECT_CHANNEL_BUFFER_SIZE);
+            }
+
+            size = memoryFile.length();
             int id = nativeCreateDirectChannel(
-                    mNativeInstance, size, SensorDirectChannel.TYPE_ASHMEM,
-                    SensorDirectChannel.encodeData(ashmemFile));
+                    mNativeInstance, size, SensorDirectChannel.TYPE_ASHMEM, fd, null);
             if (id > 0) {
                 ch = new SensorDirectChannel(this, id, SensorDirectChannel.TYPE_ASHMEM, size);
             }
-        } else if (grallocMemObject != null) {
-            Log.wtf(TAG, "Implement GRALLOC or remove GRALLOC support entirely");
+        } else if (hardwareBuffer != null) {
+            if (hardwareBuffer.getFormat() != HardwareBuffer.BLOB) {
+                throw new IllegalArgumentException("Format of HardwareBuffer must be BLOB");
+            }
+            if (hardwareBuffer.getHeight() != 1) {
+                throw new IllegalArgumentException("Height of HardwareBuffer must be 1");
+            }
+            if (hardwareBuffer.getWidth() < MIN_DIRECT_CHANNEL_BUFFER_SIZE) {
+                throw new IllegalArgumentException(
+                        "Width if HaradwareBuffer must be greater than "
+                        + MIN_DIRECT_CHANNEL_BUFFER_SIZE);
+            }
+            if ((hardwareBuffer.getUsage() & HardwareBuffer.USAGE0_SENSOR_DIRECT_DATA) == 0) {
+                throw new IllegalArgumentException(
+                        "HardwareBuffer must set usage flag USAGE0_SENSOR_DIRECT_DATA");
+            }
+            size = hardwareBuffer.getWidth();
+            int id = nativeCreateDirectChannel(
+                    mNativeInstance, size, SensorDirectChannel.TYPE_HARDWARE_BUFFER,
+                    -1, hardwareBuffer);
+            if (id > 0) {
+                ch = new SensorDirectChannel(
+                        this, id, SensorDirectChannel.TYPE_HARDWARE_BUFFER, size);
+            }
         } else {
             throw new IllegalArgumentException("Invalid parameter");
         }
diff --git a/core/java/android/hardware/camera2/CameraDevice.java b/core/java/android/hardware/camera2/CameraDevice.java
index 45cd084..493ed8c 100644
--- a/core/java/android/hardware/camera2/CameraDevice.java
+++ b/core/java/android/hardware/camera2/CameraDevice.java
@@ -19,6 +19,10 @@
 import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.annotation.IntDef;
+import android.annotation.SystemApi;
+import android.annotation.TestApi;
+import static android.hardware.camera2.ICameraDeviceUser.NORMAL_MODE;
+import static android.hardware.camera2.ICameraDeviceUser.CONSTRAINED_HIGH_SPEED_MODE;
 import android.hardware.camera2.params.InputConfiguration;
 import android.hardware.camera2.params.StreamConfigurationMap;
 import android.hardware.camera2.params.OutputConfiguration;
@@ -719,6 +723,84 @@
             throws CameraAccessException;
 
     /**
+     * Standard camera operation mode.
+     *
+     * @see #createCustomCaptureSession
+     * @hide
+     */
+    @SystemApi
+    @TestApi
+    public static final int SESSION_OPERATION_MODE_NORMAL =
+            ICameraDeviceUser.NORMAL_MODE;
+
+    /**
+     * Constrained high-speed operation mode.
+     *
+     * @see #createCustomCaptureSession
+     * @hide
+     */
+    @SystemApi
+    @TestApi
+    public static final int SESSION_OPERATION_MODE_CONSTRAINED_HIGH_SPEED =
+            ICameraDeviceUser.CONSTRAINED_HIGH_SPEED_MODE;
+
+    /**
+     * First vendor-specific operating mode
+     *
+     * @see #createCustomCaptureSession
+     * @hide
+     */
+    @SystemApi
+    @TestApi
+    public static final int SESSION_OPERATION_MODE_VENDOR_START =
+            ICameraDeviceUser.VENDOR_MODE_START;
+
+    /** @hide */
+    @Retention(RetentionPolicy.SOURCE)
+    @IntDef(
+            {SESSION_OPERATION_MODE_NORMAL,
+             SESSION_OPERATION_MODE_CONSTRAINED_HIGH_SPEED,
+             SESSION_OPERATION_MODE_VENDOR_START})
+    public @interface SessionOperatingMode {};
+
+    /**
+     * Create a new camera capture session with a custom operating mode.
+     *
+     * @param inputConfig The configuration for the input {@link Surface} if a reprocessing session
+     *                is desired, or {@code null} otherwise.
+     * @param outputs The new set of {@link OutputConfiguration OutputConfigurations} that should be
+     *                made available as targets for captured image data.
+     * @param operatingMode The custom operating mode to use; a nonnegative value, either a custom
+     *                vendor value or one of the SESSION_OPERATION_MODE_* values.
+     * @param callback The callback to notify about the status of the new capture session.
+     * @param handler The handler on which the callback should be invoked, or {@code null} to use
+     *                the current thread's {@link android.os.Looper looper}.
+     *
+     * @throws IllegalArgumentException if the input configuration is null or not supported, the set
+     *                                  of output Surfaces do not meet the requirements, the
+     *                                  callback is null, or the handler is null but the current
+     *                                  thread has no looper.
+     * @throws CameraAccessException if the camera device is no longer connected or has
+     *                               encountered a fatal error
+     * @throws IllegalStateException if the camera device has been closed
+     *
+     * @see #createCaptureSession
+     * @see #createReprocessableCaptureSession
+     * @see CameraCaptureSession
+     * @see OutputConfiguration
+     * @hide
+     */
+    @SystemApi
+    @TestApi
+    public abstract void createCustomCaptureSession(
+            InputConfiguration inputConfig,
+            @NonNull List<OutputConfiguration> outputs,
+            @SessionOperatingMode int operatingMode,
+            @NonNull CameraCaptureSession.StateCallback callback,
+            @Nullable Handler handler)
+            throws CameraAccessException;
+
+    /**
      * <p>Create a {@link CaptureRequest.Builder} for new capture requests,
      * initialized with template for a target use case. The settings are chosen
      * to be the best options for the specific camera device, so it is not
diff --git a/core/java/android/hardware/camera2/impl/CameraCaptureSessionImpl.java b/core/java/android/hardware/camera2/impl/CameraCaptureSessionImpl.java
index 891df63..16ffee0 100644
--- a/core/java/android/hardware/camera2/impl/CameraCaptureSessionImpl.java
+++ b/core/java/android/hardware/camera2/impl/CameraCaptureSessionImpl.java
@@ -19,6 +19,7 @@
 import android.hardware.camera2.CameraCaptureSession;
 import android.hardware.camera2.CameraDevice;
 import android.hardware.camera2.CaptureRequest;
+import android.hardware.camera2.ICameraDeviceUser;
 import android.hardware.camera2.dispatch.ArgumentReplacingDispatcher;
 import android.hardware.camera2.dispatch.BroadcastDispatcher;
 import android.hardware.camera2.dispatch.DuckTypingDispatcher;
@@ -742,7 +743,7 @@
                     try {
                         // begin transition to unconfigured
                         mDeviceImpl.configureStreamsChecked(/*inputConfig*/null, /*outputs*/null,
-                                /*isConstrainedHighSpeed*/false);
+                                /*operatingMode*/ ICameraDeviceUser.NORMAL_MODE);
                     } catch (CameraAccessException e) {
                         // OK: do not throw checked exceptions.
                         Log.e(TAG, mIdString + "Exception while unconfiguring outputs: ", e);
diff --git a/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java b/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java
index 2364ebe..8bc65af 100644
--- a/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java
+++ b/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java
@@ -356,7 +356,7 @@
             outputConfigs.add(new OutputConfiguration(s));
         }
         configureStreamsChecked(/*inputConfig*/null, outputConfigs,
-                /*isConstrainedHighSpeed*/false);
+                /*operatingMode*/ICameraDeviceUser.NORMAL_MODE);
 
     }
 
@@ -374,13 +374,14 @@
      *
      * @param inputConfig input configuration or {@code null} for no input
      * @param outputs a list of one or more surfaces, or {@code null} to unconfigure
-     * @param isConstrainedHighSpeed If the streams configuration is for constrained high speed output.
+     * @param operatingMode If the stream configuration is for a normal session,
+     *     a constrained high speed session, or something else.
      * @return whether or not the configuration was successful
      *
      * @throws CameraAccessException if there were any unexpected problems during configuration
      */
     public boolean configureStreamsChecked(InputConfiguration inputConfig,
-            List<OutputConfiguration> outputs, boolean isConstrainedHighSpeed)
+            List<OutputConfiguration> outputs, int operatingMode)
                     throws CameraAccessException {
         // Treat a null input the same an empty list
         if (outputs == null) {
@@ -456,7 +457,7 @@
                     }
                 }
 
-                mRemoteDevice.endConfigure(isConstrainedHighSpeed);
+                mRemoteDevice.endConfigure(operatingMode);
 
                 success = true;
             } catch (IllegalArgumentException e) {
@@ -492,7 +493,7 @@
             outConfigurations.add(new OutputConfiguration(surface));
         }
         createCaptureSessionInternal(null, outConfigurations, callback, handler,
-                /*isConstrainedHighSpeed*/false);
+                /*operatingMode*/ICameraDeviceUser.NORMAL_MODE);
     }
 
     @Override
@@ -508,7 +509,7 @@
         List<OutputConfiguration> currentOutputs = new ArrayList<>(outputConfigurations);
 
         createCaptureSessionInternal(null, currentOutputs, callback, handler,
-                /*isConstrainedHighSpeed*/false);
+                /*operatingMode*/ICameraDeviceUser.NORMAL_MODE);
     }
 
     @Override
@@ -528,7 +529,7 @@
             outConfigurations.add(new OutputConfiguration(surface));
         }
         createCaptureSessionInternal(inputConfig, outConfigurations, callback, handler,
-                /*isConstrainedHighSpeed*/false);
+                /*operatingMode*/ICameraDeviceUser.NORMAL_MODE);
     }
 
     @Override
@@ -556,7 +557,7 @@
             currentOutputs.add(new OutputConfiguration(output));
         }
         createCaptureSessionInternal(inputConfig, currentOutputs,
-                callback, handler, /*isConstrainedHighSpeed*/false);
+                callback, handler, /*operatingMode*/ICameraDeviceUser.NORMAL_MODE);
     }
 
     @Override
@@ -576,13 +577,26 @@
             outConfigurations.add(new OutputConfiguration(surface));
         }
         createCaptureSessionInternal(null, outConfigurations, callback, handler,
-                /*isConstrainedHighSpeed*/true);
+                /*operatingMode*/ICameraDeviceUser.CONSTRAINED_HIGH_SPEED_MODE);
+    }
+
+    @Override
+    public void createCustomCaptureSession(InputConfiguration inputConfig,
+            List<OutputConfiguration> outputs,
+            int operatingMode,
+            android.hardware.camera2.CameraCaptureSession.StateCallback callback,
+            Handler handler) throws CameraAccessException {
+        List<OutputConfiguration> currentOutputs = new ArrayList<OutputConfiguration>();
+        for (OutputConfiguration output : outputs) {
+            currentOutputs.add(new OutputConfiguration(output));
+        }
+        createCaptureSessionInternal(inputConfig, currentOutputs, callback, handler, operatingMode);
     }
 
     private void createCaptureSessionInternal(InputConfiguration inputConfig,
             List<OutputConfiguration> outputConfigurations,
             CameraCaptureSession.StateCallback callback, Handler handler,
-            boolean isConstrainedHighSpeed) throws CameraAccessException {
+            int operatingMode) throws CameraAccessException {
         synchronized(mInterfaceLock) {
             if (DEBUG) {
                 Log.d(TAG, "createCaptureSessionInternal");
@@ -590,6 +604,8 @@
 
             checkIfCameraClosedOrInError();
 
+            boolean isConstrainedHighSpeed =
+                    (operatingMode == ICameraDeviceUser.CONSTRAINED_HIGH_SPEED_MODE);
             if (isConstrainedHighSpeed && inputConfig != null) {
                 throw new IllegalArgumentException("Constrained high speed session doesn't support"
                         + " input configuration yet.");
@@ -608,7 +624,7 @@
             try {
                 // configure streams and then block until IDLE
                 configureSuccess = configureStreamsChecked(inputConfig, outputConfigurations,
-                        isConstrainedHighSpeed);
+                        operatingMode);
                 if (configureSuccess == true && inputConfig != null) {
                     input = mRemoteDevice.getInputSurface();
                 }
diff --git a/core/java/android/hardware/camera2/impl/ICameraDeviceUserWrapper.java b/core/java/android/hardware/camera2/impl/ICameraDeviceUserWrapper.java
index d9f666e..27087a2 100644
--- a/core/java/android/hardware/camera2/impl/ICameraDeviceUserWrapper.java
+++ b/core/java/android/hardware/camera2/impl/ICameraDeviceUserWrapper.java
@@ -106,9 +106,9 @@
         }
     }
 
-    public void endConfigure(boolean isConstrainedHighSpeed) throws CameraAccessException {
+    public void endConfigure(int operatingMode) throws CameraAccessException {
         try {
-            mRemoteDevice.endConfigure(isConstrainedHighSpeed);
+            mRemoteDevice.endConfigure(operatingMode);
         } catch (Throwable t) {
             CameraManager.throwAsPublicException(t);
             throw new UnsupportedOperationException("Unexpected exception", t);
diff --git a/core/java/android/hardware/camera2/legacy/CameraDeviceUserShim.java b/core/java/android/hardware/camera2/legacy/CameraDeviceUserShim.java
index d8ec4df..f87d8c1 100644
--- a/core/java/android/hardware/camera2/legacy/CameraDeviceUserShim.java
+++ b/core/java/android/hardware/camera2/legacy/CameraDeviceUserShim.java
@@ -497,7 +497,7 @@
     }
 
     @Override
-    public void endConfigure(boolean isConstrainedHighSpeed) {
+    public void endConfigure(int operatingMode) {
         if (DEBUG) {
             Log.d(TAG, "endConfigure called.");
         }
@@ -507,6 +507,12 @@
             throw new ServiceSpecificException(ICameraService.ERROR_DISCONNECTED, err);
         }
 
+        if (operatingMode != ICameraDeviceUser.NORMAL_MODE) {
+            String err = "LEGACY devices do not support this operating mode";
+            Log.e(TAG, err);
+            throw new ServiceSpecificException(ICameraService.ERROR_ILLEGAL_ARGUMENT, err);
+        }
+
         SparseArray<Surface> surfaces = null;
         synchronized(mConfigureLock) {
             if (!mConfiguring) {
diff --git a/core/java/android/metrics/LogMaker.java b/core/java/android/metrics/LogMaker.java
index 0ee2574..612b135 100644
--- a/core/java/android/metrics/LogMaker.java
+++ b/core/java/android/metrics/LogMaker.java
@@ -60,26 +60,51 @@
         return this;
     }
 
+    public LogMaker clearCategory() {
+        entries.remove(MetricsEvent.RESERVED_FOR_LOGBUILDER_CATEGORY);
+        return this;
+    }
+
     public LogMaker setType(int type) {
         entries.put(MetricsEvent.RESERVED_FOR_LOGBUILDER_TYPE, type);
         return this;
     }
 
+    public LogMaker clearType() {
+        entries.remove(MetricsEvent.RESERVED_FOR_LOGBUILDER_TYPE);
+        return this;
+    }
+
     public LogMaker setSubtype(int subtype) {
         entries.put(MetricsEvent.RESERVED_FOR_LOGBUILDER_SUBTYPE, subtype);
         return this;
     }
 
+    public LogMaker clearSubtype() {
+        entries.remove(MetricsEvent.RESERVED_FOR_LOGBUILDER_SUBTYPE);
+        return this;
+    }
+
     public LogMaker setTimestamp(long timestamp) {
         entries.put(MetricsEvent.RESERVED_FOR_LOGBUILDER_TIMESTAMP, timestamp);
         return this;
     }
 
+    public LogMaker clearTimestamp() {
+        entries.remove(MetricsEvent.RESERVED_FOR_LOGBUILDER_TIMESTAMP);
+        return this;
+    }
+
     public LogMaker setPackageName(String packageName) {
         entries.put(MetricsEvent.RESERVED_FOR_LOGBUILDER_PACKAGENAME, packageName);
         return this;
     }
 
+    public LogMaker clearPackageName() {
+        entries.remove(MetricsEvent.RESERVED_FOR_LOGBUILDER_PACKAGENAME);
+        return this;
+    }
+
     public LogMaker setCounterName(String name) {
         entries.put(MetricsEvent.RESERVED_FOR_LOGBUILDER_NAME, name);
         return this;
diff --git a/core/java/android/metrics/MetricsReader.java b/core/java/android/metrics/MetricsReader.java
index 079c2c9..dd8a74d 100644
--- a/core/java/android/metrics/MetricsReader.java
+++ b/core/java/android/metrics/MetricsReader.java
@@ -16,10 +16,15 @@
 package android.metrics;
 
 import android.annotation.SystemApi;
+import android.util.EventLog;
+import android.util.EventLog.Event;
+import android.util.Log;
 
-import com.android.internal.logging.legacy.LegacyConversionLogger;
-import com.android.internal.logging.legacy.EventLogCollector;
+import com.android.internal.logging.MetricsLogger;
 
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.LinkedList;
 import java.util.Queue;
 
 /**
@@ -28,41 +33,87 @@
  */
 @SystemApi
 public class MetricsReader {
-    private EventLogCollector mReader;
-    private Queue<LogMaker> mEventQueue;
+    private Queue<LogMaker> mEventQueue = new LinkedList<>();
     private long mLastEventMs;
     private long mCheckpointMs;
+    private int[] LOGTAGS = { MetricsLogger.LOGTAG };
 
-    /** Open a new session and start reading logs.
+    /**
+     * Read the available logs into a new session.
      *
-     * Starts reading from the oldest log not already read by this reader object.
-     * On first invocation starts from the oldest available log ion the system.
+     * The session will contain events starting from the oldest available
+     * log on the system up to the most recent at the time of this call.
+     *
+     * A call to {@link #checkpoint()} will cause the session to contain
+     * only events that occured after that call.
+     *
+     * This call will not return until the system buffer overflows the
+     * specified timestamp. If the specified timestamp is 0, then the
+     * call will return immediately since any logs 1970 have already been
+     * overwritten (n.b. if the underlying system has the capability to
+     * store many decades of system logs, this call may fail in
+     * interesting ways.)
+     *
+     * @param horizonMs block until this timestamp is overwritten, 0 for non-blocking read.
      */
-    public void read(long startMs) {
-        EventLogCollector reader = EventLogCollector.getInstance();
-        LegacyConversionLogger logger = new LegacyConversionLogger();
-        mLastEventMs = reader.collect(logger, startMs);
-        mEventQueue = logger.getEvents();
+    public void read(long horizonMs) {
+        ArrayList<Event> nativeEvents = new ArrayList<>();
+        try {
+            EventLog.readEventsOnWrapping(LOGTAGS, horizonMs, nativeEvents);
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        mEventQueue.clear();
+        for (EventLog.Event event : nativeEvents) {
+            final long eventTimestampMs = event.getTimeNanos() / 1000000;
+            if (eventTimestampMs > mCheckpointMs) {
+                Object data = event.getData();
+                Object[] objects;
+                if (data instanceof Object[]) {
+                    objects = (Object[]) data;
+                } else {
+                    // wrap scalar objects
+                    objects = new Object[1];
+                    objects[0] = data;
+                }
+                mEventQueue.add(new LogMaker(objects)
+                        .setTimestamp(eventTimestampMs));
+                mLastEventMs = eventTimestampMs;
+            }
+        }
     }
 
+    /** Cause this session to only contain events that occur after this call. */
     public void checkpoint() {
+        // read the log to find the most recent event.
         read(0L);
+        // any queued event is now too old, so drop them.
+        mEventQueue.clear();
         mCheckpointMs = mLastEventMs;
-        mEventQueue = null;
     }
 
+    /**
+     * Rewind the session to the beginning of time and read all available logs.
+     *
+     * A prior call to {@link #checkpoint()} will cause the reader to ignore
+     * any event with a timestamp before the time of that call.
+     *
+     * The underlying log buffer is live: between calls to {@link #reset()}, older
+     * events may be lost from the beginning of the session, and new events may
+     * appear at the end.
+     */
     public void reset() {
-        read(mCheckpointMs);
+        read(0l);
     }
 
     /* Does the current log session have another entry? */
     public boolean hasNext() {
-        return mEventQueue == null ? false : !mEventQueue.isEmpty();
+        return !mEventQueue.isEmpty();
     }
 
-    /* Next entry in the current log session. */
+    /* Return the next entry in the current log session. */
     public LogMaker next() {
-        return mEventQueue == null ? null : mEventQueue.remove();
+        return mEventQueue.poll();
     }
 
 }
diff --git a/core/java/android/net/ConnectivityManager.java b/core/java/android/net/ConnectivityManager.java
index ab4904c..14333f7 100644
--- a/core/java/android/net/ConnectivityManager.java
+++ b/core/java/android/net/ConnectivityManager.java
@@ -2636,10 +2636,12 @@
         public void onLost(Network network) {}
 
         /**
-         * Called if no network is found in the given timeout time.  If no timeout is given,
-         * this will not be called. The associated {@link NetworkRequest} will have already
-         * been removed and released, as if {@link #unregisterNetworkCallback} had been called.
-         * @hide
+         * Called if no network is found in the timeout time specified in
+         * {@link #requestNetwork(NetworkRequest, int, NetworkCallback)} call. This callback is not
+         * called for the version of {@link #requestNetwork(NetworkRequest, NetworkCallback)}
+         * without timeout. When this callback is invoked the associated
+         * {@link NetworkRequest} will have already been removed and released, as if
+         * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
          */
         public void onUnavailable() {}
 
@@ -2922,7 +2924,9 @@
      * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
      *
      * This {@link NetworkRequest} will live until released via
-     * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits.
+     * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits. A
+     * version of the method which takes a timeout is
+     * {@link #requestNetwork(NetworkRequest, int, NetworkCallback)}.
      * Status of the request can be followed by listening to the various
      * callbacks described in {@link NetworkCallback}.  The {@link Network}
      * can be used to direct traffic to the network.
@@ -2955,7 +2959,9 @@
      * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}.
      *
      * This {@link NetworkRequest} will live until released via
-     * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits.
+     * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits. A
+     * version of the method which takes a timeout is
+     * {@link #requestNetwork(NetworkRequest, int, NetworkCallback)}.
      * Status of the request can be followed by listening to the various
      * callbacks described in {@link NetworkCallback}.  The {@link Network}
      * can be used to direct traffic to the network.
@@ -2989,13 +2995,25 @@
     }
 
     /**
+     * Note: this is a deprecated version of
+     * {@link #requestNetwork(NetworkRequest, int, NetworkCallback)} - please transition code to use
+     * the unhidden version of the function.
+     * TODO: replace all callers with the new version of the API
+     *
      * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
      * by a timeout.
      *
-     * This function behaves identically to the non-timedout version, but if a suitable
-     * network is not found within the given time (in milliseconds) the
-     * {@link NetworkCallback#onUnavailable()} callback is called.  The request must
-     * still be released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
+     * This function behaves identically to the non-timed-out version
+     * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
+     * is not found within the given time (in milliseconds) the
+     * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
+     * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
+     * not have to be released if timed-out (it is automatically released). Unregistering a
+     * request that timed out is not an error.
+     *
+     * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
+     * timeout) - the {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
+     * for that purpose. Calling this method will attempt to bring up the requested network.
      *
      * <p>This method requires the caller to hold either the
      * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
@@ -3003,15 +3021,56 @@
      * {@link android.provider.Settings.System#canWrite}.</p>
      *
      * @param request {@link NetworkRequest} describing this request.
-     * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
-     *                        the callback must not be shared - it uniquely specifies this request.
-     *                        The callback is invoked on the default internal Handler.
+     * @param networkCallback The callbacks to be utilized for this request.  Note
+     *                        the callbacks must not be shared - they uniquely specify
+     *                        this request.
      * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
-     *                  before {@link NetworkCallback#onUnavailable()} is called.
+     *                  before {@link NetworkCallback#onUnavailable()} is called. The timeout must
+     *                  be a positive value (i.e. >0).
      * @hide
      */
     public void requestNetwork(NetworkRequest request, NetworkCallback networkCallback,
             int timeoutMs) {
+        if (timeoutMs <= 0) {
+            throw new IllegalArgumentException("Non-positive timeoutMs: " + timeoutMs);
+        }
+        int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
+        requestNetwork(request, networkCallback, timeoutMs, legacyType, getDefaultHandler());
+    }
+
+    /**
+     * Request a network to satisfy a set of {@link android.net.NetworkCapabilities}, limited
+     * by a timeout.
+     *
+     * This function behaves identically to the non-timed-out version
+     * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
+     * is not found within the given time (in milliseconds) the
+     * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
+     * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
+     * not have to be released if timed-out (it is automatically released). Unregistering a
+     * request that timed out is not an error.
+     *
+     * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
+     * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
+     * for that purpose. Calling this method will attempt to bring up the requested network.
+     *
+     * <p>This method requires the caller to hold either the
+     * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
+     * or the ability to modify system settings as determined by
+     * {@link android.provider.Settings.System#canWrite}.</p>
+     *
+     * @param request {@link NetworkRequest} describing this request.
+     * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
+     *                  before {@link NetworkCallback#onUnavailable()} is called. The timeout must
+     *                  be a positive value (i.e. >0).
+     * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
+     *                        the callback must not be shared - it uniquely specifies this request.
+     */
+    public void requestNetwork(NetworkRequest request, int timeoutMs,
+            NetworkCallback networkCallback) {
+        if (timeoutMs <= 0) {
+            throw new IllegalArgumentException("Non-positive timeoutMs: " + timeoutMs);
+        }
         int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
         requestNetwork(request, networkCallback, timeoutMs, legacyType, getDefaultHandler());
     }
@@ -3023,8 +3082,14 @@
      *
      * This function behaves identically to the non-timedout version, but if a suitable
      * network is not found within the given time (in milliseconds) the
-     * {@link NetworkCallback#onUnavailable} callback is called.  The request must
-     * still be released normally by calling {@link unregisterNetworkCallback(NetworkCallback)}.
+     * {@link NetworkCallback#onUnavailable} callback is called. The request can still be
+     * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
+     * not have to be released if timed-out (it is automatically released). Unregistering a
+     * request that timed out is not an error.
+     *
+     * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
+     * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
+     * for that purpose. Calling this method will attempt to bring up the requested network.
      *
      * <p>This method requires the caller to hold either the
      * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
@@ -3032,16 +3097,19 @@
      * {@link android.provider.Settings.System#canWrite}.</p>
      *
      * @param request {@link NetworkRequest} describing this request.
-     * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
-     *                        the callback must not be shared - it uniquely specifies this request.
      * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
      *                  before {@link NetworkCallback#onUnavailable} is called.
+     * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
+     *                        the callback must not be shared - it uniquely specifies this request.
      * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
      *
      * @hide
      */
-    public void requestNetwork(NetworkRequest request, NetworkCallback networkCallback,
-            int timeoutMs, Handler handler) {
+    public void requestNetwork(NetworkRequest request, int timeoutMs,
+            NetworkCallback networkCallback, Handler handler) {
+        if (timeoutMs <= 0) {
+            throw new IllegalArgumentException("Non-positive timeoutMs");
+        }
         int legacyType = inferLegacyTypeForNetworkCapabilities(request.networkCapabilities);
         CallbackHandler cbHandler = new CallbackHandler(handler);
         requestNetwork(request, networkCallback, timeoutMs, legacyType, cbHandler);
diff --git a/core/java/android/net/NetworkScoreManager.java b/core/java/android/net/NetworkScoreManager.java
index 7b7a21c..e6fe0d0 100644
--- a/core/java/android/net/NetworkScoreManager.java
+++ b/core/java/android/net/NetworkScoreManager.java
@@ -171,6 +171,43 @@
      */
     public static final int CACHE_FILTER_SCAN_RESULTS = 2;
 
+    /** @hide */
+    @IntDef({RECOMMENDATIONS_ENABLED_FORCED_OFF, RECOMMENDATIONS_ENABLED_OFF,
+            RECOMMENDATIONS_ENABLED_ON})
+    @Retention(RetentionPolicy.SOURCE)
+    public @interface RecommendationsEnabledSetting {}
+
+    /**
+     * Recommendations have been forced off.
+     * <p>
+     * This value is never set by any of the NetworkScore classes, it must be set via other means.
+     * This state is also "sticky" and we won't transition out of this state once entered. To move
+     * to a different state this value has to be explicitly set to a different value via
+     * other means.
+     * @hide
+     */
+    public static final int RECOMMENDATIONS_ENABLED_FORCED_OFF = -1;
+
+    /**
+     * Recommendations are not enabled.
+     * <p>
+     * This is a transient state that can be entered when the default recommendation app is enabled
+     * but no longer valid. This state will transition to RECOMMENDATIONS_ENABLED_ON when a valid
+     * recommendation app is enabled.
+     * @hide
+     */
+    public static final int RECOMMENDATIONS_ENABLED_OFF = 0;
+
+    /**
+     * Recommendations are enabled.
+     * <p>
+     * This is a transient state that means a valid recommendation app is active. This state will
+     * transition to RECOMMENDATIONS_ENABLED_OFF if the current and default recommendation apps
+     * become invalid.
+     * @hide
+     */
+    public static final int RECOMMENDATIONS_ENABLED_ON = 1;
+
     private final Context mContext;
     private final INetworkScoreService mService;
 
diff --git a/core/java/android/os/BaseBundle.java b/core/java/android/os/BaseBundle.java
index 14760ab..e82fe03 100644
--- a/core/java/android/os/BaseBundle.java
+++ b/core/java/android/os/BaseBundle.java
@@ -341,7 +341,7 @@
                     final int N = fromMap.size();
                     mMap = new ArrayMap<>(N);
                     for (int i = 0; i < N; i++) {
-                        mMap.append(fromMap.keyAt(i), deepcopyValue(fromMap.valueAt(i)));
+                        mMap.append(fromMap.keyAt(i), deepCopyValue(fromMap.valueAt(i)));
                     }
                 }
             } else {
@@ -352,14 +352,14 @@
         }
     }
 
-    Object deepcopyValue(Object value) {
+    Object deepCopyValue(Object value) {
         if (value == null) {
             return null;
         }
         if (value instanceof Bundle) {
-            return ((Bundle)value).deepcopy();
+            return ((Bundle)value).deepCopy();
         } else if (value instanceof PersistableBundle) {
-            return ((PersistableBundle)value).deepcopy();
+            return ((PersistableBundle)value).deepCopy();
         } else if (value instanceof ArrayList) {
             return deepcopyArrayList((ArrayList) value);
         } else if (value.getClass().isArray()) {
@@ -388,7 +388,7 @@
         final int N = from.size();
         ArrayList out = new ArrayList(N);
         for (int i=0; i<N; i++) {
-            out.add(deepcopyValue(from.get(i)));
+            out.add(deepCopyValue(from.get(i)));
         }
         return out;
     }
diff --git a/core/java/android/os/BatteryStats.java b/core/java/android/os/BatteryStats.java
index 013972d..d50a838 100644
--- a/core/java/android/os/BatteryStats.java
+++ b/core/java/android/os/BatteryStats.java
@@ -2186,7 +2186,11 @@
     public static final int NETWORK_WIFI_TX_DATA = 3;
     public static final int NETWORK_BT_RX_DATA = 4;
     public static final int NETWORK_BT_TX_DATA = 5;
-    public static final int NUM_NETWORK_ACTIVITY_TYPES = NETWORK_BT_TX_DATA + 1;
+    public static final int NETWORK_MOBILE_BG_RX_DATA = 6;
+    public static final int NETWORK_MOBILE_BG_TX_DATA = 7;
+    public static final int NETWORK_WIFI_BG_RX_DATA = 8;
+    public static final int NETWORK_WIFI_BG_TX_DATA = 9;
+    public static final int NUM_NETWORK_ACTIVITY_TYPES = NETWORK_WIFI_BG_TX_DATA + 1;
 
     public abstract long getNetworkActivityBytes(int type, int which);
     public abstract long getNetworkActivityPackets(int type, int which);
@@ -3233,16 +3237,39 @@
             final long wifiWakeup = u.getWifiRadioApWakeupCount(which);
             final long btBytesRx = u.getNetworkActivityBytes(NETWORK_BT_RX_DATA, which);
             final long btBytesTx = u.getNetworkActivityBytes(NETWORK_BT_TX_DATA, which);
+            // Background data transfers
+            final long mobileBytesBgRx = u.getNetworkActivityBytes(NETWORK_MOBILE_BG_RX_DATA,
+                    which);
+            final long mobileBytesBgTx = u.getNetworkActivityBytes(NETWORK_MOBILE_BG_TX_DATA,
+                    which);
+            final long wifiBytesBgRx = u.getNetworkActivityBytes(NETWORK_WIFI_BG_RX_DATA, which);
+            final long wifiBytesBgTx = u.getNetworkActivityBytes(NETWORK_WIFI_BG_TX_DATA, which);
+            final long mobilePacketsBgRx = u.getNetworkActivityPackets(NETWORK_MOBILE_BG_RX_DATA,
+                    which);
+            final long mobilePacketsBgTx = u.getNetworkActivityPackets(NETWORK_MOBILE_BG_TX_DATA,
+                    which);
+            final long wifiPacketsBgRx = u.getNetworkActivityPackets(NETWORK_WIFI_BG_RX_DATA,
+                    which);
+            final long wifiPacketsBgTx = u.getNetworkActivityPackets(NETWORK_WIFI_BG_TX_DATA,
+                    which);
+
             if (mobileBytesRx > 0 || mobileBytesTx > 0 || wifiBytesRx > 0 || wifiBytesTx > 0
                     || mobilePacketsRx > 0 || mobilePacketsTx > 0 || wifiPacketsRx > 0
                     || wifiPacketsTx > 0 || mobileActiveTime > 0 || mobileActiveCount > 0
-                    || btBytesRx > 0 || btBytesTx > 0 || mobileWakeup > 0 || wifiWakeup > 0) {
+                    || btBytesRx > 0 || btBytesTx > 0 || mobileWakeup > 0 || wifiWakeup > 0
+                    || mobileBytesBgRx > 0 || mobileBytesBgTx > 0 || wifiBytesBgRx > 0
+                    || wifiBytesBgTx > 0
+                    || mobilePacketsBgRx > 0 || mobilePacketsBgTx > 0 || wifiPacketsBgRx > 0
+                    || wifiPacketsBgTx > 0) {
                 dumpLine(pw, uid, category, NETWORK_DATA, mobileBytesRx, mobileBytesTx,
                         wifiBytesRx, wifiBytesTx,
                         mobilePacketsRx, mobilePacketsTx,
                         wifiPacketsRx, wifiPacketsTx,
                         mobileActiveTime, mobileActiveCount,
-                        btBytesRx, btBytesTx, mobileWakeup, wifiWakeup);
+                        btBytesRx, btBytesTx, mobileWakeup, wifiWakeup,
+                        mobileBytesBgRx, mobileBytesBgTx, wifiBytesBgRx, wifiBytesBgTx,
+                        mobilePacketsBgRx, mobilePacketsBgTx, wifiPacketsBgRx, wifiPacketsBgTx
+                        );
             }
 
             // Dump modem controller data, per UID.
diff --git a/core/java/android/os/Bundle.java b/core/java/android/os/Bundle.java
index d04d6c2..c1292e7 100644
--- a/core/java/android/os/Bundle.java
+++ b/core/java/android/os/Bundle.java
@@ -98,9 +98,12 @@
 
     /**
      * Constructs a Bundle containing a copy of the mappings from the given
-     * Bundle.
+     * Bundle.  Does only a shallow copy of the original Bundle -- see
+     * {@link #deepCopy()} if that is not what you want.
      *
      * @param b a Bundle to be copied.
+     *
+     * @see #deepCopy()
      */
     public Bundle(Bundle b) {
         super(b);
@@ -109,9 +112,10 @@
 
     /**
      * Constructs a Bundle containing a copy of the mappings from the given
-     * PersistableBundle.
+     * PersistableBundle.  Does only a shallow copy of the PersistableBundle -- see
+     * {@link PersistableBundle#deepCopy()} if you don't want that.
      *
-     * @param b a Bundle to be copied.
+     * @param b a PersistableBundle to be copied.
      */
     public Bundle(PersistableBundle b) {
         super(b);
@@ -209,7 +213,7 @@
      * primitive arrays.  Other types of objects (such as Parcelable or Serializable)
      * are referenced as-is and not copied in any way.
      */
-    public Bundle deepcopy() {
+    public Bundle deepCopy() {
         Bundle b = new Bundle(false);
         b.copyInternal(this, true);
         return b;
diff --git a/core/java/android/os/Environment.java b/core/java/android/os/Environment.java
index 39f4d42..5b0e5bbc 100644
--- a/core/java/android/os/Environment.java
+++ b/core/java/android/os/Environment.java
@@ -301,11 +301,6 @@
     }
 
     /** {@hide} */
-    public static File getDataProfilesDeForeignDexDirectory(int userId) {
-        return buildPath(getDataProfilesDeDirectory(userId), "foreign-dex");
-    }
-
-    /** {@hide} */
     public static File getDataAppDirectory(String volumeUuid) {
         return new File(getDataDirectory(volumeUuid), "app");
     }
diff --git a/core/java/android/os/PatternMatcher.java b/core/java/android/os/PatternMatcher.java
index 3890fbf..1f3a1e6 100644
--- a/core/java/android/os/PatternMatcher.java
+++ b/core/java/android/os/PatternMatcher.java
@@ -56,10 +56,8 @@
      * with full support for character ranges and the not ({@code ^}) modifier.
      * Supported modifiers include star ({@code *}) for zero-or-more, plus ({@code +})
      * for one-or-more and full range ({@code {...}}) support. This is a simple
-     * evaulation implementation in which matching is done against the pattern in
-     * realtime with no backtracking support.
-     *
-     * {@hide} Pending approval for public API
+     * evaluation implementation in which matching is done against the pattern in
+     * real time with no backtracking support.
      */
     public static final int PATTERN_ADVANCED_GLOB = 3;
 
diff --git a/core/java/android/os/PersistableBundle.java b/core/java/android/os/PersistableBundle.java
index 9b607837..75f9c11 100644
--- a/core/java/android/os/PersistableBundle.java
+++ b/core/java/android/os/PersistableBundle.java
@@ -76,9 +76,12 @@
 
     /**
      * Constructs a PersistableBundle containing a copy of the mappings from the given
-     * PersistableBundle.
+     * PersistableBundle.  Does only a shallow copy of the original PersistableBundle -- see
+     * {@link #deepCopy()} if that is not what you want.
      *
      * @param b a PersistableBundle to be copied.
+     *
+     * @see #deepCopy()
      */
     public PersistableBundle(PersistableBundle b) {
         super(b);
@@ -87,7 +90,7 @@
 
 
     /**
-     * Constructs a PersistableBundle from a Bundle.
+     * Constructs a PersistableBundle from a Bundle.  Does only a shallow copy of the Bundle.
      *
      * @param b a Bundle to be copied.
      *
@@ -167,7 +170,7 @@
      * primitive arrays.  Other types of objects (such as Parcelable or Serializable)
      * are referenced as-is and not copied in any way.
      */
-    public PersistableBundle deepcopy() {
+    public PersistableBundle deepCopy() {
         PersistableBundle b = new PersistableBundle(false);
         b.copyInternal(this, true);
         return b;
diff --git a/core/java/android/os/RemoteCallbackList.java b/core/java/android/os/RemoteCallbackList.java
index 819afb4..9db58ee 100644
--- a/core/java/android/os/RemoteCallbackList.java
+++ b/core/java/android/os/RemoteCallbackList.java
@@ -329,15 +329,38 @@
     }
 
     /**
-     * Return the cookies associated with a currently registered callback.  Note that this is
-     * <em>not</em> the same as {@link #getBroadcastCookie} and should not be used
-     * interchangeably with it.  This method returns the current cookied registered at the given
+     * Return a currently registered callback.  Note that this is
+     * <em>not</em> the same as {@link #getBroadcastItem} and should not be used
+     * interchangeably with it.  This method returns the registered callback at the given
      * index, not the current broadcast state.  This means that it is not itself thread-safe:
      * any call to {@link #register} or {@link #unregister} will change these indices, so you
      * must do your own thread safety between these to protect from such changes.
      *
-     * @param index Index of which registration cookie to return from 0 to
-     * {@link #getRegisteredCallbackCount()}.
+     * @param index Index of which callback registration to return, from 0 to
+     * {@link #getRegisteredCallbackCount()} - 1.
+     *
+     * @return Returns whatever callback is associated with this index, or null if
+     * {@link #kill()} has been called.
+     */
+    public E getRegisteredCallbackItem(int index) {
+        synchronized (mCallbacks) {
+            if (mKilled) {
+                return null;
+            }
+            return mCallbacks.valueAt(index).mCallback;
+        }
+    }
+
+    /**
+     * Return any cookie associated with a currently registered callback.  Note that this is
+     * <em>not</em> the same as {@link #getBroadcastCookie} and should not be used
+     * interchangeably with it.  This method returns the current cookie registered at the given
+     * index, not the current broadcast state.  This means that it is not itself thread-safe:
+     * any call to {@link #register} or {@link #unregister} will change these indices, so you
+     * must do your own thread safety between these to protect from such changes.
+     *
+     * @param index Index of which registration cookie to return, from 0 to
+     * {@link #getRegisteredCallbackCount()} - 1.
      *
      * @return Returns whatever cookie object is associated with this index, or null if
      * {@link #kill()} has been called.
diff --git a/core/java/android/preference/PreferenceActivity.java b/core/java/android/preference/PreferenceActivity.java
index c0c5db6..02fa7ed 100644
--- a/core/java/android/preference/PreferenceActivity.java
+++ b/core/java/android/preference/PreferenceActivity.java
@@ -40,6 +40,7 @@
 import android.util.TypedValue;
 import android.util.Xml;
 import android.view.LayoutInflater;
+import android.view.MenuItem;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.view.ViewGroup;
@@ -75,12 +76,11 @@
  * however vary; currently there are two major approaches it may take:
  *
  * <ul>
- * <li>On a small screen it may display only the headers as a single list
- * when first launched.  Selecting one of the header items will re-launch
- * the activity with it only showing the PreferenceFragment of that header.
- * <li>On a large screen in may display both the headers and current
- * PreferenceFragment together as panes.  Selecting a header item switches
- * to showing the correct PreferenceFragment for that item.
+ * <li>On a small screen it may display only the headers as a single list when first launched.
+ * Selecting one of the header items will only show the PreferenceFragment of that header (on
+ * Android N and lower a new Activity is launched).
+ * <li>On a large screen in may display both the headers and current PreferenceFragment together as
+ * panes. Selecting a header item switches to showing the correct PreferenceFragment for that item.
  * </ul>
  *
  * <p>Subclasses of PreferenceActivity should implement
@@ -540,6 +540,16 @@
     }
 
     @Override
+    public boolean onOptionsItemSelected(MenuItem item) {
+        if (item.getItemId() == android.R.id.home) {
+            // Override home navigation button to call onBackPressed (b/35152749).
+            onBackPressed();
+            return true;
+        }
+        return super.onOptionsItemSelected(item);
+    }
+
+    @Override
     protected void onCreate(@Nullable Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
 
diff --git a/core/java/android/provider/FontsContract.java b/core/java/android/provider/FontsContract.java
index 90e710f..96dd76b 100644
--- a/core/java/android/provider/FontsContract.java
+++ b/core/java/android/provider/FontsContract.java
@@ -19,9 +19,12 @@
 import android.content.ContentResolver;
 import android.content.ContentUris;
 import android.content.Context;
+import android.content.pm.PackageInfo;
 import android.content.pm.PackageManager;
 import android.content.pm.ProviderInfo;
+import android.content.pm.Signature;
 import android.database.Cursor;
+import android.graphics.Typeface;
 import android.graphics.fonts.FontRequest;
 import android.graphics.fonts.FontResult;
 import android.net.Uri;
@@ -34,9 +37,13 @@
 import android.util.Log;
 
 import com.android.internal.annotations.GuardedBy;
+import com.android.internal.annotations.VisibleForTesting;
 
 import java.io.FileNotFoundException;
 import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
 
 /**
  * Utility class to deal with Font ContentProviders.
@@ -107,6 +114,13 @@
         mPackageManager = mContext.getPackageManager();
     }
 
+    /** @hide */
+    @VisibleForTesting
+    public FontsContract(Context context, PackageManager packageManager) {
+        mContext = context;
+        mPackageManager = packageManager;
+    }
+
     // We use a background thread to post the content resolving work for all requests on. This
     // thread should be quit/stopped after all requests are done.
     private final Runnable mReplaceDispatcherThreadRunnable = new Runnable() {
@@ -133,31 +147,79 @@
                 mHandler = new Handler(mThread.getLooper());
             }
             mHandler.post(() -> {
-                String providerAuthority = request.getProviderAuthority();
-                // TODO: Implement cert checking for non-system apps
-                ProviderInfo providerInfo = mPackageManager.resolveContentProvider(
-                        providerAuthority, PackageManager.MATCH_SYSTEM_ONLY);
+                ProviderInfo providerInfo = getProvider(request);
                 if (providerInfo == null) {
                     receiver.send(RESULT_CODE_PROVIDER_NOT_FOUND, null);
                     return;
                 }
-                Bundle result = getFontFromProvider(request, receiver, providerInfo);
-                if (result == null) {
-                    receiver.send(RESULT_CODE_FONT_NOT_FOUND, null);
-                    return;
-                }
-                receiver.send(RESULT_CODE_OK, result);
+                getFontFromProvider(request, receiver, providerInfo.authority);
             });
             mHandler.removeCallbacks(mReplaceDispatcherThreadRunnable);
             mHandler.postDelayed(mReplaceDispatcherThreadRunnable, THREAD_RENEWAL_THRESHOLD_MS);
         }
     }
 
-    private Bundle getFontFromProvider(FontRequest request, ResultReceiver receiver,
-            ProviderInfo providerInfo) {
+    /** @hide */
+    @VisibleForTesting
+    public ProviderInfo getProvider(FontRequest request) {
+        String providerAuthority = request.getProviderAuthority();
+        ProviderInfo info = mPackageManager.resolveContentProvider(providerAuthority, 0);
+        if (info == null) {
+            Log.e(TAG, "Can't find content provider " + providerAuthority);
+            return null;
+        }
+
+        if (!info.packageName.equals(request.getProviderPackage())) {
+            Log.e(TAG, "Found content provider " + providerAuthority + ", but package was not "
+                    + request.getProviderPackage());
+            return null;
+        }
+        // Trust system apps without signature checks
+        if (info.applicationInfo.isSystemApp()) {
+            return info;
+        }
+
+        Set<byte[]> signatures;
+        try {
+            PackageInfo packageInfo = mPackageManager.getPackageInfo(info.packageName,
+                    PackageManager.GET_SIGNATURES);
+            signatures = convertToSet(packageInfo.signatures);
+        } catch (PackageManager.NameNotFoundException e) {
+            Log.e(TAG, "Can't find content provider " + providerAuthority, e);
+            return null;
+        }
+        List<List<byte[]>> requestCertificatesList = request.getCertificates();
+        for (int i = 0; i < requestCertificatesList.size(); ++i) {
+            final Set<byte[]> requestCertificates = convertToSet(requestCertificatesList.get(i));
+            if (signatures.equals(requestCertificates)) {
+                return info;
+            }
+        }
+        Log.e(TAG, "Certificates don't match for given provider " + providerAuthority);
+        return null;
+    }
+
+    private Set<byte[]> convertToSet(Signature[] signatures) {
+        Set<byte[]> shas = new HashSet<>();
+        for (int i = 0; i < signatures.length; ++i) {
+            shas.add(signatures[i].toByteArray());
+        }
+        return shas;
+    }
+
+    private Set<byte[]> convertToSet(List<byte[]> certs) {
+        Set<byte[]> shas = new HashSet<>();
+        shas.addAll(certs);
+        return shas;
+    }
+
+    /** @hide */
+    @VisibleForTesting
+    public void getFontFromProvider(FontRequest request, ResultReceiver receiver,
+            String authority) {
         ArrayList<FontResult> result = null;
         Uri uri = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT)
-                .authority(providerInfo.authority)
+                .authority(authority)
                 .build();
         try (Cursor cursor = mContext.getContentResolver().query(uri, new String[] { Columns._ID,
                         Columns.TTC_INDEX, Columns.VARIATION_SETTINGS, Columns.STYLE },
@@ -176,13 +238,16 @@
                     try {
                         ParcelFileDescriptor pfd =
                                 mContext.getContentResolver().openFileDescriptor(fileUri, "r");
-                        final int ttcIndex = cursor.getInt(ttcIndexColumnIndex);
-                        final String variationSettings = cursor.getString(vsColumnIndex);
-                        final int style = cursor.getInt(styleColumnIndex);
+                        final int ttcIndex = ttcIndexColumnIndex != -1
+                                ? cursor.getInt(ttcIndexColumnIndex) : 0;
+                        final String variationSettings = vsColumnIndex != -1
+                                ? cursor.getString(vsColumnIndex) : null;
+                        final int style = styleColumnIndex != -1
+                                ? cursor.getInt(styleColumnIndex) : Typeface.NORMAL;
                         result.add(new FontResult(pfd, ttcIndex, variationSettings, style));
                     } catch (FileNotFoundException e) {
                         Log.e(TAG, "FileNotFoundException raised when interacting with content "
-                                + "provider " + providerInfo.authority, e);
+                                + "provider " + authority, e);
                     }
                 }
             }
@@ -190,8 +255,9 @@
         if (result != null && !result.isEmpty()) {
             Bundle bundle = new Bundle();
             bundle.putParcelableArrayList(PARCEL_FONT_RESULTS, result);
-            return bundle;
+            receiver.send(RESULT_CODE_OK, bundle);
+            return;
         }
-        return null;
+        receiver.send(RESULT_CODE_FONT_NOT_FOUND, null);
     }
 }
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index 73d61c3..280400a 100755
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -8234,7 +8234,14 @@
          * Value to specify if network recommendations from
          * {@link com.android.server.NetworkScoreService} are enabled.
          *
-         * Type: int (0 for false, 1 for true)
+         * Type: int
+         * Valid values:
+         *   -1 = Forced off
+         *    0 = Disabled
+         *    1 = Enabled
+         *
+         * Most readers of this setting should simply check if value == 1 to determined the
+         * enabled state.
          * @hide
          */
         @SystemApi
diff --git a/core/java/android/service/autofill/FillResponse.java b/core/java/android/service/autofill/FillResponse.java
index ef551ad..c457c56 100644
--- a/core/java/android/service/autofill/FillResponse.java
+++ b/core/java/android/service/autofill/FillResponse.java
@@ -169,35 +169,15 @@
     private FillResponse(@NonNull Builder builder) {
         mDatasets = builder.mDatasets;
 
-        if (false) {
-            // TODO(b/33197203, 35727295): this is how mSaveInfo will be set once we don't support
-            // FillResponse.addSavableIds()
-            mSaveInfo = builder.mSaveInfo;
-            if (mSaveInfo != null) {
-                mSaveInfo.addSavableIds(mDatasets);
-                if (mSaveInfo.getSavableIds() == null) {
-                    throw new IllegalArgumentException(
-                            "need to provide at least one savable id on SaveInfo");
-                }
+        // TODO(b/33197203, 35727295): this is how mSaveInfo will be set once we don't support
+        // FillResponse.addSavableIds()
+        mSaveInfo = builder.mSaveInfo;
+        if (mSaveInfo != null) {
+            mSaveInfo.addSavableIds(mDatasets);
+            if (mSaveInfo.getSavableIds() == null) {
+                throw new IllegalArgumentException(
+                        "need to provide at least one savable id on SaveInfo");
             }
-        } else {
-            // Temporary workaround to support FillResponse.addSavableIds()
-            SaveInfo saveInfo = builder.mSaveInfoBuilder != null ? builder.mSaveInfoBuilder.build()
-                    : builder.mSaveInfo;
-
-            // Handle the the case where service didn't call addSavableIds() because it would
-            // contain just the ids from the datasets.
-            if (saveInfo == null && mDatasets != null) {
-                saveInfo = new SaveInfo.Builder(SaveInfo.SAVE_DATA_TYPE_GENERIC).build();
-            }
-            if (saveInfo != null) {
-                saveInfo.addSavableIds(mDatasets);
-                if (saveInfo.getSavableIds() == null) {
-                    throw new IllegalArgumentException(
-                            "need to provide at least one savable id on SaveInfo");
-                }
-            }
-            mSaveInfo = saveInfo;
         }
 
         mExtras = builder.mExtras;
@@ -236,9 +216,6 @@
      */
     public static final class Builder {
         private ArrayList<Dataset> mDatasets;
-        // TODO(b/33197203, 35727295): temporary builder use by deprecated addSavableIds() method,
-        // should be removed once that method is gone
-        private SaveInfo.Builder mSaveInfoBuilder;
         private SaveInfo mSaveInfo;
         private Bundle mExtras;
         private RemoteViews mPresentation;
@@ -316,21 +293,6 @@
             return this;
         }
 
-        /** @hide */
-        // TODO(b/33197203, 35727295): remove when not used by clients
-        public @NonNull Builder addSavableFields(@Nullable AutoFillId... ids) {
-            throwIfDestroyed();
-            if (mSaveInfo != null) {
-                throw new IllegalStateException("setSaveInfo() already called");
-            }
-            if (mSaveInfoBuilder == null) {
-                mSaveInfoBuilder = new SaveInfo.Builder(SaveInfo.SAVE_DATA_TYPE_GENERIC);
-            }
-            mSaveInfoBuilder.addSavableIds(ids);
-
-            return this;
-        }
-
         /**
          * Sets the {@link SaveInfo} associated with this response.
          *
@@ -340,9 +302,6 @@
          */
         public @NonNull Builder setSaveInfo(@NonNull SaveInfo saveInfo) {
             throwIfDestroyed();
-            if (mSaveInfoBuilder != null) {
-                throw new IllegalStateException("addSavableFields() already called");
-            }
             mSaveInfo = saveInfo;
             return this;
         }
@@ -374,8 +333,7 @@
         public FillResponse build() {
             throwIfDestroyed();
 
-            if (mAuthentication == null && mDatasets == null && mSaveInfoBuilder == null
-                    && mSaveInfo == null) {
+            if (mAuthentication == null && mDatasets == null && mSaveInfo == null) {
                 throw new IllegalArgumentException("need to provide at least one DataSet or a "
                         + "SaveInfo or an authentication with a presentation");
             }
diff --git a/core/java/android/text/FontConfig.java b/core/java/android/text/FontConfig.java
index 82e44dc..1087851 100644
--- a/core/java/android/text/FontConfig.java
+++ b/core/java/android/text/FontConfig.java
@@ -403,6 +403,7 @@
         private final String mLanguage;
         private final String mVariant;
         private final String mProviderAuthority;
+        private final String mProviderPackage;
         private final String mQuery;
 
         public Family(String name, List<Font> fonts, String language, String variant) {
@@ -411,18 +412,20 @@
             mLanguage = language;
             mVariant = variant;
             mProviderAuthority = null;
+            mProviderPackage = null;
             mQuery = null;
         }
 
         /**
          * @hide
          */
-        public Family(String providerAuthority, String query) {
+        public Family(String providerAuthority, String providerPackage, String query) {
             mName = null;
             mFonts = null;
             mLanguage = null;
             mVariant = null;
             mProviderAuthority = providerAuthority;
+            mProviderPackage = providerPackage;
             mQuery = query;
         }
 
@@ -435,6 +438,7 @@
                 mFonts.add(new Font(origin.mFonts.get(i)));
             }
             mProviderAuthority = origin.mProviderAuthority;
+            mProviderPackage = origin.mProviderPackage;
             mQuery = origin.mQuery;
         }
 
@@ -476,6 +480,13 @@
         /**
          * @hide
          */
+        public String getProviderPackage() {
+            return mProviderPackage;
+        }
+
+        /**
+         * @hide
+         */
         public String getQuery() {
             return mQuery;
         }
@@ -498,6 +509,11 @@
                 mProviderAuthority = null;
             }
             if (in.readInt() == 1) {
+                mProviderPackage = in.readString();
+            } else {
+                mProviderPackage = null;
+            }
+            if (in.readInt() == 1) {
                 mQuery = in.readString();
             } else {
                 mQuery = null;
@@ -517,6 +533,10 @@
             if (mProviderAuthority != null) {
                 out.writeString(mProviderAuthority);
             }
+            out.writeInt(mProviderPackage == null ? 0 : 1);
+            if (mProviderPackage != null) {
+                out.writeString(mProviderPackage);
+            }
             out.writeInt(mQuery == null ? 0 : 1);
             if (mQuery != null) {
                 out.writeString(mQuery);
diff --git a/core/java/android/util/AtomicFile.java b/core/java/android/util/AtomicFile.java
index 3aa3447..2f1abe9 100644
--- a/core/java/android/util/AtomicFile.java
+++ b/core/java/android/util/AtomicFile.java
@@ -17,13 +17,15 @@
 package android.util;
 
 import android.os.FileUtils;
-import android.util.Log;
+
+import libcore.io.IoUtils;
 
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
 import java.io.IOException;
+import java.util.function.Consumer;
 
 /**
  * Helper class for performing atomic operations on a file by creating a
@@ -244,4 +246,19 @@
             stream.close();
         }
     }
+
+    /** @hide */
+    public void write(Consumer<FileOutputStream> writeContent) {
+        FileOutputStream out = null;
+        try {
+            out = startWrite();
+            writeContent.accept(out);
+            finishWrite(out);
+        } catch (Throwable t) {
+            failWrite(out);
+            throw ExceptionUtils.propagate(t);
+        } finally {
+            IoUtils.closeQuietly(out);
+        }
+    }
 }
diff --git a/core/java/android/util/ExceptionUtils.java b/core/java/android/util/ExceptionUtils.java
index da0b609..87231e1 100644
--- a/core/java/android/util/ExceptionUtils.java
+++ b/core/java/android/util/ExceptionUtils.java
@@ -16,8 +16,11 @@
 
 package android.util;
 
+import android.annotation.NonNull;
 import android.os.ParcelableException;
 
+import com.android.internal.util.Preconditions;
+
 import java.io.IOException;
 
 /**
@@ -51,4 +54,11 @@
     public static String getCompleteMessage(Throwable t) {
         return getCompleteMessage(null, t);
     }
+
+    public static RuntimeException propagate(@NonNull Throwable t) {
+        Preconditions.checkNotNull(t);
+        if (t instanceof Error) throw (Error)t;
+        if (t instanceof RuntimeException) throw (RuntimeException)t;
+        throw new RuntimeException(t);
+    }
 }
diff --git a/core/java/android/util/MapCollections.java b/core/java/android/util/MapCollections.java
index 28b788b..80ab23c 100644
--- a/core/java/android/util/MapCollections.java
+++ b/core/java/android/util/MapCollections.java
@@ -22,6 +22,7 @@
 import java.util.Collection;
 import java.util.Iterator;
 import java.util.Map;
+import java.util.NoSuchElementException;
 import java.util.Set;
 
 /**
@@ -52,6 +53,7 @@
 
         @Override
         public T next() {
+            if (!hasNext()) throw new NoSuchElementException();
             Object res = colGetEntry(mIndex, mOffset);
             mIndex++;
             mCanRemove = true;
@@ -87,6 +89,7 @@
 
         @Override
         public Map.Entry<K, V> next() {
+            if (!hasNext()) throw new NoSuchElementException();
             mIndex++;
             mEntryValid = true;
             return this;
diff --git a/core/java/android/util/Patterns.java b/core/java/android/util/Patterns.java
index 910a6b1..ca39854 100644
--- a/core/java/android/util/Patterns.java
+++ b/core/java/android/util/Patterns.java
@@ -243,12 +243,12 @@
     public static final String GOOD_IRI_CHAR =
         "a-zA-Z0-9\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF";
 
-    public static final Pattern IP_ADDRESS
-        = Pattern.compile(
+    private static final String IP_ADDRESS_STRING =
             "((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4]"
             + "[0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]"
             + "[0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}"
-            + "|[1-9][0-9]|[0-9]))");
+            + "|[1-9][0-9]|[0-9]))";
+    public static final Pattern IP_ADDRESS = Pattern.compile(IP_ADDRESS_STRING);
 
     /**
      * Valid UCS characters defined in RFC 3987. Excludes space characters.
@@ -298,8 +298,8 @@
 
     private static final String HOST_NAME = "(" + IRI_LABEL + "\\.)+" + TLD;
 
-    public static final Pattern DOMAIN_NAME
-        = Pattern.compile("(" + HOST_NAME + "|" + IP_ADDRESS + ")");
+    private static final String DOMAIN_NAME_STR = "(" + HOST_NAME + "|" + IP_ADDRESS_STRING + ")";
+    public static final Pattern DOMAIN_NAME = Pattern.compile(DOMAIN_NAME_STR);
 
     private static final String PROTOCOL = "(?i:http|https|rtsp)://";
 
@@ -323,7 +323,7 @@
     public static final Pattern WEB_URL = Pattern.compile("("
             + "("
             + "(?:" + PROTOCOL + "(?:" + USER_INFO + ")?" + ")?"
-            + "(?:" + DOMAIN_NAME + ")"
+            + "(?:" + DOMAIN_NAME_STR + ")"
             + "(?:" + PORT_NUMBER + ")?"
             + ")"
             + "(" + PATH_AND_QUERY + ")?"
@@ -346,14 +346,14 @@
      * Regular expression that matches domain names using either {@link #STRICT_HOST_NAME} or
      * {@link #IP_ADDRESS}
      */
-    private static final Pattern STRICT_DOMAIN_NAME
-            = Pattern.compile("(?:" + STRICT_HOST_NAME + "|" + IP_ADDRESS + ")");
+    private static final String STRICT_DOMAIN_NAME = "(?:" + STRICT_HOST_NAME + "|"
+            + IP_ADDRESS_STRING + ")";
 
     /**
      * Regular expression that matches domain names without a TLD
      */
     private static final String RELAXED_DOMAIN_NAME =
-            "(?:" + "(?:" + IRI_LABEL + "(?:\\.(?=\\S))" +"?)+" + "|" + IP_ADDRESS + ")";
+            "(?:" + "(?:" + IRI_LABEL + "(?:\\.(?=\\S))" +"?)+" + "|" + IP_ADDRESS_STRING + ")";
 
     /**
      * Regular expression to match strings that do not start with a supported protocol. The TLDs
diff --git a/core/java/android/view/SurfaceControl.java b/core/java/android/view/SurfaceControl.java
index 519c1e2..b718696 100644
--- a/core/java/android/view/SurfaceControl.java
+++ b/core/java/android/view/SurfaceControl.java
@@ -95,11 +95,6 @@
             IBinder displayToken, int mode);
     private static native void nativeDeferTransactionUntil(long nativeObject,
             IBinder handle, long frame);
-    private static native void nativeDeferTransactionUntilSurface(long nativeObject,
-            long surfaceObject, long frame);
-    private static native void nativeReparentChildren(long nativeObject,
-            IBinder handle);
-    private static native void nativeSeverChildren(long nativeObject);
     private static native void nativeSetOverrideScalingMode(long nativeObject,
             int scalingMode);
     private static native IBinder nativeGetHandle(long nativeObject);
@@ -423,23 +418,7 @@
     }
 
     public void deferTransactionUntil(IBinder handle, long frame) {
-        if (frame > 0) {
-            nativeDeferTransactionUntil(mNativeObject, handle, frame);
-        }
-    }
-
-    public void deferTransactionUntil(Surface barrier, long frame) {
-        if (frame > 0) {
-            nativeDeferTransactionUntilSurface(mNativeObject, barrier.mNativeObject, frame);
-        }
-    }
-
-    public void reparentChildren(IBinder newParentHandle) {
-        nativeReparentChildren(mNativeObject, newParentHandle);
-    }
-
-    public void detachChildren() {
-        nativeSeverChildren(mNativeObject);
+        nativeDeferTransactionUntil(mNativeObject, handle, frame);
     }
 
     public void setOverrideScalingMode(int scalingMode) {
diff --git a/core/java/android/view/SurfaceSession.java b/core/java/android/view/SurfaceSession.java
index b5912bc..3cf5af4 100644
--- a/core/java/android/view/SurfaceSession.java
+++ b/core/java/android/view/SurfaceSession.java
@@ -27,7 +27,6 @@
     private long mNativeClient; // SurfaceComposerClient*
 
     private static native long nativeCreate();
-    private static native long nativeCreateScoped(long surfacePtr);
     private static native void nativeDestroy(long ptr);
     private static native void nativeKill(long ptr);
 
@@ -36,10 +35,6 @@
         mNativeClient = nativeCreate();
     }
 
-    public SurfaceSession(Surface root) {
-        mNativeClient = nativeCreateScoped(root.mNativeObject);
-    }
-
     /* no user serviceable parts here ... */
     @Override
     protected void finalize() throws Throwable {
diff --git a/core/java/android/view/SurfaceView.java b/core/java/android/view/SurfaceView.java
index 61b1247..d2577d4 100644
--- a/core/java/android/view/SurfaceView.java
+++ b/core/java/android/view/SurfaceView.java
@@ -16,10 +16,6 @@
 
 package android.view;
 
-import static android.view.WindowManagerPolicy.APPLICATION_MEDIA_SUBLAYER;
-import static android.view.WindowManagerPolicy.APPLICATION_MEDIA_OVERLAY_SUBLAYER;
-import static android.view.WindowManagerPolicy.APPLICATION_PANEL_SUBLAYER;
-
 import android.content.Context;
 import android.content.res.CompatibilityInfo.Translator;
 import android.content.res.Configuration;
@@ -30,12 +26,16 @@
 import android.graphics.Region;
 import android.os.Handler;
 import android.os.Message;
+import android.os.ParcelFileDescriptor;
+import android.os.RemoteException;
 import android.os.SystemClock;
 import android.util.AttributeSet;
 import android.util.Log;
 
+import com.android.internal.view.BaseIWindow;
 import com.android.internal.view.SurfaceCallbackHelper;
 
+import java.lang.ref.WeakReference;
 import java.util.ArrayList;
 import java.util.concurrent.locks.ReentrantLock;
 
@@ -92,8 +92,8 @@
  * positioned asynchronously.</p>
  */
 public class SurfaceView extends View {
-    private static final String TAG = "SurfaceView";
-    private static final boolean DEBUG = false;
+    static private final String TAG = "SurfaceView";
+    static private final boolean DEBUG = false;
 
     final ArrayList<SurfaceHolder.Callback> mCallbacks
             = new ArrayList<SurfaceHolder.Callback>();
@@ -102,23 +102,28 @@
 
     final ReentrantLock mSurfaceLock = new ReentrantLock();
     final Surface mSurface = new Surface();       // Current surface in use
+    final Surface mNewSurface = new Surface();    // New surface we are switching to
     boolean mDrawingStopped = true;
-    // We use this to track if the application has produced a frame
-    // in to the Surface. Up until that point, we should be careful not to punch
-    // holes.
-    boolean mDrawFinished = false;
 
-    final Rect mScreenRect = new Rect();
-    SurfaceSession mSurfaceSession;
-
-    SurfaceControl mSurfaceControl;
+    final WindowManager.LayoutParams mLayout
+            = new WindowManager.LayoutParams();
+    IWindowSession mSession;
+    MyWindow mWindow;
+    final Rect mVisibleInsets = new Rect();
+    final Rect mWinFrame = new Rect();
+    final Rect mOverscanInsets = new Rect();
+    final Rect mContentInsets = new Rect();
+    final Rect mStableInsets = new Rect();
+    final Rect mOutsets = new Rect();
+    final Rect mBackdropFrame = new Rect();
     final Rect mTmpRect = new Rect();
     final Configuration mConfiguration = new Configuration();
 
     static final int KEEP_SCREEN_ON_MSG = 1;
-    static final int DRAW_FINISHED_MSG = 2;
+    static final int GET_NEW_SURFACE_MSG = 2;
+    static final int UPDATE_WINDOW_MSG = 3;
 
-    int mSubLayer = APPLICATION_MEDIA_SUBLAYER;
+    int mWindowType = WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA;
 
     boolean mIsCreating = false;
     private volatile boolean mRtHandlingPositionUpdates = false;
@@ -130,9 +135,11 @@
                 case KEEP_SCREEN_ON_MSG: {
                     setKeepScreenOn(msg.arg1 != 0);
                 } break;
-                case DRAW_FINISHED_MSG: {
-                    mDrawFinished = true;
-                    invalidate();
+                case GET_NEW_SURFACE_MSG: {
+                    handleGetNewSurface();
+                } break;
+                case UPDATE_WINDOW_MSG: {
+                    updateWindow();
                 } break;
             }
         }
@@ -142,7 +149,7 @@
             = new ViewTreeObserver.OnScrollChangedListener() {
                     @Override
                     public void onScrollChanged() {
-                        updateSurface();
+                        updateWindow();
                     }
             };
 
@@ -152,14 +159,13 @@
                 public boolean onPreDraw() {
                     // reposition ourselves where the surface is
                     mHaveFrame = getWidth() > 0 && getHeight() > 0;
-                    updateSurface();
+                    updateWindow();
                     return true;
                 }
             };
 
     boolean mRequestedVisible = false;
     boolean mWindowVisibility = false;
-    boolean mLastWindowVisibility = false;
     boolean mViewVisibility = false;
     int mRequestedWidth = -1;
     int mRequestedHeight = -1;
@@ -175,17 +181,19 @@
     boolean mVisible = false;
     int mWindowSpaceLeft = -1;
     int mWindowSpaceTop = -1;
-    int mSurfaceWidth = -1;
-    int mSurfaceHeight = -1;
+    int mWindowSpaceWidth = -1;
+    int mWindowSpaceHeight = -1;
     int mFormat = -1;
     final Rect mSurfaceFrame = new Rect();
     int mLastSurfaceWidth = -1, mLastSurfaceHeight = -1;
+    boolean mUpdateWindowNeeded;
+    boolean mReportDrawNeeded;
     private Translator mTranslator;
+    private int mWindowInsetLeft;
+    private int mWindowInsetTop;
 
     private boolean mGlobalListenersAdded;
 
-    private int mSurfaceFlags = SurfaceControl.HIDDEN;
-
     public SurfaceView(Context context) {
         this(context, null);
     }
@@ -219,8 +227,11 @@
     protected void onAttachedToWindow() {
         super.onAttachedToWindow();
         mParent.requestTransparentRegion(this);
+        mSession = getWindowSession();
+        mLayout.token = getWindowToken();
+        mLayout.setTitle("SurfaceView - " + getViewRootImpl().getTitle());
+        mLayout.packageName = mContext.getOpPackageName();
         mViewVisibility = getVisibility() == VISIBLE;
-        mRequestedVisible = mViewVisibility && mWindowVisibility;
 
         if (!mGlobalListenersAdded) {
             ViewTreeObserver observer = getViewTreeObserver();
@@ -235,7 +246,7 @@
         super.onWindowVisibilityChanged(visibility);
         mWindowVisibility = visibility == VISIBLE;
         mRequestedVisible = mWindowVisibility && mViewVisibility;
-        updateSurface();
+        updateWindow();
     }
 
     @Override
@@ -253,7 +264,7 @@
             requestLayout();
         }
         mRequestedVisible = newRequestedVisible;
-        updateSurface();
+        updateWindow();
     }
 
     @Override
@@ -266,14 +277,19 @@
         }
 
         mRequestedVisible = false;
-
-        updateSurface();
-        if (mSurfaceControl != null) {
-            mSurfaceControl.destroy();
-        }
-        mSurfaceControl = null;
-
+        updateWindow();
         mHaveFrame = false;
+        if (mWindow != null) {
+            try {
+                mSession.remove(mWindow);
+            } catch (RemoteException ex) {
+                // Not much we can do here...
+            }
+            mWindow = null;
+        }
+        mSession = null;
+        mLayout.token = null;
+
         super.onDetachedFromWindow();
     }
 
@@ -292,13 +308,13 @@
     @Override
     protected boolean setFrame(int left, int top, int right, int bottom) {
         boolean result = super.setFrame(left, top, right, bottom);
-        updateSurface();
+        updateWindow();
         return result;
     }
 
     @Override
     public boolean gatherTransparentRegion(Region region) {
-        if (isAboveParent()) {
+        if (mWindowType == WindowManager.LayoutParams.TYPE_APPLICATION_PANEL) {
             return super.gatherTransparentRegion(region);
         }
 
@@ -325,7 +341,7 @@
 
     @Override
     public void draw(Canvas canvas) {
-        if (mDrawFinished && !isAboveParent()) {
+        if (mWindowType != WindowManager.LayoutParams.TYPE_APPLICATION_PANEL) {
             // draw() is not called when SKIP_DRAW is set
             if ((mPrivateFlags & PFLAG_SKIP_DRAW) == 0) {
                 // punch a whole in the view-hierarchy below us
@@ -337,8 +353,8 @@
 
     @Override
     protected void dispatchDraw(Canvas canvas) {
-        if (mDrawFinished && !isAboveParent()) {
-            // draw() is not called when SKIP_DRAW is set
+        if (mWindowType != WindowManager.LayoutParams.TYPE_APPLICATION_PANEL) {
+            // if SKIP_DRAW is cleared, draw() has already punched a hole
             if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
                 // punch a whole in the view-hierarchy below us
                 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
@@ -359,8 +375,9 @@
      * <p>Calling this overrides any previous call to {@link #setZOrderOnTop}.
      */
     public void setZOrderMediaOverlay(boolean isMediaOverlay) {
-        mSubLayer = isMediaOverlay
-            ? APPLICATION_MEDIA_OVERLAY_SUBLAYER : APPLICATION_MEDIA_SUBLAYER;
+        mWindowType = isMediaOverlay
+                ? WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA_OVERLAY
+                : WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA;
     }
 
     /**
@@ -378,9 +395,12 @@
      */
     public void setZOrderOnTop(boolean onTop) {
         if (onTop) {
-            mSubLayer = APPLICATION_PANEL_SUBLAYER;
+            mWindowType = WindowManager.LayoutParams.TYPE_APPLICATION_PANEL;
+            // ensures the surface is placed below the IME
+            mLayout.flags |= WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
         } else {
-            mSubLayer = APPLICATION_MEDIA_SUBLAYER;
+            mWindowType = WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA;
+            mLayout.flags &= ~WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
         }
     }
 
@@ -398,32 +418,31 @@
      */
     public void setSecure(boolean isSecure) {
         if (isSecure) {
-            mSurfaceFlags |= SurfaceControl.SECURE;
+            mLayout.flags |= WindowManager.LayoutParams.FLAG_SECURE;
         } else {
-            mSurfaceFlags &= ~SurfaceControl.SECURE;
+            mLayout.flags &= ~WindowManager.LayoutParams.FLAG_SECURE;
         }
     }
 
-    private Rect getParentSurfaceInsets() {
-        final ViewRootImpl root = getViewRootImpl();
-        if (root == null) {
-            return null;
-        } else {
-            return root.mWindowAttributes.surfaceInsets;
-        }
+    /**
+     * Hack to allow special layering of windows.  The type is one of the
+     * types in WindowManager.LayoutParams.  This is a hack so:
+     * @hide
+     */
+    public void setWindowType(int type) {
+        mWindowType = type;
     }
 
     /** @hide */
-    protected void updateSurface() {
+    protected void updateWindow() {
         if (!mHaveFrame) {
             return;
         }
         ViewRootImpl viewRoot = getViewRootImpl();
-        if (viewRoot == null || viewRoot.mSurface == null || !viewRoot.mSurface.isValid()) {
-            return;
+        if (viewRoot != null) {
+            mTranslator = viewRoot.mTranslator;
         }
 
-        mTranslator = viewRoot.mTranslator;
         if (mTranslator != null) {
             mSurface.setCompatibilityTranslator(mTranslator);
         }
@@ -433,15 +452,17 @@
         int myHeight = mRequestedHeight;
         if (myHeight <= 0) myHeight = getHeight();
 
+        final boolean creating = mWindow == null;
         final boolean formatChanged = mFormat != mRequestedFormat;
-        final boolean creating = (mSurfaceControl == null || formatChanged)
-                && mRequestedVisible;
-        final boolean sizeChanged = mSurfaceWidth != myWidth || mSurfaceHeight != myHeight;
+        final boolean sizeChanged = mWindowSpaceWidth != myWidth || mWindowSpaceHeight != myHeight;
         final boolean visibleChanged = mVisible != mRequestedVisible;
-        final boolean windowVisibleChanged = mWindowVisibility != mLastWindowVisibility;
+        final boolean layoutSizeChanged = getWidth() != mLayout.width
+                || getHeight() != mLayout.height;
+
         boolean redrawNeeded = false;
 
-        if (creating || formatChanged || sizeChanged || visibleChanged || windowVisibleChanged) {
+        if (creating || formatChanged || sizeChanged || visibleChanged
+            || mUpdateWindowNeeded || mReportDrawNeeded) {
             getLocationInWindow(mLocation);
 
             if (DEBUG) Log.i(TAG, System.identityHashCode(this) + " "
@@ -455,77 +476,93 @@
                 final boolean visible = mVisible = mRequestedVisible;
                 mWindowSpaceLeft = mLocation[0];
                 mWindowSpaceTop = mLocation[1];
-                mSurfaceWidth = myWidth;
-                mSurfaceHeight = myHeight;
+                mWindowSpaceWidth = myWidth;
+                mWindowSpaceHeight = myHeight;
                 mFormat = mRequestedFormat;
-                mLastWindowVisibility = mWindowVisibility;
 
-                mScreenRect.left = mWindowSpaceLeft;
-                mScreenRect.top = mWindowSpaceTop;
-                mScreenRect.right = mWindowSpaceLeft + getWidth();
-                mScreenRect.bottom = mWindowSpaceTop + getHeight();
+                // Scaling/Translate window's layout here because mLayout is not used elsewhere.
+
+                // Places the window relative
+                mLayout.x = mWindowSpaceLeft;
+                mLayout.y = mWindowSpaceTop;
+                mLayout.width = getWidth();
+                mLayout.height = getHeight();
                 if (mTranslator != null) {
-                    mTranslator.translateRectInAppWindowToScreen(mScreenRect);
+                    mTranslator.translateLayoutParamsInAppWindowToScreen(mLayout);
                 }
 
-                final Rect surfaceInsets = getParentSurfaceInsets();
-                mScreenRect.offset(surfaceInsets.left, surfaceInsets.top);
-
-                if (creating) {
-                    mSurfaceSession = new SurfaceSession(viewRoot.mSurface);
-                    mSurfaceControl = new SurfaceControl(mSurfaceSession,
-                            "SurfaceView - " + viewRoot.getTitle().toString(),
-                            mSurfaceWidth, mSurfaceHeight, mFormat,
-                            mSurfaceFlags);
+                mLayout.format = mRequestedFormat;
+                mLayout.flags |=WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
+                              | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
+                              | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
+                              | WindowManager.LayoutParams.FLAG_SCALED
+                              | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
+                              | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
+                              ;
+                if (!creating && !sizeChanged) {
+                    mLayout.privateFlags |=
+                            WindowManager.LayoutParams.PRIVATE_FLAG_PRESERVE_GEOMETRY;
+                } else {
+                    mLayout.privateFlags &=
+                            ~WindowManager.LayoutParams.PRIVATE_FLAG_PRESERVE_GEOMETRY;
                 }
 
-                boolean realSizeChanged = false;
+                if (!getContext().getResources().getCompatibilityInfo().supportsScreen()) {
+                    mLayout.privateFlags |=
+                            WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
+                }
+                mLayout.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_NO_MOVE_ANIMATION
+                    | WindowManager.LayoutParams.PRIVATE_FLAG_LAYOUT_CHILD_WINDOW_IN_PARENT_FRAME;
+
+                if (mWindow == null) {
+                    Display display = getDisplay();
+                    mWindow = new MyWindow(this);
+                    mLayout.type = mWindowType;
+                    mLayout.gravity = Gravity.START|Gravity.TOP;
+                    mSession.addToDisplayWithoutInputChannel(mWindow, mWindow.mSeq, mLayout,
+                            mVisible ? VISIBLE : GONE, display.getDisplayId(), mContentInsets,
+                            mStableInsets);
+                }
+
+                boolean realSizeChanged;
+                boolean reportDrawNeeded;
+
+                int relayoutResult;
 
                 mSurfaceLock.lock();
                 try {
+                    mUpdateWindowNeeded = false;
+                    reportDrawNeeded = mReportDrawNeeded;
+                    mReportDrawNeeded = false;
                     mDrawingStopped = !visible;
 
                     if (DEBUG) Log.i(TAG, System.identityHashCode(this) + " "
                             + "Cur surface: " + mSurface);
 
-                    SurfaceControl.openTransaction();
-                    try {
-                        mSurfaceControl.setLayer(mSubLayer);
-                        if (mViewVisibility) {
-                            mSurfaceControl.show();
-                        } else {
-                            mSurfaceControl.hide();
-                        }
-
-                        // While creating the surface, we will set it's initial
-                        // geometry. Outside of that though, we should generally
-                        // leave it to the RenderThread.
-                        if (creating || !mRtHandlingPositionUpdates) {
-                            mSurfaceControl.setPosition(mScreenRect.left, mScreenRect.top);
-                            mSurfaceControl.setMatrix(mScreenRect.width() / (float) mSurfaceWidth,
-                                    0.0f, 0.0f,
-                                    mScreenRect.height() / (float) mSurfaceHeight);
-                        }
-                        if (sizeChanged) {
-                            mSurfaceControl.setSize(mSurfaceWidth, mSurfaceHeight);
-                        }
-                    } finally {
-                        SurfaceControl.closeTransaction();
+                    relayoutResult = mSession.relayout(
+                        mWindow, mWindow.mSeq, mLayout, mWindowSpaceWidth, mWindowSpaceHeight,
+                            visible ? VISIBLE : GONE,
+                            WindowManagerGlobal.RELAYOUT_DEFER_SURFACE_DESTROY,
+                            mWinFrame, mOverscanInsets, mContentInsets,
+                            mVisibleInsets, mStableInsets, mOutsets, mBackdropFrame,
+                            mConfiguration, mNewSurface);
+                    if ((relayoutResult & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) {
+                        reportDrawNeeded = true;
                     }
 
-                    if (sizeChanged || creating) {
-                        redrawNeeded = true;
-                    }
+                    if (DEBUG) Log.i(TAG, System.identityHashCode(this) + " "
+                            + "New surface: " + mNewSurface
+                            + ", vis=" + visible + ", frame=" + mWinFrame);
 
                     mSurfaceFrame.left = 0;
                     mSurfaceFrame.top = 0;
                     if (mTranslator == null) {
-                        mSurfaceFrame.right = mSurfaceWidth;
-                        mSurfaceFrame.bottom = mSurfaceHeight;
+                        mSurfaceFrame.right = mWinFrame.width();
+                        mSurfaceFrame.bottom = mWinFrame.height();
                     } else {
                         float appInvertedScale = mTranslator.applicationInvertedScale;
-                        mSurfaceFrame.right = (int) (mSurfaceWidth * appInvertedScale + 0.5f);
-                        mSurfaceFrame.bottom = (int) (mSurfaceHeight * appInvertedScale + 0.5f);
+                        mSurfaceFrame.right = (int) (mWinFrame.width() * appInvertedScale + 0.5f);
+                        mSurfaceFrame.bottom = (int) (mWinFrame.height() * appInvertedScale + 0.5f);
                     }
 
                     final int surfaceWidth = mSurfaceFrame.right;
@@ -539,11 +576,12 @@
                 }
 
                 try {
-                    redrawNeeded |= visible && !mDrawFinished;
+                    redrawNeeded |= creating | reportDrawNeeded;
 
                     SurfaceHolder.Callback callbacks[] = null;
 
-                    final boolean surfaceChanged = creating;
+                    final boolean surfaceChanged = (relayoutResult
+                            & WindowManagerGlobal.RELAYOUT_RES_SURFACE_CHANGED) != 0;
                     if (mSurfaceCreated && (surfaceChanged || (!visible && visibleChanged))) {
                         mSurfaceCreated = false;
                         if (mSurface.isValid()) {
@@ -570,10 +608,7 @@
                         }
                     }
 
-                    if (creating) {
-                        mSurface.copyFrom(mSurfaceControl);
-                    }
-
+                    mSurface.transferFrom(mNewSurface);
                     if (visible && mSurface.isValid()) {
                         if (!mSurfaceCreated && (surfaceChanged || visibleChanged)) {
                             mSurfaceCreated = true;
@@ -606,55 +641,53 @@
                                 callbacks = getSurfaceCallbacks();
                             }
                             SurfaceCallbackHelper sch =
-                                    new SurfaceCallbackHelper(this::onDrawFinished);
+                                    new SurfaceCallbackHelper(mSession, mWindow);
                             sch.dispatchSurfaceRedrawNeededAsync(mSurfaceHolder, callbacks);
                         }
                     }
                 } finally {
                     mIsCreating = false;
-                    if (mSurfaceControl != null && !mSurfaceCreated) {
-                        mSurfaceControl.destroy();
-                        mSurfaceControl = null;
-                    }
+                    mSession.performDeferredDestroy(mWindow);
                 }
-            } catch (Exception ex) {
+            } catch (RemoteException ex) {
                 Log.e(TAG, "Exception from relayout", ex);
             }
             if (DEBUG) Log.v(
-                TAG, "Layout: x=" + mScreenRect.left + " y=" + mScreenRect.top
-                + " w=" + mScreenRect.width() + " h=" + mScreenRect.height()
-                + ", frame=" + mSurfaceFrame);
+                TAG, "Layout: x=" + mLayout.x + " y=" + mLayout.y +
+                " w=" + mLayout.width + " h=" + mLayout.height +
+                ", frame=" + mSurfaceFrame);
         } else {
             // Calculate the window position in case RT loses the window
             // and we need to fallback to a UI-thread driven position update
-            getLocationInSurface(mLocation);
+            getLocationInWindow(mLocation);
             final boolean positionChanged = mWindowSpaceLeft != mLocation[0]
                     || mWindowSpaceTop != mLocation[1];
-            final boolean layoutSizeChanged = getWidth() != mScreenRect.width()
-                    || getHeight() != mScreenRect.height();
             if (positionChanged || layoutSizeChanged) { // Only the position has changed
                 mWindowSpaceLeft = mLocation[0];
                 mWindowSpaceTop = mLocation[1];
-                // For our size changed check, we keep mScreenRect.width() and mScreenRect.height()
+                // For our size changed check, we keep mLayout.width and mLayout.height
                 // in view local space.
-                mLocation[0] = getWidth();
-                mLocation[1] = getHeight();
+                mLocation[0] = mLayout.width = getWidth();
+                mLocation[1] = mLayout.height = getHeight();
 
-                mScreenRect.set(mWindowSpaceLeft, mWindowSpaceTop,
+                transformFromViewToWindowSpace(mLocation);
+
+                mTmpRect.set(mWindowSpaceLeft, mWindowSpaceTop,
                         mLocation[0], mLocation[1]);
 
                 if (mTranslator != null) {
-                    mTranslator.translateRectInAppWindowToScreen(mScreenRect);
+                    mTranslator.translateRectInAppWindowToScreen(mTmpRect);
                 }
 
                 if (!isHardwareAccelerated() || !mRtHandlingPositionUpdates) {
                     try {
-                        if (DEBUG) Log.d(TAG, String.format("%d updateSurfacePosition UI, " +
+                        if (DEBUG) Log.d(TAG, String.format("%d updateWindowPosition UI, " +
                                 "postion = [%d, %d, %d, %d]", System.identityHashCode(this),
-                                mScreenRect.left, mScreenRect.top,
-                                mScreenRect.right, mScreenRect.bottom));
-                        setParentSpaceRectangle(mScreenRect, -1);
-                    } catch (Exception ex) {
+                                mTmpRect.left, mTmpRect.top,
+                                mTmpRect.right, mTmpRect.bottom));
+                        mSession.repositionChild(mWindow, mTmpRect.left, mTmpRect.top,
+                                mTmpRect.right, mTmpRect.bottom, -1, mTmpRect);
+                    } catch (RemoteException ex) {
                         Log.e(TAG, "Exception from relayout", ex);
                     }
                 }
@@ -662,43 +695,20 @@
         }
     }
 
-    private void onDrawFinished() {
-        if (DEBUG) {
-            Log.i(TAG, System.identityHashCode(this) + " "
-                    + "finishedDrawing");
-        }
-        mHandler.sendEmptyMessage(DRAW_FINISHED_MSG);
-    }
-
-    private void setParentSpaceRectangle(Rect position, long frameNumber) {
-        ViewRootImpl viewRoot = getViewRootImpl();
-
-        SurfaceControl.openTransaction();
-        try {
-            if (frameNumber > 0) {
-                mSurfaceControl.deferTransactionUntil(viewRoot.mSurface, frameNumber);
-            }
-            mSurfaceControl.setPosition(position.left, position.top);
-            mSurfaceControl.setMatrix(position.width() / (float) mSurfaceWidth,
-                    0.0f, 0.0f,
-                    position.height() / (float) mSurfaceHeight);
-        } finally {
-            SurfaceControl.closeTransaction();
-        }
-    }
-
     private Rect mRTLastReportedPosition = new Rect();
 
     /**
      * Called by native by a Rendering Worker thread to update the window position
      * @hide
      */
-    public final void updateSurfacePosition_renderWorker(long frameNumber,
+    public final void updateWindowPosition_renderWorker(long frameNumber,
             int left, int top, int right, int bottom) {
-        if (mSurfaceControl == null) {
+        IWindowSession session = mSession;
+        MyWindow window = mWindow;
+        if (session == null || window == null) {
+            // Guess we got detached, that sucks
             return;
         }
-
         // TODO: This is teensy bit racey in that a brand new SurfaceView moving on
         // its 2nd frame if RenderThread is running slowly could potentially see
         // this as false, enter the branch, get pre-empted, then this comes along
@@ -716,29 +726,35 @@
         }
         try {
             if (DEBUG) {
-                Log.d(TAG, String.format("%d updateSurfacePosition RenderWorker, frameNr = %d, " +
+                Log.d(TAG, String.format("%d updateWindowPosition RenderWorker, frameNr = %d, " +
                         "postion = [%d, %d, %d, %d]", System.identityHashCode(this),
                         frameNumber, left, top, right, bottom));
             }
-            mRTLastReportedPosition.set(left, top, right, bottom);
-            setParentSpaceRectangle(mRTLastReportedPosition, frameNumber);
+            // Just using mRTLastReportedPosition as a dummy rect here
+            session.repositionChild(window, left, top, right, bottom,
+                    frameNumber,
+                    mRTLastReportedPosition);
             // Now overwrite mRTLastReportedPosition with our values
-        } catch (Exception ex) {
+            mRTLastReportedPosition.set(left, top, right, bottom);
+        } catch (RemoteException ex) {
             Log.e(TAG, "Exception from repositionChild", ex);
         }
     }
 
     /**
-     * Called by native on RenderThread to notify that the view is no longer in the
+     * Called by native on RenderThread to notify that the window is no longer in the
      * draw tree. UI thread is blocked at this point.
      * @hide
      */
-    public final void surfacePositionLost_uiRtSync(long frameNumber) {
+    public final void windowPositionLost_uiRtSync(long frameNumber) {
         if (DEBUG) {
             Log.d(TAG, String.format("%d windowPositionLost, frameNr = %d",
                     System.identityHashCode(this), frameNumber));
         }
-        if (mSurfaceControl == null) {
+        IWindowSession session = mSession;
+        MyWindow window = mWindow;
+        if (session == null || window == null) {
+            // We got detached prior to receiving this, abort
             return;
         }
         if (mRtHandlingPositionUpdates) {
@@ -747,14 +763,19 @@
             // safely access other member variables at this time.
             // So do what the UI thread would have done if RT wasn't handling position
             // updates.
-            if (!mScreenRect.isEmpty() && !mScreenRect.equals(mRTLastReportedPosition)) {
+            mTmpRect.set(mLayout.x, mLayout.y,
+                    mLayout.x + mLayout.width,
+                    mLayout.y + mLayout.height);
+
+            if (!mTmpRect.isEmpty() && !mTmpRect.equals(mRTLastReportedPosition)) {
                 try {
-                    if (DEBUG) Log.d(TAG, String.format("%d updateSurfacePosition, " +
+                    if (DEBUG) Log.d(TAG, String.format("%d updateWindowPosition, " +
                             "postion = [%d, %d, %d, %d]", System.identityHashCode(this),
-                            mScreenRect.left, mScreenRect.top,
-                            mScreenRect.right, mScreenRect.bottom));
-                    setParentSpaceRectangle(mScreenRect, frameNumber);
-                } catch (Exception ex) {
+                            mTmpRect.left, mTmpRect.top,
+                            mTmpRect.right, mTmpRect.bottom));
+                    session.repositionChild(window, mTmpRect.left, mTmpRect.top,
+                            mTmpRect.right, mTmpRect.bottom, frameNumber, mWinFrame);
+                } catch (RemoteException ex) {
                     Log.e(TAG, "Exception from relayout", ex);
                 }
             }
@@ -771,6 +792,10 @@
         return callbacks;
     }
 
+    void handleGetNewSurface() {
+        updateWindow();
+    }
+
     /**
      * Check to see if the surface has fixed size dimensions or if the surface's
      * dimensions are dimensions are dependent on its current layout.
@@ -782,8 +807,65 @@
         return (mRequestedWidth != -1 || mRequestedHeight != -1);
     }
 
-    private boolean isAboveParent() {
-        return mSubLayer >= 0;
+    private static class MyWindow extends BaseIWindow {
+        private final WeakReference<SurfaceView> mSurfaceView;
+
+        public MyWindow(SurfaceView surfaceView) {
+            mSurfaceView = new WeakReference<SurfaceView>(surfaceView);
+        }
+
+        @Override
+        public void resized(Rect frame, Rect overscanInsets, Rect contentInsets,
+                Rect visibleInsets, Rect stableInsets, Rect outsets, boolean reportDraw,
+                Configuration newConfig, Rect backDropRect, boolean forceLayout,
+                boolean alwaysConsumeNavBar, int displayId) {
+            SurfaceView surfaceView = mSurfaceView.get();
+            if (surfaceView != null) {
+                if (DEBUG) Log.v(TAG, surfaceView + " got resized: w=" + frame.width()
+                        + " h=" + frame.height() + ", cur w=" + mCurWidth + " h=" + mCurHeight);
+                surfaceView.mSurfaceLock.lock();
+                try {
+                    if (reportDraw) {
+                        surfaceView.mUpdateWindowNeeded = true;
+                        surfaceView.mReportDrawNeeded = true;
+                        surfaceView.mHandler.sendEmptyMessage(UPDATE_WINDOW_MSG);
+                    } else if (surfaceView.mWinFrame.width() != frame.width()
+                            || surfaceView.mWinFrame.height() != frame.height()
+                            || forceLayout) {
+                        surfaceView.mUpdateWindowNeeded = true;
+                        surfaceView.mHandler.sendEmptyMessage(UPDATE_WINDOW_MSG);
+                    }
+                } finally {
+                    surfaceView.mSurfaceLock.unlock();
+                }
+            }
+        }
+
+        @Override
+        public void dispatchAppVisibility(boolean visible) {
+            // The point of SurfaceView is to let the app control the surface.
+        }
+
+        @Override
+        public void dispatchGetNewSurface() {
+            SurfaceView surfaceView = mSurfaceView.get();
+            if (surfaceView != null) {
+                Message msg = surfaceView.mHandler.obtainMessage(GET_NEW_SURFACE_MSG);
+                surfaceView.mHandler.sendMessage(msg);
+            }
+        }
+
+        @Override
+        public void windowFocusChanged(boolean hasFocus, boolean touchEnabled) {
+            Log.w("SurfaceView", "Unexpected focus in surface: focus=" + hasFocus + ", touchEnabled=" + touchEnabled);
+        }
+
+        @Override
+        public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
+        }
+
+        int mCurWidth = -1;
+        int mCurHeight = -1;
     }
 
     private final SurfaceHolder mSurfaceHolder = new SurfaceHolder() {
@@ -831,14 +913,15 @@
 
         @Override
         public void setFormat(int format) {
+
             // for backward compatibility reason, OPAQUE always
             // means 565 for SurfaceView
             if (format == PixelFormat.OPAQUE)
                 format = PixelFormat.RGB_565;
 
             mRequestedFormat = format;
-            if (mSurfaceControl != null) {
-                updateSurface();
+            if (mWindow != null) {
+                updateWindow();
             }
         }
 
@@ -899,10 +982,10 @@
             mSurfaceLock.lock();
 
             if (DEBUG) Log.i(TAG, System.identityHashCode(this) + " " + "Locking canvas... stopped="
-                    + mDrawingStopped + ", surfaceControl=" + mSurfaceControl);
+                    + mDrawingStopped + ", win=" + mWindow);
 
             Canvas c = null;
-            if (!mDrawingStopped && mSurfaceControl != null) {
+            if (!mDrawingStopped && mWindow != null) {
                 try {
                     if (hardware) {
                         c = mSurface.lockHardwareCanvas();
diff --git a/core/java/android/view/ViewDebug.java b/core/java/android/view/ViewDebug.java
index 047a515..66c0578 100644
--- a/core/java/android/view/ViewDebug.java
+++ b/core/java/android/view/ViewDebug.java
@@ -107,10 +107,10 @@
          * these human readable values:
          *
          * <pre>
-         * @ViewDebug.ExportedProperty(mapping = {
-         *     @ViewDebug.IntToString(from = 0, to = "VISIBLE"),
-         *     @ViewDebug.IntToString(from = 4, to = "INVISIBLE"),
-         *     @ViewDebug.IntToString(from = 8, to = "GONE")
+         * {@literal @}ViewDebug.ExportedProperty(mapping = {
+         *     {@literal @}ViewDebug.IntToString(from = 0, to = "VISIBLE"),
+         *     {@literal @}ViewDebug.IntToString(from = 4, to = "INVISIBLE"),
+         *     {@literal @}ViewDebug.IntToString(from = 8, to = "GONE")
          * })
          * public int getVisibility() { ...
          * <pre>
@@ -127,10 +127,10 @@
          * of an array:
          *
          * <pre>
-         * @ViewDebug.ExportedProperty(indexMapping = {
-         *     @ViewDebug.IntToString(from = 0, to = "INVALID"),
-         *     @ViewDebug.IntToString(from = 1, to = "FIRST"),
-         *     @ViewDebug.IntToString(from = 2, to = "SECOND")
+         * {@literal @}ViewDebug.ExportedProperty(indexMapping = {
+         *     {@literal @}ViewDebug.IntToString(from = 0, to = "INVALID"),
+         *     {@literal @}ViewDebug.IntToString(from = 1, to = "FIRST"),
+         *     {@literal @}ViewDebug.IntToString(from = 2, to = "SECOND")
          * })
          * private int[] mElements;
          * <pre>
@@ -148,9 +148,11 @@
          * for the flags of an integer:
          *
          * <pre>
-         * @ViewDebug.ExportedProperty(flagMapping = {
-         *     @ViewDebug.FlagToString(mask = ENABLED_MASK, equals = ENABLED, name = "ENABLED"),
-         *     @ViewDebug.FlagToString(mask = ENABLED_MASK, equals = DISABLED, name = "DISABLED"),
+         * {@literal @}ViewDebug.ExportedProperty(flagMapping = {
+         *     {@literal @}ViewDebug.FlagToString(mask = ENABLED_MASK, equals = ENABLED,
+         *             name = "ENABLED"),
+         *     {@literal @}ViewDebug.FlagToString(mask = ENABLED_MASK, equals = DISABLED,
+         *             name = "DISABLED"),
          * })
          * private int mFlags;
          * <pre>
diff --git a/core/java/android/view/ViewRootImpl.java b/core/java/android/view/ViewRootImpl.java
index f9863b0..20d960f 100644
--- a/core/java/android/view/ViewRootImpl.java
+++ b/core/java/android/view/ViewRootImpl.java
@@ -2632,14 +2632,6 @@
         }
     }
 
-    private void onDrawFinished() {
-        try {
-            mWindowSession.finishDrawing(mWindow);
-        } catch (RemoteException e) {
-            // Have fun!
-        }
-    }
-
     private void performDraw() {
         if (mAttachInfo.mDisplayState == Display.STATE_OFF && !mReportNextDraw) {
             return;
@@ -2690,7 +2682,7 @@
             }
 
             if (mSurfaceHolder != null && mSurface.isValid()) {
-                SurfaceCallbackHelper sch = new SurfaceCallbackHelper(this::onDrawFinished);
+                SurfaceCallbackHelper sch = new SurfaceCallbackHelper(mWindowSession, mWindow);
                 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
 
                 sch.dispatchSurfaceRedrawNeededAsync(mSurfaceHolder, callbacks);
diff --git a/core/java/android/webkit/WebView.java b/core/java/android/webkit/WebView.java
index 1e7cddf..4757757 100644
--- a/core/java/android/webkit/WebView.java
+++ b/core/java/android/webkit/WebView.java
@@ -2784,6 +2784,10 @@
      * package that was used to load it. Otherwise, the package that would be used if the WebView
      * was loaded right now will be returned; this does not cause WebView to be loaded, so this
      * information may become outdated at any time.
+     * The WebView package changes either when the current WebView package is updated, disabled, or
+     * uninstalled. It can also be changed through a Developer Setting.
+     * If the WebView package changes, any app process that has loaded WebView will be killed. The
+     * next time the app starts and loads WebView it will use the new WebView package instead.
      * @return the current WebView package, or null if there is none.
      */
     public static PackageInfo getCurrentWebViewPackage() {
diff --git a/core/java/com/android/internal/hardware/AmbientDisplayConfiguration.java b/core/java/com/android/internal/hardware/AmbientDisplayConfiguration.java
index bab7cb3..cf1bf62 100644
--- a/core/java/com/android/internal/hardware/AmbientDisplayConfiguration.java
+++ b/core/java/com/android/internal/hardware/AmbientDisplayConfiguration.java
@@ -19,7 +19,6 @@
 import com.android.internal.R;
 
 import android.content.Context;
-import android.os.Build;
 import android.provider.Settings;
 import android.text.TextUtils;
 
@@ -34,8 +33,7 @@
     public boolean enabled(int user) {
         return pulseOnNotificationEnabled(user)
                 || pulseOnPickupEnabled(user)
-                || pulseOnDoubleTapEnabled(user)
-                || alwaysOnEnabled(user);
+                || pulseOnDoubleTapEnabled(user);
     }
     
     public boolean available() {
@@ -74,16 +72,6 @@
         return mContext.getResources().getString(R.string.config_dozeDoubleTapSensorType);
     }
 
-    public boolean alwaysOnEnabled(int user) {
-        return boolSetting(Settings.Secure.DOZE_ALWAYS_ON, user)
-                && alwaysOnAvailable();
-    }
-
-    public boolean alwaysOnAvailable() {
-        // TODO: introduce config_dozeAlwaysOnAvailable. For now just debuggable builds.
-        return Build.IS_DEBUGGABLE && ambientDisplayAvailable();
-    }
-
     public String ambientDisplayComponent() {
         return mContext.getResources().getString(R.string.config_dozeComponent);
     }
diff --git a/core/java/com/android/internal/logging/MetricsLogger.java b/core/java/com/android/internal/logging/MetricsLogger.java
index c8bf302..949e7ac 100644
--- a/core/java/com/android/internal/logging/MetricsLogger.java
+++ b/core/java/com/android/internal/logging/MetricsLogger.java
@@ -29,8 +29,10 @@
  */
 public class MetricsLogger {
     // define metric categories in frameworks/base/proto/src/metrics_constants.proto.
+    // mirror changes in native version at system/core/libmetricslogger/metrics_logger.cpp
 
     public static final int VIEW_UNKNOWN = MetricsEvent.VIEW_UNKNOWN;
+    public static final int LOGTAG = EventLogTags.SYSUI_MULTI_ACTION;
 
     public static void visible(Context context, int category) throws IllegalArgumentException {
         if (Build.IS_DEBUGGABLE && category == VIEW_UNKNOWN) {
@@ -125,6 +127,7 @@
 
     /** Increment the bucket with the integer label on the histogram with the given name. */
     public static void histogram(Context context, String name, int bucket) {
+        // see LogHistogram in system/core/libmetricslogger/metrics_logger.cpp
         EventLogTags.writeSysuiHistogram(name, bucket);
         EventLogTags.writeSysuiMultiAction(
                 new LogMaker(MetricsEvent.RESERVED_FOR_LOGBUILDER_HISTOGRAM)
diff --git a/core/java/com/android/internal/logging/legacy/EventLogCollector.java b/core/java/com/android/internal/logging/legacy/EventLogCollector.java
deleted file mode 100644
index 598f0d5..0000000
--- a/core/java/com/android/internal/logging/legacy/EventLogCollector.java
+++ /dev/null
@@ -1,173 +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.
- */
-package com.android.internal.logging.legacy;
-
-import android.util.ArrayMap;
-import android.util.EventLog;
-import android.util.Log;
-
-import com.android.internal.annotations.VisibleForTesting;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-
-/**
- * Scan the event log for interaction metrics events.
- * @hide
- */
-public class EventLogCollector {
-    private static final String TAG = "EventLogCollector";
-
-    // TODO replace this with GoogleLogTags.TRON_HEARTBEAT
-    @VisibleForTesting
-    static final int TRON_HEARTBEAT = 208000;
-
-    private static EventLogCollector sInstance;
-
-    private final ArrayMap<Integer, TagParser> mTagParsers;
-    private int[] mInterestingTags;
-
-    private LogReader mLogReader;
-
-    private EventLogCollector() {
-        mTagParsers = new ArrayMap<>();
-        addParser(new PowerScreenStateParser());
-        addParser(new SysuiMultiActionParser());
-
-        mLogReader = new LogReader();
-    }
-
-    public static EventLogCollector getInstance() {
-        if (sInstance == null) {
-            sInstance = new EventLogCollector();
-        }
-        return sInstance;
-    }
-
-    @VisibleForTesting
-    public void setLogReader(LogReader logReader) {
-        mLogReader = logReader;
-    }
-
-    private int[] getInterestingTags() {
-        if (mInterestingTags == null) {
-            mInterestingTags = new int[mTagParsers.size()];
-            for (int i = 0; i < mTagParsers.size(); i++) {
-                mInterestingTags[i] = mTagParsers.valueAt(i).getTag();
-            }
-        }
-        return mInterestingTags;
-    }
-
-    // I would customize ArrayMap to add put(TagParser), but ArrayMap is final.
-    @VisibleForTesting
-    void addParser(TagParser parser) {
-        mTagParsers.put(parser.getTag(), parser);
-        mInterestingTags = null;
-    }
-
-    public void collect(LegacyConversionLogger logger) {
-        collect(logger, 0L);
-    }
-
-    public long collect(TronLogger logger, long lastSeenEventMs) {
-        long lastEventMs = 0L;
-        final boolean debug = Util.debug();
-
-        if (debug) {
-            Log.d(TAG, "Eventlog Collection");
-        }
-        ArrayList<Event> events = new ArrayList<>();
-        try {
-            mLogReader.readEvents(getInterestingTags(), events);
-        } catch (IOException e) {
-            e.printStackTrace();
-        }
-        if (debug) {
-            Log.d(TAG, "read this many events: " + events.size());
-        }
-
-        for (Event event : events) {
-            final long millis = event.getTimeNanos() / 1000000;
-            if (millis > lastSeenEventMs) {
-                final int tag = event.getTag();
-                TagParser parser = mTagParsers.get(tag);
-                if (parser == null) {
-                    if (debug) {
-                        Log.d(TAG, "unknown tag: " + tag);
-                    }
-                    continue;
-                }
-                if (debug) {
-                    Log.d(TAG, "parsing tag: " + tag);
-                }
-                parser.parseEvent(logger, event);
-                lastEventMs = Math.max(lastEventMs, millis);
-            } else {
-                if (debug) {
-                    Log.d(TAG, "old event: " + millis + " < " + lastSeenEventMs);
-                }
-            }
-        }
-        return lastEventMs;
-    }
-
-    @VisibleForTesting
-    static class Event {
-        long mTimeNanos;
-        int mTag;
-        Object mData;
-
-        Event(long timeNanos, int tag, Object data) {
-            super();
-            mTimeNanos = timeNanos;
-            mTag = tag;
-            mData = data;
-        }
-
-        Event(EventLog.Event event) {
-            mTimeNanos = event.getTimeNanos();
-            mTag = event.getTag();
-            mData = event.getData();
-        }
-
-        public long getTimeNanos() {
-            return mTimeNanos;
-        }
-
-        public int getTag() {
-            return mTag;
-        }
-
-        public Object getData() {
-            return mData;
-        }
-    }
-
-    @VisibleForTesting
-    static class LogReader {
-        public void readEvents(int[] tags, Collection<Event> events) throws IOException {
-            // Testing in Android: the Static Final Class Strikes Back!
-            ArrayList<EventLog.Event> nativeEvents = new ArrayList<>();
-            EventLog.readEventsOnWrapping(tags, 0L, nativeEvents);
-            for (EventLog.Event nativeEvent : nativeEvents) {
-                Event event = new Event(nativeEvent);
-                events.add(event);
-            }
-        }
-    }
-}
diff --git a/core/java/com/android/internal/logging/legacy/LegacyConversionLogger.java b/core/java/com/android/internal/logging/legacy/LegacyConversionLogger.java
deleted file mode 100644
index 1209e4d..0000000
--- a/core/java/com/android/internal/logging/legacy/LegacyConversionLogger.java
+++ /dev/null
@@ -1,101 +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.
- */
-package com.android.internal.logging.legacy;
-
-import android.metrics.LogMaker;
-import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
-
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.Queue;
-
-/** @hide */
-public class LegacyConversionLogger implements TronLogger {
-    private final Queue<LogMaker> mQueue;
-    private HashMap<String, Boolean> mConfig;
-
-    public LegacyConversionLogger() {
-        mQueue = new LinkedList<>();
-    }
-
-    public Queue<LogMaker> getEvents() {
-        return mQueue;
-    }
-
-    @Override
-    public void increment(String counterName) {
-        LogMaker b = new LogMaker(MetricsEvent.RESERVED_FOR_LOGBUILDER_COUNTER)
-                .setCounterName(counterName)
-                .setCounterValue(1);
-        mQueue.add(b);
-    }
-
-    @Override
-    public void incrementBy(String counterName, int value) {
-        LogMaker b = new LogMaker(MetricsEvent.RESERVED_FOR_LOGBUILDER_COUNTER)
-                .setCounterName(counterName)
-                .setCounterValue(value);
-        mQueue.add(b);
-    }
-
-    @Override
-    public void incrementIntHistogram(String counterName, int bucket) {
-        LogMaker b = new LogMaker(MetricsEvent.RESERVED_FOR_LOGBUILDER_HISTOGRAM)
-                .setCounterName(counterName)
-                .setCounterBucket(bucket)
-                .setCounterValue(1);
-        mQueue.add(b);
-    }
-
-    @Override
-    public void incrementLongHistogram(String counterName, long bucket) {
-        LogMaker b = new LogMaker(MetricsEvent.RESERVED_FOR_LOGBUILDER_HISTOGRAM)
-                .setCounterName(counterName)
-                .setCounterBucket(bucket)
-                .setCounterValue(1);
-        mQueue.add(b);
-    }
-
-    @Override
-    public LogMaker obtain() {
-        return new LogMaker(MetricsEvent.VIEW_UNKNOWN);
-    }
-
-    @Override
-    public void dispose(LogMaker proto) {
-    }
-
-    @Override
-    public void addEvent(LogMaker proto) {
-        mQueue.add(proto);
-    }
-
-    @Override
-    public boolean getConfig(String configName) {
-        if (mConfig != null && mConfig.containsKey(configName)) {
-            return mConfig.get(configName);
-        }
-        return false;
-    }
-
-    @Override
-    public void setConfig(String configName, boolean newValue) {
-        if (mConfig == null) {
-            mConfig = new HashMap<>();
-        }
-        mConfig.put(configName, newValue);
-    }
-}
diff --git a/core/java/com/android/internal/logging/legacy/PowerScreenStateParser.java b/core/java/com/android/internal/logging/legacy/PowerScreenStateParser.java
deleted file mode 100644
index e9baf9b..0000000
--- a/core/java/com/android/internal/logging/legacy/PowerScreenStateParser.java
+++ /dev/null
@@ -1,66 +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.
- */
-package com.android.internal.logging.legacy;
-
-import android.util.Log;
-
-import android.metrics.LogMaker;
-import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
-
-/**
- * Parse the Android lockscreen gesture logs.
- * @hide
- */
-public class PowerScreenStateParser extends TagParser {
-    private static final String TAG = "PowerScreenStateParser";
-    private static final int EVENTLOG_TAG = 2728;
-
-    // source of truth is android.view.WindowManagerPolicy, why:
-    // 0: on
-    // 1: OFF_BECAUSE_OF_ADMIN
-    // 2: OFF_BECAUSE_OF_USER
-    // 3: OFF_BECAUSE_OF_TIMEOUT
-
-    @Override
-    public int getTag() {
-        return EVENTLOG_TAG;
-    }
-
-    @Override
-    public void parseEvent(TronLogger logger, long eventTimeMs, Object[] operands) {
-        final boolean debug = Util.debug();
-        if (operands.length >= 2) {
-            try {
-                // (offOrOn|1|5),(becauseOfUser|1|5),(totalTouchDownTime|2|3),(touchCycles|1|1)
-                boolean state = (((Integer) operands[0]).intValue()) == 1;
-                int why = ((Integer) operands[1]).intValue();
-
-                LogMaker proto = logger.obtain();
-                proto.setCategory(MetricsEvent.SCREEN);
-                proto.setType(state ? MetricsEvent.TYPE_OPEN : MetricsEvent.TYPE_CLOSE);
-                proto.setTimestamp(eventTimeMs);
-                proto.setSubtype(why);
-                logger.addEvent(proto);
-            } catch (ClassCastException e) {
-                if (debug) {
-                    Log.e(TAG, "unexpected operand type: ", e);
-                }
-            }
-        } else if (debug) {
-            Log.w(TAG, "wrong number of operands: " + operands.length);
-        }
-    }
-}
diff --git a/core/java/com/android/internal/logging/legacy/SysuiMultiActionParser.java b/core/java/com/android/internal/logging/legacy/SysuiMultiActionParser.java
deleted file mode 100644
index 0c77b7a..0000000
--- a/core/java/com/android/internal/logging/legacy/SysuiMultiActionParser.java
+++ /dev/null
@@ -1,48 +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.
- */
-package com.android.internal.logging.legacy;
-
-import android.util.Log;
-
-import android.metrics.LogMaker;
-
-/**
- * ...and one parser to rule them all.
- *
- * This should, at some point in the future, be the only parser.
- * @hide
- */
-public class SysuiMultiActionParser extends TagParser {
-    private static final String TAG = "SysuiMultiActionParser";
-    private static final int EVENTLOG_TAG = 524292;
-
-    @Override
-    public int getTag() {
-        return EVENTLOG_TAG;
-    }
-
-    @Override
-    public void parseEvent(TronLogger logger, long eventTimeMs, Object[] operands) {
-        final boolean debug = Util.debug();
-        try {
-            logger.addEvent(new LogMaker(operands).setTimestamp(eventTimeMs));
-        } catch (ClassCastException e) {
-            if (debug) {
-                Log.e(TAG, "unexpected operand type: ", e);
-            }
-        }
-    }
-}
diff --git a/core/java/com/android/internal/logging/legacy/TagParser.java b/core/java/com/android/internal/logging/legacy/TagParser.java
deleted file mode 100755
index 3bffdd5..0000000
--- a/core/java/com/android/internal/logging/legacy/TagParser.java
+++ /dev/null
@@ -1,104 +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.
- */
-package com.android.internal.logging.legacy;
-
-import android.util.Log;
-
-import android.metrics.LogMaker;
-import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
-
-/**
- * Abstraction layer between EventLog static classes and the actual TagParsers.
- * @hide
- */
-public abstract class TagParser {
-    private static final String TAG = "TagParser";
-
-    protected int mSinceCreationMillis;
-    protected int mSinceUpdateMillis;
-    protected int mSinceVisibleMillis;
-
-    abstract int getTag();
-
-    @VisibleForTesting
-    abstract public void parseEvent(TronLogger logger, long eventTimeMs, Object[] objects);
-
-    /**
-     * Parse the event into the proto: return true if proto was modified.
-     */
-    public void  parseEvent(TronLogger logger, EventLogCollector.Event event) {
-        final boolean debug = Util.debug();
-        Object data = event.getData();
-        Object[] objects;
-        if (data instanceof Object[]) {
-            objects = (Object[]) data;
-            for (int i = 0; i < objects.length; i++) {
-                if (objects[i] == null) {
-                    if (debug) {
-                        Log.d(TAG, "unexpected null value:" + event.getTag());
-                    }
-                    return;
-                }
-            }
-        } else {
-            // wrap scalar objects
-            objects = new Object[1];
-            objects[0] = data;
-        }
-
-        parseEvent(logger, event.getTimeNanos() / 1000000, objects);
-    }
-
-    protected void resetTimes() {
-        mSinceCreationMillis = 0;
-        mSinceUpdateMillis = 0;
-        mSinceVisibleMillis = 0;
-    }
-
-    public void parseTimes(Object[] operands, int index) {
-        resetTimes();
-
-        if (operands.length > index && operands[index] instanceof Integer) {
-            mSinceCreationMillis = (Integer) operands[index];
-        }
-
-        index++;
-        if (operands.length > index && operands[index] instanceof Integer) {
-            mSinceUpdateMillis = (Integer) operands[index];
-        }
-
-        index++;
-        if (operands.length > index && operands[index] instanceof Integer) {
-            mSinceVisibleMillis = (Integer) operands[index];
-        }
-    }
-
-   public void filltimes(LogMaker proto) {
-        if (mSinceCreationMillis != 0) {
-            proto.addTaggedData(MetricsEvent.NOTIFICATION_SINCE_CREATE_MILLIS,
-                    mSinceCreationMillis);
-        }
-        if (mSinceUpdateMillis != 0) {
-            proto.addTaggedData(MetricsEvent.NOTIFICATION_SINCE_UPDATE_MILLIS,
-                    mSinceUpdateMillis);
-        }
-        if (mSinceVisibleMillis != 0) {
-            proto.addTaggedData(MetricsEvent.NOTIFICATION_SINCE_VISIBLE_MILLIS,
-                    mSinceVisibleMillis);
-        }
-    }
-}
diff --git a/core/java/com/android/internal/logging/legacy/TronCounters.java b/core/java/com/android/internal/logging/legacy/TronCounters.java
deleted file mode 100644
index e0828a2..0000000
--- a/core/java/com/android/internal/logging/legacy/TronCounters.java
+++ /dev/null
@@ -1,72 +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.
- */
-package com.android.internal.logging.legacy;
-
-/**
- * Names of the counters that the Tron package defines.
- *
- * Other counter names may be generated by AOSP code.
- * @hide
- */
-public class TronCounters {
-
-    static final String TRON_COLLECTIONS = "tron_collections";
-
-    static final String TRON_COLLECTION_PERIOD = "tron_collection_period_minutes";
-
-    static final String TRON_EVENTLOG_LENGTH = "tron_eventlog_horizon";
-
-    static final String TRON_NOTE_DISMISS = "tron_note_dismiss";
-
-    static final String TRON_NOTE_DISMISS_BY_USER = "tron_note_dismiss_user";
-
-    static final String TRON_NOTE_DISMISS_BY_CLICK = "tron_note_dismiss_click";
-
-    static final String TRON_NOTE_DISMISS_BY_LISTENER = "tron_note_dismiss_listener";
-
-    static final String TRON_NOTE_DISMISS_BY_BAN = "tron_note_dismiss_ban";
-
-    static final String TRON_NOTE_REVEALED = "tron_note_revealed";
-
-    static final String TRON_NOTIFICATION_LOAD = "tron_notification_load";
-
-    static final String TRON_VIEW = "tron_view";
-
-    static final String TRON_ACTION = "tron_action";
-
-    static final String TRON_DETAIL = "tron_detail";
-
-    static final String TRON_NOTE_LIFETIME = "tron_note_lifetime";
-
-    /** Append the AOSP-generated name */
-    static final String TRON_AOSP_PREFIX = "tron_varz_";
-
-    static final String TRON_ACTION_BAD_INT = "tron_action_bad_int";
-
-    static final String TRON_NOTE_FRESHNESS = "tron_note_freshness";
-
-    static final String TRON_NOTE_BUZZ = "tron_note_buzz";
-
-    static final String TRON_NOTE_BEEP = "tron_note_beep";
-
-    static final String TRON_NOTE_BLINK = "tron_note_blink";
-
-    static final String TRON_DISABLE = "tron_disable";
-
-    static final String TRON_LAST_HEART_AGE = "tron_last_heart_minutes";
-
-    static final String TRON_HEARTS_SEEN = "tron_hearts_seen";
-}
diff --git a/core/java/com/android/internal/logging/legacy/TronLogger.java b/core/java/com/android/internal/logging/legacy/TronLogger.java
deleted file mode 100644
index ee9341a..0000000
--- a/core/java/com/android/internal/logging/legacy/TronLogger.java
+++ /dev/null
@@ -1,49 +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.
- */
-package com.android.internal.logging.legacy;
-
-import android.metrics.LogMaker;
-
-/**
- * An entity that knows how to log events and counters.
- */
-public interface TronLogger {
-    /** Add one to the named counter. */
-    void increment(String counterName);
-
-    /** Add an arbitrary value to the named counter. */
-    void incrementBy(String counterName, int value);
-
-    /** Increment a specified bucket on the named histogram by one. */
-    void incrementIntHistogram(String counterName, int bucket);
-
-    /** Increment the specified bucket on the named histogram by one. */
-    void incrementLongHistogram(String counterName, long bucket);
-
-    /** Obtain a SystemUiEvent proto, must release this with dispose() or addEvent(). */
-    LogMaker obtain();
-
-    void dispose(LogMaker proto);
-
-    /** Submit an event to be logged. Logger will dispose of proto. */
-    void addEvent(LogMaker proto);
-
-    /** Get a config flag. */
-    boolean getConfig(String configName);
-
-    /** Set a config flag. */
-    void setConfig(String configName, boolean newValue);
-}
diff --git a/core/java/com/android/internal/os/BatteryStatsImpl.java b/core/java/com/android/internal/os/BatteryStatsImpl.java
index 12d96e2..85aa6e6 100644
--- a/core/java/com/android/internal/os/BatteryStatsImpl.java
+++ b/core/java/com/android/internal/os/BatteryStatsImpl.java
@@ -8870,6 +8870,10 @@
                 if (entry.rxBytes != 0) {
                     u.noteNetworkActivityLocked(NETWORK_WIFI_RX_DATA, entry.rxBytes,
                             entry.rxPackets);
+                    if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
+                        u.noteNetworkActivityLocked(NETWORK_WIFI_BG_RX_DATA, entry.rxBytes,
+                                entry.rxPackets);
+                    }
                     mNetworkByteActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
                             entry.rxBytes);
                     mNetworkPacketActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
@@ -8885,6 +8889,10 @@
                 if (entry.txBytes != 0) {
                     u.noteNetworkActivityLocked(NETWORK_WIFI_TX_DATA, entry.txBytes,
                             entry.txPackets);
+                    if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
+                        u.noteNetworkActivityLocked(NETWORK_WIFI_BG_TX_DATA, entry.txBytes,
+                                entry.txPackets);
+                    }
                     mNetworkByteActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
                             entry.txBytes);
                     mNetworkPacketActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
@@ -9104,6 +9112,12 @@
                 final Uid u = getUidStatsLocked(mapUid(entry.uid));
                 u.noteNetworkActivityLocked(NETWORK_MOBILE_RX_DATA, entry.rxBytes, entry.rxPackets);
                 u.noteNetworkActivityLocked(NETWORK_MOBILE_TX_DATA, entry.txBytes, entry.txPackets);
+                if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
+                    u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_RX_DATA,
+                            entry.rxBytes, entry.rxPackets);
+                    u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_TX_DATA,
+                            entry.txBytes, entry.txPackets);
+                }
 
                 mNetworkByteActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
                         entry.rxBytes);
diff --git a/core/java/com/android/internal/util/ArrayUtils.java b/core/java/com/android/internal/util/ArrayUtils.java
index 2b16254..be69d9f8 100644
--- a/core/java/com/android/internal/util/ArrayUtils.java
+++ b/core/java/com/android/internal/util/ArrayUtils.java
@@ -31,6 +31,7 @@
 import java.util.Collections;
 import java.util.List;
 import java.util.Objects;
+import java.util.function.Function;
 
 /**
  * ArrayUtils contains some methods that you can call to find out
@@ -474,12 +475,25 @@
         }
     }
 
+    public static int size(@Nullable Collection<?> cur) {
+        return cur != null ? cur.size() : 0;
+    }
+
+    public static @NonNull <I, O> List<O> map(@Nullable List<I> cur,
+            Function<? super I, ? extends O> f) {
+        if (cur == null || cur.isEmpty()) return Collections.emptyList();
+        final ArrayList<O> result = new ArrayList<>();
+        for (int i = 0; i < cur.size(); i++) {
+            result.add(f.apply(cur.get(i)));
+        }
+        return result;
+    }
+
     /**
      * Returns the given list, or an immutable empty list if the provided list is null
      *
      * @see Collections#emptyList
      */
-
     public static @NonNull <T> List<T> emptyIfNull(@Nullable List<T> cur) {
         return cur == null ? Collections.emptyList() : cur;
     }
diff --git a/core/java/com/android/internal/util/ExponentiallyBucketedHistogram.java b/core/java/com/android/internal/util/ExponentiallyBucketedHistogram.java
new file mode 100644
index 0000000..dc9f3f4
--- /dev/null
+++ b/core/java/com/android/internal/util/ExponentiallyBucketedHistogram.java
@@ -0,0 +1,97 @@
+/*
+ * 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.
+ */
+package com.android.internal.util;
+
+import android.annotation.IntRange;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.util.Log;
+
+import java.util.Arrays;
+
+/**
+ * A histogram for positive integers where each bucket is twice the size of the previous one.
+ */
+public class ExponentiallyBucketedHistogram {
+    @NonNull
+    private final int[] mData;
+
+    /**
+     * Create a new histogram.
+     *
+     * @param numBuckets The number of buckets. The highest bucket is for all value >=
+     *                   2<sup>numBuckets - 1</sup>
+     */
+    public ExponentiallyBucketedHistogram(@IntRange(from = 1, to = 31) int numBuckets) {
+        numBuckets = Preconditions.checkArgumentInRange(numBuckets, 1, 31, "numBuckets");
+
+        mData = new int[numBuckets];
+    }
+
+    /**
+     * Add a new value to the histogram.
+     *
+     * All values <= 0 are in the first bucket. The last bucket contains all values >=
+     * 2<sup>numBuckets - 1</sup>
+     *
+     * @param value The value to add
+     */
+    public void add(int value) {
+        if (value <= 0) {
+            mData[0]++;
+        } else {
+            mData[Math.min(mData.length - 1, 32 - Integer.numberOfLeadingZeros(value))]++;
+        }
+    }
+
+    /**
+     * Clear all data from the histogram
+     */
+    public void reset() {
+        Arrays.fill(mData, 0);
+    }
+
+    /**
+     * Write the histogram to the log.
+     *
+     * @param tag    The tag to use when logging
+     * @param prefix A custom prefix that is printed in front of the histogram
+     */
+    public void log(@NonNull String tag, @Nullable CharSequence prefix) {
+        StringBuilder builder = new StringBuilder(prefix);
+        builder.append('[');
+
+        for (int i = 0; i < mData.length; i++) {
+            if (i != 0) {
+                builder.append(", ");
+            }
+
+            if (i < mData.length - 1) {
+                builder.append("<");
+                builder.append(1 << i);
+            } else {
+                builder.append(">=");
+                builder.append(1 << (i - 1));
+            }
+
+            builder.append(": ");
+            builder.append(mData[i]);
+        }
+        builder.append("]");
+
+        Log.d(tag, builder.toString());
+    }
+}
diff --git a/core/java/com/android/internal/view/SurfaceCallbackHelper.java b/core/java/com/android/internal/view/SurfaceCallbackHelper.java
index 507b673..5b6a82c 100644
--- a/core/java/com/android/internal/view/SurfaceCallbackHelper.java
+++ b/core/java/com/android/internal/view/SurfaceCallbackHelper.java
@@ -17,11 +17,14 @@
 package com.android.internal.view;
 
 import android.os.RemoteException;
+import android.view.IWindow;
+import android.view.IWindowSession;
 import android.view.Surface;
 import android.view.SurfaceHolder;
 
 public class SurfaceCallbackHelper {
-    Runnable mRunnable;
+    IWindowSession mSession;
+    IWindow.Stub mWindow;
 
     int mFinishDrawingCollected = 0;
     int mFinishDrawingExpected = 0;
@@ -34,18 +37,26 @@
                     if (mFinishDrawingCollected < mFinishDrawingExpected) {
                         return;
                     }
-                    mRunnable.run();
+                    try {
+                        mSession.finishDrawing(mWindow);
+                    } catch (RemoteException e) {
+                    }
                 }
             }
     };
 
-    public SurfaceCallbackHelper(Runnable callbacksCollected) {
-        mRunnable = callbacksCollected;
+    public SurfaceCallbackHelper(IWindowSession session,
+            IWindow.Stub window) {
+        mSession = session;
+        mWindow = window;
     }
 
     public void dispatchSurfaceRedrawNeededAsync(SurfaceHolder holder, SurfaceHolder.Callback callbacks[]) {
         if (callbacks == null || callbacks.length == 0) {
-            mRunnable.run();
+            try {
+                mSession.finishDrawing(mWindow);
+            } catch (RemoteException e) {
+            }
             return;
         }
 
diff --git a/core/java/com/android/internal/view/menu/ActionMenuItem.java b/core/java/com/android/internal/view/menu/ActionMenuItem.java
index ace0cce..ac226dd 100644
--- a/core/java/com/android/internal/view/menu/ActionMenuItem.java
+++ b/core/java/com/android/internal/view/menu/ActionMenuItem.java
@@ -145,12 +145,12 @@
     }
 
     public MenuItem setAlphabeticShortcut(char alphaChar) {
-        mShortcutAlphabeticChar = alphaChar;
+        mShortcutAlphabeticChar = Character.toLowerCase(alphaChar);
         return this;
     }
 
     public MenuItem setAlphabeticShortcut(char alphachar, int alphaModifiers) {
-        mShortcutAlphabeticChar = alphachar;
+        mShortcutAlphabeticChar = Character.toLowerCase(alphachar);
         mShortcutAlphabeticModifiers = KeyEvent.normalizeMetaState(alphaModifiers);
         return this;
     }
@@ -210,7 +210,7 @@
 
     public MenuItem setShortcut(char numericChar, char alphaChar) {
         mShortcutNumericChar = numericChar;
-        mShortcutAlphabeticChar = alphaChar;
+        mShortcutAlphabeticChar = Character.toLowerCase(alphaChar);
         return this;
     }
 
@@ -218,7 +218,7 @@
             int alphaModifiers) {
         mShortcutNumericChar = numericChar;
         mShortcutNumericModifiers = KeyEvent.normalizeMetaState(numericModifiers);
-        mShortcutAlphabeticChar = alphaChar;
+        mShortcutAlphabeticChar = Character.toLowerCase(alphaChar);
         mShortcutAlphabeticModifiers = KeyEvent.normalizeMetaState(alphaModifiers);
         return this;
     }
diff --git a/core/java/com/android/internal/view/menu/MenuItemImpl.java b/core/java/com/android/internal/view/menu/MenuItemImpl.java
index 4c3118d..9310d14 100644
--- a/core/java/com/android/internal/view/menu/MenuItemImpl.java
+++ b/core/java/com/android/internal/view/menu/MenuItemImpl.java
@@ -255,7 +255,7 @@
             return this;
         }
 
-        mShortcutAlphabeticChar = alphaChar;
+        mShortcutAlphabeticChar = Character.toLowerCase(alphaChar);
         mShortcutAlphabeticModifiers = KeyEvent.normalizeMetaState(alphaModifiers);
 
         mMenu.onItemsChanged(false);
@@ -307,7 +307,7 @@
             int alphaModifiers) {
         mShortcutNumericChar = numericChar;
         mShortcutNumericModifiers = KeyEvent.normalizeMetaState(numericModifiers);
-        mShortcutAlphabeticChar = alphaChar;
+        mShortcutAlphabeticChar = Character.toLowerCase(alphaChar);
         mShortcutAlphabeticModifiers = KeyEvent.normalizeMetaState(alphaModifiers);
 
         mMenu.onItemsChanged(false);
diff --git a/core/jni/Android.mk b/core/jni/Android.mk
index 68392a9..c9f9d6f 100644
--- a/core/jni/Android.mk
+++ b/core/jni/Android.mk
@@ -249,6 +249,7 @@
     libbinder \
     libui \
     libgui \
+    libsensor \
     libinput \
     libcamera_client \
     libcamera_metadata \
diff --git a/core/jni/android/graphics/Bitmap.cpp b/core/jni/android/graphics/Bitmap.cpp
index a196540..e4493b1 100755
--- a/core/jni/android/graphics/Bitmap.cpp
+++ b/core/jni/android/graphics/Bitmap.cpp
@@ -9,6 +9,7 @@
 #include "SkColor.h"
 #include "SkColorPriv.h"
 #include "SkHalf.h"
+#include "SkMatrix44.h"
 #include "SkPM4f.h"
 #include "SkPM4fPriv.h"
 #include "GraphicsJNI.h"
@@ -923,7 +924,13 @@
     const bool        isMutable = p->readInt32() != 0;
     const SkColorType colorType = (SkColorType)p->readInt32();
     const SkAlphaType alphaType = (SkAlphaType)p->readInt32();
-    const bool        isSRGB = p->readInt32() != 0;
+    const uint32_t    colorSpaceSize = p->readUint32();
+    sk_sp<SkColorSpace> colorSpace;
+    if (kRGBA_F16_SkColorType == colorType) {
+        colorSpace = SkColorSpace::MakeSRGBLinear();
+    } else if (colorSpaceSize > 0) {
+        colorSpace = SkColorSpace::Deserialize(p->readInplace(colorSpaceSize), colorSpaceSize);
+    }
     const int         width = p->readInt32();
     const int         height = p->readInt32();
     const int         rowBytes = p->readInt32();
@@ -940,14 +947,6 @@
     }
 
     std::unique_ptr<SkBitmap> bitmap(new SkBitmap);
-
-    sk_sp<SkColorSpace> colorSpace;
-    if (kRGBA_F16_SkColorType == colorType) {
-        colorSpace = SkColorSpace::MakeSRGBLinear();
-    } else {
-        colorSpace = isSRGB ? SkColorSpace::MakeSRGB() : nullptr;
-    }
-
     if (!bitmap->setInfo(SkImageInfo::Make(width, height, colorType, alphaType, colorSpace),
             rowBytes)) {
         return NULL;
@@ -1064,13 +1063,20 @@
     auto bitmapWrapper = reinterpret_cast<BitmapWrapper*>(bitmapHandle);
     bitmapWrapper->getSkBitmap(&bitmap);
 
-    sk_sp<SkColorSpace> sRGB = SkColorSpace::MakeSRGB();
-    bool isSRGB = bitmap.colorSpace() == sRGB.get();
-
     p->writeInt32(isMutable);
     p->writeInt32(bitmap.colorType());
     p->writeInt32(bitmap.alphaType());
-    p->writeInt32(isSRGB); // TODO: We should write the color space (b/32072280)
+    SkColorSpace* colorSpace = bitmap.colorSpace();
+    if (colorSpace != nullptr && bitmap.colorType() != kRGBA_F16_SkColorType) {
+        sk_sp<SkData> data = colorSpace->serialize();
+        size_t size = data->size();
+        p->writeUint32(size);
+        if (size > 0) {
+            p->write(data->data(), size);
+        }
+    } else {
+        p->writeUint32(0);
+    }
     p->writeInt32(bitmap.width());
     p->writeInt32(bitmap.height());
     p->writeInt32(bitmap.rowBytes());
@@ -1168,6 +1174,61 @@
 
 ///////////////////////////////////////////////////////////////////////////////
 
+static jboolean Bitmap_isSRGB(JNIEnv* env, jobject, jlong bitmapHandle) {
+    LocalScopedBitmap bitmapHolder(bitmapHandle);
+    if (!bitmapHolder.valid()) return JNI_TRUE;
+
+    SkColorSpace* colorSpace = bitmapHolder->info().colorSpace();
+    return colorSpace == nullptr ||
+           colorSpace == SkColorSpace::MakeSRGB().get() ||
+           colorSpace == SkColorSpace::MakeRGB(
+                  SkColorSpace::kSRGB_RenderTargetGamma,
+                  SkColorSpace::kSRGB_Gamut,
+                  SkColorSpace::kNonLinearBlending_ColorSpaceFlag).get();
+}
+
+static jboolean Bitmap_getColorSpace(JNIEnv* env, jobject, jlong bitmapHandle,
+        jfloatArray xyzArray, jfloatArray paramsArray) {
+
+    LocalScopedBitmap bitmapHolder(bitmapHandle);
+    if (!bitmapHolder.valid()) return JNI_FALSE;
+
+    SkColorSpace* colorSpace = bitmapHolder->info().colorSpace();
+    if (colorSpace == nullptr) return JNI_FALSE;
+
+    SkMatrix44 xyzMatrix(SkMatrix44::kUninitialized_Constructor);
+    if (!colorSpace->toXYZD50(&xyzMatrix)) return JNI_FALSE;
+
+    jfloat* xyz = env->GetFloatArrayElements(xyzArray, NULL);
+    xyz[0] = xyzMatrix.getFloat(0, 0);
+    xyz[1] = xyzMatrix.getFloat(1, 0);
+    xyz[2] = xyzMatrix.getFloat(2, 0);
+    xyz[3] = xyzMatrix.getFloat(0, 1);
+    xyz[4] = xyzMatrix.getFloat(1, 1);
+    xyz[5] = xyzMatrix.getFloat(2, 1);
+    xyz[6] = xyzMatrix.getFloat(0, 2);
+    xyz[7] = xyzMatrix.getFloat(1, 2);
+    xyz[8] = xyzMatrix.getFloat(2, 2);
+    env->ReleaseFloatArrayElements(xyzArray, xyz, 0);
+
+    SkColorSpaceTransferFn transferParams;
+    if (!colorSpace->isNumericalTransferFn(&transferParams)) return JNI_FALSE;
+
+    jfloat* params = env->GetFloatArrayElements(paramsArray, NULL);
+    params[0] = transferParams.fA;
+    params[1] = transferParams.fB;
+    params[2] = transferParams.fC;
+    params[3] = transferParams.fD;
+    params[4] = transferParams.fE;
+    params[5] = transferParams.fF;
+    params[6] = transferParams.fG;
+    env->ReleaseFloatArrayElements(paramsArray, params, 0);
+
+    return JNI_TRUE;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+
 static jint Bitmap_getPixel(JNIEnv* env, jobject, jlong bitmapHandle,
         jint x, jint y) {
     SkBitmap bitmap;
@@ -1459,7 +1520,9 @@
     {   "nativeCreateHardwareBitmap", "(Landroid/graphics/GraphicBuffer;)Landroid/graphics/Bitmap;",
         (void*) Bitmap_createHardwareBitmap },
     {   "nativeCreateGraphicBufferHandle", "(J)Landroid/graphics/GraphicBuffer;",
-        (void*) Bitmap_createGraphicBufferHandle }
+        (void*) Bitmap_createGraphicBufferHandle },
+    {   "nativeGetColorSpace",      "(J[F[F)Z", (void*)Bitmap_getColorSpace },
+    {   "nativeIsSRGB",             "(J)Z", (void*)Bitmap_isSRGB },
 };
 
 int register_android_graphics_Bitmap(JNIEnv* env)
diff --git a/core/jni/android_database_CursorWindow.cpp b/core/jni/android_database_CursorWindow.cpp
index 3fc3aaf..f1fa76a 100644
--- a/core/jni/android_database_CursorWindow.cpp
+++ b/core/jni/android_database_CursorWindow.cpp
@@ -205,6 +205,10 @@
     if (type == CursorWindow::FIELD_TYPE_BLOB || type == CursorWindow::FIELD_TYPE_STRING) {
         size_t size;
         const void* value = window->getFieldSlotValueBlob(fieldSlot, &size);
+        if (!value) {
+            throw_sqlite3_exception(env, "Native could not read blob slot");
+            return NULL;
+        }
         jbyteArray byteArray = env->NewByteArray(size);
         if (!byteArray) {
             env->ExceptionClear();
@@ -240,6 +244,10 @@
     if (type == CursorWindow::FIELD_TYPE_STRING) {
         size_t sizeIncludingNull;
         const char* value = window->getFieldSlotValueString(fieldSlot, &sizeIncludingNull);
+        if (!value) {
+            throw_sqlite3_exception(env, "Native could not read string slot");
+            return NULL;
+        }
         if (sizeIncludingNull <= 1) {
             return gEmptyString;
         }
diff --git a/core/jni/android_hardware_SensorManager.cpp b/core/jni/android_hardware_SensorManager.cpp
index bc2fc1c..dae4310 100644
--- a/core/jni/android_hardware_SensorManager.cpp
+++ b/core/jni/android_hardware_SensorManager.cpp
@@ -23,9 +23,10 @@
 #include <ScopedUtfChars.h>
 #include <ScopedLocalRef.h>
 #include <android_runtime/AndroidRuntime.h>
-#include <gui/Sensor.h>
-#include <gui/SensorEventQueue.h>
-#include <gui/SensorManager.h>
+#include <android_runtime/android_hardware_HardwareBuffer.h>
+#include <sensor/Sensor.h>
+#include <sensor/SensorEventQueue.h>
+#include <sensor/SensorManager.h>
 #include <cutils/native_handle.h>
 #include <utils/Log.h>
 #include <utils/Looper.h>
@@ -245,39 +246,28 @@
 }
 
 static jint nativeCreateDirectChannel(JNIEnv *_env, jclass _this, jlong sensorManager,
-        jlong size, jint channelType, jlongArray channelData) {
-    jint ret = -1;
-    jsize len = _env->GetArrayLength(channelData);
-    if (len > 2) {
-        jlong *data = _env->GetLongArrayElements(channelData, NULL);
-        if (data != nullptr) {
-            // construct native handle from jlong*
-            jlong numFd = data[0];
-            jlong numInt = data[1];
-            if ((numFd + numInt + 2) == len) {
-                native_handle_t *nativeHandle = native_handle_create(numFd, numInt);
-                if (nativeHandle != nullptr) {
-                    const jlong *readPointer = data + 2;
-                    int *writePointer = nativeHandle->data;
-                    size_t n = static_cast<size_t>(numFd + numInt);
-                    while (n--) {
-                        // native type of data is int, jlong is just to ensure Java does not
-                        // truncate data on 64-bit system. The cast here is safe.
-                        *writePointer++ = static_cast<int>(*readPointer++);
-                    }
+        jlong size, jint channelType, jint fd, jobject hardwareBufferObj) {
+    const native_handle_t *nativeHandle = nullptr;
+    NATIVE_HANDLE_DECLARE_STORAGE(ashmemHandle, 1, 0);
 
-                    SensorManager* mgr = reinterpret_cast<SensorManager*>(sensorManager);
-                    ret = mgr->createDirectChannel(size, channelType, nativeHandle);
-
-                    // do not native_handle_close() here as handle is owned by java
-                    native_handle_delete(nativeHandle);
-                }
-            }
-            // unidirectional parameter passing, thus JNI_ABORT
-            _env->ReleaseLongArrayElements(channelData, data, JNI_ABORT);
+    if (channelType == SENSOR_DIRECT_MEM_TYPE_ASHMEM) {
+        native_handle_t *handle = native_handle_init(ashmemHandle, 1, 0);
+        handle->data[0] = fd;
+        nativeHandle = handle;
+    } else if (channelType == SENSOR_DIRECT_MEM_TYPE_GRALLOC) {
+        AHardwareBuffer *hardwareBuffer =
+                android_hardware_HardwareBuffer_getNativeHardwareBuffer(_env, hardwareBufferObj);
+        if (hardwareBuffer != nullptr) {
+            nativeHandle = AHardwareBuffer_getNativeHandle(hardwareBuffer);
         }
     }
-    return ret;
+
+    if (nativeHandle == nullptr) {
+        return BAD_VALUE;
+    }
+
+    SensorManager* mgr = reinterpret_cast<SensorManager*>(sensorManager);
+    return mgr->createDirectChannel(size, channelType, nativeHandle);
 }
 
 static void nativeDestroyDirectChannel(JNIEnv *_env, jclass _this, jlong sensorManager,
@@ -499,7 +489,7 @@
             (void*)nativeIsDataInjectionEnabled },
 
     {"nativeCreateDirectChannel",
-            "(JJI[J)I",
+            "(JJIILandroid/hardware/HardwareBuffer;)I",
             (void*)nativeCreateDirectChannel },
 
     {"nativeDestroyDirectChannel",
diff --git a/core/jni/android_util_AssetManager.cpp b/core/jni/android_util_AssetManager.cpp
index c2800e7..373bda9 100644
--- a/core/jni/android_util_AssetManager.cpp
+++ b/core/jni/android_util_AssetManager.cpp
@@ -119,6 +119,96 @@
     return block;
 }
 
+// This is called by zygote (running as user root) as part of preloadResources.
+static void verifySystemIdmaps()
+{
+    pid_t pid;
+    char system_id[10];
+
+    snprintf(system_id, sizeof(system_id), "%d", AID_SYSTEM);
+
+    switch (pid = fork()) {
+        case -1:
+            ALOGE("failed to fork for idmap: %s", strerror(errno));
+            break;
+        case 0: // child
+            {
+                struct __user_cap_header_struct capheader;
+                struct __user_cap_data_struct capdata;
+
+                memset(&capheader, 0, sizeof(capheader));
+                memset(&capdata, 0, sizeof(capdata));
+
+                capheader.version = _LINUX_CAPABILITY_VERSION;
+                capheader.pid = 0;
+
+                if (capget(&capheader, &capdata) != 0) {
+                    ALOGE("capget: %s\n", strerror(errno));
+                    exit(1);
+                }
+
+                capdata.effective = capdata.permitted;
+                if (capset(&capheader, &capdata) != 0) {
+                    ALOGE("capset: %s\n", strerror(errno));
+                    exit(1);
+                }
+
+                if (setgid(AID_SYSTEM) != 0) {
+                    ALOGE("setgid: %s\n", strerror(errno));
+                    exit(1);
+                }
+
+                if (setuid(AID_SYSTEM) != 0) {
+                    ALOGE("setuid: %s\n", strerror(errno));
+                    exit(1);
+                }
+
+                // Generic idmap parameters
+                const char* argv[8];
+                int argc = 0;
+                struct stat st;
+
+                memset(argv, NULL, sizeof(argv));
+                argv[argc++] = AssetManager::IDMAP_BIN;
+                argv[argc++] = "--scan";
+                argv[argc++] = AssetManager::TARGET_PACKAGE_NAME;
+                argv[argc++] = AssetManager::TARGET_APK_PATH;
+                argv[argc++] = AssetManager::IDMAP_DIR;
+
+                // Directories to scan for overlays: if OVERLAY_THEME_DIR_PROPERTY is defined,
+                // use OVERLAY_DIR/<value of OVERLAY_THEME_DIR_PROPERTY> in addition to OVERLAY_DIR.
+                char subdir[PROP_VALUE_MAX];
+                int len = __system_property_get(AssetManager::OVERLAY_THEME_DIR_PERSIST_PROPERTY,
+                        subdir);
+                if (len == 0) {
+                    len = __system_property_get(AssetManager::OVERLAY_THEME_DIR_PROPERTY, subdir);
+                }
+                if (len > 0) {
+                    String8 overlayPath = String8(AssetManager::OVERLAY_DIR) + "/" + subdir;
+                    if (stat(overlayPath.string(), &st) == 0) {
+                        argv[argc++] = overlayPath.string();
+                    }
+                }
+                if (stat(AssetManager::OVERLAY_DIR, &st) == 0) {
+                    argv[argc++] = AssetManager::OVERLAY_DIR;
+                }
+
+                // Finally, invoke idmap (if any overlay directory exists)
+                if (argc > 5) {
+                    execv(AssetManager::IDMAP_BIN, (char* const*)argv);
+                    ALOGE("failed to execv for idmap: %s", strerror(errno));
+                    exit(1); // should never get here
+                } else {
+                    exit(0);
+                }
+            }
+            break;
+        default: // parent
+            waitpid(pid, NULL, 0);
+            break;
+    }
+}
+
 // ----------------------------------------------------------------------------
 
 // this guy is exported to other jni routines
@@ -1507,6 +1597,9 @@
 
 static void android_content_AssetManager_init(JNIEnv* env, jobject clazz, jboolean isSystem)
 {
+    if (isSystem) {
+        verifySystemIdmaps();
+    }
     AssetManager* am = new AssetManager();
     if (am == NULL) {
         jniThrowException(env, "java/lang/OutOfMemoryError", "");
diff --git a/core/jni/android_view_RenderNode.cpp b/core/jni/android_view_RenderNode.cpp
index 6e8c931..f221392 100644
--- a/core/jni/android_view_RenderNode.cpp
+++ b/core/jni/android_view_RenderNode.cpp
@@ -452,6 +452,10 @@
             const RenderProperties& props = node.properties();
             uirenderer::Rect bounds(props.getWidth(), props.getHeight());
             transform.mapRect(bounds);
+            bounds.left -= info.windowInsetLeft;
+            bounds.right -= info.windowInsetLeft;
+            bounds.top -= info.windowInsetTop;
+            bounds.bottom -= info.windowInsetTop;
 
             if (CC_LIKELY(transform.isPureTranslate())) {
                 // snap/round the computed bounds, so they match the rounding behavior
@@ -623,9 +627,9 @@
 int register_android_view_RenderNode(JNIEnv* env) {
     jclass clazz = FindClassOrDie(env, "android/view/SurfaceView");
     gSurfaceViewPositionUpdateMethod = GetMethodIDOrDie(env, clazz,
-            "updateSurfacePosition_renderWorker", "(JIIII)V");
+            "updateWindowPosition_renderWorker", "(JIIII)V");
     gSurfaceViewPositionLostMethod = GetMethodIDOrDie(env, clazz,
-            "surfacePositionLost_uiRtSync", "(J)V");
+            "windowPositionLost_uiRtSync", "(J)V");
     return RegisterMethodsOrDie(env, kClassPathName, gMethods, NELEM(gMethods));
 }
 
diff --git a/core/jni/android_view_SurfaceControl.cpp b/core/jni/android_view_SurfaceControl.cpp
index be86f5c..a81901d 100644
--- a/core/jni/android_view_SurfaceControl.cpp
+++ b/core/jni/android_view_SurfaceControl.cpp
@@ -693,6 +693,7 @@
     return JNI_TRUE;
 }
 
+
 static void nativeDeferTransactionUntil(JNIEnv* env, jclass clazz, jlong nativeObject,
         jobject handleObject, jlong frameNumber) {
     auto ctrl = reinterpret_cast<SurfaceControl *>(nativeObject);
@@ -701,27 +702,6 @@
     ctrl->deferTransactionUntil(handle, frameNumber);
 }
 
-static void nativeDeferTransactionUntilSurface(JNIEnv* env, jclass clazz, jlong nativeObject,
-        jobject surfaceObject, jlong frameNumber) {
-    auto ctrl = reinterpret_cast<SurfaceControl *>(nativeObject);
-    sp<Surface> barrier = reinterpret_cast<Surface *>(surfaceObject);
-
-    ctrl->deferTransactionUntil(barrier, frameNumber);
-}
-
-static void nativeReparentChildren(JNIEnv* env, jclass clazz, jlong nativeObject,
-        jobject newParentObject) {
-    auto ctrl = reinterpret_cast<SurfaceControl *>(nativeObject);
-    sp<IBinder> handle = ibinderForJavaObject(env, newParentObject);
-
-    ctrl->reparentChildren(handle);
-}
-
-static void nativeSeverChildren(JNIEnv* env, jclass clazz, jlong nativeObject) {
-    auto ctrl = reinterpret_cast<SurfaceControl *>(nativeObject);
-    ctrl->detachChildren();
-}
-
 static void nativeSetOverrideScalingMode(JNIEnv* env, jclass clazz, jlong nativeObject,
         jint scalingMode) {
     auto ctrl = reinterpret_cast<SurfaceControl *>(nativeObject);
@@ -844,12 +824,6 @@
             (void*)nativeSetDisplayPowerMode },
     {"nativeDeferTransactionUntil", "(JLandroid/os/IBinder;J)V",
             (void*)nativeDeferTransactionUntil },
-    {"nativeDeferTransactionUntilSurface", "(JJJ)V",
-            (void*)nativeDeferTransactionUntilSurface },
-    {"nativeReparentChildren", "(JLandroid/os/IBinder;)V",
-            (void*)nativeReparentChildren } ,
-    {"nativeSeverChildren", "(J)V",
-            (void*)nativeSeverChildren } ,
     {"nativeSetOverrideScalingMode", "(JI)V",
             (void*)nativeSetOverrideScalingMode },
     {"nativeGetHandle", "(J)Landroid/os/IBinder;",
diff --git a/core/jni/android_view_SurfaceSession.cpp b/core/jni/android_view_SurfaceSession.cpp
index 508d897..dad6958 100644
--- a/core/jni/android_view_SurfaceSession.cpp
+++ b/core/jni/android_view_SurfaceSession.cpp
@@ -24,7 +24,6 @@
 #include <utils/RefBase.h>
 
 #include <gui/SurfaceComposerClient.h>
-#include <gui/Surface.h>
 
 namespace android {
 
@@ -46,13 +45,6 @@
     return reinterpret_cast<jlong>(client);
 }
 
-static jlong nativeCreateScoped(JNIEnv* env, jclass clazz, jlong surfaceObject) {
-    Surface *parent = reinterpret_cast<Surface*>(surfaceObject);
-    SurfaceComposerClient* client = new SurfaceComposerClient(parent->getIGraphicBufferProducer());
-    client->incStrong((void*)nativeCreate);
-    return reinterpret_cast<jlong>(client);
-}
-
 static void nativeDestroy(JNIEnv* env, jclass clazz, jlong ptr) {
     SurfaceComposerClient* client = reinterpret_cast<SurfaceComposerClient*>(ptr);
     client->decStrong((void*)nativeCreate);
@@ -63,12 +55,11 @@
     client->dispose();
 }
 
+
 static const JNINativeMethod gMethods[] = {
     /* name, signature, funcPtr */
     { "nativeCreate", "()J",
             (void*)nativeCreate },
-    { "nativeCreateScoped", "(J)J",
-            (void*)nativeCreateScoped },
     { "nativeDestroy", "(J)V",
             (void*)nativeDestroy },
     { "nativeKill", "(J)V",
diff --git a/core/jni/android_view_ThreadedRenderer.cpp b/core/jni/android_view_ThreadedRenderer.cpp
index 99edf6e..37eae48a 100644
--- a/core/jni/android_view_ThreadedRenderer.cpp
+++ b/core/jni/android_view_ThreadedRenderer.cpp
@@ -178,9 +178,13 @@
             }
         }
         // TODO: This is hacky
+        info.windowInsetLeft = -stagingProperties().getLeft();
+        info.windowInsetTop = -stagingProperties().getTop();
         info.updateWindowPositions = true;
         RenderNode::prepareTree(info);
         info.updateWindowPositions = false;
+        info.windowInsetLeft = 0;
+        info.windowInsetTop = 0;
         info.errorHandler = nullptr;
     }
 
diff --git a/core/res/res/values/attrs.xml b/core/res/res/values/attrs.xml
index 55b154a..f8d5241 100644
--- a/core/res/res/values/attrs.xml
+++ b/core/res/res/values/attrs.xml
@@ -8567,6 +8567,7 @@
     <!-- Attributes that are read when parsing a <fontfamily> tag. -->
     <declare-styleable name="FontFamily">
         <attr name="fontProviderAuthority" format="string" />
+        <attr name="fontProviderPackage" format="string" />
         <attr name="fontProviderQuery" format="string" />
     </declare-styleable>
 
diff --git a/core/res/res/values/attrs_manifest.xml b/core/res/res/values/attrs_manifest.xml
index deacc24b..bfe666e 100644
--- a/core/res/res/values/attrs_manifest.xml
+++ b/core/res/res/values/attrs_manifest.xml
@@ -1891,6 +1891,7 @@
         <attr name="path" />
         <attr name="pathPrefix" />
         <attr name="pathPattern" />
+        <attr name="pathAdvancedPattern" />
         <attr name="permission" />
         <attr name="readPermission" />
         <attr name="writePermission" />
@@ -2280,6 +2281,17 @@
              "\\\\".  This is basically the same as what you would need to
              write if constructing the string in Java code. -->
         <attr name="pathPattern" />
+        <!-- Specify a URI path that matches an advanced pattern, as per
+             {@link android.content.IntentFilter#addDataPath
+             IntentFilter.addDataPath()} with
+             {@link android.os.PatternMatcher#PATTERN_ADVANCED_GLOB}.
+             Note that because '\' is used as an escape character when
+             reading the string from XML (before it is parsed as a pattern),
+             you will need to double-escape: for example a literal "*" would
+             be written as "\\*" and a literal "\" would be written as
+             "\\\\".  This is basically the same as what you would need to
+             write if constructing the string in Java code. -->
+        <attr name="pathAdvancedPattern" />
     </declare-styleable>
 
     <!-- Attributes that can be supplied in an AndroidManifest.xml
diff --git a/core/res/res/values/public.xml b/core/res/res/values/public.xml
index df3962c..0d90cd2 100644
--- a/core/res/res/values/public.xml
+++ b/core/res/res/values/public.xml
@@ -2802,6 +2802,7 @@
         <public name="requiredFeature" />
         <public name="requiredNotFeature" />
         <public name="autoFillHint" />
+        <public name="fontProviderPackage" />
     </public-group>
 
     <public-group type="style" first-id="0x010302e0">
diff --git a/core/tests/coretests/Android.mk b/core/tests/coretests/Android.mk
index ef09c35..1a16b3b 100644
--- a/core/tests/coretests/Android.mk
+++ b/core/tests/coretests/Android.mk
@@ -29,7 +29,6 @@
     frameworks-core-util-lib \
     mockwebserver \
     guava \
-    littlemock \
     android-support-test \
     mockito-target-minus-junit4 \
     espresso-core \
diff --git a/core/tests/coretests/res/font/samplexmldownloadedfont.xml b/core/tests/coretests/res/font/samplexmldownloadedfont.xml
index 35391bd..f1bdc47 100644
--- a/core/tests/coretests/res/font/samplexmldownloadedfont.xml
+++ b/core/tests/coretests/res/font/samplexmldownloadedfont.xml
@@ -1,5 +1,6 @@
 <?xml version="1.0" encoding="utf-8"?>
 <font-family xmlns:android="http://schemas.android.com/apk/res/android"
-        android:fontProviderAuthority="com.example.test.fontprovider"
+        android:fontProviderAuthority="com.example.test.fontprovider.authority"
+        android:fontProviderPackage="com.example.test.fontprovider.package"
         android:fontProviderQuery="MyRequestedFont">
 </font-family>
\ No newline at end of file
diff --git a/core/tests/coretests/src/android/content/res/FontResourcesParserTest.java b/core/tests/coretests/src/android/content/res/FontResourcesParserTest.java
index 8b536a7..23d3aa5 100644
--- a/core/tests/coretests/src/android/content/res/FontResourcesParserTest.java
+++ b/core/tests/coretests/src/android/content/res/FontResourcesParserTest.java
@@ -91,7 +91,8 @@
         List<FontConfig.Family> families = result.getFamilies();
         assertEquals(1, families.size());
         FontConfig.Family family = families.get(0);
-        assertEquals("com.example.test.fontprovider", family.getProviderAuthority());
+        assertEquals("com.example.test.fontprovider.authority", family.getProviderAuthority());
+        assertEquals("com.example.test.fontprovider.package", family.getProviderPackage());
         assertEquals("MyRequestedFont", family.getQuery());
         assertNull(family.getFonts());
     }
diff --git a/core/tests/coretests/src/android/graphics/drawable/AdaptiveIconDrawableTest.java b/core/tests/coretests/src/android/graphics/drawable/AdaptiveIconDrawableTest.java
new file mode 100644
index 0000000..5ade66e
--- /dev/null
+++ b/core/tests/coretests/src/android/graphics/drawable/AdaptiveIconDrawableTest.java
@@ -0,0 +1,193 @@
+package android.graphics.drawable;
+
+import static org.junit.Assert.assertTrue;
+
+import android.graphics.Bitmap;
+import android.graphics.Bitmap.Config;
+import android.graphics.BitmapFactory;
+import android.graphics.Canvas;
+import android.graphics.Color;
+import android.graphics.Paint;
+import android.graphics.Path;
+import android.graphics.Path.Direction;
+import android.graphics.Rect;
+import android.graphics.Region;
+import android.test.AndroidTestCase;
+import android.util.Log;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.util.Arrays;
+import org.junit.Test;
+
+public class AdaptiveIconDrawableTest extends AndroidTestCase {
+
+    public static final String TAG = AdaptiveIconDrawableTest.class.getSimpleName();
+    public static void L(String s, Object... parts) {
+        Log.d(TAG, (parts.length == 0) ? s : String.format(s, parts));
+    }
+    private Drawable mBackgroundDrawable;
+    private Drawable mForegroundDrawable;
+    private AdaptiveIconDrawable mIconDrawable;
+    private File mDir;
+
+    /**
+     * When setBound isn't called before draw method is called.
+     * Nothing is drawn.
+     */
+    @Test
+    public void testDrawWithoutSetBounds() throws Exception {
+        mBackgroundDrawable = new ColorDrawable(Color.BLUE);
+        mForegroundDrawable = new ColorDrawable(Color.RED);
+        mIconDrawable = new AdaptiveIconDrawable(mBackgroundDrawable, mForegroundDrawable);
+        mDir = getContext().getExternalFilesDir(null);
+        L("writing temp bitmaps to %s...", mDir);
+
+        final Bitmap bm_test = Bitmap.createBitmap(150, 150, Bitmap.Config.ARGB_8888);
+        final Bitmap bm_org = bm_test.copy(Config.ARGB_8888, false);
+        final Canvas can1 = new Canvas(bm_test);
+
+        // Even when setBounds is not called, should not crash
+        mIconDrawable.draw(can1);
+        // Draws nothing! Hence same as original.
+        if (!equalBitmaps(bm_test, bm_org)) {
+            findBitmapDifferences(bm_test, bm_org);
+            fail("bm differs, check " + mDir);
+        }
+    }
+
+    /**
+     * When setBound is called, translate accordingly.
+     */
+    @Test
+    public void testDrawSetBounds() throws Exception {
+        int dpi = 4 ;
+        int top = 18 * dpi;
+        int left = 18 * dpi;
+        int right = 90 * dpi;
+        int bottom = 90 * dpi;
+        int width = right - left;
+        int height = bottom - top;
+
+        mIconDrawable = (AdaptiveIconDrawable) getContext().getResources().getDrawable(android.R.drawable.sym_def_app_icon);
+        mDir = getContext().getExternalFilesDir(null);
+        L("writing temp bitmaps to %s...", mDir);
+        final Bitmap bm_org = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
+        final Canvas can_org = new Canvas(bm_org);
+        mIconDrawable.setBounds(0, 0, width, height);
+        mIconDrawable.draw(can_org);
+
+        // Tested bitmap is drawn from the adaptive icon drawable.
+        final Bitmap bm_test = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
+        final Canvas can_test = new Canvas(bm_test);
+
+        mIconDrawable.setBounds(left, top, right, bottom);
+        can_test.translate(-left, -top);
+        mIconDrawable.draw(can_test);
+        can_test.translate(left, top);
+
+
+        bm_org.compress(Bitmap.CompressFormat.PNG, 100,
+            new FileOutputStream(new File(mDir, "adaptive-bm-original.png")));
+        bm_test.compress(Bitmap.CompressFormat.PNG, 100,
+            new FileOutputStream(new File(mDir, "adaptive-bm-test.png")));
+        Region region = new Region(new Rect(0, 0, width, height));
+
+        Path circle = new Path();
+        circle.addCircle(width / 2, height / 2,  (right - left)/2 -10 /* room for anti-alias */, Direction.CW);
+
+        region.setPath(circle, region);
+        if (!equalBitmaps(bm_test, bm_org, region)) {
+            findBitmapDifferences(bm_test, bm_org);
+            fail("bm differs, check " + mDir);
+        }
+    }
+
+    //
+    // Utils
+    //
+
+    boolean equalBitmaps(Bitmap a, Bitmap b) {
+      return equalBitmaps(a, b, null);
+    }
+
+    boolean equalBitmaps(Bitmap a, Bitmap b, Region region) {
+        if (a.getWidth() != b.getWidth() || a.getHeight() != b.getHeight()) return false;
+
+        final int w = a.getWidth();
+        final int h = a.getHeight();
+        int[] aPix = new int[w * h];
+        int[] bPix = new int[w * h];
+
+        if (region != null) {
+            for (int i = 0; i < w; i++) {
+                for (int j = 0; j < h; j++) {
+                    int ra = (a.getPixel(i, j) >> 16) & 0xff;
+                    int ga = (a.getPixel(i, j) >> 8) & 0xff;
+                    int ba = a.getPixel(i, j) & 0xff;
+                    int rb = (b.getPixel(i, j) >> 16) & 0xff;
+                    int gb = (b.getPixel(i, j) >> 8) & 0xff;
+                    int bb = b.getPixel(i, j) & 0xff;
+                    if (region.contains(i, j) && a.getPixel(i, j) != b.getPixel(i, j) ) {
+                        return false;
+                    }
+                }
+            }
+            return true;
+        } else {
+            a.getPixels(aPix, 0, w, 0, 0, w, h);
+            b.getPixels(bPix, 0, w, 0, 0, w, h);
+            return Arrays.equals(aPix, bPix);
+        }
+    }
+
+    void findBitmapDifferences(Bitmap a, Bitmap b) {
+        if (a.getWidth() != b.getWidth() || a.getHeight() != b.getHeight()) {
+            L("different sizes: %dx%d vs %dx%d",
+                a.getWidth(), a.getHeight(), b.getWidth(), b.getHeight());
+            return;
+        }
+
+        final int w = a.getWidth();
+        final int h = a.getHeight();
+        int[] aPix = new int[w * h];
+        int[] bPix = new int[w * h];
+
+        a.getPixels(aPix, 0, w, 0, 0, w, h);
+        b.getPixels(bPix, 0, w, 0, 0, w, h);
+
+        L("bitmap a (%dx%d)", w, h);
+        printBits(aPix, w, h);
+        L("bitmap b (%dx%d)", w, h);
+        printBits(bPix, w, h);
+
+        StringBuffer sb = new StringBuffer("Different pixels: ");
+        for (int i=0; i<w; i++) {
+            for (int j=0; j<h; j++) {
+                if (aPix[i+w*j] != bPix[i+w*j]) {
+                    sb.append(" ").append(i).append(",").append(j).append("<")
+                        .append(aPix[i+w*j]).append(",").append(bPix[i+w*j]).append(">");
+                }
+            }
+        }
+        L(sb.toString());
+    }
+
+    static void printBits(int[] a, int w, int h) {
+        final StringBuilder sb = new StringBuilder();
+        for (int i=0; i<w; i++) {
+            for (int j=0; j<h; j++) {
+                sb.append(colorToChar(a[i+w*j]));
+            }
+            sb.append('\n');
+        }
+        L(sb.toString());
+    }
+
+    static char colorToChar(int color) {
+        int sum = ((color >> 16) & 0xff)
+            + ((color >> 8)  & 0xff)
+            + ((color)       & 0xff);
+        return GRADIENT[sum * (GRADIENT.length-1) / (3*0xff)];
+    }
+    static final char[] GRADIENT = " .:;+=xX$#".toCharArray();
+}
diff --git a/core/tests/coretests/src/android/metrics/LogMakerTest.java b/core/tests/coretests/src/android/metrics/LogMakerTest.java
index b9c973f..ece44be 100644
--- a/core/tests/coretests/src/android/metrics/LogMakerTest.java
+++ b/core/tests/coretests/src/android/metrics/LogMakerTest.java
@@ -122,6 +122,55 @@
         assertEquals(null, builder.getTaggedData(1));
     }
 
+    public void testClearFieldLeavesOtherFieldsIntact() {
+        LogMaker builder = new LogMaker(0);
+        builder.setPackageName("package.name");
+        builder.setSubtype(10);
+        builder.clearPackageName();
+        assertEquals(null, builder.getPackageName());
+        assertEquals(10, builder.getSubtype());
+    }
+
+    public void testSetAndClearCategory() {
+        LogMaker builder = new LogMaker(0);
+        builder.setCategory(MetricsEvent.MAIN_SETTINGS);
+        assertEquals(MetricsEvent.MAIN_SETTINGS, builder.getCategory());
+        builder.clearCategory();
+        assertEquals(MetricsEvent.VIEW_UNKNOWN, builder.getCategory());
+    }
+
+    public void testSetAndClearType() {
+        LogMaker builder = new LogMaker(0);
+        builder.setType(MetricsEvent.TYPE_OPEN);
+        assertEquals(MetricsEvent.TYPE_OPEN, builder.getType());
+        builder.clearType();
+        assertEquals(MetricsEvent.TYPE_UNKNOWN, builder.getType());
+    }
+
+    public void testSetAndClearSubtype() {
+        LogMaker builder = new LogMaker(0);
+        builder.setSubtype(1);
+        assertEquals(1, builder.getSubtype());
+        builder.clearSubtype();
+        assertEquals(0, builder.getSubtype());
+    }
+
+    public void testSetAndClearTimestamp() {
+        LogMaker builder = new LogMaker(0);
+        builder.setTimestamp(1);
+        assertEquals(1, builder.getTimestamp());
+        builder.clearTimestamp();
+        assertEquals(0, builder.getTimestamp());
+    }
+
+    public void testSetAndClearPackageName() {
+        LogMaker builder = new LogMaker(0);
+        builder.setPackageName("package.name");
+        assertEquals("package.name", builder.getPackageName());
+        builder.clearPackageName();
+        assertEquals(null, builder.getPackageName());
+    }
+
     public void testGiantLogOmitted() {
         LogMaker badBuilder = new LogMaker(0);
         StringBuilder b = new StringBuilder();
diff --git a/core/tests/coretests/src/android/net/SSLSessionCacheTest.java b/core/tests/coretests/src/android/net/SSLSessionCacheTest.java
index be19303..ec130e0 100644
--- a/core/tests/coretests/src/android/net/SSLSessionCacheTest.java
+++ b/core/tests/coretests/src/android/net/SSLSessionCacheTest.java
@@ -19,7 +19,7 @@
 import com.android.org.conscrypt.ClientSessionContext;
 import com.android.org.conscrypt.SSLClientSessionCache;
 
-import com.google.testing.littlemock.LittleMock;
+import org.mockito.Mockito;
 
 import junit.framework.TestCase;
 
@@ -39,25 +39,25 @@
 
     public void testInstall_compatibleContext() throws Exception {
         final SSLContext ctx = SSLContext.getDefault();
-        final SSLClientSessionCache mock = LittleMock.mock(SSLClientSessionCache.class);
+        final SSLClientSessionCache mock = Mockito.mock(SSLClientSessionCache.class);
         final ClientSessionContext clientCtx = (ClientSessionContext) ctx.getClientSessionContext();
 
         try {
             SSLSessionCache.install(new SSLSessionCache(mock), ctx);
             clientCtx.getSession("www.foogle.com", 443);
-            LittleMock.verify(mock).getSessionData(LittleMock.anyString(), LittleMock.anyInt());
+            Mockito.verify(mock).getSessionData(Mockito.anyString(), Mockito.anyInt());
         } finally {
             // Restore cacheless behaviour.
             SSLSessionCache.install(null, ctx);
             clientCtx.getSession("www.foogle.com", 443);
-            LittleMock.verifyNoMoreInteractions(mock);
+            Mockito.verifyNoMoreInteractions(mock);
         }
     }
 
     public void testInstall_incompatibleContext() {
         try {
             SSLSessionCache.install(
-                    new SSLSessionCache(LittleMock.mock(SSLClientSessionCache.class)),
+                    new SSLSessionCache(Mockito.mock(SSLClientSessionCache.class)),
                     new FakeSSLContext());
             fail();
         } catch (IllegalArgumentException expected) {}
@@ -102,7 +102,7 @@
 
         @Override
         protected SSLSessionContext engineGetClientSessionContext() {
-            return LittleMock.mock(SSLSessionContext.class);
+            return Mockito.mock(SSLSessionContext.class);
         }
     }
 }
diff --git a/core/tests/coretests/src/android/provider/FontsContractTest.java b/core/tests/coretests/src/android/provider/FontsContractTest.java
new file mode 100644
index 0000000..db623a4
--- /dev/null
+++ b/core/tests/coretests/src/android/provider/FontsContractTest.java
@@ -0,0 +1,235 @@
+/*
+ * 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.
+ */
+package android.provider;
+
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyInt;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.ProviderInfo;
+import android.content.pm.Signature;
+import android.graphics.Typeface;
+import android.graphics.fonts.FontRequest;
+import android.graphics.fonts.FontResult;
+import android.os.Bundle;
+import android.os.ResultReceiver;
+import android.support.test.filters.SmallTest;
+import android.test.ProviderTestCase2;
+import android.util.Base64;
+
+import org.mockito.ArgumentCaptor;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * Unit tests for {@link FontsContract}.
+ */
+@SmallTest
+public class FontsContractTest extends ProviderTestCase2<TestFontsProvider> {
+    private static final byte[] BYTE_ARRAY =
+            Base64.decode("e04fd020ea3a6910a2d808002b30", Base64.DEFAULT);
+    private static final String PACKAGE_NAME = "com.my.font.provider.package";
+
+    private final FontRequest request = new FontRequest(
+            TestFontsProvider.AUTHORITY, PACKAGE_NAME, "query");
+    private TestFontsProvider mProvider;
+    private FontsContract mContract;
+    private ResultReceiver mResultReceiver;
+    private PackageManager mPackageManager;
+
+    public FontsContractTest() {
+        super(TestFontsProvider.class, TestFontsProvider.AUTHORITY);
+    }
+
+    public void setUp() throws Exception {
+        super.setUp();
+
+        mProvider = getProvider();
+        mPackageManager = mock(PackageManager.class);
+        mContract = new FontsContract(getMockContext(), mPackageManager);
+        mResultReceiver = mock(ResultReceiver.class);
+    }
+
+    public void testGetFontFromProvider() {
+        mContract.getFontFromProvider(request, mResultReceiver, TestFontsProvider.AUTHORITY);
+
+        final ArgumentCaptor<Bundle> bundleCaptor = ArgumentCaptor.forClass(Bundle.class);
+        verify(mResultReceiver).send(eq(FontsContract.RESULT_CODE_OK), bundleCaptor.capture());
+
+        Bundle bundle = bundleCaptor.getValue();
+        assertNotNull(bundle);
+        List<FontResult> resultList =
+                bundle.getParcelableArrayList(FontsContract.PARCEL_FONT_RESULTS);
+        assertNotNull(resultList);
+        assertEquals(1, resultList.size());
+        FontResult fontResult = resultList.get(0);
+        assertEquals(TestFontsProvider.TTC_INDEX, fontResult.getTtcIndex());
+        assertEquals(TestFontsProvider.VARIATION_SETTINGS, fontResult.getFontVariationSettings());
+        assertEquals(TestFontsProvider.STYLE, fontResult.getStyle());
+        assertNotNull(fontResult.getFileDescriptor());
+    }
+
+    public void testGetFontFromProvider_providerDoesntReturnAllFields() {
+        mProvider.setReturnAllFields(false);
+
+        final ArgumentCaptor<Bundle> bundleCaptor = ArgumentCaptor.forClass(Bundle.class);
+        mContract.getFontFromProvider(request, mResultReceiver, TestFontsProvider.AUTHORITY);
+        verify(mResultReceiver).send(eq(FontsContract.RESULT_CODE_OK), bundleCaptor.capture());
+
+        Bundle bundle = bundleCaptor.getValue();
+        assertNotNull(bundle);
+        List<FontResult> resultList =
+                bundle.getParcelableArrayList(FontsContract.PARCEL_FONT_RESULTS);
+        assertNotNull(resultList);
+        assertEquals(1, resultList.size());
+        FontResult fontResult = resultList.get(0);
+        assertEquals(0, fontResult.getTtcIndex());
+        assertNull(fontResult.getFontVariationSettings());
+        assertEquals(Typeface.NORMAL, fontResult.getStyle());
+        assertNotNull(fontResult.getFileDescriptor());
+    }
+
+    public void testGetProvider_providerNotFound() {
+        when(mPackageManager.resolveContentProvider(anyString(), anyInt())).thenReturn(null);
+
+        ProviderInfo result = mContract.getProvider(request);
+
+        assertNull(result);
+    }
+
+    public void testGetProvider_providerIsSystemApp() throws PackageManager.NameNotFoundException {
+        ProviderInfo info = setupPackageManager();
+        info.applicationInfo.flags = ApplicationInfo.FLAG_SYSTEM;
+        when(mPackageManager.resolveContentProvider(anyString(), anyInt())).thenReturn(info);
+
+        ProviderInfo result = mContract.getProvider(request);
+
+        assertEquals(info, result);
+    }
+
+    public void testGetProvider_providerIsSystemAppWrongPackage()
+            throws PackageManager.NameNotFoundException {
+        ProviderInfo info = setupPackageManager();
+        info.applicationInfo.flags = ApplicationInfo.FLAG_SYSTEM;
+        when(mPackageManager.resolveContentProvider(anyString(), anyInt())).thenReturn(info);
+
+        ProviderInfo result = mContract.getProvider(
+                new FontRequest(TestFontsProvider.AUTHORITY, "com.wrong.package", "query"));
+
+        assertNull(result);
+    }
+
+    public void testGetProvider_providerIsNonSystemAppNoCerts()
+            throws PackageManager.NameNotFoundException {
+        setupPackageManager();
+
+        // The default request is missing the certificates info.
+        ProviderInfo result = mContract.getProvider(request);
+
+        assertNull(result);
+    }
+
+    public void testGetProvider_providerIsNonSystemAppWrongCerts()
+            throws PackageManager.NameNotFoundException {
+        setupPackageManager();
+
+        byte[] wrongCert = Base64.decode("this is a wrong cert", Base64.DEFAULT);
+        List<byte[]> certList = Arrays.asList(wrongCert);
+        FontRequest requestWrongCerts = new FontRequest(
+                TestFontsProvider.AUTHORITY, PACKAGE_NAME, "query", Arrays.asList(certList));
+        ProviderInfo result = mContract.getProvider(requestWrongCerts);
+
+        assertNull(result);
+    }
+
+    public void testGetProvider_providerIsNonSystemAppCorrectCerts()
+            throws PackageManager.NameNotFoundException {
+        ProviderInfo info = setupPackageManager();
+
+        List<byte[]> certList = Arrays.asList(BYTE_ARRAY);
+        FontRequest requestRightCerts = new FontRequest(
+                TestFontsProvider.AUTHORITY, PACKAGE_NAME, "query", Arrays.asList(certList));
+        ProviderInfo result = mContract.getProvider(requestRightCerts);
+
+        assertEquals(info, result);
+    }
+
+    public void testGetProvider_providerIsNonSystemAppMoreCerts()
+            throws PackageManager.NameNotFoundException {
+        setupPackageManager();
+
+        byte[] wrongCert = Base64.decode("this is a wrong cert", Base64.DEFAULT);
+        List<byte[]> certList = Arrays.asList(wrongCert, BYTE_ARRAY);
+        FontRequest requestRightCerts = new FontRequest(
+                TestFontsProvider.AUTHORITY, PACKAGE_NAME, "query", Arrays.asList(certList));
+        ProviderInfo result = mContract.getProvider(requestRightCerts);
+
+        // There is one too many certs, should fail as the set doesn't match.
+        assertNull(result);
+    }
+
+    public void testGetProvider_providerIsNonSystemAppCorrectCertsSeveralSets()
+            throws PackageManager.NameNotFoundException {
+        ProviderInfo info = setupPackageManager();
+
+        List<List<byte[]>> certList = new ArrayList<>();
+        byte[] wrongCert = Base64.decode("this is a wrong cert", Base64.DEFAULT);
+        certList.add(Arrays.asList(wrongCert));
+        certList.add(Arrays.asList(BYTE_ARRAY));
+        FontRequest requestRightCerts = new FontRequest(
+                TestFontsProvider.AUTHORITY, PACKAGE_NAME, "query", certList);
+        ProviderInfo result = mContract.getProvider(requestRightCerts);
+
+        assertEquals(info, result);
+    }
+
+    public void testGetProvider_providerIsNonSystemAppWrongPackage()
+            throws PackageManager.NameNotFoundException {
+        setupPackageManager();
+
+        List<List<byte[]>> certList = new ArrayList<>();
+        certList.add(Arrays.asList(BYTE_ARRAY));
+        FontRequest requestRightCerts = new FontRequest(
+                TestFontsProvider.AUTHORITY, "com.wrong.package.name", "query", certList);
+        ProviderInfo result = mContract.getProvider(requestRightCerts);
+
+        assertNull(result);
+    }
+
+    private ProviderInfo setupPackageManager()
+            throws PackageManager.NameNotFoundException {
+        ProviderInfo info = new ProviderInfo();
+        info.packageName = PACKAGE_NAME;
+        info.applicationInfo = new ApplicationInfo();
+        when(mPackageManager.resolveContentProvider(anyString(), anyInt())).thenReturn(info);
+        PackageInfo packageInfo = new PackageInfo();
+        Signature signature = mock(Signature.class);
+        when(signature.toByteArray()).thenReturn(BYTE_ARRAY);
+        packageInfo.packageName = PACKAGE_NAME;
+        packageInfo.signatures = new Signature[] { signature };
+        when(mPackageManager.getPackageInfo(anyString(), anyInt())).thenReturn(packageInfo);
+        return info;
+    }
+}
diff --git a/core/tests/coretests/src/android/provider/TestFontsProvider.java b/core/tests/coretests/src/android/provider/TestFontsProvider.java
new file mode 100644
index 0000000..6d40f37
--- /dev/null
+++ b/core/tests/coretests/src/android/provider/TestFontsProvider.java
@@ -0,0 +1,117 @@
+/*
+ * 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.
+ */
+package android.provider;
+
+import static android.os.ParcelFileDescriptor.MODE_READ_ONLY;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.content.ContentProvider;
+import android.content.ContentValues;
+import android.database.Cursor;
+import android.database.MatrixCursor;
+import android.graphics.Typeface;
+import android.net.Uri;
+import android.os.ParcelFileDescriptor;
+
+import java.io.File;
+import java.io.IOException;
+
+/**
+ * Provides a test Content Provider implementing {@link FontsContract}.
+ */
+public class TestFontsProvider extends ContentProvider {
+    static final String AUTHORITY = "android.provider.TestFontsProvider";
+    static final int TTC_INDEX = 2;
+    static final String VARIATION_SETTINGS = "'wdth' 1";
+    static final int STYLE = Typeface.BOLD;
+
+    private ParcelFileDescriptor mPfd;
+    private boolean mReturnAllFields = true;
+
+    /**
+     * Used by tests to switch whether all fields should be returned or not.
+     */
+    void setReturnAllFields(boolean returnAllFields) {
+        mReturnAllFields = returnAllFields;
+    }
+
+    @Override
+    public boolean onCreate() {
+        mPfd = createFontFile();
+        return true;
+    }
+
+    @Override
+    public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection,
+            @Nullable String[] selectionArgs, @Nullable String sortOrder) {
+        MatrixCursor cursor;
+        if (mReturnAllFields) {
+            cursor = new MatrixCursor(new String[] { FontsContract.Columns._ID,
+                    FontsContract.Columns.TTC_INDEX, FontsContract.Columns.VARIATION_SETTINGS,
+                    FontsContract.Columns.STYLE });
+            cursor.addRow(new Object[] { 1, TTC_INDEX, VARIATION_SETTINGS, STYLE });
+        } else {
+            cursor = new MatrixCursor(new String[] { FontsContract.Columns._ID });
+            cursor.addRow(new Object[] { 1 });
+        }
+        return cursor;
+    }
+
+    @Override
+    public ParcelFileDescriptor openFile(Uri uri, String mode) {
+        try {
+            return mPfd.dup();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+    @Override
+    public String getType(@NonNull Uri uri) {
+        return "application/x-font-ttf";
+    }
+
+    @Override
+    public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
+        return null;
+    }
+
+    @Override
+    public int delete(@NonNull Uri uri, @Nullable String selection,
+            @Nullable String[] selectionArgs) {
+        return 0;
+    }
+
+    @Override
+    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection,
+            @Nullable String[] selectionArgs) {
+        return 0;
+    }
+
+    private ParcelFileDescriptor createFontFile() {
+        try {
+            final File file = new File(getContext().getCacheDir(), "font.ttf");
+            file.getParentFile().mkdirs();
+            file.createNewFile();
+            return ParcelFileDescriptor.open(file, MODE_READ_ONLY);
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+}
diff --git a/core/tests/coretests/src/android/view/PopupWindowVisibility.java b/core/tests/coretests/src/android/view/PopupWindowVisibility.java
index 7eb0468..6e11ede 100644
--- a/core/tests/coretests/src/android/view/PopupWindowVisibility.java
+++ b/core/tests/coretests/src/android/view/PopupWindowVisibility.java
@@ -82,7 +82,7 @@
         "Cote d'Ivoire", "Cambodia", "Cameroon", "Canada", "Cape Verde",
         "Cayman Islands", "Central African Republic", "Chad", "Chile", "China",
         "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo",
-        "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic",
+        "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czechia",
         "Democratic Republic of the Congo", "Denmark", "Djibouti", "Dominica", "Dominican Republic",
         "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea",
         "Estonia", "Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji", "Finland",
diff --git a/core/tests/coretests/src/android/widget/focus/RequestFocusTest.java b/core/tests/coretests/src/android/widget/focus/RequestFocusTest.java
index f2eba23..cdfa217 100644
--- a/core/tests/coretests/src/android/widget/focus/RequestFocusTest.java
+++ b/core/tests/coretests/src/android/widget/focus/RequestFocusTest.java
@@ -16,8 +16,8 @@
 
 package android.widget.focus;
 
-import static com.google.testing.littlemock.LittleMock.inOrder;
-import static com.google.testing.littlemock.LittleMock.mock;
+import static org.mockito.Mockito.inOrder;
+import static org.mockito.Mockito.mock;
 
 import android.os.Handler;
 import android.test.ActivityInstrumentationTestCase2;
@@ -31,7 +31,7 @@
 import android.widget.Button;
 
 import com.android.frameworks.coretests.R;
-import com.google.testing.littlemock.LittleMock.InOrder;
+import org.mockito.InOrder;
 
 /**
  * {@link RequestFocusTest} is set up to exercise cases where the views that
diff --git a/core/tests/coretests/src/com/android/internal/logging/legacy/ParserTest.java b/core/tests/coretests/src/com/android/internal/logging/legacy/ParserTest.java
deleted file mode 100644
index 4adf629..0000000
--- a/core/tests/coretests/src/com/android/internal/logging/legacy/ParserTest.java
+++ /dev/null
@@ -1,111 +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.
- */
-package com.android.internal.logging.legacy;
-
-import android.metrics.LogMaker;
-import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
-
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyInt;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.when;
-
-import junit.framework.TestCase;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.mockito.stubbing.OngoingStubbing;
-
-/**
- * Common functions and temporaries for parser tests.
- */
-public class ParserTest extends TestCase {
-    @Mock
-    protected TronLogger mLogger;
-
-    protected TagParser mParser;
-
-    protected LogMaker[] mProto;
-    protected ArgumentCaptor<LogMaker> mProtoCaptor;
-    protected ArgumentCaptor<String> mNameCaptor;
-    protected ArgumentCaptor<Integer> mCountCaptor;
-    protected String mKey = "0|com.android.example.notificationshowcase|31338|null|10090";
-    protected String mTaggedKey = "0|com.android.example.notificationshowcase|31338|badger|10090";
-    protected String mKeyPackage = "com.android.example.notificationshowcase";
-    protected String mTag = "badger";
-    protected int mId = 31338;
-    protected int mSinceCreationMillis = 5000;
-    protected int mSinceUpdateMillis = 1012;
-    protected int mSinceVisibleMillis = 323;
-
-
-    public ParserTest() {
-        mProto = new LogMaker[5];
-        for (int i = 0; i < mProto.length; i++) {
-            mProto[i] = new LogMaker(MetricsEvent.VIEW_UNKNOWN);
-        }
-    }
-
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
-
-        MockitoAnnotations.initMocks(this);
-
-        mProtoCaptor = ArgumentCaptor.forClass(LogMaker.class);
-        mNameCaptor = ArgumentCaptor.forClass(String.class);
-        mCountCaptor = ArgumentCaptor.forClass(Integer.class);
-
-        OngoingStubbing<LogMaker> stub = when(mLogger.obtain()).thenReturn(mProto[0]);
-        for (int i = 1; i < mProto.length; i++) {
-            stub.thenReturn(mProto[i]);
-        }
-        doNothing().when(mLogger).addEvent(any(LogMaker.class));
-        doNothing().when(mLogger).incrementBy(anyString(), anyInt());
-    }
-
-    protected void validateNotificationTimes(LogMaker proto, int life, int freshness,
-            int exposure) {
-        validateNotificationTimes(proto, life, freshness);
-        if (exposure != 0) {
-            assertEquals(exposure,
-                proto.getTaggedData(MetricsEvent.NOTIFICATION_SINCE_VISIBLE_MILLIS));
-        } else {
-            assertNull(proto.getTaggedData(MetricsEvent.NOTIFICATION_SINCE_VISIBLE_MILLIS));
-        }
-    }
-
-    protected void validateNotificationTimes(LogMaker proto, int life, int freshness) {
-        if (life != 0) {
-            assertEquals(life,
-                proto.getTaggedData(MetricsEvent.NOTIFICATION_SINCE_CREATE_MILLIS));
-        } else {
-            assertNull(proto.getTaggedData(MetricsEvent.NOTIFICATION_SINCE_CREATE_MILLIS));
-        }
-        if (freshness != 0) {
-            assertEquals(freshness,
-                proto.getTaggedData(MetricsEvent.NOTIFICATION_SINCE_UPDATE_MILLIS));
-        } else {
-            assertNull(proto.getTaggedData(MetricsEvent.NOTIFICATION_SINCE_UPDATE_MILLIS));
-        }
-    }
-
-    protected void validateNotificationIdAndTag(LogMaker proto, int id, String tag) {
-        assertEquals(tag, proto.getTaggedData(MetricsEvent.NOTIFICATION_TAG));
-        assertEquals(id, proto.getTaggedData(MetricsEvent.NOTIFICATION_ID));
-    }
-}
diff --git a/core/tests/coretests/src/com/android/internal/logging/legacy/PowerScreenStateParserTest.java b/core/tests/coretests/src/com/android/internal/logging/legacy/PowerScreenStateParserTest.java
deleted file mode 100644
index b480e61..0000000
--- a/core/tests/coretests/src/com/android/internal/logging/legacy/PowerScreenStateParserTest.java
+++ /dev/null
@@ -1,69 +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.
- */
-package com.android.internal.logging.legacy;
-
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-
-
-import android.metrics.LogMaker;
-import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
-
-public class PowerScreenStateParserTest extends ParserTest {
-
-    public PowerScreenStateParserTest() {
-        mParser = new PowerScreenStateParser();
-    }
-
-    public void testScreenOn() throws Throwable {
-        validate(MetricsEvent.TYPE_OPEN, 0, "1,0,0,0");
-    }
-
-    public void testTimeout() throws Throwable {
-        validate(MetricsEvent.TYPE_CLOSE, 3, "0,3,0,0");
-    }
-
-    public void testUser() throws Throwable {
-        validate(MetricsEvent.TYPE_CLOSE, 2, "0,2,0,0");
-    }
-
-    public void testAdmin() throws Throwable {
-        validate(MetricsEvent.TYPE_CLOSE, 1, "0,1,0,0");
-    }
-
-    public void testIgnoreUnexpectedData() throws Throwable {
-        validate(MetricsEvent.TYPE_OPEN, 0, "1,0,0,0,5");
-    }
-
-    private void validate(int type, int subType, String log) {
-        String[] parts = log.split(",");
-        int t = 1000;
-        Object[] objects = new Object[parts.length];
-        for (int i = 0; i < parts.length; i++) {
-            objects[i] = Integer.valueOf(parts[i]);
-        }
-
-        mParser.parseEvent(mLogger, t, objects);
-
-        verify(mLogger, times(1)).addEvent(mProtoCaptor.capture());
-
-        LogMaker proto = mProtoCaptor.getValue();
-        assertEquals(t, proto.getTimestamp());
-        assertEquals(type, proto.getType());
-        assertEquals(MetricsEvent.SCREEN, proto.getCategory());
-        assertEquals(subType, proto.getSubtype());
-    }
-}
diff --git a/core/tests/coretests/src/com/android/internal/logging/legacy/SysuiMultiActionParserTest.java b/core/tests/coretests/src/com/android/internal/logging/legacy/SysuiMultiActionParserTest.java
deleted file mode 100644
index e7a05d8..0000000
--- a/core/tests/coretests/src/com/android/internal/logging/legacy/SysuiMultiActionParserTest.java
+++ /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.
- */
-package com.android.internal.logging.legacy;
-
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-
-
-import android.metrics.LogMaker;
-
-public class SysuiMultiActionParserTest extends ParserTest {
-
-    public SysuiMultiActionParserTest() {
-        mParser = new SysuiMultiActionParser();
-    }
-
-    public void testParseAllFields() {
-        int category = 10;
-        int type = 11;
-        int subtype = 12;
-        long timestamp = 1484669007890L;
-        String packageName = "com.foo.bar";
-        String counterName = "sheep";
-        int bucket = 13;
-        int value = 14;
-        LogMaker builder = new LogMaker(category);
-        builder.setType(type);
-        builder.setSubtype(subtype);
-        builder.setPackageName(packageName);
-        builder.setCounterName(counterName);
-        builder.setCounterBucket(bucket);
-        builder.setCounterValue(value);
-        builder.addTaggedData(1, "one");
-        builder.addTaggedData(2, "two");
-        Object[] out = builder.serialize();
-        int t = 1000;
-
-        mParser.parseEvent(mLogger, timestamp, out);
-
-        verify(mLogger, times(1)).addEvent(mProtoCaptor.capture());
-
-        LogMaker proto = mProtoCaptor.getValue();
-        assertEquals(category, proto.getCategory());
-        assertEquals(type, proto.getType());
-        assertEquals(subtype, proto.getSubtype());
-        assertEquals(timestamp, proto.getTimestamp());
-        assertEquals(packageName, proto.getPackageName());
-        assertEquals(counterName, proto.getCounterName());
-        assertEquals(bucket, proto.getCounterBucket());
-        assertEquals(value, proto.getCounterValue());
-        assertEquals("one", proto.getTaggedData(1));
-        assertEquals("two", proto.getTaggedData(2));
-    }
-}
diff --git a/data/etc/platform.xml b/data/etc/platform.xml
index 6248856..344f3c8 100644
--- a/data/etc/platform.xml
+++ b/data/etc/platform.xml
@@ -60,6 +60,7 @@
     </permission>
 
     <permission name="android.permission.WRITE_MEDIA_STORAGE" >
+        <group gid="media_rw" />
         <group gid="sdcard_rw" />
     </permission>
 
diff --git a/graphics/java/android/graphics/Bitmap.java b/graphics/java/android/graphics/Bitmap.java
index ba7f05d..6bb8a2c 100644
--- a/graphics/java/android/graphics/Bitmap.java
+++ b/graphics/java/android/graphics/Bitmap.java
@@ -19,12 +19,12 @@
 import android.annotation.CheckResult;
 import android.annotation.ColorInt;
 import android.annotation.NonNull;
+import android.annotation.Nullable;
 import android.os.Parcel;
 import android.os.Parcelable;
 import android.os.Trace;
 import android.util.DisplayMetrics;
 import android.util.Log;
-
 import libcore.util.NativeAllocationRegistry;
 
 import java.io.OutputStream;
@@ -73,6 +73,8 @@
     private int mHeight;
     private boolean mRecycled;
 
+    private ColorSpace mColorSpace;
+
     /** @hide */
     public int mDensity = getDefaultDensity();
 
@@ -145,6 +147,7 @@
         mWidth = width;
         mHeight = height;
         mRequestPremultiplied = requestPremultiplied;
+        mColorSpace = null;
     }
 
     /**
@@ -252,6 +255,7 @@
         nativeReconfigure(mNativePtr, width, height, config.nativeInt, mRequestPremultiplied);
         mWidth = width;
         mHeight = height;
+        mColorSpace = null;
     }
 
     /**
@@ -1435,6 +1439,47 @@
     }
 
     /**
+     * Returns the color space associated with this bitmap. If the color
+     * space is unknown, this method returns null.
+     */
+    @Nullable
+    public final ColorSpace getColorSpace() {
+        // A reconfigure can change the configuration and rgba16f is
+        // always linear scRGB at this time
+        if (getConfig() == Config.RGBA_F16) {
+            // Reset the color space for potential future reconfigurations
+            mColorSpace = null;
+            return ColorSpace.get(ColorSpace.Named.LINEAR_EXTENDED_SRGB);
+        }
+
+        // Cache the color space retrieval since it can be fairly expensive
+        if (mColorSpace == null) {
+            if (nativeIsSRGB(mNativePtr)) {
+                mColorSpace = ColorSpace.get(ColorSpace.Named.SRGB);
+            } else {
+                float[] xyz = new float[9];
+                float[] params = new float[7];
+
+                boolean hasColorSpace = nativeGetColorSpace(mNativePtr, xyz, params);
+                if (hasColorSpace) {
+                    ColorSpace.Rgb.TransferParameters parameters =
+                            new ColorSpace.Rgb.TransferParameters(
+                                    params[0], params[1], params[2],
+                                    params[3], params[4], params[5], params[6]);
+                    ColorSpace cs = ColorSpace.match(xyz, parameters);
+                    if (cs != null) {
+                        mColorSpace = cs;
+                    } else {
+                        mColorSpace = new ColorSpace.Rgb("Unknown", xyz, parameters);
+                    }
+                }
+            }
+        }
+
+        return mColorSpace;
+    }
+
+    /**
      * Fills the bitmap's pixels with the specified {@link Color}.
      *
      * @throws IllegalStateException if the bitmap is not mutable.
@@ -1816,4 +1861,6 @@
     private static native Bitmap nativeCopyPreserveInternalConfig(long nativeBitmap);
     private static native Bitmap nativeCreateHardwareBitmap(GraphicBuffer buffer);
     private static native GraphicBuffer nativeCreateGraphicBufferHandle(long nativeBitmap);
+    private static native boolean nativeGetColorSpace(long nativePtr, float[] xyz, float[] params);
+    private static native boolean nativeIsSRGB(long nativePtr);
 }
diff --git a/graphics/java/android/graphics/ColorSpace.java b/graphics/java/android/graphics/ColorSpace.java
index b1a433c..908ec50 100644
--- a/graphics/java/android/graphics/ColorSpace.java
+++ b/graphics/java/android/graphics/ColorSpace.java
@@ -20,8 +20,8 @@
 import android.annotation.ColorInt;
 import android.annotation.IntRange;
 import android.annotation.NonNull;
-import android.annotation.Size;
 import android.annotation.Nullable;
+import android.annotation.Size;
 import android.util.Pair;
 
 import java.util.ArrayList;
@@ -263,18 +263,18 @@
          *     <tr><td>Name</td><td colspan="4">sRGB IEC61966-2.1</td></tr>
          *     <tr><td>CIE standard illuminant</td><td colspan="4">D65</td></tr>
          *     <tr>
-         *         <td>Opto-electronic transfer function</td>
+         *         <td>Opto-electronic transfer function (OETF)</td>
          *         <td colspan="4">\(\begin{equation}
-         *             C_{sRGB} = \begin{cases} 12.92 \times C_{linear} & C_{linear} \le 0.0031308 \\
-         *             1.055 \times C_{linear}^{\frac{1}{2.4}} - 0.055 & C_{linear} \gt 0.0031308 \end{cases}
+         *             C_{sRGB} = \begin{cases} 12.92 \times C_{linear} & C_{linear} \lt 0.0031308 \\
+         *             1.055 \times C_{linear}^{\frac{1}{2.4}} - 0.055 & C_{linear} \ge 0.0031308 \end{cases}
          *             \end{equation}\)
          *         </td>
          *     </tr>
          *     <tr>
-         *         <td>Electro-optical transfer function</td>
+         *         <td>Electro-optical transfer function (EOTF)</td>
          *         <td colspan="4">\(\begin{equation}
-         *             C_{linear} = \begin{cases}\frac{C_{sRGB}}{12.92} & C_{sRGB} \le 0.04045 \\
-         *             \left( \frac{C_{sRGB} + 0.055}{1.055} \right) ^{2.4} & C_{sRGB} \gt 0.04045 \end{cases}
+         *             C_{linear} = \begin{cases}\frac{C_{sRGB}}{12.92} & C_{sRGB} \lt 0.04045 \\
+         *             \left( \frac{C_{sRGB} + 0.055}{1.055} \right) ^{2.4} & C_{sRGB} \ge 0.04045 \end{cases}
          *             \end{equation}\)
          *         </td>
          *     </tr>
@@ -298,11 +298,11 @@
          *     <tr><td>Name</td><td colspan="4">sRGB IEC61966-2.1 (Linear)</td></tr>
          *     <tr><td>CIE standard illuminant</td><td colspan="4">D65</td></tr>
          *     <tr>
-         *         <td>Opto-electronic transfer function</td>
+         *         <td>Opto-electronic transfer function (OETF)</td>
          *         <td colspan="4">\(C_{sRGB} = C_{linear}\)</td>
          *     </tr>
          *     <tr>
-         *         <td>Electro-optical transfer function</td>
+         *         <td>Electro-optical transfer function (EOTF)</td>
          *         <td colspan="4">\(C_{linear} = C_{sRGB}\)</td>
          *     </tr>
          *     <tr><td>Range</td><td colspan="4">\([0..1]\)</td></tr>
@@ -325,22 +325,22 @@
          *     <tr><td>Name</td><td colspan="4">scRGB-nl IEC 61966-2-2:2003</td></tr>
          *     <tr><td>CIE standard illuminant</td><td colspan="4">D65</td></tr>
          *     <tr>
-         *         <td>Opto-electronic transfer function</td>
+         *         <td>Opto-electronic transfer function (OETF)</td>
          *         <td colspan="4">\(\begin{equation}
          *             C_{scRGB} = \begin{cases} sign(C_{linear}) 12.92 \times \left| C_{linear} \right| &
-         *                      \left| C_{linear} \right| \le 0.0031308 \\
+         *                      \left| C_{linear} \right| \lt 0.0031308 \\
          *             sign(C_{linear}) 1.055 \times \left| C_{linear} \right| ^{\frac{1}{2.4}} - 0.055 &
-         *                      \left| C_{linear} \right| \gt 0.0031308 \end{cases}
+         *                      \left| C_{linear} \right| \ge 0.0031308 \end{cases}
          *             \end{equation}\)
          *         </td>
          *     </tr>
          *     <tr>
-         *         <td>Electro-optical transfer function</td>
+         *         <td>Electro-optical transfer function (EOTF)</td>
          *         <td colspan="4">\(\begin{equation}
          *             C_{linear} = \begin{cases}sign(C_{scRGB}) \frac{\left| C_{scRGB} \right|}{12.92} &
-         *                  \left| C_{scRGB} \right| \le 0.04045 \\
+         *                  \left| C_{scRGB} \right| \lt 0.04045 \\
          *             sign(C_{scRGB}) \left( \frac{\left| C_{scRGB} \right| + 0.055}{1.055} \right) ^{2.4} &
-         *                  \left| C_{scRGB} \right| \gt 0.04045 \end{cases}
+         *                  \left| C_{scRGB} \right| \ge 0.04045 \end{cases}
          *             \end{equation}\)
          *         </td>
          *     </tr>
@@ -364,11 +364,11 @@
          *     <tr><td>Name</td><td colspan="4">scRGB IEC 61966-2-2:2003</td></tr>
          *     <tr><td>CIE standard illuminant</td><td colspan="4">D65</td></tr>
          *     <tr>
-         *         <td>Opto-electronic transfer function</td>
+         *         <td>Opto-electronic transfer function (OETF)</td>
          *         <td colspan="4">\(C_{scRGB} = C_{linear}\)</td>
          *     </tr>
          *     <tr>
-         *         <td>Electro-optical transfer function</td>
+         *         <td>Electro-optical transfer function (EOTF)</td>
          *         <td colspan="4">\(C_{linear} = C_{scRGB}\)</td>
          *     </tr>
          *     <tr><td>Range</td><td colspan="4">\([-0.5..7.499[\)</td></tr>
@@ -391,7 +391,7 @@
          *     <tr><td>Name</td><td colspan="4">Rec. ITU-R BT.709-5</td></tr>
          *     <tr><td>CIE standard illuminant</td><td colspan="4">D65</td></tr>
          *     <tr>
-         *         <td>Opto-electronic transfer function</td>
+         *         <td>Opto-electronic transfer function (OETF)</td>
          *         <td colspan="4">\(\begin{equation}
          *             C_{BT709} = \begin{cases} 4.5 \times C_{linear} & C_{linear} \lt 0.018 \\
          *             1.099 \times C_{linear}^{\frac{1}{2.2}} - 0.099 & C_{linear} \ge 0.018 \end{cases}
@@ -399,7 +399,7 @@
          *         </td>
          *     </tr>
          *     <tr>
-         *         <td>Electro-optical transfer function</td>
+         *         <td>Electro-optical transfer function (EOTF)</td>
          *         <td colspan="4">\(\begin{equation}
          *             C_{linear} = \begin{cases}\frac{C_{BT709}}{4.5} & C_{BT709} \lt 0.081 \\
          *             \left( \frac{C_{BT709} + 0.099}{1.099} \right) ^{2.2} & C_{BT709} \ge 0.081 \end{cases}
@@ -426,7 +426,7 @@
          *     <tr><td>Name</td><td colspan="4">Rec. ITU-R BT.2020-1</td></tr>
          *     <tr><td>CIE standard illuminant</td><td colspan="4">D65</td></tr>
          *     <tr>
-         *         <td>Opto-electronic transfer function</td>
+         *         <td>Opto-electronic transfer function (OETF)</td>
          *         <td colspan="4">\(\begin{equation}
          *             C_{BT2020} = \begin{cases} 4.5 \times C_{linear} & C_{linear} \lt 0.0181 \\
          *             1.0993 \times C_{linear}^{\frac{1}{2.2}} - 0.0993 & C_{linear} \ge 0.0181 \end{cases}
@@ -434,7 +434,7 @@
          *         </td>
          *     </tr>
          *     <tr>
-         *         <td>Electro-optical transfer function</td>
+         *         <td>Electro-optical transfer function (EOTF)</td>
          *         <td colspan="4">\(\begin{equation}
          *             C_{linear} = \begin{cases}\frac{C_{BT2020}}{4.5} & C_{BT2020} \lt 0.08145 \\
          *             \left( \frac{C_{BT2020} + 0.0993}{1.0993} \right) ^{2.2} & C_{BT2020} \ge 0.08145 \end{cases}
@@ -461,11 +461,11 @@
          *     <tr><td>Name</td><td colspan="4">SMPTE RP 431-2-2007 DCI (P3)</td></tr>
          *     <tr><td>CIE standard illuminant</td><td colspan="4">N/A</td></tr>
          *     <tr>
-         *         <td>Opto-electronic transfer function</td>
+         *         <td>Opto-electronic transfer function (OETF)</td>
          *         <td colspan="4">\(C_{P3} = C_{linear}^{\frac{1}{2.6}}\)</td>
          *     </tr>
          *     <tr>
-         *         <td>Electro-optical transfer function</td>
+         *         <td>Electro-optical transfer function (EOTF)</td>
          *         <td colspan="4">\(C_{linear} = C_{P3}^{2.6}\)</td>
          *     </tr>
          *     <tr><td>Range</td><td colspan="4">\([0..1]\)</td></tr>
@@ -488,18 +488,18 @@
          *     <tr><td>Name</td><td colspan="4">Display P3</td></tr>
          *     <tr><td>CIE standard illuminant</td><td colspan="4">D65</td></tr>
          *     <tr>
-         *         <td>Opto-electronic transfer function</td>
+         *         <td>Opto-electronic transfer function (OETF)</td>
          *         <td colspan="4">\(\begin{equation}
-         *             C_{sRGB} = \begin{cases} 12.92 \times C_{linear} & C_{linear} \le 0.0031308 \\
-         *             1.055 \times C_{linear}^{\frac{1}{2.4}} - 0.055 & C_{linear} \gt 0.0031308 \end{cases}
+         *             C_{sRGB} = \begin{cases} 12.92 \times C_{linear} & C_{linear} \lt 0.0031308 \\
+         *             1.055 \times C_{linear}^{\frac{1}{2.4}} - 0.055 & C_{linear} \ge 0.0031308 \end{cases}
          *             \end{equation}\)
          *         </td>
          *     </tr>
          *     <tr>
-         *         <td>Electro-optical transfer function</td>
+         *         <td>Electro-optical transfer function (EOTF)</td>
          *         <td colspan="4">\(\begin{equation}
-         *             C_{linear} = \begin{cases}\frac{C_{sRGB}}{12.92} & C_{sRGB} \le 0.04045 \\
-         *             \left( \frac{C_{sRGB} + 0.055}{1.055} \right) ^{2.4} & C_{sRGB} \gt 0.04045 \end{cases}
+         *             C_{linear} = \begin{cases}\frac{C_{sRGB}}{12.92} & C_{sRGB} \lt 0.04045 \\
+         *             \left( \frac{C_{sRGB} + 0.055}{1.055} \right) ^{2.4} & C_{sRGB} \ge 0.04045 \end{cases}
          *             \end{equation}\)
          *         </td>
          *     </tr>
@@ -523,7 +523,7 @@
          *     <tr><td>Name</td><td colspan="4">NTSC (1953)</td></tr>
          *     <tr><td>CIE standard illuminant</td><td colspan="4">C</td></tr>
          *     <tr>
-         *         <td>Opto-electronic transfer function</td>
+         *         <td>Opto-electronic transfer function (OETF)</td>
          *         <td colspan="4">\(\begin{equation}
          *             C_{BT709} = \begin{cases} 4.5 \times C_{linear} & C_{linear} \lt 0.018 \\
          *             1.099 \times C_{linear}^{\frac{1}{2.2}} - 0.099 & C_{linear} \ge 0.018 \end{cases}
@@ -531,7 +531,7 @@
          *         </td>
          *     </tr>
          *     <tr>
-         *         <td>Electro-optical transfer function</td>
+         *         <td>Electro-optical transfer function (EOTF)</td>
          *         <td colspan="4">\(\begin{equation}
          *             C_{linear} = \begin{cases}\frac{C_{BT709}}{4.5} & C_{BT709} \lt 0.081 \\
          *             \left( \frac{C_{BT709} + 0.099}{1.099} \right) ^{2.2} & C_{BT709} \ge 0.081 \end{cases}
@@ -558,7 +558,7 @@
          *     <tr><td>Name</td><td colspan="4">SMPTE-C RGB</td></tr>
          *     <tr><td>CIE standard illuminant</td><td colspan="4">D65</td></tr>
          *     <tr>
-         *         <td>Opto-electronic transfer function</td>
+         *         <td>Opto-electronic transfer function (OETF)</td>
          *         <td colspan="4">\(\begin{equation}
          *             C_{BT709} = \begin{cases} 4.5 \times C_{linear} & C_{linear} \lt 0.018 \\
          *             1.099 \times C_{linear}^{\frac{1}{2.2}} - 0.099 & C_{linear} \ge 0.018 \end{cases}
@@ -566,7 +566,7 @@
          *         </td>
          *     </tr>
          *     <tr>
-         *         <td>Electro-optical transfer function</td>
+         *         <td>Electro-optical transfer function (EOTF)</td>
          *         <td colspan="4">\(\begin{equation}
          *             C_{linear} = \begin{cases}\frac{C_{BT709}}{4.5} & C_{BT709} \lt 0.081 \\
          *             \left( \frac{C_{BT709} + 0.099}{1.099} \right) ^{2.2} & C_{BT709} \ge 0.081 \end{cases}
@@ -593,11 +593,11 @@
          *     <tr><td>Name</td><td colspan="4">Adobe RGB (1998)</td></tr>
          *     <tr><td>CIE standard illuminant</td><td colspan="4">D65</td></tr>
          *     <tr>
-         *         <td>Opto-electronic transfer function</td>
+         *         <td>Opto-electronic transfer function (OETF)</td>
          *         <td colspan="4">\(C_{RGB} = C_{linear}^{\frac{1}{2.2}}\)</td>
          *     </tr>
          *     <tr>
-         *         <td>Electro-optical transfer function</td>
+         *         <td>Electro-optical transfer function (EOTF)</td>
          *         <td colspan="4">\(C_{linear} = C_{RGB}^{2.2}\)</td>
          *     </tr>
          *     <tr><td>Range</td><td colspan="4">\([0..1]\)</td></tr>
@@ -620,7 +620,7 @@
          *     <tr><td>Name</td><td colspan="4">ROMM RGB ISO 22028-2:2013</td></tr>
          *     <tr><td>CIE standard illuminant</td><td colspan="4">D50</td></tr>
          *     <tr>
-         *         <td>Opto-electronic transfer function</td>
+         *         <td>Opto-electronic transfer function (OETF)</td>
          *         <td colspan="4">\(\begin{equation}
          *             C_{ROMM} = \begin{cases} 16 \times C_{linear} & C_{linear} \lt 0.001953 \\
          *             C_{linear}^{\frac{1}{1.8}} & C_{linear} \ge 0.001953 \end{cases}
@@ -628,7 +628,7 @@
          *         </td>
          *     </tr>
          *     <tr>
-         *         <td>Electro-optical transfer function</td>
+         *         <td>Electro-optical transfer function (EOTF)</td>
          *         <td colspan="4">\(\begin{equation}
          *             C_{linear} = \begin{cases}\frac{C_{ROMM}}{16} & C_{ROMM} \lt 0.031248 \\
          *             C_{ROMM}^{1.8} & C_{ROMM} \ge 0.031248 \end{cases}
@@ -655,11 +655,11 @@
          *     <tr><td>Name</td><td colspan="4">SMPTE ST 2065-1:2012 ACES</td></tr>
          *     <tr><td>CIE standard illuminant</td><td colspan="4">D60</td></tr>
          *     <tr>
-         *         <td>Opto-electronic transfer function</td>
+         *         <td>Opto-electronic transfer function (OETF)</td>
          *         <td colspan="4">\(C_{ACES} = C_{linear}\)</td>
          *     </tr>
          *     <tr>
-         *         <td>Electro-optical transfer function</td>
+         *         <td>Electro-optical transfer function (EOTF)</td>
          *         <td colspan="4">\(C_{linear} = C_{ACES}\)</td>
          *     </tr>
          *     <tr><td>Range</td><td colspan="4">\([-65504.0, 65504.0]\)</td></tr>
@@ -682,11 +682,11 @@
          *     <tr><td>Name</td><td colspan="4">Academy S-2014-004 ACEScg</td></tr>
          *     <tr><td>CIE standard illuminant</td><td colspan="4">D60</td></tr>
          *     <tr>
-         *         <td>Opto-electronic transfer function</td>
+         *         <td>Opto-electronic transfer function (OETF)</td>
          *         <td colspan="4">\(C_{ACEScg} = C_{linear}\)</td>
          *     </tr>
          *     <tr>
-         *         <td>Electro-optical transfer function</td>
+         *         <td>Electro-optical transfer function (EOTF)</td>
          *         <td colspan="4">\(C_{linear} = C_{ACEScg}\)</td>
          *     </tr>
          *     <tr><td>Range</td><td colspan="4">\([-65504.0, 65504.0]\)</td></tr>
@@ -1379,6 +1379,37 @@
     }
 
     /**
+     * <p>Returns a {@link Named} instance of {@link ColorSpace} that matches
+     * the specified RGB to CIE XYZ transform and transfer functions. If no
+     * instance can be found, this method returns null.</p>
+     *
+     * <p>The color transform matrix is assumed to target the CIE XYZ space
+     * a {@link #ILLUMINANT_D50 D50} standard illuminant.</p>
+     *
+     * @param toXYZD50 3x3 column-major transform matrix from RGB to the profile
+     *                 connection space CIE XYZ as an array of 9 floats, cannot be null
+     * @param function Parameters for the transfer functions
+     * @return A non-null {@link ColorSpace} if a match is found, null otherwise
+     */
+    @Nullable
+    public static ColorSpace match(
+            @NonNull @Size(9) float[] toXYZD50,
+            @NonNull Rgb.TransferParameters function) {
+
+        for (ColorSpace colorSpace : sNamedColorSpaces) {
+            if (colorSpace.getModel() == Model.RGB) {
+                ColorSpace.Rgb rgb = (ColorSpace.Rgb) adapt(colorSpace, ILLUMINANT_D50_XYZ);
+                if (compare(toXYZD50, rgb.mTransform) &&
+                        compare(function, rgb.mTransferParameters)) {
+                    return colorSpace;
+                }
+            }
+        }
+
+        return null;
+    }
+
+    /**
      * <p>Creates a new {@link Renderer} that can be used to visualize and
      * debug color spaces. See the documentation of {@link Renderer} for
      * more information.</p>
@@ -1397,17 +1428,14 @@
                 "sRGB IEC61966-2.1",
                 SRGB_PRIMARIES,
                 ILLUMINANT_D65,
-                x -> rcpResponse(x, 2.4, 1 / 1.055, 0.055 / 1.055, 1 / 12.92, 0.04045),
-                x -> response(x, 2.4, 1 / 1.055, 0.055 / 1.055, 1 / 12.92, 0.04045),
-                0.0f, 1.0f,
+                new Rgb.TransferParameters(1 / 1.055, 0.055 / 1.055, 1 / 12.92, 0.04045, 2.4),
                 Named.SRGB.ordinal()
         );
         sNamedColorSpaces[Named.LINEAR_SRGB.ordinal()] = new ColorSpace.Rgb(
                 "sRGB IEC61966-2.1 (Linear)",
                 SRGB_PRIMARIES,
                 ILLUMINANT_D65,
-                DoubleUnaryOperator.identity(),
-                DoubleUnaryOperator.identity(),
+                1.0,
                 0.0f, 1.0f,
                 Named.LINEAR_SRGB.ordinal()
         );
@@ -1415,17 +1443,16 @@
                 "scRGB-nl IEC 61966-2-2:2003",
                 SRGB_PRIMARIES,
                 ILLUMINANT_D65,
-                x -> absRcpResponse(x, 2.4, 1 / 1.055, 0.055 / 1.055, 1 / 12.92, 0.04045),
-                x -> absResponse(x, 2.4, 1 / 1.055, 0.055 / 1.055, 1 / 12.92, 0.04045),
+                x -> absRcpResponse(x, 1 / 1.055, 0.055 / 1.055, 1 / 12.92, 0.04045, 2.4),
+                x -> absResponse(x, 1 / 1.055, 0.055 / 1.055, 1 / 12.92, 0.04045, 2.4),
                 -0.799f, 2.399f,
                 Named.EXTENDED_SRGB.ordinal()
         );
         sNamedColorSpaces[Named.LINEAR_EXTENDED_SRGB.ordinal()] = new ColorSpace.Rgb(
-                "scRGB- IEC 61966-2-2:2003",
+                "scRGB IEC 61966-2-2:2003",
                 SRGB_PRIMARIES,
                 ILLUMINANT_D65,
-                DoubleUnaryOperator.identity(),
-                DoubleUnaryOperator.identity(),
+                1.0,
                 -0.5f, 7.499f,
                 Named.LINEAR_EXTENDED_SRGB.ordinal()
         );
@@ -1433,26 +1460,21 @@
                 "Rec. ITU-R BT.709-5",
                 new float[] { 0.640f, 0.330f, 0.300f, 0.600f, 0.150f, 0.060f },
                 ILLUMINANT_D65,
-                x -> rcpResponse(x, 1 / 0.45, 1 / 1.099, 0.099 / 1.099, 1 / 4.5, 0.081),
-                x -> response(x, 1 / 0.45, 1 / 1.099, 0.099 / 1.099, 1 / 4.5, 0.081),
-                0.0f, 1.0f,
+                new Rgb.TransferParameters(1 / 1.099, 0.099 / 1.099, 1 / 4.5, 0.081, 1 / 0.45),
                 Named.BT709.ordinal()
         );
         sNamedColorSpaces[Named.BT2020.ordinal()] = new ColorSpace.Rgb(
                 "Rec. ITU-R BT.2020-1",
                 new float[] { 0.708f, 0.292f, 0.170f, 0.797f, 0.131f, 0.046f },
                 ILLUMINANT_D65,
-                x -> rcpResponse(x, 1 / 0.45, 1 / 1.0993, 0.0993 / 1.0993, 1 / 4.5, 0.08145),
-                x -> response(x, 1 / 0.45, 1 / 1.0993, 0.099 / 1.0993, 1 / 4.5, 0.08145),
-                0.0f, 1.0f,
+                new Rgb.TransferParameters(1 / 1.0993, 0.0993 / 1.0993, 1 / 4.5, 0.08145, 1 / 0.45),
                 Named.BT2020.ordinal()
         );
         sNamedColorSpaces[Named.DCI_P3.ordinal()] = new ColorSpace.Rgb(
                 "SMPTE RP 431-2-2007 DCI (P3)",
                 new float[] { 0.680f, 0.320f, 0.265f, 0.690f, 0.150f, 0.060f },
                 new float[] { 0.314f, 0.351f },
-                x -> Math.pow(x < 0.0f ? 0.0f : x, 1 / 2.6),
-                x -> Math.pow(x < 0.0f ? 0.0f : x, 2.6),
+                2.6,
                 0.0f, 1.0f,
                 Named.DCI_P3.ordinal()
         );
@@ -1460,35 +1482,28 @@
                 "Display P3",
                 new float[] { 0.680f, 0.320f, 0.265f, 0.690f, 0.150f, 0.060f },
                 ILLUMINANT_D65,
-                x -> rcpResponse(x, 2.4, 1 / 1.055, 0.055 / 1.055, 1 / 12.92, 0.04045),
-                x -> response(x, 2.4, 1 / 1.055, 0.055 / 1.055, 1 / 12.92, 0.04045),
-                0.0f, 1.0f,
+                new Rgb.TransferParameters(1 / 1.055, 0.055 / 1.055, 1 / 12.92, 0.04045, 2.4),
                 Named.DISPLAY_P3.ordinal()
         );
         sNamedColorSpaces[Named.NTSC_1953.ordinal()] = new ColorSpace.Rgb(
                 "NTSC (1953)",
                 NTSC_1953_PRIMARIES,
                 ILLUMINANT_C,
-                x -> rcpResponse(x, 1 / 0.45, 1 / 1.099, 0.099 / 1.099, 1 / 4.5, 0.081),
-                x -> response(x, 1 / 0.45, 1 / 1.099, 0.099 / 1.099, 1 / 4.5, 0.081),
-                0.0f, 1.0f,
+                new Rgb.TransferParameters(1 / 1.099, 0.099 / 1.099, 1 / 4.5, 0.081, 1 / 0.45),
                 Named.NTSC_1953.ordinal()
         );
         sNamedColorSpaces[Named.SMPTE_C.ordinal()] = new ColorSpace.Rgb(
                 "SMPTE-C RGB",
                 new float[] { 0.630f, 0.340f, 0.310f, 0.595f, 0.155f, 0.070f },
                 ILLUMINANT_D65,
-                x -> rcpResponse(x, 1 / 0.45, 1 / 1.099, 0.099 / 1.099, 1 / 4.5, 0.081),
-                x -> response(x, 1 / 0.45, 1 / 1.099, 0.099 / 1.099, 1 / 4.5, 0.081),
-                0.0f, 1.0f,
+                new Rgb.TransferParameters(1 / 1.099, 0.099 / 1.099, 1 / 4.5, 0.081, 1 / 0.45),
                 Named.SMPTE_C.ordinal()
         );
         sNamedColorSpaces[Named.ADOBE_RGB.ordinal()] = new ColorSpace.Rgb(
                 "Adobe RGB (1998)",
                 new float[] { 0.64f, 0.33f, 0.21f, 0.71f, 0.15f, 0.06f },
                 ILLUMINANT_D65,
-                x -> Math.pow(x < 0.0f ? 0.0f : x, 1 / 2.2),
-                x -> Math.pow(x < 0.0f ? 0.0f : x, 2.2),
+                2.2,
                 0.0f, 1.0f,
                 Named.ADOBE_RGB.ordinal()
         );
@@ -1496,17 +1511,14 @@
                 "ROMM RGB ISO 22028-2:2013",
                 new float[] { 0.7347f, 0.2653f, 0.1596f, 0.8404f, 0.0366f, 0.0001f },
                 ILLUMINANT_D50,
-                x -> rcpResponse(x, 1.8, 1.0, 0.0, 1 / 16.0, 0.031248),
-                x -> response(x, 1.8, 1.0, 0.0, 1 / 16.0, 0.031248),
-                0.0f, 1.0f,
+                new Rgb.TransferParameters(1.0, 0.0, 1 / 16.0, 0.031248, 1.8),
                 Named.PRO_PHOTO_RGB.ordinal()
         );
         sNamedColorSpaces[Named.ACES.ordinal()] = new ColorSpace.Rgb(
                 "SMPTE ST 2065-1:2012 ACES",
                 new float[] { 0.73470f, 0.26530f, 0.0f, 1.0f, 0.00010f, -0.0770f },
                 ILLUMINANT_D60,
-                DoubleUnaryOperator.identity(),
-                DoubleUnaryOperator.identity(),
+                1.0,
                 -65504.0f, 65504.0f,
                 Named.ACES.ordinal()
         );
@@ -1514,8 +1526,7 @@
                 "Academy S-2014-004 ACEScg",
                 new float[] { 0.713f, 0.293f, 0.165f, 0.830f, 0.128f, 0.044f },
                 ILLUMINANT_D60,
-                DoubleUnaryOperator.identity(),
-                DoubleUnaryOperator.identity(),
+                1.0,
                 -65504.0f, 65504.0f,
                 Named.ACESCG.ordinal()
         );
@@ -1530,27 +1541,61 @@
     }
 
     // Reciprocal piecewise gamma response
-    private static double rcpResponse(double x, double g,double a, double b, double c, double d) {
+    private static double rcpResponse(double x, double a, double b, double c, double d, double g) {
         return x >= d * c ? (Math.pow(x, 1.0 / g) - b) / a : x / c;
     }
 
     // Piecewise gamma response
-    private static double response(double x, double g, double a, double b, double c, double d) {
+    private static double response(double x, double a, double b, double c, double d, double g) {
         return x >= d ? Math.pow(a * x + b, g) : c * x;
     }
 
+    // Reciprocal piecewise gamma response
+    private static double rcpResponse(double x, double a, double b, double c, double d,
+            double e, double f, double g) {
+        return x >= d * c ? (Math.pow(x - e, 1.0 / g) - b) / a : (x - f) / c;
+    }
+
+    // Piecewise gamma response
+    private static double response(double x, double a, double b, double c, double d,
+            double e, double f, double g) {
+        return x >= d ? Math.pow(a * x + b, g) + e : c * x + f;
+    }
+
     // Reciprocal piecewise gamma response, encoded as sign(x).f(abs(x)) for color
     // spaces that allow negative values
     @SuppressWarnings("SameParameterValue")
-    private static double absRcpResponse(double x, double g, double a, double b, double c, double d) {
-        return Math.copySign(rcpResponse(x < 0.0 ? -x : x, g, a, b, c, d), x);
+    private static double absRcpResponse(double x, double a, double b, double c, double d, double g) {
+        return Math.copySign(rcpResponse(x < 0.0 ? -x : x, a, b, c, d, g), x);
     }
 
     // Piecewise gamma response, encoded as sign(x).f(abs(x)) for color spaces that
     // allow negative values
     @SuppressWarnings("SameParameterValue")
-    private static double absResponse(double x, double g, double a, double b, double c, double d) {
-        return Math.copySign(response(x < 0.0 ? -x : x, g, a, b, c, d), x);
+    private static double absResponse(double x, double a, double b, double c, double d, double g) {
+        return Math.copySign(response(x < 0.0 ? -x : x, a, b, c, d, g), x);
+    }
+
+    /**
+     * Compares two sets of parametric transfer functions parameters with a precision of 1e-3.
+     *
+     * @param a The first set of parameters to compare
+     * @param b The second set of parameters to compare
+     * @return True if the two sets are equal, false otherwise
+     */
+    private static boolean compare(
+            @Nullable Rgb.TransferParameters a,
+            @Nullable Rgb.TransferParameters b) {
+        //noinspection SimplifiableIfStatement
+        if (a == null && b == null) return true;
+        return a != null && b != null &&
+                Math.abs(a.a - b.a) < 1e-3 &&
+                Math.abs(a.b - b.b) < 1e-3 &&
+                Math.abs(a.c - b.c) < 1e-3 &&
+                Math.abs(a.d - b.d) < 1e-3 &&
+                Math.abs(a.e - b.e) < 1e-3 &&
+                Math.abs(a.f - b.f) < 1e-3 &&
+                Math.abs(a.g - b.g) < 1e-3;
     }
 
     /**
@@ -1710,7 +1755,7 @@
      * <p>Computes the chromatic adaptation transform from the specified
      * source white point to the specified destination white point.</p>
      *
-     * <p>The transform is computed using the von Kris method, described
+     * <p>The transform is computed using the von Kries method, described
      * in more details in the documentation of {@link Adaptation}. The
      * {@link Adaptation} enum provides different matrices that can be
      * used to perform the adaptation.</p>
@@ -1925,6 +1970,11 @@
      *
      * $$RGB_{out} = OETF(f(EOTF(RGB_{in})))$$
      *
+     * <p>If the transfer functions of the color space can be expressed as an
+     * ICC parametric curve as defined in ICC.1:2004-10, the numeric parameters
+     * can be retrieved by calling {@link #getTransferParameters()}. This can
+     * be useful to match color spaces for instance.</p>
+     *
      * <p class="note">Some RGB color spaces, such as {@link Named#ACES} and
      * {@link Named#LINEAR_EXTENDED_SRGB scRGB}, are said to be linear because
      * their transfer functions are the identity function: \(f(x) = x\).
@@ -1967,14 +2017,175 @@
      */
     @AnyThread
     public static class Rgb extends ColorSpace {
+        /**
+         * {@usesMathJax}
+         *
+         * <p>Defines the parameters for the ICC parametric curve type 4, as
+         * defined in ICC.1:2004-10, section 10.15.</p>
+         *
+         * <p>The EOTF is of the form:</p>
+         *
+         * \(\begin{equation}
+         * Y = \begin{cases}c X + f & X \lt d \\
+         * \left( a X + b \right) ^{g} + e & X \ge d \end{cases}
+         * \end{equation}\)
+         *
+         * <p>The corresponding OETF is simply the inverse function.</p>
+         *
+         * <p>The parameters defined by this class form a valid transfer
+         * function only if all the following conditions are met:</p>
+         * <ul>
+         *     <li>No parameter is a {@link Double#isNaN(double) Not-a-Number}</li>
+         *     <li>\(d\) is in the range \([0..1]\)</li>
+         *     <li>The function is not constant</li>
+         *     <li>The function is positive and increasing</li>
+         * </ul>
+         */
+        public static class TransferParameters {
+            /** Variable \(a\) in the equation of the EOTF described above. */
+            public final double a;
+            /** Variable \(b\) in the equation of the EOTF described above. */
+            public final double b;
+            /** Variable \(c\) in the equation of the EOTF described above. */
+            public final double c;
+            /** Variable \(d\) in the equation of the EOTF described above. */
+            public final double d;
+            /** Variable \(e\) in the equation of the EOTF described above. */
+            public final double e;
+            /** Variable \(f\) in the equation of the EOTF described above. */
+            public final double f;
+            /** Variable \(g\) in the equation of the EOTF described above. */
+            public final double g;
+
+            /**
+             * <p>Defines the parameters for the ICC parametric curve type 3, as
+             * defined in ICC.1:2004-10, section 10.15.</p>
+             *
+             * <p>The EOTF is of the form:</p>
+             *
+             * \(\begin{equation}
+             * Y = \begin{cases}c X & X \lt d \\
+             * \left( a X + b \right) ^{g} & X \ge d \end{cases}
+             * \end{equation}\)
+             *
+             * <p>This constructor is equivalent to setting  \(e\) and \(f\) to 0.</p>
+             *
+             * @param a The value of \(a\) in the equation of the EOTF described above
+             * @param b The value of \(b\) in the equation of the EOTF described above
+             * @param c The value of \(c\) in the equation of the EOTF described above
+             * @param d The value of \(d\) in the equation of the EOTF described above
+             * @param g The value of \(g\) in the equation of the EOTF described above
+             *
+             * @throws IllegalArgumentException If the parameters form an invalid transfer function
+             */
+            public TransferParameters(double a, double b, double c, double d, double g) {
+                this(a, b, c, d, 0.0, 0.0, g);
+            }
+
+            /**
+             * <p>Defines the parameters for the ICC parametric curve type 4, as
+             * defined in ICC.1:2004-10, section 10.15.</p>
+             *
+             * @param a The value of \(a\) in the equation of the EOTF described above
+             * @param b The value of \(b\) in the equation of the EOTF described above
+             * @param c The value of \(c\) in the equation of the EOTF described above
+             * @param d The value of \(d\) in the equation of the EOTF described above
+             * @param e The value of \(e\) in the equation of the EOTF described above
+             * @param f The value of \(f\) in the equation of the EOTF described above
+             * @param g The value of \(g\) in the equation of the EOTF described above
+             *
+             * @throws IllegalArgumentException If the parameters form an invalid transfer function
+             */
+            public TransferParameters(double a, double b, double c, double d, double e,
+                    double f, double g) {
+
+                if (Double.isNaN(a) || Double.isNaN(b) || Double.isNaN(c) ||
+                        Double.isNaN(d) || Double.isNaN(e) || Double.isNaN(f) ||
+                        Double.isNaN(g)) {
+                    throw new IllegalArgumentException("Parameters cannot be NaN");
+                }
+
+                if (!(d >= 0.0 && d <= 1.0 + Math.ulp(1.0))) {
+                    throw new IllegalArgumentException("Parameter d must be in the range [0..1]");
+                }
+
+                if (d == 0.0 && (a == 0.0 || g == 0.0)) {
+                    throw new IllegalArgumentException(
+                            "Parameter a or g is zero, the transfer function is constant");
+                }
+
+                if (d >= 1.0 && c == 0.0) {
+                    throw new IllegalArgumentException(
+                            "Parameter c is zero, the transfer function is constant");
+                }
+
+                if ((a == 0.0 || g == 0.0) && c == 0.0) {
+                    throw new IllegalArgumentException("Parameter a or g is zero," +
+                            " and c is zero, the transfer function is constant");
+                }
+
+                if (c < 0.0) {
+                    throw new IllegalArgumentException("The transfer function must be increasing");
+                }
+
+                if (a < 0.0 || g < 0.0) {
+                    throw new IllegalArgumentException("The transfer function must be " +
+                            "positive or increasing");
+                }
+
+                this.a = a;
+                this.b = b;
+                this.c = c;
+                this.d = d;
+                this.e = e;
+                this.f = f;
+                this.g = g;
+            }
+
+            @SuppressWarnings("SimplifiableIfStatement")
+            @Override
+            public boolean equals(Object o) {
+                if (this == o) return true;
+                if (o == null || getClass() != o.getClass()) return false;
+
+                TransferParameters that = (TransferParameters) o;
+
+                if (Double.compare(that.a, a) != 0) return false;
+                if (Double.compare(that.b, b) != 0) return false;
+                if (Double.compare(that.c, c) != 0) return false;
+                if (Double.compare(that.d, d) != 0) return false;
+                if (Double.compare(that.e, e) != 0) return false;
+                if (Double.compare(that.f, f) != 0) return false;
+                return Double.compare(that.g, g) == 0;
+            }
+
+            @Override
+            public int hashCode() {
+                int result;
+                long temp;
+                temp = Double.doubleToLongBits(a);
+                result = (int) (temp ^ (temp >>> 32));
+                temp = Double.doubleToLongBits(b);
+                result = 31 * result + (int) (temp ^ (temp >>> 32));
+                temp = Double.doubleToLongBits(c);
+                result = 31 * result + (int) (temp ^ (temp >>> 32));
+                temp = Double.doubleToLongBits(d);
+                result = 31 * result + (int) (temp ^ (temp >>> 32));
+                temp = Double.doubleToLongBits(e);
+                result = 31 * result + (int) (temp ^ (temp >>> 32));
+                temp = Double.doubleToLongBits(f);
+                result = 31 * result + (int) (temp ^ (temp >>> 32));
+                temp = Double.doubleToLongBits(g);
+                result = 31 * result + (int) (temp ^ (temp >>> 32));
+                return result;
+            }
+        }
+
         @NonNull private final float[] mWhitePoint;
         @NonNull private final float[] mPrimaries;
         @NonNull private final float[] mTransform;
         @NonNull private final float[] mInverseTransform;
 
-        @NonNull private final boolean mIsWideGamut;
-        @NonNull private final boolean mIsSrgb;
-
         @NonNull private final DoubleUnaryOperator mOetf;
         @NonNull private final DoubleUnaryOperator mEotf;
         @NonNull private final DoubleUnaryOperator mClampedOetf;
@@ -1983,6 +2194,11 @@
         private final float mMin;
         private final float mMax;
 
+        private final boolean mIsWideGamut;
+        private final boolean mIsSrgb;
+
+        @Nullable private TransferParameters mTransferParameters;
+
         /**
          * <p>Creates a new RGB color space using a 3x3 column-major transform matrix.
          * The transform matrix must convert from the RGB space to the profile connection
@@ -2010,7 +2226,7 @@
                 @NonNull @Size(9) float[] toXYZ,
                 @NonNull DoubleUnaryOperator oetf,
                 @NonNull DoubleUnaryOperator eotf) {
-            this(name, computePrimaries(toXYZ, eotf), computeWhitePoint(toXYZ, eotf),
+            this(name, computePrimaries(toXYZ), computeWhitePoint(toXYZ),
                     oetf, eotf, 0.0f, 1.0f, MIN_ID);
         }
 
@@ -2065,6 +2281,251 @@
         }
 
         /**
+         * <p>Creates a new RGB color space using a 3x3 column-major transform matrix.
+         * The transform matrix must convert from the RGB space to the profile connection
+         * space CIE XYZ.</p>
+         *
+         * <p class="note">The range of the color space is imposed to be \([0..1]\).</p>
+         *
+         * @param name Name of the color space, cannot be null, its length must be >= 1
+         * @param toXYZ 3x3 column-major transform matrix from RGB to the profile
+         *              connection space CIE XYZ as an array of 9 floats, cannot be null
+         * @param function Parameters for the transfer functions
+         *
+         * @throws IllegalArgumentException If any of the following conditions is met:
+         * <ul>
+         *     <li>The name is null or has a length of 0.</li>
+         *     <li>Gamma is negative.</li>
+         * </ul>
+         *
+         * @see #get(Named)
+         */
+        public Rgb(
+                @NonNull @Size(min = 1) String name,
+                @NonNull @Size(9) float[] toXYZ,
+                @NonNull TransferParameters function) {
+            this(name, computePrimaries(toXYZ), computeWhitePoint(toXYZ), function, MIN_ID);
+        }
+
+        /**
+         * <p>Creates a new RGB color space using a specified set of primaries
+         * and a specified white point.</p>
+         *
+         * <p>The primaries and white point can be specified in the CIE xyY space
+         * or in CIE XYZ. The length of the arrays depends on the chosen space:</p>
+         *
+         * <table summary="Parameters length">
+         *     <tr><th>Space</th><th>Primaries length</th><th>White point length</th></tr>
+         *     <tr><td>xyY</td><td>6</td><td>2</td></tr>
+         *     <tr><td>XYZ</td><td>9</td><td>3</td></tr>
+         * </table>
+         *
+         * <p>When the primaries and/or white point are specified in xyY, the Y component
+         * does not need to be specified and is assumed to be 1.0. Only the xy components
+         * are required.</p>
+         *
+         * @param name Name of the color space, cannot be null, its length must be >= 1
+         * @param primaries RGB primaries as an array of 6 (xy) or 9 (XYZ) floats
+         * @param whitePoint Reference white as an array of 2 (xy) or 3 (XYZ) floats
+         * @param function Parameters for the transfer functions
+         *
+         * @throws IllegalArgumentException If any of the following conditions is met:
+         * <ul>
+         *     <li>The name is null or has a length of 0.</li>
+         *     <li>The primaries array is null or has a length that is neither 6 or 9.</li>
+         *     <li>The white point array is null or has a length that is neither 2 or 3.</li>
+         *     <li>The transfer parameters are invalid.</li>
+         * </ul>
+         *
+         * @see #get(Named)
+         */
+        public Rgb(
+                @NonNull @Size(min = 1) String name,
+                @NonNull @Size(min = 6, max = 9) float[] primaries,
+                @NonNull @Size(min = 2, max = 3) float[] whitePoint,
+                @NonNull TransferParameters function) {
+            this(name, primaries, whitePoint, function, MIN_ID);
+        }
+
+        /**
+         * <p>Creates a new RGB color space using a specified set of primaries
+         * and a specified white point.</p>
+         *
+         * <p>The primaries and white point can be specified in the CIE xyY space
+         * or in CIE XYZ. The length of the arrays depends on the chosen space:</p>
+         *
+         * <table summary="Parameters length">
+         *     <tr><th>Space</th><th>Primaries length</th><th>White point length</th></tr>
+         *     <tr><td>xyY</td><td>6</td><td>2</td></tr>
+         *     <tr><td>XYZ</td><td>9</td><td>3</td></tr>
+         * </table>
+         *
+         * <p>When the primaries and/or white point are specified in xyY, the Y component
+         * does not need to be specified and is assumed to be 1.0. Only the xy components
+         * are required.</p>
+         *
+         * @param name Name of the color space, cannot be null, its length must be >= 1
+         * @param primaries RGB primaries as an array of 6 (xy) or 9 (XYZ) floats
+         * @param whitePoint Reference white as an array of 2 (xy) or 3 (XYZ) floats
+         * @param function Parameters for the transfer functions
+         * @param id ID of this color space as an integer between {@link #MIN_ID} and {@link #MAX_ID}
+         *
+         * @throws IllegalArgumentException If any of the following conditions is met:
+         * <ul>
+         *     <li>The name is null or has a length of 0.</li>
+         *     <li>The primaries array is null or has a length that is neither 6 or 9.</li>
+         *     <li>The white point array is null or has a length that is neither 2 or 3.</li>
+         *     <li>The ID is not between {@link #MIN_ID} and {@link #MAX_ID}.</li>
+         *     <li>The transfer parameters are invalid.</li>
+         * </ul>
+         *
+         * @see #get(Named)
+         */
+        private Rgb(
+                @NonNull @Size(min = 1) String name,
+                @NonNull @Size(min = 6, max = 9) float[] primaries,
+                @NonNull @Size(min = 2, max = 3) float[] whitePoint,
+                @NonNull TransferParameters function,
+                @IntRange(from = MIN_ID, to = MAX_ID) int id) {
+            this(name, primaries, whitePoint,
+                    function.e == 0.0 && function.f == 0.0 ?
+                            x -> rcpResponse(x, function.a, function.b,
+                                    function.c, function.d, function.g) :
+                            x -> rcpResponse(x, function.a, function.b, function.c,
+                                    function.d, function.e, function.f, function.g),
+                    function.e == 0.0 && function.f == 0.0 ?
+                            x -> response(x, function.a, function.b,
+                                    function.c, function.d, function.g) :
+                            x -> response(x, function.a, function.b, function.c,
+                                    function.d, function.e, function.f, function.g),
+                    0.0f, 1.0f, id);
+            mTransferParameters = function;
+        }
+
+        /**
+         * <p>Creates a new RGB color space using a 3x3 column-major transform matrix.
+         * The transform matrix must convert from the RGB space to the profile connection
+         * space CIE XYZ.</p>
+         *
+         * <p class="note">The range of the color space is imposed to be \([0..1]\).</p>
+         *
+         * @param name Name of the color space, cannot be null, its length must be >= 1
+         * @param toXYZ 3x3 column-major transform matrix from RGB to the profile
+         *              connection space CIE XYZ as an array of 9 floats, cannot be null
+         * @param gamma Gamma to use as the transfer function
+         *
+         * @throws IllegalArgumentException If any of the following conditions is met:
+         * <ul>
+         *     <li>The name is null or has a length of 0.</li>
+         *     <li>Gamma is negative.</li>
+         * </ul>
+         *
+         * @see #get(Named)
+         */
+        public Rgb(
+                @NonNull @Size(min = 1) String name,
+                @NonNull @Size(9) float[] toXYZ,
+                double gamma) {
+            this(name, computePrimaries(toXYZ), computeWhitePoint(toXYZ), gamma, 0.0f, 1.0f, MIN_ID);
+        }
+
+        /**
+         * <p>Creates a new RGB color space using a specified set of primaries
+         * and a specified white point.</p>
+         *
+         * <p>The primaries and white point can be specified in the CIE xyY space
+         * or in CIE XYZ. The length of the arrays depends on the chosen space:</p>
+         *
+         * <table summary="Parameters length">
+         *     <tr><th>Space</th><th>Primaries length</th><th>White point length</th></tr>
+         *     <tr><td>xyY</td><td>6</td><td>2</td></tr>
+         *     <tr><td>XYZ</td><td>9</td><td>3</td></tr>
+         * </table>
+         *
+         * <p>When the primaries and/or white point are specified in xyY, the Y component
+         * does not need to be specified and is assumed to be 1.0. Only the xy components
+         * are required.</p>
+         *
+         * @param name Name of the color space, cannot be null, its length must be >= 1
+         * @param primaries RGB primaries as an array of 6 (xy) or 9 (XYZ) floats
+         * @param whitePoint Reference white as an array of 2 (xy) or 3 (XYZ) floats
+         * @param gamma Gamma to use as the transfer function
+         *
+         * @throws IllegalArgumentException If any of the following conditions is met:
+         * <ul>
+         *     <li>The name is null or has a length of 0.</li>
+         *     <li>The primaries array is null or has a length that is neither 6 or 9.</li>
+         *     <li>The white point array is null or has a length that is neither 2 or 3.</li>
+         *     <li>Gamma is negative.</li>
+         * </ul>
+         *
+         * @see #get(Named)
+         */
+        public Rgb(
+                @NonNull @Size(min = 1) String name,
+                @NonNull @Size(min = 6, max = 9) float[] primaries,
+                @NonNull @Size(min = 2, max = 3) float[] whitePoint,
+                double gamma) {
+            this(name, primaries, whitePoint, gamma, 0.0f, 1.0f, MIN_ID);
+        }
+
+        /**
+         * <p>Creates a new RGB color space using a specified set of primaries
+         * and a specified white point.</p>
+         *
+         * <p>The primaries and white point can be specified in the CIE xyY space
+         * or in CIE XYZ. The length of the arrays depends on the chosen space:</p>
+         *
+         * <table summary="Parameters length">
+         *     <tr><th>Space</th><th>Primaries length</th><th>White point length</th></tr>
+         *     <tr><td>xyY</td><td>6</td><td>2</td></tr>
+         *     <tr><td>XYZ</td><td>9</td><td>3</td></tr>
+         * </table>
+         *
+         * <p>When the primaries and/or white point are specified in xyY, the Y component
+         * does not need to be specified and is assumed to be 1.0. Only the xy components
+         * are required.</p>
+         *
+         * @param name Name of the color space, cannot be null, its length must be >= 1
+         * @param primaries RGB primaries as an array of 6 (xy) or 9 (XYZ) floats
+         * @param whitePoint Reference white as an array of 2 (xy) or 3 (XYZ) floats
+         * @param gamma Gamma to use as the transfer function
+         * @param min The minimum valid value in this color space's RGB range
+         * @param max The maximum valid value in this color space's RGB range
+         * @param id ID of this color space as an integer between {@link #MIN_ID} and {@link #MAX_ID}
+         *
+         * @throws IllegalArgumentException If any of the following conditions is met:
+         * <ul>
+         *     <li>The name is null or has a length of 0.</li>
+         *     <li>The primaries array is null or has a length that is neither 6 or 9.</li>
+         *     <li>The white point array is null or has a length that is neither 2 or 3.</li>
+         *     <li>The minimum valid value is >= the maximum valid value.</li>
+         *     <li>The ID is not between {@link #MIN_ID} and {@link #MAX_ID}.</li>
+         *     <li>Gamma is negative.</li>
+         * </ul>
+         *
+         * @see #get(Named)
+         */
+        private Rgb(
+                @NonNull @Size(min = 1) String name,
+                @NonNull @Size(min = 6, max = 9) float[] primaries,
+                @NonNull @Size(min = 2, max = 3) float[] whitePoint,
+                double gamma,
+                float min,
+                float max,
+                @IntRange(from = MIN_ID, to = MAX_ID) int id) {
+            this(name, primaries, whitePoint,
+                    gamma == 1.0 ? DoubleUnaryOperator.identity() :
+                            x -> Math.pow(x < 0.0 ? 0.0 : x, 1 / gamma),
+                    gamma == 1.0 ? DoubleUnaryOperator.identity() :
+                            x -> Math.pow(x < 0.0 ? 0.0 : x, gamma),
+                    min, max, id);
+            mTransferParameters = gamma == 1.0 ?
+                    new TransferParameters(0.0, 0.0, 1.0, 1.0 + Math.ulp(1.0), gamma) :
+                    new TransferParameters(1.0, 0.0, 0.0, 0.0, gamma);
+        }
+
+        /**
          * <p>Creates a new RGB color space using a specified set of primaries
          * and a specified white point.</p>
          *
@@ -2183,6 +2644,8 @@
 
             mIsWideGamut = colorSpace.mIsWideGamut;
             mIsSrgb = colorSpace.mIsSrgb;
+
+            mTransferParameters = colorSpace.mTransferParameters;
         }
 
         /**
@@ -2360,6 +2823,7 @@
          * @return A transfer function that converts from linear space to "gamma space"
          *
          * @see #getEotf()
+         * @see #getTransferParameters()
          */
         @NonNull
         public DoubleUnaryOperator getOetf() {
@@ -2383,12 +2847,31 @@
          * @return A transfer function that converts from "gamma space" to linear space
          *
          * @see #getOetf()
+         * @see #getTransferParameters()
          */
         @NonNull
         public DoubleUnaryOperator getEotf() {
             return mClampedEotf;
         }
 
+        /**
+         * <p>Returns the parameters used by the {@link #getEotf() electro-optical}
+         * and {@link #getOetf() opto-electronic} transfer functions. If the transfer
+         * functions do not match the ICC parametric curves defined in ICC.1:2004-10
+         * (section 10.15), this method returns null.</p>
+         *
+         * <p>See {@link TransferParameters} for a full description of the transfer
+         * functions.</p>
+         *
+         * @return An instance of {@link TransferParameters} or null if this color
+         *         space's transfer functions do not match the equation defined in
+         *         {@link TransferParameters}
+         */
+        @Nullable
+        public TransferParameters getTransferParameters() {
+            return mTransferParameters;
+        }
+
         @Override
         public boolean isSrgb() {
             return mIsSrgb;
@@ -2544,6 +3027,11 @@
             if (Float.compare(rgb.mMax, mMax) != 0) return false;
             if (!Arrays.equals(mWhitePoint, rgb.mWhitePoint)) return false;
             if (!Arrays.equals(mPrimaries, rgb.mPrimaries)) return false;
+            if (mTransferParameters != null) {
+                return mTransferParameters.equals(rgb.mTransferParameters);
+            } else if (rgb.mTransferParameters == null) {
+                return true;
+            }
             //noinspection SimplifiableIfStatement
             if (!mOetf.equals(rgb.mOetf)) return false;
             return mEotf.equals(rgb.mEotf);
@@ -2554,10 +3042,14 @@
             int result = super.hashCode();
             result = 31 * result + Arrays.hashCode(mWhitePoint);
             result = 31 * result + Arrays.hashCode(mPrimaries);
-            result = 31 * result + mOetf.hashCode();
-            result = 31 * result + mEotf.hashCode();
             result = 31 * result + (mMin != +0.0f ? Float.floatToIntBits(mMin) : 0);
             result = 31 * result + (mMax != +0.0f ? Float.floatToIntBits(mMax) : 0);
+            result = 31 * result +
+                    (mTransferParameters != null ? mTransferParameters.hashCode() : 0);
+            if (mTransferParameters == null) {
+                result = 31 * result + mOetf.hashCode();
+                result = 31 * result + mEotf.hashCode();
+            }
             return result;
         }
 
@@ -2746,18 +3238,15 @@
          * range of the color space is [0..1].
          *
          * @param toXYZ The color space's 3x3 transform matrix to XYZ
-         * @param EOTF The color space's electro-optical transfer function
          * @return A new array of 6 floats containing the color space's
          *         primaries in CIE xyY
          */
         @NonNull
         @Size(6)
-        private static float[] computePrimaries(@NonNull @Size(9) float[] toXYZ,
-                DoubleUnaryOperator EOTF) {
-            float one = (float) EOTF.applyAsDouble(1.0);
-            float[] r = mul3x3Float3(toXYZ, new float[] { one, 0.0f, 0.0f });
-            float[] g = mul3x3Float3(toXYZ, new float[] { 0.0f, one, 0.0f });
-            float[] b = mul3x3Float3(toXYZ, new float[] { 0.0f, 0.0f, one });
+        private static float[] computePrimaries(@NonNull @Size(9) float[] toXYZ) {
+            float[] r = mul3x3Float3(toXYZ, new float[] { 1.0f, 0.0f, 0.0f });
+            float[] g = mul3x3Float3(toXYZ, new float[] { 0.0f, 1.0f, 0.0f });
+            float[] b = mul3x3Float3(toXYZ, new float[] { 0.0f, 0.0f, 1.0f });
 
             float rSum = r[0] + r[1] + r[2];
             float gSum = g[0] + g[1] + g[2];
@@ -2776,16 +3265,13 @@
          * range of the color space is [0..1].
          *
          * @param toXYZ The color space's 3x3 transform matrix to XYZ
-         * @param EOTF The color space's electro-optical transfer function
          * @return A new array of 2 floats containing the color space's
          *         white point in CIE xyY
          */
         @NonNull
         @Size(2)
-        private static float[] computeWhitePoint(@NonNull @Size(9) float[] toXYZ,
-                @NonNull DoubleUnaryOperator EOTF) {
-            float one = (float) EOTF.applyAsDouble(1.0);
-            float[] w = mul3x3Float3(toXYZ, new float[] { one, one, one });
+        private static float[] computeWhitePoint(@NonNull @Size(9) float[] toXYZ) {
+            float[] w = mul3x3Float3(toXYZ, new float[] { 1.0f, 1.0f, 1.0f });
             float sum = w[0] + w[1] + w[2];
             return new float[] { w[0] / sum, w[1] / sum };
         }
@@ -2988,6 +3474,7 @@
          * Computes an extra transform to apply in XYZ space depending on the
          * selected rendering intent.
          */
+        @Nullable
         private static float[] computeTransform(@NonNull ColorSpace source,
                 @NonNull ColorSpace destination, @NonNull RenderIntent intent) {
             if (intent != RenderIntent.ABSOLUTE) return null;
diff --git a/graphics/java/android/graphics/Typeface.java b/graphics/java/android/graphics/Typeface.java
index 52e18a9..8b30903 100644
--- a/graphics/java/android/graphics/Typeface.java
+++ b/graphics/java/android/graphics/Typeface.java
@@ -186,8 +186,8 @@
                 }
                 // Downloaded font and it wasn't cached, request it again and return a
                 // default font instead (nothing we can do now).
-                create(new FontRequest(family.getProviderAuthority(), family.getQuery()),
-                        NO_OP_REQUEST_CALLBACK);
+                create(new FontRequest(family.getProviderAuthority(), family.getProviderPackage(),
+                        family.getQuery()), NO_OP_REQUEST_CALLBACK);
                 return DEFAULT;
             }
 
diff --git a/graphics/java/android/graphics/drawable/AdaptiveIconDrawable.java b/graphics/java/android/graphics/drawable/AdaptiveIconDrawable.java
index 9896a88..0722c18 100644
--- a/graphics/java/android/graphics/drawable/AdaptiveIconDrawable.java
+++ b/graphics/java/android/graphics/drawable/AdaptiveIconDrawable.java
@@ -256,9 +256,12 @@
         }
     }
 
+    /**
+     * Set the child layer bounds bigger than the view port size by {@link #DEFAULT_VIEW_PORT_SCALE}
+     */
     private void updateLayerBoundsInternal(Rect bounds) {
-        int cX = bounds.centerX();
-        int cY = bounds.centerY();
+        int cX = bounds.width() / 2;
+        int cY = bounds.height() / 2;
 
         for (int i = 0, count = mLayerState.N_CHILDREN; i < count; i++) {
             final ChildDrawable r = mLayerState.mChildren[i];
@@ -283,7 +286,11 @@
         mMaskMatrix.setScale(b.width() / MASK_SIZE, b.height() / MASK_SIZE);
         sMask.transform(mMaskMatrix, mMask);
 
-        mMaskBitmap = Bitmap.createBitmap(b.width(), b.height(), Bitmap.Config.ALPHA_8);
+        if (mMaskBitmap == null || mMaskBitmap.getWidth() != b.width() ||
+            mMaskBitmap.getHeight() != b.height()) {
+            mMaskBitmap = Bitmap.createBitmap(b.width(), b.height(), Bitmap.Config.ALPHA_8);
+            mLayersBitmap = Bitmap.createBitmap(b.width(), b.height(), Bitmap.Config.ARGB_8888);
+        }
         mCanvas.setBitmap(mMaskBitmap);
         mPaint.setShader(null);
         mCanvas.drawPath(mMask, mPaint);
@@ -291,7 +298,6 @@
         // reset everything that depends on the view bounds
         mTransparentRegion.setEmpty();
         mLayersShader = null;
-        mLayersBitmap = Bitmap.createBitmap(b.width(), b.height(), Bitmap.Config.ARGB_8888);
     }
 
     @Override
@@ -310,7 +316,10 @@
             mLayersShader = new BitmapShader(mLayersBitmap, TileMode.CLAMP, TileMode.CLAMP);
             mPaint.setShader(mLayersShader);
         }
-        canvas.drawBitmap(mMaskBitmap, 0.0f, 0.0f, mPaint);
+        if (mMaskBitmap != null) {
+            Rect bounds = getBounds();
+            canvas.drawBitmap(mMaskBitmap, bounds.left, bounds.top, mPaint);
+        }
     }
 
     @Override
diff --git a/graphics/java/android/graphics/fonts/FontRequest.java b/graphics/java/android/graphics/fonts/FontRequest.java
index e50df6f..c7a5830 100644
--- a/graphics/java/android/graphics/fonts/FontRequest.java
+++ b/graphics/java/android/graphics/fonts/FontRequest.java
@@ -18,24 +18,56 @@
 import android.annotation.NonNull;
 import android.os.Parcel;
 import android.os.Parcelable;
+import android.util.Base64;
 
 import com.android.internal.util.Preconditions;
 
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
 /**
  * Information about a font request that may be sent to a Font Provider.
  */
 public final class FontRequest implements Parcelable {
     private final String mProviderAuthority;
+    private final String mProviderPackage;
     private final String mQuery;
+    private final List<List<byte[]>> mCertificates;
+
+    /**
+     * @param providerAuthority The authority of the Font Provider to be used for the request. This
+     *         should be a system installed app.
+     * @param providerPackage The package for the Font Provider to be used for the request. This is
+     *         used to verify the identity of the provider.
+     * @param query The query to be sent over to the provider. Refer to your font provider's
+     *         documentation on the format of this string.
+     */
+    public FontRequest(@NonNull String providerAuthority, @NonNull String providerPackage,
+            @NonNull String query) {
+        mProviderAuthority = Preconditions.checkNotNull(providerAuthority);
+        mQuery = Preconditions.checkNotNull(query);
+        mProviderPackage = Preconditions.checkNotNull(providerPackage);
+        mCertificates = Collections.emptyList();
+    }
 
     /**
      * @param providerAuthority The authority of the Font Provider to be used for the request.
      * @param query The query to be sent over to the provider. Refer to your font provider's
-     *              documentation on the format of this string.
+     *         documentation on the format of this string.
+     * @param providerPackage The package for the Font Provider to be used for the request. This is
+     *         used to verify the identity of the provider.
+     * @param certificates The list of sets of hashes for the certificates the provider should be
+     *         signed with. This is used to verify the identity of the provider. Each set in the
+     *         list represents one collection of signature hashes. Refer to your font provider's
+     *         documentation for these values.
      */
-    public FontRequest(@NonNull String providerAuthority, @NonNull String query) {
+    public FontRequest(@NonNull String providerAuthority, @NonNull String providerPackage,
+            @NonNull String query, @NonNull List<List<byte[]>> certificates) {
         mProviderAuthority = Preconditions.checkNotNull(providerAuthority);
+        mProviderPackage = Preconditions.checkNotNull(providerPackage);
         mQuery = Preconditions.checkNotNull(query);
+        mCertificates = Preconditions.checkNotNull(certificates);
     }
 
     /**
@@ -47,6 +79,14 @@
     }
 
     /**
+     * Returns the selected font provider's package. This helps the system verify that the provider
+     * identified by the given authority is the one requested.
+     */
+    public String getProviderPackage() {
+        return mProviderPackage;
+    }
+
+    /**
      * Returns the query string. Refer to your font provider's documentation on the format of this
      * string.
      */
@@ -54,6 +94,14 @@
         return mQuery;
     }
 
+    /**
+     * Returns the list of certificate sets given for this provider. This helps the system verify
+     * that the provider identified by the given authority is the one requested.
+     */
+    public List<List<byte[]>> getCertificates() {
+        return mCertificates;
+    }
+
     @Override
     public int describeContents() {
         return 0;
@@ -62,12 +110,17 @@
     @Override
     public void writeToParcel(Parcel dest, int flags) {
         dest.writeString(mProviderAuthority);
+        dest.writeString(mProviderPackage);
         dest.writeString(mQuery);
+        dest.writeList(mCertificates);
     }
 
     private FontRequest(Parcel in) {
         mProviderAuthority = in.readString();
+        mProviderPackage = in.readString();
         mQuery = in.readString();
+        mCertificates = new ArrayList<>();
+        in.readList(mCertificates, null);
     }
 
     public static final Parcelable.Creator<FontRequest> CREATOR =
@@ -85,9 +138,24 @@
 
     @Override
     public String toString() {
-        return "FontRequest {"
+        StringBuilder builder = new StringBuilder();
+        builder.append("FontRequest {"
                 + "mProviderAuthority: " + mProviderAuthority
+                + ", mProviderPackage: " + mProviderPackage
                 + ", mQuery: " + mQuery
-                + "}";
+                + ", mCertificates:");
+        for (int i = 0; i < mCertificates.size(); i++) {
+            builder.append(" [");
+            List<byte[]> set = mCertificates.get(i);
+            for (int j = 0; j < set.size(); j++) {
+                builder.append(" \"");
+                byte[] array = set.get(j);
+                builder.append(Base64.encodeToString(array, Base64.DEFAULT));
+                builder.append("\"");
+            }
+            builder.append(" ]");
+        }
+        builder.append("}");
+        return builder.toString();
     }
 }
diff --git a/libs/androidfw/AssetManager.cpp b/libs/androidfw/AssetManager.cpp
index 84111ae..acacd76 100644
--- a/libs/androidfw/AssetManager.cpp
+++ b/libs/androidfw/AssetManager.cpp
@@ -202,6 +202,15 @@
         *cookie = static_cast<int32_t>(mAssetPaths.size());
     }
 
+#ifdef __ANDROID__
+    // Load overlays, if any
+    asset_path oap;
+    for (size_t idx = 0; mZipSet.getOverlay(ap.path, idx, &oap); idx++) {
+        oap.isSystemAsset = isSystemAsset;
+        mAssetPaths.add(oap);
+    }
+#endif
+
     if (mResources != NULL) {
         appendPathToResTable(ap, appAsLib);
     }
@@ -484,6 +493,11 @@
 }
 
 bool AssetManager::appendPathToResTable(const asset_path& ap, bool appAsLib) const {
+    // skip those ap's that correspond to system overlays
+    if (ap.isSystemOverlay) {
+        return true;
+    }
+
     Asset* ass = NULL;
     ResTable* sharedRes = NULL;
     bool shared = true;
@@ -525,6 +539,14 @@
                 ALOGV("Creating shared resources for %s", ap.path.string());
                 sharedRes = new ResTable();
                 sharedRes->add(ass, idmap, nextEntryIdx + 1, false);
+#ifdef __ANDROID__
+                const char* data = getenv("ANDROID_DATA");
+                LOG_ALWAYS_FATAL_IF(data == NULL, "ANDROID_DATA not set");
+                String8 overlaysListPath(data);
+                overlaysListPath.appendPath(kResourceCache);
+                overlaysListPath.appendPath("overlays.list");
+                addSystemOverlays(overlaysListPath.string(), ap.path, sharedRes, nextEntryIdx);
+#endif
                 sharedRes = const_cast<AssetManager*>(this)->
                     mZipSet.setZipResourceTable(ap.path, sharedRes);
             }
@@ -633,6 +655,58 @@
     return ass;
 }
 
+void AssetManager::addSystemOverlays(const char* pathOverlaysList,
+        const String8& targetPackagePath, ResTable* sharedRes, size_t offset) const
+{
+    FILE* fin = fopen(pathOverlaysList, "r");
+    if (fin == NULL) {
+        return;
+    }
+
+#ifndef _WIN32
+    if (TEMP_FAILURE_RETRY(flock(fileno(fin), LOCK_SH)) != 0) {
+        fclose(fin);
+        return;
+    }
+#endif
+    char buf[1024];
+    while (fgets(buf, sizeof(buf), fin)) {
+        // format of each line:
+        //   <path to apk><space><path to idmap><newline>
+        char* space = strchr(buf, ' ');
+        char* newline = strchr(buf, '\n');
+        asset_path oap;
+
+        if (space == NULL || newline == NULL || newline < space) {
+            continue;
+        }
+
+        oap.path = String8(buf, space - buf);
+        oap.type = kFileTypeRegular;
+        oap.idmap = String8(space + 1, newline - space - 1);
+        oap.isSystemOverlay = true;
+
+        Asset* oass = const_cast<AssetManager*>(this)->
+            openNonAssetInPathLocked("resources.arsc",
+                    Asset::ACCESS_BUFFER,
+                    oap);
+
+        if (oass != NULL) {
+            Asset* oidmap = openIdmapLocked(oap);
+            offset++;
+            sharedRes->add(oass, oidmap, offset + 1, false);
+            const_cast<AssetManager*>(this)->mAssetPaths.add(oap);
+            const_cast<AssetManager*>(this)->mZipSet.addOverlay(targetPackagePath, oap);
+            delete oidmap;
+        }
+    }
+
+#ifndef _WIN32
+    TEMP_FAILURE_RETRY(flock(fileno(fin), LOCK_UN));
+#endif
+    fclose(fin);
+}
+
 const ResTable& AssetManager::getResources(bool required) const
 {
     const ResTable* rt = getResTable(required);
@@ -1372,6 +1446,20 @@
     return mModWhen == modWhen;
 }
 
+void AssetManager::SharedZip::addOverlay(const asset_path& ap)
+{
+    mOverlays.add(ap);
+}
+
+bool AssetManager::SharedZip::getOverlay(size_t idx, asset_path* out) const
+{
+    if (idx >= mOverlays.size()) {
+        return false;
+    }
+    *out = mOverlays[idx];
+    return true;
+}
+
 AssetManager::SharedZip::~SharedZip()
 {
     if (kIsDebug) {
@@ -1490,6 +1578,22 @@
     return true;
 }
 
+void AssetManager::ZipSet::addOverlay(const String8& path, const asset_path& overlay)
+{
+    int idx = getIndex(path);
+    sp<SharedZip> zip = mZipFile[idx];
+    zip->addOverlay(overlay);
+}
+
+bool AssetManager::ZipSet::getOverlay(const String8& path, size_t idx, asset_path* out) const
+{
+    sp<SharedZip> zip = SharedZip::get(path, false);
+    if (zip == NULL) {
+        return false;
+    }
+    return zip->getOverlay(idx, out);
+}
+
 /*
  * Compute the zip file's index.
  *
diff --git a/libs/androidfw/include/androidfw/AssetManager.h b/libs/androidfw/include/androidfw/AssetManager.h
index f1e8b93..becd307 100644
--- a/libs/androidfw/include/androidfw/AssetManager.h
+++ b/libs/androidfw/include/androidfw/AssetManager.h
@@ -202,10 +202,12 @@
 private:
     struct asset_path
     {
-        asset_path() : path(""), type(kFileTypeRegular), idmap(""), isSystemAsset(false) {}
+        asset_path() : path(""), type(kFileTypeRegular), idmap(""),
+                       isSystemOverlay(false), isSystemAsset(false) {}
         String8 path;
         FileType type;
         String8 idmap;
+        bool isSystemOverlay;
         bool isSystemAsset;
     };
 
@@ -235,6 +237,9 @@
 
     Asset* openIdmapLocked(const struct asset_path& ap) const;
 
+    void addSystemOverlays(const char* pathOverlaysList, const String8& targetPackagePath,
+            ResTable* sharedRes, size_t offset) const;
+
     class SharedZip : public RefBase {
     public:
         static sp<SharedZip> get(const String8& path, bool createIfNotPresent = true);
@@ -249,6 +254,9 @@
 
         bool isUpToDate();
 
+        void addOverlay(const asset_path& ap);
+        bool getOverlay(size_t idx, asset_path* out) const;
+
     protected:
         ~SharedZip();
 
@@ -263,6 +271,8 @@
         Asset* mResourceTableAsset;
         ResTable* mResourceTable;
 
+        Vector<asset_path> mOverlays;
+
         static Mutex gLock;
         static DefaultKeyedVector<String8, wp<SharedZip> > gOpen;
     };
@@ -296,6 +306,9 @@
 
         bool isUpToDate();
 
+        void addOverlay(const String8& path, const asset_path& overlay);
+        bool getOverlay(const String8& path, size_t idx, asset_path* out) const;
+
     private:
         void closeZip(int idx);
 
diff --git a/libs/hwui/BakedOpState.cpp b/libs/hwui/BakedOpState.cpp
index 9f98241..9823a02 100644
--- a/libs/hwui/BakedOpState.cpp
+++ b/libs/hwui/BakedOpState.cpp
@@ -31,7 +31,7 @@
 }
 
 ResolvedRenderState::ResolvedRenderState(LinearAllocator& allocator, Snapshot& snapshot,
-        const RecordedOp& recordedOp, bool expandForStroke) {
+        const RecordedOp& recordedOp, bool expandForStroke, bool expandForPathTexture) {
     // resolvedMatrix = parentMatrix * localMatrix
     transform.loadMultiply(*snapshot.transform, recordedOp.localMatrix);
 
@@ -40,6 +40,8 @@
     if (CC_UNLIKELY(expandForStroke)) {
         // account for non-hairline stroke
         clippedBounds.outset(recordedOp.paint->getStrokeWidth() * 0.5f);
+    } else if (CC_UNLIKELY(expandForPathTexture)) {
+        clippedBounds.outset(1);
     }
     transform.mapRect(clippedBounds);
     if (CC_UNLIKELY(expandForStroke
@@ -111,7 +113,7 @@
         Snapshot& snapshot, const RecordedOp& recordedOp) {
     if (CC_UNLIKELY(snapshot.getRenderTargetClip().isEmpty())) return nullptr;
     BakedOpState* bakedState = allocator.create_trivial<BakedOpState>(
-            allocator, snapshot, recordedOp, false);
+            allocator, snapshot, recordedOp, false, false);
     if (bakedState->computedState.clippedBounds.isEmpty()) {
         // bounds are empty, so op is rejected
         allocator.rewindIfLastAlloc(bakedState);
@@ -127,14 +129,14 @@
 }
 
 BakedOpState* BakedOpState::tryStrokeableOpConstruct(LinearAllocator& allocator,
-        Snapshot& snapshot, const RecordedOp& recordedOp, StrokeBehavior strokeBehavior) {
+        Snapshot& snapshot, const RecordedOp& recordedOp, StrokeBehavior strokeBehavior,
+        bool expandForPathTexture) {
     if (CC_UNLIKELY(snapshot.getRenderTargetClip().isEmpty())) return nullptr;
-    bool expandForStroke = (strokeBehavior == StrokeBehavior::StyleDefined)
-            ? (recordedOp.paint && recordedOp.paint->getStyle() != SkPaint::kFill_Style)
-            : true;
+    bool expandForStroke = (strokeBehavior == StrokeBehavior::Forced
+            || (recordedOp.paint && recordedOp.paint->getStyle() != SkPaint::kFill_Style));
 
     BakedOpState* bakedState = allocator.create_trivial<BakedOpState>(
-           allocator, snapshot, recordedOp, expandForStroke);
+           allocator, snapshot, recordedOp, expandForStroke, expandForPathTexture);
     if (bakedState->computedState.clippedBounds.isEmpty()) {
         // bounds are empty, so op is rejected
         // NOTE: this won't succeed if a clip was allocated
diff --git a/libs/hwui/BakedOpState.h b/libs/hwui/BakedOpState.h
index e1441fc..7b0b34f 100644
--- a/libs/hwui/BakedOpState.h
+++ b/libs/hwui/BakedOpState.h
@@ -53,7 +53,7 @@
 class ResolvedRenderState {
 public:
     ResolvedRenderState(LinearAllocator& allocator, Snapshot& snapshot,
-            const RecordedOp& recordedOp, bool expandForStroke);
+            const RecordedOp& recordedOp, bool expandForStroke, bool expandForPathTexture);
 
     // Constructor for unbounded ops *with* transform/clip
     ResolvedRenderState(LinearAllocator& allocator, Snapshot& snapshot,
@@ -117,7 +117,8 @@
     };
 
     static BakedOpState* tryStrokeableOpConstruct(LinearAllocator& allocator,
-            Snapshot& snapshot, const RecordedOp& recordedOp, StrokeBehavior strokeBehavior);
+            Snapshot& snapshot, const RecordedOp& recordedOp, StrokeBehavior strokeBehavior,
+            bool expandForPathTexture);
 
     static BakedOpState* tryShadowOpConstruct(LinearAllocator& allocator,
             Snapshot& snapshot, const ShadowOp* shadowOpPtr);
@@ -140,8 +141,8 @@
     friend class LinearAllocator;
 
     BakedOpState(LinearAllocator& allocator, Snapshot& snapshot,
-            const RecordedOp& recordedOp, bool expandForStroke)
-            : computedState(allocator, snapshot, recordedOp, expandForStroke)
+            const RecordedOp& recordedOp, bool expandForStroke, bool expandForPathTexture)
+            : computedState(allocator, snapshot, recordedOp, expandForStroke, expandForPathTexture)
             , alpha(snapshot.alpha)
             , roundRectClipState(snapshot.roundRectClipState)
             , op(&recordedOp) {}
diff --git a/libs/hwui/Caches.h b/libs/hwui/Caches.h
index 7c2e78c..19063e3 100644
--- a/libs/hwui/Caches.h
+++ b/libs/hwui/Caches.h
@@ -133,7 +133,7 @@
      * this function returns GL_SRGB8_ALPHA8, otherwise it returns GL_RGBA
      */
     constexpr GLint rgbaInternalFormat(bool needSRGB = true) const {
-        return extensions().hasSRGB() && needSRGB ? GL_SRGB8_ALPHA8 : GL_RGBA;
+        return extensions().hasLinearBlending() && needSRGB ? GL_SRGB8_ALPHA8 : GL_RGBA;
     }
 
     /**
diff --git a/libs/hwui/Extensions.cpp b/libs/hwui/Extensions.cpp
index 00238a2..1e71cb0 100644
--- a/libs/hwui/Extensions.cpp
+++ b/libs/hwui/Extensions.cpp
@@ -20,6 +20,8 @@
 #include "Properties.h"
 #include "utils/StringUtils.h"
 
+#include <cutils/compiler.h>
+
 #include <GLES2/gl2.h>
 #include <GLES2/gl2ext.h>
 
@@ -28,14 +30,6 @@
 namespace android {
 namespace uirenderer {
 
-// Debug
-#if DEBUG_EXTENSIONS
-    #define EXT_LOGD(...) ALOGD(__VA_ARGS__)
-#else
-    #define EXT_LOGD(...)
-#endif
-
-
 Extensions::Extensions() {
     const char* version = (const char*) glGetString(GL_VERSION);
 
@@ -66,17 +60,18 @@
     mHas4BitStencil = extensions.has("GL_OES_stencil4");
     mHasUnpackSubImage = extensions.has("GL_EXT_unpack_subimage");
 
-#ifdef ANDROID_ENABLE_LINEAR_BLENDING
     mHasSRGB = mVersionMajor >= 3 || extensions.has("GL_EXT_sRGB");
     mHasSRGBWriteControl = extensions.has("GL_EXT_sRGB_write_control");
 
+#ifdef ANDROID_ENABLE_LINEAR_BLENDING
     // If linear blending is enabled, the device must have (ES3.0 or EXT_sRGB)
     // and EXT_sRGB_write_control
     LOG_ALWAYS_FATAL_IF(!mHasSRGB, "Linear blending requires ES 3.0 or EXT_sRGB");
     LOG_ALWAYS_FATAL_IF(!mHasSRGBWriteControl, "Linear blending requires EXT_sRGB_write_control");
+
+    mHasLinearBlending = true;
 #else
-    mHasSRGB = false;
-    mHasSRGBWriteControl = false;
+    mHasLinearBlending = false;
 #endif
 }
 
diff --git a/libs/hwui/Extensions.h b/libs/hwui/Extensions.h
index 2c38507..0ecfdb1 100644
--- a/libs/hwui/Extensions.h
+++ b/libs/hwui/Extensions.h
@@ -17,11 +17,6 @@
 #ifndef ANDROID_HWUI_EXTENSIONS_H
 #define ANDROID_HWUI_EXTENSIONS_H
 
-#include <cutils/compiler.h>
-
-#include <string>
-#include <unordered_set>
-
 namespace android {
 namespace uirenderer {
 
@@ -45,6 +40,7 @@
     inline bool hasFloatTextures() const { return mVersionMajor >= 3; }
     inline bool hasSRGB() const { return mHasSRGB; }
     inline bool hasSRGBWriteControl() const { return hasSRGB() && mHasSRGBWriteControl; }
+    inline bool hasLinearBlending() const { return hasSRGB() && mHasLinearBlending; }
 
     inline int getMajorGlVersion() const { return mVersionMajor; }
     inline int getMinorGlVersion() const { return mVersionMinor; }
@@ -59,6 +55,7 @@
     bool mHasUnpackSubImage;
     bool mHasSRGB;
     bool mHasSRGBWriteControl;
+    bool mHasLinearBlending;
 
     int mVersionMajor;
     int mVersionMinor;
diff --git a/libs/hwui/FrameBuilder.cpp b/libs/hwui/FrameBuilder.cpp
index 1b57e29..86f9a5d 100644
--- a/libs/hwui/FrameBuilder.cpp
+++ b/libs/hwui/FrameBuilder.cpp
@@ -562,10 +562,11 @@
  * for paint's style on the bounds being computed.
  */
 BakedOpState* FrameBuilder::deferStrokeableOp(const RecordedOp& op, batchid_t batchId,
-        BakedOpState::StrokeBehavior strokeBehavior) {
+        BakedOpState::StrokeBehavior strokeBehavior, bool expandForPathTexture) {
     // Note: here we account for stroke when baking the op
     BakedOpState* bakedState = BakedOpState::tryStrokeableOpConstruct(
-            mAllocator, *mCanvasState.writableSnapshot(), op, strokeBehavior);
+            mAllocator, *mCanvasState.writableSnapshot(), op,
+            strokeBehavior, expandForPathTexture);
     if (!bakedState) return nullptr; // quick rejected
 
     if (op.opId == RecordedOpId::RectOp && op.paint->getStyle() != SkPaint::kStroke_Style) {
@@ -590,7 +591,10 @@
 }
 
 void FrameBuilder::deferArcOp(const ArcOp& op) {
-    deferStrokeableOp(op, tessBatchId(op));
+    // Pass true below since arcs have a tendency to draw outside their expected bounds within
+    // their path textures. Passing true makes it more likely that we'll scissor, instead of
+    // corrupting the frame by drawing outside of clip bounds.
+    deferStrokeableOp(op, tessBatchId(op), BakedOpState::StrokeBehavior::StyleDefined, true);
 }
 
 static bool hasMergeableClip(const BakedOpState& state) {
@@ -748,7 +752,7 @@
 void FrameBuilder::deferTextOp(const TextOp& op) {
     BakedOpState* bakedState = BakedOpState::tryStrokeableOpConstruct(
             mAllocator, *mCanvasState.writableSnapshot(), op,
-            BakedOpState::StrokeBehavior::StyleDefined);
+            BakedOpState::StrokeBehavior::StyleDefined, false);
     if (!bakedState) return; // quick rejected
 
     batchid_t batchId = textBatchId(*(op.paint));
diff --git a/libs/hwui/FrameBuilder.h b/libs/hwui/FrameBuilder.h
index b915443..46048f7 100644
--- a/libs/hwui/FrameBuilder.h
+++ b/libs/hwui/FrameBuilder.h
@@ -211,7 +211,8 @@
     }
 
     BakedOpState* deferStrokeableOp(const RecordedOp& op, batchid_t batchId,
-            BakedOpState::StrokeBehavior strokeBehavior = BakedOpState::StrokeBehavior::StyleDefined);
+            BakedOpState::StrokeBehavior strokeBehavior = BakedOpState::StrokeBehavior::StyleDefined,
+            bool expandForPathTexture = false);
 
     /**
      * Declares all FrameBuilder::deferXXXXOp() methods for every RecordedOp type.
diff --git a/libs/hwui/GradientCache.cpp b/libs/hwui/GradientCache.cpp
index 71bee93..18bfcc2 100644
--- a/libs/hwui/GradientCache.cpp
+++ b/libs/hwui/GradientCache.cpp
@@ -68,7 +68,7 @@
         , mMaxSize(Properties::gradientCacheSize)
         , mUseFloatTexture(extensions.hasFloatTextures())
         , mHasNpot(extensions.hasNPot())
-        , mHasSRGB(extensions.hasSRGB()) {
+        , mHasLinearBlending(extensions.hasLinearBlending()) {
     glGetIntegerv(GL_MAX_TEXTURE_SIZE, &mMaxTextureSize);
 
     mCache.setOnEntryRemovedListener(this);
@@ -263,7 +263,7 @@
     if (mUseFloatTexture) {
         texture->upload(GL_RGBA16F, width, height, GL_RGBA, GL_FLOAT, pixels);
     } else {
-        GLint internalFormat = mHasSRGB ? GL_SRGB8_ALPHA8 : GL_RGBA;
+        GLint internalFormat = mHasLinearBlending ? GL_SRGB8_ALPHA8 : GL_RGBA;
         texture->upload(internalFormat, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
     }
 
diff --git a/libs/hwui/GradientCache.h b/libs/hwui/GradientCache.h
index 5e35435..f299a40 100644
--- a/libs/hwui/GradientCache.h
+++ b/libs/hwui/GradientCache.h
@@ -170,7 +170,7 @@
     GLint mMaxTextureSize;
     bool mUseFloatTexture;
     bool mHasNpot;
-    bool mHasSRGB;
+    bool mHasLinearBlending;
 
     mutable Mutex mLock;
 }; // class GradientCache
diff --git a/libs/hwui/ProgramCache.cpp b/libs/hwui/ProgramCache.cpp
index ca05648..40ab778 100644
--- a/libs/hwui/ProgramCache.cpp
+++ b/libs/hwui/ProgramCache.cpp
@@ -418,7 +418,7 @@
 
 ProgramCache::ProgramCache(Extensions& extensions)
         : mHasES3(extensions.getMajorGlVersion() >= 3)
-        , mHasSRGB(extensions.hasSRGB()) {
+        , mHasLinearBlending(extensions.hasLinearBlending()) {
 }
 
 ProgramCache::~ProgramCache() {
@@ -642,11 +642,11 @@
     }
     if (description.hasBitmap || ((description.hasTexture || description.hasExternalTexture) &&
             !description.hasAlpha8Texture)) {
-        shader.append(gFS_OETF[description.hasLinearTexture && !mHasSRGB]);
+        shader.append(gFS_OETF[description.hasLinearTexture && !mHasLinearBlending]);
     }
     if (description.hasGradient) {
         shader.append(gFS_Gradient_Functions);
-        shader.append(gFS_Gradient_Preamble[mHasSRGB]);
+        shader.append(gFS_Gradient_Preamble[mHasLinearBlending]);
     }
 
     // Begin the shader
diff --git a/libs/hwui/ProgramCache.h b/libs/hwui/ProgramCache.h
index c2f715d..cedd854b 100644
--- a/libs/hwui/ProgramCache.h
+++ b/libs/hwui/ProgramCache.h
@@ -59,7 +59,7 @@
     std::map<programid, std::unique_ptr<Program>> mCache;
 
     const bool mHasES3;
-    const bool mHasSRGB;
+    const bool mHasLinearBlending;
 }; // class ProgramCache
 
 }; // namespace uirenderer
diff --git a/libs/hwui/Texture.cpp b/libs/hwui/Texture.cpp
index 0dbd767..cfc2744 100644
--- a/libs/hwui/Texture.cpp
+++ b/libs/hwui/Texture.cpp
@@ -241,21 +241,23 @@
     }
 }
 
-SkBitmap Texture::uploadToN32(const SkBitmap& bitmap, bool hasSRGB, sk_sp<SkColorSpace> sRGB) {
+SkBitmap Texture::uploadToN32(const SkBitmap& bitmap, bool hasLinearBlending,
+        sk_sp<SkColorSpace> sRGB) {
     SkBitmap rgbaBitmap;
     rgbaBitmap.allocPixels(SkImageInfo::MakeN32(bitmap.width(), bitmap.height(),
-            bitmap.info().alphaType(), hasSRGB ? sRGB : nullptr));
+            bitmap.info().alphaType(), hasLinearBlending ? sRGB : nullptr));
     rgbaBitmap.eraseColor(0);
     SkCanvas canvas(rgbaBitmap);
     canvas.drawBitmap(bitmap, 0.0f, 0.0f, nullptr);
     return rgbaBitmap;
 }
 
-bool Texture::hasUnsupportedColorType(const SkImageInfo& info, bool hasSRGB, SkColorSpace* sRGB) {
+bool Texture::hasUnsupportedColorType(const SkImageInfo& info, bool hasLinearBlending,
+        SkColorSpace* sRGB) {
     bool needSRGB = info.colorSpace() == sRGB;
     return info.colorType() == kARGB_4444_SkColorType
         || info.colorType() == kIndex_8_SkColorType
-        || (info.colorType() == kRGB_565_SkColorType && hasSRGB && needSRGB);
+        || (info.colorType() == kRGB_565_SkColorType && hasLinearBlending && needSRGB);
 }
 
 
@@ -295,11 +297,11 @@
     mCaches.textureState().bindTexture(mTarget, mId);
 
     // TODO: Handle sRGB gray bitmaps
-    bool hasSRGB = mCaches.extensions().hasSRGB();
-    if (CC_UNLIKELY(hasUnsupportedColorType(bitmap.info(), hasSRGB, sRGB.get()))) {
+    bool hasLinearBlending = mCaches.extensions().hasLinearBlending();
+    if (CC_UNLIKELY(hasUnsupportedColorType(bitmap.info(), hasLinearBlending, sRGB.get()))) {
         SkBitmap skBitmap;
         bitmap.getSkBitmap(&skBitmap);
-        SkBitmap rgbaBitmap = uploadToN32(skBitmap, hasSRGB, std::move(sRGB));
+        SkBitmap rgbaBitmap = uploadToN32(skBitmap, hasLinearBlending, std::move(sRGB));
         uploadToTexture(needsAlloc, internalFormat, format, type, rgbaBitmap.rowBytesAsPixels(),
                 rgbaBitmap.bytesPerPixel(), rgbaBitmap.width(),
                 rgbaBitmap.height(), rgbaBitmap.getPixels());
diff --git a/libs/hwui/Texture.h b/libs/hwui/Texture.h
index ce9d4dc..e7fbf20 100644
--- a/libs/hwui/Texture.h
+++ b/libs/hwui/Texture.h
@@ -40,8 +40,10 @@
  */
 class Texture : public GpuMemoryTracker {
 public:
-    static SkBitmap uploadToN32(const SkBitmap& bitmap, bool hasSRGB, sk_sp<SkColorSpace> sRGB);
-    static bool hasUnsupportedColorType(const SkImageInfo& info, bool hasSRGB, SkColorSpace* sRGB);
+    static SkBitmap uploadToN32(const SkBitmap& bitmap,
+            bool hasLinearBlending, sk_sp<SkColorSpace> sRGB);
+    static bool hasUnsupportedColorType(const SkImageInfo& info,
+            bool hasLinearBlending, SkColorSpace* sRGB);
     static void colorTypeToGlFormatAndType(const Caches& caches, SkColorType colorType,
             bool needSRGB, GLint* outInternalFormat, GLint* outFormat, GLint* outType);
 
diff --git a/libs/hwui/TextureCache.h b/libs/hwui/TextureCache.h
index a55b061..db4ff39 100644
--- a/libs/hwui/TextureCache.h
+++ b/libs/hwui/TextureCache.h
@@ -19,6 +19,8 @@
 
 #include <SkBitmap.h>
 
+#include <cutils/compiler.h>
+
 #include <utils/LruCache.h>
 #include <utils/Mutex.h>
 
diff --git a/libs/hwui/TreeInfo.h b/libs/hwui/TreeInfo.h
index e39614b..c6fbe2b 100644
--- a/libs/hwui/TreeInfo.h
+++ b/libs/hwui/TreeInfo.h
@@ -91,6 +91,8 @@
     LayerUpdateQueue* layerUpdateQueue = nullptr;
     ErrorHandler* errorHandler = nullptr;
 
+    int32_t windowInsetLeft = 0;
+    int32_t windowInsetTop = 0;
     bool updateWindowPositions = false;
 
     struct Out {
diff --git a/libs/hwui/hwui/Bitmap.cpp b/libs/hwui/hwui/Bitmap.cpp
index f9730c9..49b69eb 100644
--- a/libs/hwui/hwui/Bitmap.cpp
+++ b/libs/hwui/hwui/Bitmap.cpp
@@ -234,7 +234,7 @@
 
     sk_sp<SkColorSpace> sRGB = SkColorSpace::MakeSRGB();
     bool needSRGB = skBitmap.info().colorSpace() == sRGB.get();
-    bool hasSRGB = caches.extensions().hasSRGB();
+    bool hasLinearBlending = caches.extensions().hasLinearBlending();
     GLint format, type, internalFormat;
     uirenderer::Texture::colorTypeToGlFormatAndType(caches, skBitmap.colorType(),
             needSRGB, &internalFormat, &format, &type);
@@ -252,8 +252,8 @@
 
     SkBitmap bitmap;
     if (CC_UNLIKELY(uirenderer::Texture::hasUnsupportedColorType(skBitmap.info(),
-            hasSRGB, sRGB.get()))) {
-        bitmap = uirenderer::Texture::uploadToN32(skBitmap, hasSRGB, std::move(sRGB));
+            hasLinearBlending, sRGB.get()))) {
+        bitmap = uirenderer::Texture::uploadToN32(skBitmap, hasLinearBlending, std::move(sRGB));
     } else {
         bitmap = skBitmap;
     }
diff --git a/libs/hwui/renderstate/RenderState.cpp b/libs/hwui/renderstate/RenderState.cpp
index 7dfc2ee..8bce990 100644
--- a/libs/hwui/renderstate/RenderState.cpp
+++ b/libs/hwui/renderstate/RenderState.cpp
@@ -174,13 +174,15 @@
     meshState().disableTexCoordsVertexArray();
     debugOverdraw(false, false);
     // TODO: We need a way to know whether the functor is sRGB aware (b/32072673)
-    if (mCaches->extensions().hasSRGBWriteControl()) {
+    if (mCaches->extensions().hasLinearBlending() &&
+            mCaches->extensions().hasSRGBWriteControl()) {
         glDisable(GL_FRAMEBUFFER_SRGB_EXT);
     }
 }
 
 void RenderState::resumeFromFunctorInvoke() {
-    if (mCaches->extensions().hasSRGBWriteControl()) {
+    if (mCaches->extensions().hasLinearBlending() &&
+            mCaches->extensions().hasSRGBWriteControl()) {
         glEnable(GL_FRAMEBUFFER_SRGB_EXT);
     }
 
diff --git a/libs/hwui/tests/unit/BakedOpStateTests.cpp b/libs/hwui/tests/unit/BakedOpStateTests.cpp
index 0f8e047..d51db2e 100644
--- a/libs/hwui/tests/unit/BakedOpStateTests.cpp
+++ b/libs/hwui/tests/unit/BakedOpStateTests.cpp
@@ -35,7 +35,7 @@
     {
         // recorded with transform, no parent transform
         auto parentSnapshot = TestUtils::makeSnapshot(Matrix4::identity(), Rect(100, 200));
-        ResolvedRenderState state(allocator, *parentSnapshot, recordedOp, false);
+        ResolvedRenderState state(allocator, *parentSnapshot, recordedOp, false, false);
         EXPECT_MATRIX_APPROX_EQ(state.transform, translate10x20);
         EXPECT_EQ(Rect(100, 200), state.clipRect());
         EXPECT_EQ(Rect(40, 60, 100, 200), state.clippedBounds); // translated and also clipped
@@ -44,7 +44,7 @@
     {
         // recorded with transform and parent transform
         auto parentSnapshot = TestUtils::makeSnapshot(translate10x20, Rect(100, 200));
-        ResolvedRenderState state(allocator, *parentSnapshot, recordedOp, false);
+        ResolvedRenderState state(allocator, *parentSnapshot, recordedOp, false, false);
 
         Matrix4 expectedTranslate;
         expectedTranslate.loadTranslate(20, 40, 0);
@@ -70,14 +70,14 @@
     {
         // recorded with transform, no parent transform
         auto parentSnapshot = TestUtils::makeSnapshot(Matrix4::identity(), Rect(100, 200));
-        ResolvedRenderState state(allocator, *parentSnapshot, recordedOp, false);
+        ResolvedRenderState state(allocator, *parentSnapshot, recordedOp, false, false);
         EXPECT_EQ(Rect(-10, -20, 90, 180), state.computeLocalSpaceClip())
             << "Local clip rect should be 100x200, offset by -10,-20";
     }
     {
         // recorded with transform + parent transform
         auto parentSnapshot = TestUtils::makeSnapshot(translate10x20, Rect(100, 200));
-        ResolvedRenderState state(allocator, *parentSnapshot, recordedOp, false);
+        ResolvedRenderState state(allocator, *parentSnapshot, recordedOp, false, false);
         EXPECT_EQ(Rect(-10, -20, 80, 160), state.computeLocalSpaceClip())
             << "Local clip rect should be 90x190, offset by -10,-20";
     }
@@ -170,7 +170,7 @@
         snapshotMatrix.loadScale(testCase.scale, testCase.scale, 1);
         auto parentSnapshot = TestUtils::makeSnapshot(snapshotMatrix, Rect(200, 200));
 
-        ResolvedRenderState state(allocator, *parentSnapshot, recordedOp, true);
+        ResolvedRenderState state(allocator, *parentSnapshot, recordedOp, true, false);
         testCase.validator(state);
     }
 }
@@ -234,7 +234,7 @@
         RectOp rejectOp(Rect(100, 200), Matrix4::identity(), &clip, &paint);
         auto snapshot = TestUtils::makeSnapshot(Matrix4::identity(), Rect()); // Note: empty clip
         auto bakedState = BakedOpState::tryStrokeableOpConstruct(allocator, *snapshot, rejectOp,
-                BakedOpState::StrokeBehavior::StyleDefined);
+                BakedOpState::StrokeBehavior::StyleDefined, false);
 
         EXPECT_EQ(nullptr, bakedState);
         EXPECT_GT(8u, allocator.usedSize()); // no significant allocation space used for rejected op
@@ -248,7 +248,7 @@
         RectOp rejectOp(Rect(50, 50, 150, 150), Matrix4::identity(), &clip, &paint);
         auto snapshot = TestUtils::makeSnapshot(Matrix4::identity(), Rect(200, 200));
         auto bakedState = BakedOpState::tryStrokeableOpConstruct(allocator, *snapshot, rejectOp,
-                BakedOpState::StrokeBehavior::StyleDefined);
+                BakedOpState::StrokeBehavior::StyleDefined, false);
 
         ASSERT_NE(nullptr, bakedState);
         EXPECT_EQ(Rect(45, 45, 155, 155), bakedState->computedState.clippedBounds);
@@ -263,7 +263,7 @@
         RectOp rejectOp(Rect(50, 50, 150, 150), Matrix4::identity(), &clip, &paint);
         auto snapshot = TestUtils::makeSnapshot(Matrix4::identity(), Rect(200, 200));
         auto bakedState = BakedOpState::tryStrokeableOpConstruct(allocator, *snapshot, rejectOp,
-                BakedOpState::StrokeBehavior::Forced);
+                BakedOpState::StrokeBehavior::Forced, false);
 
         ASSERT_NE(nullptr, bakedState);
         EXPECT_EQ(Rect(45, 45, 155, 155), bakedState->computedState.clippedBounds);
diff --git a/libs/hwui/tests/unit/FrameBuilderTests.cpp b/libs/hwui/tests/unit/FrameBuilderTests.cpp
index 95d9459..a329980 100644
--- a/libs/hwui/tests/unit/FrameBuilderTests.cpp
+++ b/libs/hwui/tests/unit/FrameBuilderTests.cpp
@@ -171,6 +171,35 @@
     EXPECT_EQ(1, renderer.getIndex());
 }
 
+
+RENDERTHREAD_OPENGL_PIPELINE_TEST(FrameBuilder, arcStrokeClip) {
+    class ArcStrokeClipTestRenderer : public TestRendererBase {
+    public:
+        void onArcOp(const ArcOp& op, const BakedOpState& state) override {
+            EXPECT_EQ(0, mIndex++);
+            EXPECT_EQ(Rect(25, 25, 175, 175), op.unmappedBounds);
+            EXPECT_EQ(Rect(25, 25, 175, 175), state.computedState.clippedBounds);
+            EXPECT_EQ(OpClipSideFlags::Full, state.computedState.clipSideFlags)
+                    << "Arc op clipped conservatively, since path texture may be expanded";
+        }
+    };
+
+    auto node = TestUtils::createNode<RecordingCanvas>(0, 0, 200, 200,
+            [](RenderProperties& props, RecordingCanvas& canvas) {
+        canvas.clipRect(25, 25, 175, 175, SkClipOp::kIntersect);
+        SkPaint aaPaint;
+        aaPaint.setAntiAlias(true);
+        canvas.drawArc(25, 25, 175, 175, 40, 180, true, aaPaint);
+    });
+    FrameBuilder frameBuilder(SkRect::MakeWH(200, 200), 200, 200,
+            sLightGeometry, Caches::getInstance());
+    frameBuilder.deferRenderNode(*TestUtils::getSyncedNode(node));
+
+    ArcStrokeClipTestRenderer renderer;
+    frameBuilder.replayBakedOps<TestDispatcher>(renderer);
+    EXPECT_EQ(1, renderer.getIndex());
+}
+
 RENDERTHREAD_OPENGL_PIPELINE_TEST(FrameBuilder, simpleRejection) {
     auto node = TestUtils::createNode<RecordingCanvas>(0, 0, 200, 200,
             [](RenderProperties& props, RecordingCanvas& canvas) {
diff --git a/libs/hwui/utils/Color.h b/libs/hwui/utils/Color.h
index 0950eb8..4a27ca2f 100644
--- a/libs/hwui/utils/Color.h
+++ b/libs/hwui/utils/Color.h
@@ -121,4 +121,4 @@
 } /* namespace uirenderer */
 } /* namespace android */
 
-#endif /* TEST_UTILS_H */
+#endif /* COLOR_H */
diff --git a/media/java/android/media/tv/TvView.java b/media/java/android/media/tv/TvView.java
index e5af357..aee9d38e 100644
--- a/media/java/android/media/tv/TvView.java
+++ b/media/java/android/media/tv/TvView.java
@@ -776,8 +776,8 @@
         mSurface = null;
         mSurfaceView = new SurfaceView(getContext(), mAttrs, mDefStyleAttr) {
             @Override
-            protected void updateSurface() {
-                super.updateSurface();
+            protected void updateWindow() {
+                super.updateWindow();
                 relayoutSessionOverlayView();
             }};
         // The surface view's content should be treated as secure all the time.
diff --git a/native/android/Android.mk b/native/android/Android.mk
index 57f996c..6e15331 100644
--- a/native/android/Android.mk
+++ b/native/android/Android.mk
@@ -32,6 +32,7 @@
     libbinder \
     libui \
     libgui \
+    libsensor \
     libandroid_runtime \
     libnetd_client \
 
diff --git a/native/android/libandroid.map.txt b/native/android/libandroid.map.txt
index 1b1f28c..c7bed9b 100644
--- a/native/android/libandroid.map.txt
+++ b/native/android/libandroid.map.txt
@@ -169,6 +169,7 @@
     ASensorEventQueue_enableSensor;
     ASensorEventQueue_getEvents;
     ASensorEventQueue_hasEvents;
+    ASensorEventQueue_registerSensor; # introduced=26
     ASensorEventQueue_setEventRate;
     ASensorManager_configureDirectReport; # introduced=26
     ASensorManager_createEventQueue;
diff --git a/native/android/sensor.cpp b/native/android/sensor.cpp
index c7bc885..ae16949 100644
--- a/native/android/sensor.cpp
+++ b/native/android/sensor.cpp
@@ -22,9 +22,9 @@
 #include <android/sensor.h>
 #include <android/sharedmem.h>
 #include <cutils/native_handle.h>
-#include <gui/Sensor.h>
-#include <gui/SensorManager.h>
-#include <gui/SensorEventQueue.h>
+#include <sensor/Sensor.h>
+#include <sensor/SensorManager.h>
+#include <sensor/SensorEventQueue.h>
 #include <utils/Looper.h>
 #include <utils/RefBase.h>
 #include <utils/Timers.h>
@@ -41,7 +41,7 @@
 /*****************************************************************************/
 #define ERROR_INVALID_PARAMETER(message) ALOGE("%s: " message, __func__)
 
-// frequently used check
+// frequently used checks
 #define RETURN_IF_MANAGER_IS_NULL(retval) do {\
         if (manager == nullptr) { \
             ERROR_INVALID_PARAMETER("manager cannot be NULL"); \
@@ -54,14 +54,18 @@
             return retval; \
         } \
     } while (false)
+#define RETURN_IF_QUEUE_IS_NULL(retval) do {\
+        if (queue == nullptr) { \
+            ERROR_INVALID_PARAMETER("queue cannot be NULL"); \
+            return retval; \
+        } \
+    } while (false)
 
-ASensorManager* ASensorManager_getInstance()
-{
-    return ASensorManager_getInstanceForPackage(NULL);
+ASensorManager* ASensorManager_getInstance() {
+    return ASensorManager_getInstanceForPackage(nullptr);
 }
 
-ASensorManager* ASensorManager_getInstanceForPackage(const char* packageName)
-{
+ASensorManager* ASensorManager_getInstanceForPackage(const char* packageName) {
     if (packageName) {
         return &SensorManager::getInstanceForPackage(String16(packageName));
     } else {
@@ -69,9 +73,8 @@
     }
 }
 
-int ASensorManager_getSensorList(ASensorManager* manager,
-        ASensorList* list)
-{
+int ASensorManager_getSensorList(ASensorManager* manager, ASensorList* list) {
+    RETURN_IF_MANAGER_IS_NULL(android::BAD_VALUE);
     Sensor const* const* l;
     int c = static_cast<SensorManager*>(manager)->getSensorList(&l);
     if (list) {
@@ -80,13 +83,13 @@
     return c;
 }
 
-ASensor const* ASensorManager_getDefaultSensor(ASensorManager* manager, int type)
-{
+ASensor const* ASensorManager_getDefaultSensor(ASensorManager* manager, int type) {
+    RETURN_IF_MANAGER_IS_NULL(nullptr);
     return static_cast<SensorManager*>(manager)->getDefaultSensor(type);
 }
 
-ASensor const* ASensorManager_getDefaultSensorEx(ASensorManager* manager,
-        int type, bool wakeUp) {
+ASensor const* ASensorManager_getDefaultSensorEx(ASensorManager* manager, int type, bool wakeUp) {
+    RETURN_IF_MANAGER_IS_NULL(nullptr);
     Sensor const* const* sensorList;
     size_t size = static_cast<SensorManager*>(manager)->getSensorList(&sensorList);
     for (size_t i = 0; i < size; ++i) {
@@ -95,12 +98,18 @@
             return reinterpret_cast<ASensor const *>(sensorList[i]);
        }
     }
-    return NULL;
+    return nullptr;
 }
 
 ASensorEventQueue* ASensorManager_createEventQueue(ASensorManager* manager,
-        ALooper* looper, int ident, ALooper_callbackFunc callback, void* data)
-{
+        ALooper* looper, int ident, ALooper_callbackFunc callback, void* data) {
+    RETURN_IF_MANAGER_IS_NULL(nullptr);
+
+    if (looper == nullptr) {
+        ERROR_INVALID_PARAMETER("looper cannot be NULL");
+        return nullptr;
+    }
+
     sp<SensorEventQueue> queue =
             static_cast<SensorManager*>(manager)->createEventQueue();
     if (queue != 0) {
@@ -111,17 +120,17 @@
     return static_cast<ASensorEventQueue*>(queue.get());
 }
 
-int ASensorManager_destroyEventQueue(ASensorManager* manager,
-        ASensorEventQueue* inQueue)
-{
-    sp<SensorEventQueue> queue = static_cast<SensorEventQueue*>(inQueue);
-    ALooper_removeFd(queue->looper, queue->getFd());
-    queue->decStrong(manager);
+int ASensorManager_destroyEventQueue(ASensorManager* manager, ASensorEventQueue* queue) {
+    RETURN_IF_MANAGER_IS_NULL(android::BAD_VALUE);
+    RETURN_IF_QUEUE_IS_NULL(android::BAD_VALUE);
+
+    sp<SensorEventQueue> q = static_cast<SensorEventQueue*>(queue);
+    ALooper_removeFd(q->looper, q->getFd());
+    q->decStrong(manager);
     return 0;
 }
 
-int ASensorManager_createSharedMemoryDirectChannel(
-        ASensorManager *manager, int fd, size_t size) {
+int ASensorManager_createSharedMemoryDirectChannel(ASensorManager *manager, int fd, size_t size) {
     RETURN_IF_MANAGER_IS_NULL(android::BAD_VALUE);
 
     if (fd < 0) {
@@ -131,6 +140,7 @@
 
     if (size < sizeof(ASensorEvent)) {
         ERROR_INVALID_PARAMETER("size has to be greater or equal to sizeof(ASensorEvent).");
+        return android::BAD_VALUE;
     }
 
     native_handle_t *resourceHandle = native_handle_create(1 /* nFd */, 0 /* nInt */);
@@ -156,6 +166,7 @@
 
     if (size < sizeof(ASensorEvent)) {
         ERROR_INVALID_PARAMETER("size has to be greater or equal to sizeof(ASensorEvent).");
+        return android::BAD_VALUE;
     }
 
     const native_handle_t *resourceHandle = AHardwareBuffer_getNativeHandle(buffer);
@@ -195,34 +206,51 @@
 /*****************************************************************************/
 
 int ASensorEventQueue_registerSensor(ASensorEventQueue* queue, ASensor const* sensor,
-        int32_t samplingPeriodUs, int maxBatchReportLatencyUs)
-{
+        int32_t samplingPeriodUs, int64_t maxBatchReportLatencyUs) {
+    RETURN_IF_QUEUE_IS_NULL(android::BAD_VALUE);
+    RETURN_IF_SENSOR_IS_NULL(android::BAD_VALUE);
+    if (samplingPeriodUs < 0 || maxBatchReportLatencyUs < 0) {
+        ERROR_INVALID_PARAMETER("samplingPeriodUs and maxBatchReportLatencyUs cannot be negative");
+        return android::BAD_VALUE;
+    }
+
     return static_cast<SensorEventQueue*>(queue)->enableSensor(
             static_cast<Sensor const*>(sensor)->getHandle(), samplingPeriodUs,
                     maxBatchReportLatencyUs, 0);
 }
 
-int ASensorEventQueue_enableSensor(ASensorEventQueue* queue, ASensor const* sensor)
-{
+int ASensorEventQueue_enableSensor(ASensorEventQueue* queue, ASensor const* sensor) {
+    RETURN_IF_QUEUE_IS_NULL(android::BAD_VALUE);
+    RETURN_IF_SENSOR_IS_NULL(android::BAD_VALUE);
+
     return static_cast<SensorEventQueue*>(queue)->enableSensor(
             static_cast<Sensor const*>(sensor));
 }
 
-int ASensorEventQueue_disableSensor(ASensorEventQueue* queue, ASensor const* sensor)
-{
+int ASensorEventQueue_disableSensor(ASensorEventQueue* queue, ASensor const* sensor) {
+    RETURN_IF_QUEUE_IS_NULL(android::BAD_VALUE);
+    RETURN_IF_SENSOR_IS_NULL(android::BAD_VALUE);
+
     return static_cast<SensorEventQueue*>(queue)->disableSensor(
             static_cast<Sensor const*>(sensor));
 }
 
-int ASensorEventQueue_setEventRate(ASensorEventQueue* queue, ASensor const* sensor,
-        int32_t usec)
-{
+int ASensorEventQueue_setEventRate(ASensorEventQueue* queue, ASensor const* sensor, int32_t usec) {
+    RETURN_IF_QUEUE_IS_NULL(android::BAD_VALUE);
+    RETURN_IF_SENSOR_IS_NULL(android::BAD_VALUE);
+
+    if (usec < 0) {
+        ERROR_INVALID_PARAMETER("usec cannot be negative");
+        return android::BAD_VALUE;
+    }
+
     return static_cast<SensorEventQueue*>(queue)->setEventRate(
             static_cast<Sensor const*>(sensor), us2ns(usec));
 }
 
-int ASensorEventQueue_hasEvents(ASensorEventQueue* queue)
-{
+int ASensorEventQueue_hasEvents(ASensorEventQueue* queue) {
+    RETURN_IF_QUEUE_IS_NULL(android::BAD_VALUE);
+
     struct pollfd pfd;
     pfd.fd = static_cast<SensorEventQueue*>(queue)->getFd();
     pfd.events = POLLIN;
@@ -239,9 +267,13 @@
     return (nfd == 0) ? 0 : 1;
 }
 
-ssize_t ASensorEventQueue_getEvents(ASensorEventQueue* queue,
-                ASensorEvent* events, size_t count)
-{
+ssize_t ASensorEventQueue_getEvents(ASensorEventQueue* queue, ASensorEvent* events, size_t count) {
+    RETURN_IF_QUEUE_IS_NULL(android::BAD_VALUE);
+    if (events == nullptr) {
+        ERROR_INVALID_PARAMETER("events cannot be NULL");
+        return android::BAD_VALUE;
+    }
+
     ssize_t actual = static_cast<SensorEventQueue*>(queue)->read(events, count);
     if (actual > 0) {
         static_cast<SensorEventQueue*>(queue)->sendAck(events, actual);
@@ -251,53 +283,53 @@
 
 /*****************************************************************************/
 
-const char* ASensor_getName(ASensor const* sensor)
-{
+const char* ASensor_getName(ASensor const* sensor) {
+    RETURN_IF_SENSOR_IS_NULL(nullptr);
     return static_cast<Sensor const*>(sensor)->getName().string();
 }
 
-const char* ASensor_getVendor(ASensor const* sensor)
-{
+const char* ASensor_getVendor(ASensor const* sensor) {
+    RETURN_IF_SENSOR_IS_NULL(nullptr);
     return static_cast<Sensor const*>(sensor)->getVendor().string();
 }
 
-int ASensor_getType(ASensor const* sensor)
-{
+int ASensor_getType(ASensor const* sensor) {
+    RETURN_IF_SENSOR_IS_NULL(ASENSOR_TYPE_INVALID);
     return static_cast<Sensor const*>(sensor)->getType();
 }
 
-float ASensor_getResolution(ASensor const* sensor)
-{
+float ASensor_getResolution(ASensor const* sensor) {
+    RETURN_IF_SENSOR_IS_NULL(ASENSOR_RESOLUTION_INVALID);
     return static_cast<Sensor const*>(sensor)->getResolution();
 }
 
-int ASensor_getMinDelay(ASensor const* sensor)
-{
+int ASensor_getMinDelay(ASensor const* sensor) {
+    RETURN_IF_SENSOR_IS_NULL(ASENSOR_DELAY_INVALID);
     return static_cast<Sensor const*>(sensor)->getMinDelay();
 }
 
-int ASensor_getFifoMaxEventCount(ASensor const* sensor)
-{
+int ASensor_getFifoMaxEventCount(ASensor const* sensor) {
+    RETURN_IF_SENSOR_IS_NULL(ASENSOR_FIFO_COUNT_INVALID);
     return static_cast<Sensor const*>(sensor)->getFifoMaxEventCount();
 }
 
-int ASensor_getFifoReservedEventCount(ASensor const* sensor)
-{
+int ASensor_getFifoReservedEventCount(ASensor const* sensor) {
+    RETURN_IF_SENSOR_IS_NULL(ASENSOR_FIFO_COUNT_INVALID);
     return static_cast<Sensor const*>(sensor)->getFifoReservedEventCount();
 }
 
-const char* ASensor_getStringType(ASensor const* sensor)
-{
+const char* ASensor_getStringType(ASensor const* sensor) {
+    RETURN_IF_SENSOR_IS_NULL(nullptr);
     return static_cast<Sensor const*>(sensor)->getStringType().string();
 }
 
-int ASensor_getReportingMode(ASensor const* sensor)
-{
+int ASensor_getReportingMode(ASensor const* sensor) {
+    RETURN_IF_SENSOR_IS_NULL(AREPORTING_MODE_INVALID);
     return static_cast<Sensor const*>(sensor)->getReportingMode();
 }
 
-bool ASensor_isWakeUpSensor(ASensor const* sensor)
-{
+bool ASensor_isWakeUpSensor(ASensor const* sensor) {
+    RETURN_IF_SENSOR_IS_NULL(false);
     return static_cast<Sensor const*>(sensor)->isWakeUpSensor();
 }
 
diff --git a/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/DeviceChooserActivity.java b/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/DeviceChooserActivity.java
index 25127ef..12bab18 100644
--- a/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/DeviceChooserActivity.java
+++ b/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/DeviceChooserActivity.java
@@ -92,7 +92,7 @@
         try {
             final PackageManager packageManager = getPackageManager();
             return packageManager.getApplicationLabel(
-                    packageManager.getApplicationInfo(getService().mCallingPackage, 0));
+                    packageManager.getApplicationInfo(getCallingPackage(), 0));
         } catch (PackageManager.NameNotFoundException e) {
             throw new RuntimeException(e);
         }
@@ -128,7 +128,7 @@
     }
 
     protected void onPairTapped(BluetoothDevice selectedDevice) {
-        getService().onDeviceSelected();
+        getService().onDeviceSelected(getCallingPackage(), selectedDevice.getAddress());
         setResult(RESULT_OK,
                 new Intent().putExtra(CompanionDeviceManager.EXTRA_DEVICE, selectedDevice));
         finish();
diff --git a/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/DeviceDiscoveryService.java b/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/DeviceDiscoveryService.java
index 11c722d..f0f9108 100644
--- a/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/DeviceDiscoveryService.java
+++ b/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/DeviceDiscoveryService.java
@@ -33,6 +33,7 @@
 import android.bluetooth.le.ScanSettings;
 import android.companion.AssociationRequest;
 import android.companion.BluetoothLEDeviceFilter;
+import android.companion.CompanionDeviceManager;
 import android.companion.ICompanionDeviceDiscoveryService;
 import android.companion.ICompanionDeviceDiscoveryServiceCallback;
 import android.companion.IFindDeviceCallback;
@@ -71,7 +72,6 @@
     DevicesAdapter mDevicesAdapter;
     IFindDeviceCallback mFindCallback;
     ICompanionDeviceDiscoveryServiceCallback mServiceCallback;
-    String mCallingPackage;
 
     private final ICompanionDeviceDiscoveryService mBinder =
             new ICompanionDeviceDiscoveryService.Stub() {
@@ -88,7 +88,6 @@
             }
             mFindCallback = findCallback;
             mServiceCallback = serviceCallback;
-            mCallingPackage = callingPackage;
             DeviceDiscoveryService.this.startDiscovery(request);
         }
     };
@@ -174,14 +173,6 @@
         return super.onUnbind(intent);
     }
 
-    public void onDeviceSelected() {
-        try {
-            mServiceCallback.onDeviceSelected(mCallingPackage, getUserId());
-        } catch (RemoteException e) {
-            Log.e(LOG_TAG, "Error reporting selected device");
-        }
-    }
-
     private void stopScan() {
         if (DEBUG) Log.i(LOG_TAG, "stopScan() called");
         mBluetoothAdapter.cancelDiscovery();
@@ -234,6 +225,17 @@
         }
     }
 
+    void onDeviceSelected(String callingPackage, String deviceAddress) {
+        try {
+            mServiceCallback.onDeviceSelected(
+                    //TODO is this the right userId?
+                    callingPackage, getUserId(), deviceAddress);
+        } catch (RemoteException e) {
+            Log.e(LOG_TAG, "Failed to record association: "
+                    + callingPackage + " <-> " + deviceAddress);
+        }
+    }
+
     class DevicesAdapter extends ArrayAdapter<BluetoothDevice> {
         private Drawable BLUETOOTH_ICON = icon(android.R.drawable.stat_sys_data_bluetooth);
 
diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeFactory.java b/packages/SystemUI/src/com/android/systemui/doze/DozeFactory.java
index e38f922..5d57daa 100644
--- a/packages/SystemUI/src/com/android/systemui/doze/DozeFactory.java
+++ b/packages/SystemUI/src/com/android/systemui/doze/DozeFactory.java
@@ -53,7 +53,7 @@
 
         DozeMachine machine = new DozeMachine(
                 DozeScreenStatePreventingAdapter.wrapIfNeeded(dozeService, params),
-                config,
+                params,
                 wakeLock);
         machine.setParts(new DozeMachine.Part[]{
                 createDozeTriggers(context, sensorManager, host, config, params, handler, wakeLock,
diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeMachine.java b/packages/SystemUI/src/com/android/systemui/doze/DozeMachine.java
index c852b49..c9eb790 100644
--- a/packages/SystemUI/src/com/android/systemui/doze/DozeMachine.java
+++ b/packages/SystemUI/src/com/android/systemui/doze/DozeMachine.java
@@ -17,12 +17,11 @@
 package com.android.systemui.doze;
 
 import android.annotation.MainThread;
-import android.os.UserHandle;
 import android.util.Log;
 import android.view.Display;
 
-import com.android.internal.hardware.AmbientDisplayConfiguration;
 import com.android.internal.util.Preconditions;
+import com.android.systemui.statusbar.phone.DozeParameters;
 import com.android.systemui.util.Assert;
 
 import java.io.PrintWriter;
@@ -96,17 +95,16 @@
 
     private final Service mDozeService;
     private final DozeFactory.WakeLock mWakeLock;
-    private final AmbientDisplayConfiguration mConfig;
+    private final DozeParameters mParams;
     private Part[] mParts;
 
     private final ArrayList<State> mQueuedRequests = new ArrayList<>();
     private State mState = State.UNINITIALIZED;
     private boolean mWakeLockHeldForCurrentState = false;
 
-    public DozeMachine(Service service, AmbientDisplayConfiguration config,
-            DozeFactory.WakeLock wakeLock) {
+    public DozeMachine(Service service, DozeParameters params, DozeFactory.WakeLock wakeLock) {
         mDozeService = service;
-        mConfig = config;
+        mParams = params;
         mWakeLock = wakeLock;
     }
 
@@ -269,7 +267,7 @@
         switch (state) {
             case INITIALIZED:
             case DOZE_PULSE_DONE:
-                transitionTo(mConfig.alwaysOnEnabled(UserHandle.USER_CURRENT)
+                transitionTo(mParams.getAlwaysOn()
                         ? DozeMachine.State.DOZE_AOD : DozeMachine.State.DOZE);
                 break;
             default:
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/DozeParameters.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/DozeParameters.java
index 7b2e997..4a2ec88 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/DozeParameters.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/DozeParameters.java
@@ -17,6 +17,7 @@
 package com.android.systemui.statusbar.phone;
 
 import android.content.Context;
+import android.os.Build;
 import android.os.SystemProperties;
 import android.os.UserHandle;
 import android.provider.Settings;
@@ -24,7 +25,6 @@
 import android.util.MathUtils;
 import android.util.SparseBooleanArray;
 
-import com.android.internal.hardware.AmbientDisplayConfiguration;
 import com.android.systemui.R;
 
 import java.io.PrintWriter;
@@ -32,15 +32,14 @@
 public class DozeParameters {
     private static final int MAX_DURATION = 60 * 1000;
     public static final String DOZE_SENSORS_WAKE_UP_FULLY = "doze_sensors_wake_up_fully";
+    public static final boolean ALWAYS_ON_AVAILABLE = Build.IS_DEBUGGABLE;
 
     private final Context mContext;
-    private final AmbientDisplayConfiguration mAmbientDisplayConfiguration;
 
     private static IntInOutMatcher sPickupSubtypePerformsProxMatcher;
 
     public DozeParameters(Context context) {
         mContext = context;
-        mAmbientDisplayConfiguration = new AmbientDisplayConfiguration(mContext);
     }
 
     public void dump(PrintWriter pw) {
@@ -59,7 +58,8 @@
         pw.print("    getPickupVibrationThreshold(): "); pw.println(getPickupVibrationThreshold());
         pw.print("    getPickupSubtypePerformsProxCheck(): ");pw.println(
                 dumpPickupSubtypePerformsProxCheck());
-        if (mAmbientDisplayConfiguration.alwaysOnAvailable()) {
+        if (ALWAYS_ON_AVAILABLE) {
+            pw.print("    getAlwaysOn(): "); pw.println(getAlwaysOn());
             pw.print("    getSensorsWakeUpFully(): "); pw.println(getSensorsWakeUpFully());
         }
     }
@@ -119,11 +119,13 @@
     }
 
     public boolean getAlwaysOn() {
-        return mAmbientDisplayConfiguration.alwaysOnEnabled(UserHandle.USER_CURRENT);
+        return ALWAYS_ON_AVAILABLE
+                && Settings.Secure.getIntForUser(mContext.getContentResolver(),
+                Settings.Secure.DOZE_ALWAYS_ON, 0, UserHandle.USER_CURRENT) != 0;
     }
 
     public boolean getSensorsWakeUpFully() {
-        return mAmbientDisplayConfiguration.alwaysOnAvailable()
+        return ALWAYS_ON_AVAILABLE
                 && Settings.Secure.getIntForUser(mContext.getContentResolver(),
                 DOZE_SENSORS_WAKE_UP_FULLY, 1, UserHandle.USER_CURRENT) != 0;
     }
diff --git a/packages/SystemUI/src/com/android/systemui/tuner/TunerFragment.java b/packages/SystemUI/src/com/android/systemui/tuner/TunerFragment.java
index e7bce708..209b439 100644
--- a/packages/SystemUI/src/com/android/systemui/tuner/TunerFragment.java
+++ b/packages/SystemUI/src/com/android/systemui/tuner/TunerFragment.java
@@ -26,11 +26,11 @@
 import android.view.MenuInflater;
 import android.view.MenuItem;
 
-import com.android.internal.hardware.AmbientDisplayConfiguration;
 import com.android.internal.logging.MetricsLogger;
 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
 import com.android.systemui.R;
 import com.android.systemui.plugins.PluginPrefs;
+import com.android.systemui.statusbar.phone.DozeParameters;
 
 public class TunerFragment extends PreferenceFragment {
 
@@ -65,7 +65,7 @@
         if (!PluginPrefs.hasPlugins(getContext())) {
             getPreferenceScreen().removePreference(findPreference(KEY_PLUGINS));
         }
-        if (!alwaysOnAvailable()) {
+        if (!DozeParameters.ALWAYS_ON_AVAILABLE) {
             getPreferenceScreen().removePreference(findPreference(KEY_DOZE));
         }
 
@@ -77,10 +77,6 @@
         }
     }
 
-    private boolean alwaysOnAvailable() {
-        return new AmbientDisplayConfiguration(getContext()).alwaysOnAvailable();
-    }
-
     @Override
     public void onResume() {
         super.onResume();
diff --git a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeMachineTest.java b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeMachineTest.java
index 267580e..32afee9 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeMachineTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeMachineTest.java
@@ -28,9 +28,8 @@
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
-import static org.mockito.ArgumentMatchers.anyInt;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
 import static org.mockito.Mockito.doAnswer;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.never;
@@ -43,7 +42,7 @@
 import android.support.test.runner.AndroidJUnit4;
 import android.view.Display;
 
-import com.android.internal.hardware.AmbientDisplayConfiguration;
+import com.android.systemui.statusbar.phone.DozeParameters;
 
 import org.junit.Before;
 import org.junit.Test;
@@ -57,17 +56,17 @@
 
     private DozeServiceFake mServiceFake;
     private WakeLockFake mWakeLockFake;
-    private AmbientDisplayConfiguration mConfigMock;
+    private DozeParameters mParamsMock;
     private DozeMachine.Part mPartMock;
 
     @Before
     public void setUp() {
         mServiceFake = new DozeServiceFake();
         mWakeLockFake = new WakeLockFake();
-        mConfigMock = mock(AmbientDisplayConfiguration.class);
+        mParamsMock = mock(DozeParameters.class);
         mPartMock = mock(DozeMachine.Part.class);
 
-        mMachine = new DozeMachine(mServiceFake, mConfigMock, mWakeLockFake);
+        mMachine = new DozeMachine(mServiceFake, mParamsMock, mWakeLockFake);
 
         mMachine.setParts(new DozeMachine.Part[]{mPartMock});
     }
@@ -83,7 +82,7 @@
     @Test
     @UiThreadTest
     public void testInitialize_goesToDoze() {
-        when(mConfigMock.alwaysOnEnabled(anyInt())).thenReturn(false);
+        when(mParamsMock.getAlwaysOn()).thenReturn(false);
 
         mMachine.requestState(INITIALIZED);
 
@@ -94,7 +93,7 @@
     @Test
     @UiThreadTest
     public void testInitialize_goesToAod() {
-        when(mConfigMock.alwaysOnEnabled(anyInt())).thenReturn(true);
+        when(mParamsMock.getAlwaysOn()).thenReturn(true);
 
         mMachine.requestState(INITIALIZED);
 
@@ -105,7 +104,7 @@
     @Test
     @UiThreadTest
     public void testPulseDone_goesToDoze() {
-        when(mConfigMock.alwaysOnEnabled(anyInt())).thenReturn(false);
+        when(mParamsMock.getAlwaysOn()).thenReturn(false);
         mMachine.requestState(INITIALIZED);
         mMachine.requestState(DOZE_REQUEST_PULSE);
         mMachine.requestState(DOZE_PULSING);
@@ -119,7 +118,7 @@
     @Test
     @UiThreadTest
     public void testPulseDone_goesToAoD() {
-        when(mConfigMock.alwaysOnEnabled(anyInt())).thenReturn(true);
+        when(mParamsMock.getAlwaysOn()).thenReturn(true);
         mMachine.requestState(INITIALIZED);
         mMachine.requestState(DOZE_REQUEST_PULSE);
         mMachine.requestState(DOZE_PULSING);
diff --git a/proto/src/metrics_constants.proto b/proto/src/metrics_constants.proto
index 819f96c..20aeb11 100644
--- a/proto/src/metrics_constants.proto
+++ b/proto/src/metrics_constants.proto
@@ -3495,6 +3495,36 @@
     // FIELD: The new value of preference when it is changed in Settings
     FIELD_SETTINGS_PREFERENCE_CHANGE_VALUE = 855;
 
+    // OPEN: Notification channel created. CLOSE: Notification channel deleted. UPDATE: notification
+    // channel updated
+    // PACKAGE: the package the channel belongs too
+    // CATEGORY: NOTIFICATION
+    // OS: O
+    ACTION_NOTIFICATION_CHANNEL = 856;
+
+    // Tagged data for notification channel. String.
+    FIELD_NOTIFICATION_CHANNEL_ID = 857;
+
+    // Tagged data for notification channel. int.
+    FIELD_NOTIFICATION_CHANNEL_IMPORTANCE = 858;
+
+    // OPEN: Notification channel group created.
+    // PACKAGE: the package the group belongs to
+    // CATEGORY: NOTIFICATION
+    // OS: O
+    ACTION_NOTIFICATION_CHANNEL_GROUP = 859;
+
+    // Tagged data for notification channel group. String.
+    FIELD_NOTIFICATION_CHANNEL_GROUP_ID = 860;
+
+    // OPEN: Settings > Wi-Fi > Wifi Preferences -> Advanced -> Network Scorer
+    // CATEGORY: SETTINGS
+    // OS: O
+    SETTINGS_NETWORK_SCORER = 861;
+
+    // OPEN: Settings > About device > Model > Hardware info dialog
+    DIALOG_SETTINGS_HARDWARE_INFO = 862;
+
     // ---- End O Constants, all O constants go above this line ----
 
     // Add new aosp constants above this line.
diff --git a/services/autofill/java/com/android/server/autofill/RemoteFillService.java b/services/autofill/java/com/android/server/autofill/RemoteFillService.java
index 04eeb32..7058248 100644
--- a/services/autofill/java/com/android/server/autofill/RemoteFillService.java
+++ b/services/autofill/java/com/android/server/autofill/RemoteFillService.java
@@ -135,13 +135,13 @@
 
     public void onFillRequest(@NonNull AssistStructure structure, @Nullable Bundle extras) {
         cancelScheduledUnbind();
-        PendingFillRequest request = new PendingFillRequest(structure, extras, this);
+        final PendingFillRequest request = new PendingFillRequest(structure, extras, this);
         mHandler.obtainMessageO(MyHandler.MSG_ON_PENDING_REQUEST, request).sendToTarget();
     }
 
     public void onSaveRequest(@NonNull AssistStructure structure, @Nullable Bundle extras) {
         cancelScheduledUnbind();
-        PendingSaveRequest request = new PendingSaveRequest(structure, extras, this);
+        final PendingSaveRequest request = new PendingSaveRequest(structure, extras, this);
         mHandler.obtainMessageO(MyHandler.MSG_ON_PENDING_REQUEST, request).sendToTarget();
     }
 
diff --git a/services/core/java/com/android/server/LockSettingsService.java b/services/core/java/com/android/server/LockSettingsService.java
index d9073f6..bcee2c1b 100644
--- a/services/core/java/com/android/server/LockSettingsService.java
+++ b/services/core/java/com/android/server/LockSettingsService.java
@@ -2220,6 +2220,12 @@
                 Slog.i(TAG, "Postpone disabling escrow tokens until device is provisioned");
                 return;
             }
+
+            // Escrow tokens are enabled on automotive builds.
+            if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
+                return;
+            }
+
             // Disable escrow token permanently on all other device/user types.
             Slog.i(TAG, "Disabling escrow token on user " + userId);
             if (isSyntheticPasswordBasedCredentialLocked(userId)) {
diff --git a/services/core/java/com/android/server/NetworkScoreService.java b/services/core/java/com/android/server/NetworkScoreService.java
index b83dbd6..46c9f25 100644
--- a/services/core/java/com/android/server/NetworkScoreService.java
+++ b/services/core/java/com/android/server/NetworkScoreService.java
@@ -277,8 +277,8 @@
 
     private void refreshBinding() {
         if (DBG) Log.d(TAG, "refreshBinding()");
-        // Apply the default package name if the Setting isn't set.
-        mNetworkScorerAppManager.revertToDefaultIfNoActive();
+        // Make sure the scorer is up-to-date
+        mNetworkScorerAppManager.updateState();
         registerPackageMonitorIfNeeded();
         bindToScoringServiceIfNeeded();
     }
@@ -291,6 +291,10 @@
         final Uri timeoutUri = Global.getUriFor(Global.NETWORK_RECOMMENDATION_REQUEST_TIMEOUT_MS);
         mContentObserver.observe(timeoutUri,
                 ServiceHandler.MSG_RECOMMENDATION_REQUEST_TIMEOUT_CHANGED);
+
+        final Uri settingUri = Global.getUriFor(Global.NETWORK_RECOMMENDATIONS_ENABLED);
+        mContentObserver.observe(settingUri,
+                ServiceHandler.MSG_RECOMMENDATION_ENABLED_SETTING_CHANGED);
     }
 
     /**
@@ -1171,6 +1175,7 @@
         public static final int MSG_RECOMMENDATION_REQUEST_TIMEOUT = 1;
         public static final int MSG_RECOMMENDATIONS_PACKAGE_CHANGED = 2;
         public static final int MSG_RECOMMENDATION_REQUEST_TIMEOUT_CHANGED = 3;
+        public static final int MSG_RECOMMENDATION_ENABLED_SETTING_CHANGED = 4;
 
         public ServiceHandler(Looper looper) {
             super(looper);
@@ -1192,6 +1197,7 @@
                     break;
 
                 case MSG_RECOMMENDATIONS_PACKAGE_CHANGED:
+                case MSG_RECOMMENDATION_ENABLED_SETTING_CHANGED:
                     refreshBinding();
                     break;
 
diff --git a/services/core/java/com/android/server/NetworkScorerAppManager.java b/services/core/java/com/android/server/NetworkScorerAppManager.java
index 90a33a4..5b627d9 100644
--- a/services/core/java/com/android/server/NetworkScorerAppManager.java
+++ b/services/core/java/com/android/server/NetworkScorerAppManager.java
@@ -155,6 +155,11 @@
     @Nullable
     @VisibleForTesting
     public NetworkScorerAppData getActiveScorer() {
+        final int enabledSetting = getNetworkRecommendationsEnabledSetting();
+        if (enabledSetting == NetworkScoreManager.RECOMMENDATIONS_ENABLED_FORCED_OFF) {
+            return null;
+        }
+
         return getScorer(getNetworkRecommendationsPackage());
     }
 
@@ -194,39 +199,73 @@
      */
     @VisibleForTesting
     public boolean setActiveScorer(String packageName) {
-        String oldPackageName = getNetworkRecommendationsPackage();
+        final String oldPackageName = getNetworkRecommendationsPackage();
+
         if (TextUtils.equals(oldPackageName, packageName)) {
             // No change.
             return true;
         }
 
-        Log.i(TAG, "Changing network scorer from " + oldPackageName + " to " + packageName);
-
         if (packageName == null) {
             // revert to the default setting.
-            setNetworkRecommendationsPackage(getDefaultPackageSetting());
+            packageName = getDefaultPackageSetting();
+        }
+
+        Log.i(TAG, "Changing network scorer from " + oldPackageName + " to " + packageName);
+
+        // We only make the change if the new package is valid.
+        if (getScorer(packageName) != null) {
+            setNetworkRecommendationsPackage(packageName);
             return true;
         } else {
-            // We only make the change if the new package is valid.
-            if (getScorer(packageName) != null) {
-                setNetworkRecommendationsPackage(packageName);
-                return true;
-            } else {
-                Log.w(TAG, "Requested network scorer is not valid: " + packageName);
-                return false;
-            }
+            Log.w(TAG, "Requested network scorer is not valid: " + packageName);
+            return false;
         }
     }
 
     /**
-     * If the active scorer is null then revert to the default scorer.
+     * Ensures the {@link Settings.Global#NETWORK_RECOMMENDATIONS_PACKAGE} setting points to a valid
+     * package and {@link Settings.Global#NETWORK_RECOMMENDATIONS_ENABLED} is consistent.
+     *
+     * If {@link Settings.Global#NETWORK_RECOMMENDATIONS_PACKAGE} doesn't point to a valid package
+     * then it will be reverted to the default package specified by
+     * {@link R.string#config_defaultNetworkRecommendationProviderPackage}. If the default package
+     * is no longer valid then {@link Settings.Global#NETWORK_RECOMMENDATIONS_ENABLED} will be set
+     * to <code>0</code> (disabled).
      */
     @VisibleForTesting
-    public void revertToDefaultIfNoActive() {
-        if (getActiveScorer() == null) {
-            final String defaultPackage = getDefaultPackageSetting();
-            setNetworkRecommendationsPackage(defaultPackage);
-            Log.i(TAG, "Defaulted the network recommendations app to: " + defaultPackage);
+    public void updateState() {
+        final int enabledSetting = getNetworkRecommendationsEnabledSetting();
+        if (enabledSetting == NetworkScoreManager.RECOMMENDATIONS_ENABLED_FORCED_OFF) {
+            // Don't change anything if it's forced off.
+            if (DEBUG) Log.d(TAG, "Recommendations forced off.");
+            return;
+        }
+
+        // First, see if the current package is still valid. If so, then we can exit early.
+        final String currentPackageName = getNetworkRecommendationsPackage();
+        if (getScorer(currentPackageName) != null) {
+            if (VERBOSE) Log.v(TAG, currentPackageName + " is the active scorer.");
+            setNetworkRecommendationsEnabledSetting(NetworkScoreManager.RECOMMENDATIONS_ENABLED_ON);
+            return;
+        }
+
+        // the active scorer isn't valid, revert to the default if it's different
+        final String defaultPackageName = getDefaultPackageSetting();
+        if (!TextUtils.equals(currentPackageName, defaultPackageName)) {
+            setNetworkRecommendationsPackage(defaultPackageName);
+            if (DEBUG) {
+                Log.d(TAG, "Defaulted the network recommendations app to: " + defaultPackageName);
+            }
+            if (getScorer(defaultPackageName) != null) { // the default is valid
+                if (DEBUG) Log.d(TAG, defaultPackageName + " is now the active scorer.");
+                setNetworkRecommendationsEnabledSetting(
+                        NetworkScoreManager.RECOMMENDATIONS_ENABLED_ON);
+            } else { // the default isn't valid either, we're disabled at this point
+                if (DEBUG) Log.d(TAG, defaultPackageName + " is not an active scorer.");
+                setNetworkRecommendationsEnabledSetting(
+                        NetworkScoreManager.RECOMMENDATIONS_ENABLED_OFF);
+            }
         }
     }
 
@@ -244,6 +283,15 @@
                 Settings.Global.NETWORK_RECOMMENDATIONS_PACKAGE, packageName);
     }
 
+    private int getNetworkRecommendationsEnabledSetting() {
+        return mSettingsFacade.getInt(mContext, Settings.Global.NETWORK_RECOMMENDATIONS_ENABLED, 0);
+    }
+
+    private void setNetworkRecommendationsEnabledSetting(int value) {
+        mSettingsFacade.putInt(mContext,
+                Settings.Global.NETWORK_RECOMMENDATIONS_ENABLED, value);
+    }
+
     /**
      * Wrapper around Settings to make testing easier.
      */
@@ -255,5 +303,13 @@
         public String getString(Context context, String name) {
             return Settings.Global.getString(context.getContentResolver(), name);
         }
+
+        public boolean putInt(Context context, String name, int value) {
+            return Settings.Global.putInt(context.getContentResolver(), name, value);
+        }
+
+        public int getInt(Context context, String name, int defaultValue) {
+            return Settings.Global.getInt(context.getContentResolver(), name, defaultValue);
+        }
     }
 }
diff --git a/services/core/java/com/android/server/am/ActivityStackSupervisor.java b/services/core/java/com/android/server/am/ActivityStackSupervisor.java
index 6e138a1..bd70861 100644
--- a/services/core/java/com/android/server/am/ActivityStackSupervisor.java
+++ b/services/core/java/com/android/server/am/ActivityStackSupervisor.java
@@ -2770,7 +2770,7 @@
                 // while pausing because that changes the focused stack and may prevent the new
                 // starting activity from resuming.
                 if (moveHomeStackToFront && task.getTaskToReturnTo() == HOME_ACTIVITY_TYPE
-                        && !r.supportsPictureInPictureWhilePausing) {
+                        && (r.state == RESUMED || !r.supportsPictureInPictureWhilePausing)) {
                     // Move the home stack forward if the task we just moved to the pinned stack
                     // was launched from home so home should be visible behind it.
                     moveHomeStackToFront(reason);
diff --git a/services/core/java/com/android/server/notification/NotificationManagerService.java b/services/core/java/com/android/server/notification/NotificationManagerService.java
index 0e767da..be8aaf0 100644
--- a/services/core/java/com/android/server/notification/NotificationManagerService.java
+++ b/services/core/java/com/android/server/notification/NotificationManagerService.java
@@ -2792,6 +2792,7 @@
             dump.put("bans", mRankingHelper.dumpBansJson(filter));
             dump.put("ranking", mRankingHelper.dumpJson(filter));
             dump.put("stats", mUsageStats.dumpJson(filter));
+            dump.put("channels", mRankingHelper.dumpChannelsJson(filter));
         } catch (JSONException e) {
             e.printStackTrace();
         }
diff --git a/services/core/java/com/android/server/notification/NotificationRecord.java b/services/core/java/com/android/server/notification/NotificationRecord.java
index 3016b17..d751a22 100644
--- a/services/core/java/com/android/server/notification/NotificationRecord.java
+++ b/services/core/java/com/android/server/notification/NotificationRecord.java
@@ -778,9 +778,9 @@
                     .addTaggedData(MetricsEvent.NOTIFICATION_TAG, sbn.getTag());
         }
         return mLogMaker
-                .setCategory(MetricsEvent.VIEW_UNKNOWN)
-                .setType(MetricsEvent.TYPE_UNKNOWN)
-                .setSubtype(0)
+                .clearCategory()
+                .clearType()
+                .clearSubtype()
                 .clearTaggedData(MetricsEvent.NOTIFICATION_SHADE_INDEX)
                 .addTaggedData(MetricsEvent.NOTIFICATION_SINCE_CREATE_MILLIS, getLifespanMs(now))
                 .addTaggedData(MetricsEvent.NOTIFICATION_SINCE_UPDATE_MILLIS, getFreshnessMs(now))
diff --git a/services/core/java/com/android/server/notification/RankingHelper.java b/services/core/java/com/android/server/notification/RankingHelper.java
index 53d1068..6097071 100644
--- a/services/core/java/com/android/server/notification/RankingHelper.java
+++ b/services/core/java/com/android/server/notification/RankingHelper.java
@@ -19,6 +19,8 @@
 
 import com.android.internal.R;
 import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.logging.MetricsLogger;
+import com.android.internal.logging.nano.MetricsProto;
 import com.android.internal.util.Preconditions;
 
 import android.app.Notification;
@@ -30,6 +32,7 @@
 import android.content.pm.PackageManager;
 import android.content.pm.PackageManager.NameNotFoundException;
 import android.content.pm.ParceledListSlice;
+import android.metrics.LogMaker;
 import android.os.Build;
 import android.os.UserHandle;
 import android.provider.Settings;
@@ -485,6 +488,12 @@
         if (r == null) {
             throw new IllegalArgumentException("Invalid package");
         }
+        LogMaker lm = new LogMaker(MetricsProto.MetricsEvent.ACTION_NOTIFICATION_CHANNEL_GROUP)
+                .setType(MetricsProto.MetricsEvent.TYPE_UPDATE)
+                .addTaggedData(MetricsProto.MetricsEvent.FIELD_NOTIFICATION_CHANNEL_GROUP_ID,
+                        group.getId())
+                .setPackageName(pkg);
+        MetricsLogger.action(lm);
         r.groups.put(group.getId(), group);
         updateConfig();
     }
@@ -512,12 +521,16 @@
         }
 
         NotificationChannel existing = r.channels.get(channel.getId());
-        // Keep existing settings
-        if (existing != null) {
+        // Keep existing settings, except deleted status and name
+        if (existing != null && fromTargetApp) {
             if (existing.isDeleted()) {
                 existing.setDeleted(false);
-                updateConfig();
             }
+
+            existing.setNameResId(channel.getNameResId());
+
+            MetricsLogger.action(getChannelLog(channel, pkg));
+            updateConfig();
             return;
         }
         if (channel.getImportance() < NotificationManager.IMPORTANCE_NONE
@@ -541,6 +554,8 @@
                     Notification.AUDIO_ATTRIBUTES_DEFAULT);
         }
         r.channels.put(channel.getId(), channel);
+        MetricsLogger.action(getChannelLog(channel, pkg).setType(
+                MetricsProto.MetricsEvent.TYPE_OPEN));
         updateConfig();
     }
 
@@ -568,6 +583,8 @@
             updatedChannel.setLockscreenVisibility(Ranking.VISIBILITY_NO_OVERRIDE);
         }
         r.channels.put(updatedChannel.getId(), updatedChannel);
+
+        MetricsLogger.action(getChannelLog(updatedChannel, pkg));
         updateConfig();
     }
 
@@ -615,6 +632,7 @@
         }
         // Assistant cannot change the group
 
+        MetricsLogger.action(getChannelLog(channel, pkg));
         r.channels.put(channel.getId(), channel);
         updateConfig();
     }
@@ -664,6 +682,9 @@
         if (channel != null) {
             channel.setDeleted(true);
         }
+        LogMaker lm = getChannelLog(channel, pkg);
+        lm.setType(MetricsProto.MetricsEvent.TYPE_CLOSE);
+        MetricsLogger.action(lm);
     }
 
     @Override
@@ -935,6 +956,49 @@
         return packageBans;
     }
 
+    /**
+     * Dump only the channel information as structured JSON for the stats collector.
+     *
+     * This is intentionally redundant with {#link dumpJson} because the old
+     * scraper will expect this format.
+     *
+     * @param filter
+     * @return
+     */
+    public JSONArray dumpChannelsJson(NotificationManagerService.DumpFilter filter) {
+        JSONArray channels = new JSONArray();
+        Map<String, Integer> packageChannels = getPackageChannels();
+        for(Entry<String, Integer> channelCount : packageChannels.entrySet()) {
+            final String packageName = channelCount.getKey();
+            if (filter == null || filter.matches(packageName)) {
+                JSONObject channelCountJson = new JSONObject();
+                try {
+                    channelCountJson.put("packageName", packageName);
+                    channelCountJson.put("channelCount", channelCount.getValue());
+                } catch (JSONException e) {
+                    e.printStackTrace();
+                }
+                channels.put(channelCountJson);
+            }
+        }
+        return channels;
+    }
+
+    private Map<String, Integer> getPackageChannels() {
+        ArrayMap<String, Integer> packageChannels = new ArrayMap<>();
+        for (int i = 0; i < mRecords.size(); i++) {
+            final Record r = mRecords.valueAt(i);
+            int channelCount = 0;
+            for (int j = 0; j < r.channels.size();j++) {
+                if (!r.channels.valueAt(j).isDeleted()) {
+                    channelCount++;
+                }
+            }
+            packageChannels.put(r.pkg, channelCount);
+        }
+        return packageChannels;
+    }
+
     public void onPackagesChanged(boolean removingPackage, int changeUserId, String[] pkgList,
             int[] uidList) {
         if (pkgList == null || pkgList.length == 0) {
@@ -982,6 +1046,16 @@
         }
     }
 
+    private LogMaker getChannelLog(NotificationChannel channel, String pkg) {
+        return new LogMaker(MetricsProto.MetricsEvent.ACTION_NOTIFICATION_CHANNEL)
+                .setType(MetricsProto.MetricsEvent.TYPE_UPDATE)
+                .setPackageName(pkg)
+                .addTaggedData(MetricsProto.MetricsEvent.FIELD_NOTIFICATION_CHANNEL_ID,
+                        channel.getId())
+                .addTaggedData(MetricsProto.MetricsEvent.FIELD_NOTIFICATION_CHANNEL_IMPORTANCE,
+                        channel.getImportance());
+    }
+
     private static class Record {
         static int UNKNOWN_UID = UserHandle.USER_NULL;
 
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index 6450a46..e2358c2 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -8721,60 +8721,9 @@
             return;
         }
         destroyAppProfilesLeafLIF(pkg);
-        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
         for (int i = 0; i < childCount; i++) {
             destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
-            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
-                    true /* removeBaseMarker */);
-        }
-    }
-
-    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
-            boolean removeBaseMarker) {
-        if (pkg.isForwardLocked()) {
-            return;
-        }
-
-        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
-            try {
-                path = PackageManagerServiceUtils.realpath(new File(path));
-            } catch (IOException e) {
-                // TODO: Should we return early here ?
-                Slog.w(TAG, "Failed to get canonical path", e);
-                continue;
-            }
-
-            final String useMarker = path.replace('/', '@');
-            for (int realUserId : resolveUserIds(userId)) {
-                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
-                if (removeBaseMarker) {
-                    File foreignUseMark = new File(profileDir, useMarker);
-                    if (foreignUseMark.exists()) {
-                        if (!foreignUseMark.delete()) {
-                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
-                                    + pkg.packageName);
-                        }
-                    }
-                }
-
-                File[] markers = profileDir.listFiles();
-                if (markers != null) {
-                    final String searchString = "@" + pkg.packageName + "@";
-                    // We also delete all markers that contain the package name we're
-                    // uninstalling. These are associated with secondary dex-files belonging
-                    // to the package. Reconstructing the path of these dex files is messy
-                    // in general.
-                    for (File marker : markers) {
-                        if (marker.getName().indexOf(searchString) > 0) {
-                            if (!marker.delete()) {
-                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
-                                    + pkg.packageName);
-                            }
-                        }
-                    }
-                }
-            }
         }
     }
 
@@ -8792,10 +8741,6 @@
             return;
         }
         clearAppProfilesLeafLIF(pkg);
-        // We don't remove the base foreign use marker when clearing profiles because
-        // we will rename it when the app is updated. Unlike the actual profile contents,
-        // the foreign use marker is good across installs.
-        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
         for (int i = 0; i < childCount; i++) {
             clearAppProfilesLeafLIF(pkg.childPackages.get(i));
@@ -10056,15 +10001,6 @@
         synchronized (mPackages) {
             // We don't expect installation to fail beyond this point
 
-            if (pkgSetting.pkg != null) {
-                // Note that |user| might be null during the initial boot scan. If a codePath
-                // for an app has changed during a boot scan, it's due to an app update that's
-                // part of the system partition and marker changes must be applied to all users.
-                final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier();
-                final int[] userIds = resolveUserIds(userId);
-                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds);
-            }
-
             // Add the new setting to mSettings
             mSettings.insertPackageSettingLPw(pkgSetting, pkg);
             // Add the new setting to mPackages
@@ -10398,74 +10334,6 @@
         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
     }
 
-    private static void maybeRenameForeignDexMarkers(PackageParser.Package existing,
-            PackageParser.Package update, int[] userIds) {
-        if (existing.applicationInfo == null || update.applicationInfo == null) {
-            // This isn't due to an app installation.
-            return;
-        }
-
-        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
-        final File newCodePath = new File(update.applicationInfo.getCodePath());
-
-        // The codePath hasn't changed, so there's nothing for us to do.
-        if (Objects.equals(oldCodePath, newCodePath)) {
-            return;
-        }
-
-        File canonicalNewCodePath;
-        try {
-            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
-        } catch (IOException e) {
-            Slog.w(TAG, "Failed to get canonical path.", e);
-            return;
-        }
-
-        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
-        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
-        // that the last component of the path (i.e, the name) doesn't need canonicalization
-        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
-        // but may change in the future. Hopefully this function won't exist at that point.
-        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
-                oldCodePath.getName());
-
-        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
-        // with "@".
-        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
-        if (!oldMarkerPrefix.endsWith("@")) {
-            oldMarkerPrefix += "@";
-        }
-        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
-        if (!newMarkerPrefix.endsWith("@")) {
-            newMarkerPrefix += "@";
-        }
-
-        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
-        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
-        for (String updatedPath : updatedPaths) {
-            String updatedPathName = new File(updatedPath).getName();
-            markerSuffixes.add(updatedPathName.replace('/', '@'));
-        }
-
-        for (int userId : userIds) {
-            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
-
-            for (String markerSuffix : markerSuffixes) {
-                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
-                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
-                if (oldForeignUseMark.exists()) {
-                    try {
-                        Os.rename(oldForeignUseMark.getAbsolutePath(),
-                                newForeignUseMark.getAbsolutePath());
-                    } catch (ErrnoException e) {
-                        Slog.w(TAG, "Failed to rename foreign use marker", e);
-                        oldForeignUseMark.delete();
-                    }
-                }
-            }
-        }
-    }
-
     /**
      * Derive the ABI of a non-system package located at {@code scanFile}. This information
      * is derived purely on the basis of the contents of {@code scanFile} and
@@ -17541,6 +17409,7 @@
         }
 
         PackageSetting uninstalledPs = null;
+        PackageParser.Package pkg = null;
 
         // for the uninstall-updates case and restricted profiles, remember the per-
         // user handle installed state
@@ -17561,7 +17430,7 @@
 
             // Static shared libs can be declared by any package, so let us not
             // allow removing a package if it provides a lib others depend on.
-            PackageParser.Package pkg = mPackages.get(packageName);
+            pkg = mPackages.get(packageName);
             if (pkg != null && pkg.staticSharedLibName != null) {
                 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
                         pkg.staticSharedLibVersion);
@@ -17600,8 +17469,9 @@
             }
             synchronized (mPackages) {
                 if (res) {
-                    mInstantAppRegistry.onPackageUninstalledLPw(uninstalledPs.pkg,
-                            info.removedUsers);
+                    if (pkg != null) {
+                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
+                    }
                     updateSequenceNumberLP(packageName, info.removedUsers);
                 }
             }
@@ -18448,8 +18318,6 @@
         try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
             synchronized (mInstallLock) {
                 clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
-                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
-                        true /* removeBaseMarker */);
             }
         }
     }
@@ -18757,11 +18625,8 @@
     @Override
     public void getPackageSizeInfo(final String packageName, int userHandle,
             final IPackageStatsObserver observer) {
-        Slog.w(TAG, "Shame on you for calling a hidden API. Shame!");
-        try {
-            observer.onGetStatsCompleted(null, false);
-        } catch (Throwable ignored) {
-        }
+        throw new UnsupportedOperationException(
+                "Shame on you for calling a hidden API. Shame!");
     }
 
     private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
diff --git a/services/core/java/com/android/server/storage/AppCollector.java b/services/core/java/com/android/server/storage/AppCollector.java
index ee9c5bf..25880fb 100644
--- a/services/core/java/com/android/server/storage/AppCollector.java
+++ b/services/core/java/com/android/server/storage/AppCollector.java
@@ -17,6 +17,8 @@
 package com.android.server.storage;
 
 import android.annotation.NonNull;
+import android.app.usage.StorageStats;
+import android.app.usage.StorageStatsManager;
 import android.content.Context;
 import android.content.pm.ApplicationInfo;
 import android.content.pm.IPackageStatsObserver;
@@ -64,7 +66,8 @@
         mBackgroundHandler = new BackgroundHandler(BackgroundThread.get().getLooper(),
                 volume,
                 context.getPackageManager(),
-                (UserManager) context.getSystemService(Context.USER_SERVICE));
+                (UserManager) context.getSystemService(Context.USER_SERVICE),
+                (StorageStatsManager) context.getSystemService(Context.STORAGE_STATS_SERVICE));
     }
 
     /**
@@ -93,39 +96,20 @@
         return value;
     }
 
-    private class StatsObserver extends IPackageStatsObserver.Stub {
-        private AtomicInteger mCount;
-        private final ArrayList<PackageStats> mPackageStats;
-
-        public StatsObserver(int count) {
-            mCount = new AtomicInteger(count);
-            mPackageStats = new ArrayList<>(count);
-        }
-
-        @Override
-        public void onGetStatsCompleted(PackageStats packageStats, boolean succeeded)
-                throws RemoteException {
-            if (succeeded) {
-                mPackageStats.add(packageStats);
-            }
-
-            if (mCount.decrementAndGet() == 0) {
-                mStats.complete(mPackageStats);
-            }
-        }
-    }
-
     private class BackgroundHandler extends Handler {
         static final int MSG_START_LOADING_SIZES = 0;
         private final VolumeInfo mVolume;
         private final PackageManager mPm;
         private final UserManager mUm;
+        private final StorageStatsManager mStorageStatsManager;
 
-        BackgroundHandler(Looper looper, @NonNull VolumeInfo volume, PackageManager pm, UserManager um) {
+        BackgroundHandler(Looper looper, @NonNull VolumeInfo volume,
+                PackageManager pm, UserManager um, StorageStatsManager storageStatsManager) {
             super(looper);
             mVolume = volume;
             mPm = pm;
             mUm = um;
+            mStorageStatsManager = storageStatsManager;
         }
 
         @Override
@@ -149,14 +133,20 @@
                         mStats.complete(new ArrayList<>());
                     }
 
-                    // Kick off the async package size query for all apps.
-                    final StatsObserver observer = new StatsObserver(count);
+                    List<PackageStats> stats = new ArrayList<>();
                     for (UserInfo user : users) {
                         for (ApplicationInfo app : volumeApps) {
-                            mPm.getPackageSizeInfoAsUser(app.packageName, user.id,
-                                    observer);
+                            PackageStats packageStats = new PackageStats(app.packageName, user.id);
+                            StorageStats storageStats = mStorageStatsManager.queryStatsForPackage(
+                                    app.volumeUuid, app.packageName, user.getUserHandle());
+                            packageStats.cacheSize = storageStats.getCacheBytes();
+                            packageStats.codeSize = storageStats.getCodeBytes();
+                            packageStats.dataSize = storageStats.getDataBytes();
+                            stats.add(packageStats);
                         }
                     }
+
+                    mStats.complete(stats);
                 }
             }
         }
diff --git a/services/core/java/com/android/server/wm/AppWindowToken.java b/services/core/java/com/android/server/wm/AppWindowToken.java
index 4aa013a..647adbf 100644
--- a/services/core/java/com/android/server/wm/AppWindowToken.java
+++ b/services/core/java/com/android/server/wm/AppWindowToken.java
@@ -785,16 +785,6 @@
         if (canFreezeBounds()) {
             freezeBounds();
         }
-
-        // In the process of tearing down before relaunching, the app will
-        // try and clean up it's child surfaces. We need to prevent this from
-        // happening, so we sever the children, transfering their ownership
-        // from the client it-self to the parent surface (owned by us).
-        for (int i = mChildren.size() - 1; i >= 0; i--) {
-            final WindowState w = mChildren.get(i);
-            w.mWinAnimator.detachChildren();
-        }
-
         mPendingRelaunchCount++;
     }
 
diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java
index 66ec8f0..8b62236 100644
--- a/services/core/java/com/android/server/wm/WindowManagerService.java
+++ b/services/core/java/com/android/server/wm/WindowManagerService.java
@@ -2199,15 +2199,6 @@
         if (mAccessibilityController != null && win.getDisplayId() == DEFAULT_DISPLAY) {
             mAccessibilityController.onWindowTransitionLocked(win, transit);
         }
-
-        // When we start the exit animation we take the Surface from the client
-        // so it will stop perturbing it. We need to likewise takeaway the SurfaceFlinger
-        // side child surfaces, so they will remain preserved in their current state
-        // (rather than be cleaned up immediately by the app code).
-        SurfaceControl.openTransaction();
-        winAnimator.detachChildren();
-        SurfaceControl.closeTransaction();
-
         return focusMayChange;
     }
 
diff --git a/services/core/java/com/android/server/wm/WindowState.java b/services/core/java/com/android/server/wm/WindowState.java
index 4806068..6d572d7 100644
--- a/services/core/java/com/android/server/wm/WindowState.java
+++ b/services/core/java/com/android/server/wm/WindowState.java
@@ -1532,13 +1532,6 @@
             return changed;
         }
 
-        // Next up we will notify the client that it's visibility has changed.
-        // We need to prevent it from destroying child surfaces until
-        // the animation has finished.
-        if (!visible && isVisibleNow()) {
-            mWinAnimator.detachChildren();
-        }
-
         if (visible != isVisibleNow()) {
             if (!runningAppAnimation) {
                 final AccessibilityController accessibilityController =
diff --git a/services/core/java/com/android/server/wm/WindowStateAnimator.java b/services/core/java/com/android/server/wm/WindowStateAnimator.java
index 0b1f906..98598e1 100644
--- a/services/core/java/com/android/server/wm/WindowStateAnimator.java
+++ b/services/core/java/com/android/server/wm/WindowStateAnimator.java
@@ -566,20 +566,6 @@
         if (!mDestroyPreservedSurfaceUponRedraw) {
             return;
         }
-        if (mSurfaceController != null) {
-            if (mPendingDestroySurface != null) {
-                // If we are preserving a surface but we aren't relaunching that means
-                // we are just doing an in-place switch. In that case any SurfaceFlinger side
-                // child layers need to be reparented to the new surface to make this
-                // transparent to the app.
-                if (mWin.mAppToken == null || mWin.mAppToken.isRelaunching() == false) {
-                    SurfaceControl.openTransaction();
-                    mPendingDestroySurface.reparentChildrenInTransaction(mSurfaceController);
-                    SurfaceControl.closeTransaction();
-                }
-            }
-        }
-
         destroyDeferredSurfaceLocked();
         mDestroyPreservedSurfaceUponRedraw = false;
     }
@@ -1979,11 +1965,4 @@
         }
         return mForceScaleUntilResize;
     }
-
-    void detachChildren() {
-        Slog.i(TAG, "detaching children: " + this);
-        if (mSurfaceController != null) {
-            mSurfaceController.detachChildren();
-        }
-    }
 }
diff --git a/services/core/java/com/android/server/wm/WindowSurfaceController.java b/services/core/java/com/android/server/wm/WindowSurfaceController.java
index f7d3343..f8e7428 100644
--- a/services/core/java/com/android/server/wm/WindowSurfaceController.java
+++ b/services/core/java/com/android/server/wm/WindowSurfaceController.java
@@ -135,20 +135,6 @@
         }
     }
 
-    void reparentChildrenInTransaction(WindowSurfaceController other) {
-        if (SHOW_TRANSACTIONS) Slog.i(TAG, "REPARENT from: " + this + " to: " + other);
-        if ((mSurfaceControl != null) && (other.mSurfaceControl != null)) {
-            mSurfaceControl.reparentChildren(other.getHandle());
-        }
-    }
-
-    void detachChildren() {
-        if (SHOW_TRANSACTIONS) Slog.i(TAG, "SEVER CHILDREN");
-        if (mSurfaceControl != null) {
-            mSurfaceControl.detachChildren();
-        }
-    }
-
     void hideInTransaction(String reason) {
         if (SHOW_TRANSACTIONS) logSurface("HIDE ( " + reason + " )", null);
         mHiddenForOtherReasons = true;
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/SecurityLogMonitor.java b/services/devicepolicy/java/com/android/server/devicepolicy/SecurityLogMonitor.java
index 18f06be..2413561 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/SecurityLogMonitor.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/SecurityLogMonitor.java
@@ -69,6 +69,10 @@
      */
     private static final long RATE_LIMIT_INTERVAL_MILLISECONDS = TimeUnit.HOURS.toMillis(2);
     /**
+     * How often to retry the notification about available logs if it is ignored or missed by DO.
+     */
+    private static final long BROADCAST_RETRY_INTERVAL_MILLISECONDS = TimeUnit.MINUTES.toMillis(30);
+    /**
      * Internally how often should the monitor poll the security logs from logd.
      */
     private static final long POLLING_INTERVAL_MILLISECONDS = TimeUnit.MINUTES.toMillis(1);
@@ -82,7 +86,7 @@
 
     /**
      * When DO will be allowed to retrieve the log, in milliseconds since boot (as per
-     * {@link SystemClock#elapsedRealtime()})
+     * {@link SystemClock#elapsedRealtime()}). After that it will mark the time to retry broadcast.
      */
     @GuardedBy("mLock")
     private long mNextAllowedRetrievalTimeMillis = -1;
@@ -256,36 +260,35 @@
     }
 
     private void notifyDeviceOwnerIfNeeded() throws InterruptedException {
-        boolean shouldNotifyDO = false;
-        boolean allowToRetrieveNow = false;
+        boolean allowRetrievalAndNotifyDO = false;
         mLock.lockInterruptibly();
         try {
             if (mPaused) {
                 return;
             }
-
-            // STOPSHIP(b/34186771): If the previous notification didn't reach the DO and logs were
-            // not retrieved (e.g. the broadcast was sent before the user was unlocked), no more
-            // subsequent callbacks will be sent. We should make sure that the DO gets notified
-            // before logs are lost.
-            int logSize = mPendingLogs.size();
+            final int logSize = mPendingLogs.size();
             if (logSize >= BUFFER_ENTRIES_NOTIFICATION_LEVEL) {
                 // Allow DO to retrieve logs if too many pending logs
-                allowToRetrieveNow = true;
-                if (DEBUG) Slog.d(TAG, "Number of log entries over threshold: " + logSize);
-            } else if (logSize > 0) {
-                if (SystemClock.elapsedRealtime() >= mNextAllowedRetrievalTimeMillis) {
-                    // Rate limit reset
-                    allowToRetrieveNow = true;
-                    if (DEBUG) Slog.d(TAG, "Timeout reached");
+                if (!mAllowedToRetrieve) {
+                    allowRetrievalAndNotifyDO = true;
                 }
+                if (DEBUG) Slog.d(TAG, "Number of log entries over threshold: " + logSize);
             }
-            shouldNotifyDO = (!mAllowedToRetrieve) && allowToRetrieveNow;
-            mAllowedToRetrieve = allowToRetrieveNow;
+            if (logSize > 0 && SystemClock.elapsedRealtime() >= mNextAllowedRetrievalTimeMillis) {
+                // Rate limit reset
+                allowRetrievalAndNotifyDO = true;
+                if (DEBUG) Slog.d(TAG, "Timeout reached");
+            }
+            if (allowRetrievalAndNotifyDO) {
+                mAllowedToRetrieve = true;
+                // Set the timeout to retry the notification if the DO misses it.
+                mNextAllowedRetrievalTimeMillis = SystemClock.elapsedRealtime()
+                        + BROADCAST_RETRY_INTERVAL_MILLISECONDS;
+            }
         } finally {
             mLock.unlock();
         }
-        if (shouldNotifyDO) {
+        if (allowRetrievalAndNotifyDO) {
             Slog.i(TAG, "notify DO");
             mService.sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_SECURITY_LOGS_AVAILABLE,
                     null);
diff --git a/services/print/java/com/android/server/print/CompanionDeviceManagerService.java b/services/print/java/com/android/server/print/CompanionDeviceManagerService.java
index 9ac8295..ad64e4e 100644
--- a/services/print/java/com/android/server/print/CompanionDeviceManagerService.java
+++ b/services/print/java/com/android/server/print/CompanionDeviceManagerService.java
@@ -20,6 +20,7 @@
 import static com.android.internal.util.Preconditions.checkNotNull;
 
 import android.Manifest;
+import android.annotation.Nullable;
 import android.companion.AssociationRequest;
 import android.companion.CompanionDeviceManager;
 import android.companion.ICompanionDeviceDiscoveryService;
@@ -34,16 +35,39 @@
 import android.content.pm.PackageManager;
 import android.net.NetworkPolicyManager;
 import android.os.Binder;
+import android.os.Environment;
 import android.os.IBinder;
 import android.os.IDeviceIdleController;
 import android.os.RemoteException;
 import android.os.ServiceManager;
+import android.os.UserHandle;
+import android.util.AtomicFile;
+import android.util.ExceptionUtils;
 import android.util.Slog;
+import android.util.Xml;
 
 import com.android.internal.util.ArrayUtils;
 import com.android.server.SystemService;
 
+import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
+import org.xmlpull.v1.XmlSerializer;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.function.Function;
+
 //TODO move to own package!
+//TODO un/linkToDeath & onBinderDied - unbind
+//TODO onStop schedule unbind in 5 seconds
+//TODO Prune association on app uninstall
 /** @hide */
 public class CompanionDeviceManagerService extends SystemService {
 
@@ -54,7 +78,14 @@
     private static final boolean DEBUG = false;
     private static final String LOG_TAG = "CompanionDeviceManagerService";
 
+    private static final String XML_TAG_ASSOCIATIONS = "associations";
+    private static final String XML_TAG_ASSOCIATION = "association";
+    private static final String XML_ATTR_PACKAGE = "package";
+    private static final String XML_ATTR_DEVICE = "device";
+    private static final String XML_FILE_NAME = "companion_device_manager_associations.xml";
+
     private final CompanionDeviceManagerImpl mImpl;
+    private final ConcurrentMap<Integer, AtomicFile> mUidToStorage = new ConcurrentHashMap<>();
 
     public CompanionDeviceManagerService(Context context) {
         super(context);
@@ -89,6 +120,24 @@
                 Binder.restoreCallingIdentity(callingIdentity);
             }
         }
+
+
+        @Override
+        public List<String> getAssociations(String callingPackage) {
+            return ArrayUtils.map(
+                    readAllAssociations(getUserId(), callingPackage),
+                    (a) -> a.deviceAddress);
+        }
+
+        @Override
+        public void disassociate(String deviceMacAddress, String callingPackage) {
+            updateAssociations((associations) -> ArrayUtils.remove(associations,
+                    new Association(getUserId(), checkNotNull(deviceMacAddress), callingPackage)));
+        }
+    }
+
+    private int getUserId() {
+        return UserHandle.getUserId(Binder.getCallingUid());
     }
 
     private ServiceConnection getServiceConnection(
@@ -125,9 +174,12 @@
 
     private ICompanionDeviceDiscoveryServiceCallback.Stub getServiceCallback() {
         return new ICompanionDeviceDiscoveryServiceCallback.Stub() {
+
             @Override
-            public void onDeviceSelected(String packageName, int userId) {
+            public void onDeviceSelected(String packageName, int userId, String deviceAddress) {
+                //TODO unbind
                 grantSpecialAccessPermissionsIfNeeded(packageName, userId);
+                recordAssociation(packageName, deviceAddress);
             }
         };
     }
@@ -136,14 +188,14 @@
         final long identity = Binder.clearCallingIdentity();
         final PackageInfo packageInfo;
         try {
-            packageInfo = getContext().getPackageManager().getPackageInfoAsUser(
-                    packageName, PackageManager.GET_PERMISSIONS, userId);
-        } catch (PackageManager.NameNotFoundException e) {
-            Slog.e(LOG_TAG, "Error granting special access permissions to package:"
-                    + packageName, e);
-            return;
-        }
-        try {
+            try {
+                packageInfo = getContext().getPackageManager().getPackageInfoAsUser(
+                        packageName, PackageManager.GET_PERMISSIONS, userId);
+            } catch (PackageManager.NameNotFoundException e) {
+                Slog.e(LOG_TAG, "Error granting special access permissions to package:"
+                        + packageName, e);
+                return;
+            }
             if (ArrayUtils.contains(packageInfo.requestedPermissions,
                     Manifest.permission.RUN_IN_BACKGROUND)) {
                 IDeviceIdleController idleController = IDeviceIdleController.Stub.asInterface(
@@ -164,4 +216,134 @@
             Binder.restoreCallingIdentity(identity);
         }
     }
+
+    private void recordAssociation(String priviledgedPackage, String deviceAddress) {
+        updateAssociations((associations) -> ArrayUtils.add(associations,
+                new Association(getUserId(), deviceAddress, priviledgedPackage)));
+    }
+
+    private void updateAssociations(
+            Function<ArrayList<Association>, ArrayList<Association>> update) {
+        final int userId = getUserId();
+        final AtomicFile file = getStorageFileForUser(userId);
+        synchronized (file) {
+            final ArrayList<Association> old = readAllAssociations(userId);
+            final ArrayList<Association> associations = update.apply(old);
+            if (Objects.equals(old, associations)) return;
+
+            file.write((out) -> {
+                XmlSerializer xml = Xml.newSerializer();
+                try {
+                    xml.setOutput(out, StandardCharsets.UTF_8.name());
+                    xml.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
+                    xml.startDocument(null, true);
+                    xml.startTag(null, XML_TAG_ASSOCIATIONS);
+
+                    for (int i = 0; i < ArrayUtils.size(associations); i++) {
+                        Association association = associations.get(i);
+                        xml.startTag(null, XML_TAG_ASSOCIATION)
+                            .attribute(null, XML_ATTR_PACKAGE, association.companionAppPackage)
+                            .attribute(null, XML_ATTR_DEVICE, association.deviceAddress)
+                            .endTag(null, XML_TAG_ASSOCIATION);
+                    }
+
+                    xml.endTag(null, XML_TAG_ASSOCIATIONS);
+                    xml.endDocument();
+                } catch (Exception e) {
+                    Slog.e(LOG_TAG, "Error while writing associations file", e);
+                    throw ExceptionUtils.propagate(e);
+                }
+
+            });
+        }
+
+
+        //TODO Show dialog before recording notification access
+//        final SettingStringHelper setting =
+//                new SettingStringHelper(
+//                        getContext().getContentResolver(),
+//                        Settings.Secure.ENABLED_NOTIFICATION_LISTENERS,
+//                        getUserId());
+//        setting.write(ColonDelimitedSet.OfStrings.add(setting.read(), priviledgedPackage));
+    }
+
+    private AtomicFile getStorageFileForUser(int uid) {
+        return mUidToStorage.computeIfAbsent(uid, (u) ->
+                new AtomicFile(new File(
+                        //TODO deprecated method - what's the right replacement?
+                        Environment.getUserSystemDirectory(u),
+                        XML_FILE_NAME)));
+    }
+
+    @Nullable
+    private ArrayList<Association> readAllAssociations(int uid) {
+        return readAllAssociations(uid, null);
+    }
+
+    @Nullable
+    private ArrayList<Association> readAllAssociations(int userId, @Nullable String packageFilter) {
+        final AtomicFile file = getStorageFileForUser(userId);
+
+        if (!file.getBaseFile().exists()) return null;
+
+        ArrayList<Association> result = null;
+        final XmlPullParser parser = Xml.newPullParser();
+        synchronized (file) {
+            try (FileInputStream in = file.openRead()) {
+                parser.setInput(in, StandardCharsets.UTF_8.name());
+                int type;
+                while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
+                    if (type != XmlPullParser.START_TAG
+                            && !XML_TAG_ASSOCIATIONS.equals(parser.getName())) continue;
+
+                    final String appPackage = parser.getAttributeValue(null, XML_ATTR_PACKAGE);
+                    final String deviceAddress = parser.getAttributeValue(null, XML_ATTR_DEVICE);
+
+                    if (appPackage == null || deviceAddress == null) continue;
+                    if (packageFilter != null && !packageFilter.equals(appPackage)) continue;
+
+                    result = ArrayUtils.add(result,
+                            new Association(userId, deviceAddress, appPackage));
+                }
+                return result;
+            } catch (XmlPullParserException | IOException e) {
+                Slog.e(LOG_TAG, "Error while reading associations file", e);
+                return null;
+            }
+        }
+    }
+
+    private class Association {
+        public final int uid;
+        public final String deviceAddress;
+        public final String companionAppPackage;
+
+        private Association(int uid, String deviceAddress, String companionAppPackage) {
+            this.uid = uid;
+            this.deviceAddress = checkNotNull(deviceAddress);
+            this.companionAppPackage = checkNotNull(companionAppPackage);
+        }
+
+        @Override
+        public boolean equals(Object o) {
+            if (this == o) return true;
+            if (o == null || getClass() != o.getClass()) return false;
+
+            Association that = (Association) o;
+
+            if (uid != that.uid) return false;
+            if (!deviceAddress.equals(that.deviceAddress)) return false;
+            return companionAppPackage.equals(that.companionAppPackage);
+
+        }
+
+        @Override
+        public int hashCode() {
+            int result = uid;
+            result = 31 * result + deviceAddress.hashCode();
+            result = 31 * result + companionAppPackage.hashCode();
+            return result;
+        }
+    }
+
 }
diff --git a/services/tests/notification/src/com/android/server/notification/RankingHelperTest.java b/services/tests/notification/src/com/android/server/notification/RankingHelperTest.java
index 876d4ad..450f9b6 100644
--- a/services/tests/notification/src/com/android/server/notification/RankingHelperTest.java
+++ b/services/tests/notification/src/com/android/server/notification/RankingHelperTest.java
@@ -15,12 +15,15 @@
  */
 package com.android.server.notification;
 
+import static android.app.NotificationManager.IMPORTANCE_DEFAULT;
 import static android.app.NotificationManager.IMPORTANCE_HIGH;
 import static android.app.NotificationManager.IMPORTANCE_LOW;
 
 import static junit.framework.Assert.assertNull;
 import static junit.framework.Assert.fail;
 
+import org.json.JSONArray;
+import org.json.JSONObject;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -48,6 +51,7 @@
 import android.support.test.InstrumentationRegistry;
 import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
+import android.util.ArrayMap;
 import android.util.Xml;
 
 import java.io.BufferedInputStream;
@@ -60,12 +64,14 @@
 import java.util.List;
 import java.util.Map;
 import java.util.Objects;
+import java.util.concurrent.ThreadLocalRandom;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
 import static org.mockito.Matchers.anyInt;
+import static org.mockito.Matchers.anyString;
 import static org.mockito.Matchers.eq;
 import static org.mockito.Mockito.when;
 
@@ -986,9 +992,58 @@
 
         assertEquals(2, actual.size());
         for (NotificationChannelGroup group : actual) {
-            if (Objects.equals(group.getId(),ncg.getId())) {
+            if (Objects.equals(group.getId(), ncg.getId())) {
                 assertEquals(1, group.getChannels().size());
             }
         }
     }
+
+    @Test
+    public void testCreateChannel_updateNameResId() throws Exception {
+        NotificationChannel nc = new NotificationChannel("id", 1, IMPORTANCE_DEFAULT);
+        mHelper.createNotificationChannel(pkg, uid, nc, true);
+
+        nc = new NotificationChannel("id", 2, IMPORTANCE_DEFAULT);
+        mHelper.createNotificationChannel(pkg, uid, nc, true);
+
+        assertEquals(2, mHelper.getNotificationChannel(pkg, uid, "id", false).getNameResId());
+    }
+
+    @Test
+    public void testDumpChannelsJson() throws Exception {
+        final ApplicationInfo upgrade = new ApplicationInfo();
+        upgrade.targetSdkVersion = Build.VERSION_CODES.O;
+        try {
+            when(mPm.getApplicationInfoAsUser(
+                    anyString(), anyInt(), anyInt())).thenReturn(upgrade);
+        } catch (PackageManager.NameNotFoundException e) {
+        }
+        ArrayMap<String, Integer> expectedChannels = new ArrayMap<>();
+        int numPackages = ThreadLocalRandom.current().nextInt(1, 5);
+        for (int i = 0; i < numPackages; i++) {
+            String pkgName = "pkg" + i;
+            int numChannels = ThreadLocalRandom.current().nextInt(1, 10);
+            for (int j = 0; j < numChannels; j++) {
+                mHelper.createNotificationChannel(pkgName, uid,
+                        new NotificationChannel("" + j, "a", IMPORTANCE_HIGH), true);
+            }
+            expectedChannels.put(pkgName, numChannels);
+        }
+
+        // delete the first channel of the first package
+        String pkg = expectedChannels.keyAt(0);
+        mHelper.deleteNotificationChannel("pkg" + 0, uid, "0");
+        // dump should not include deleted channels
+        int count = expectedChannels.get(pkg);
+        expectedChannels.put(pkg, count - 1);
+
+        JSONArray actual = mHelper.dumpChannelsJson(new NotificationManagerService.DumpFilter());
+        assertEquals(numPackages, actual.length());
+        for (int i = 0; i < numPackages; i++) {
+            JSONObject object = actual.getJSONObject(i);
+            assertTrue(expectedChannels.containsKey(object.get("packageName")));
+            assertEquals(expectedChannels.get(object.get("packageName")).intValue() + 1,
+                    object.getInt("channelCount"));
+        }
+    }
 }
diff --git a/services/tests/servicestests/src/com/android/server/NetworkScorerAppManagerTest.java b/services/tests/servicestests/src/com/android/server/NetworkScorerAppManagerTest.java
index 502bf06..64f176a 100644
--- a/services/tests/servicestests/src/com/android/server/NetworkScorerAppManagerTest.java
+++ b/services/tests/servicestests/src/com/android/server/NetworkScorerAppManagerTest.java
@@ -23,6 +23,7 @@
 
 import static org.junit.Assert.assertFalse;
 import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyInt;
 import static org.mockito.Matchers.eq;
 import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.verify;
@@ -206,15 +207,30 @@
     }
 
     @Test
-    public void testSetActiveScorer_nullPackage() throws Exception {
+    public void testSetActiveScorer_nullPackage_validDefault() throws Exception {
+        String packageName = "package";
+        String defaultPackage = "defaultPackage";
+        setNetworkRecoPackageSetting(packageName);
+        setDefaultNetworkRecommendationPackage(defaultPackage);
+        final ComponentName recoComponent = new ComponentName(defaultPackage, "class1");
+        mockScoreNetworksGranted(recoComponent.getPackageName());
+        mockRecommendationServiceAvailable(recoComponent, 924 /* packageUid */, null);
+
+        assertTrue(mNetworkScorerAppManager.setActiveScorer(null));
+        verify(mSettingsFacade).putString(mMockContext,
+                Settings.Global.NETWORK_RECOMMENDATIONS_PACKAGE, defaultPackage);
+    }
+
+    @Test
+    public void testSetActiveScorer_nullPackage_invalidDefault() throws Exception {
         String packageName = "package";
         String defaultPackage = "defaultPackage";
         setNetworkRecoPackageSetting(packageName);
         setDefaultNetworkRecommendationPackage(defaultPackage);
 
-        assertTrue(mNetworkScorerAppManager.setActiveScorer(null));
-        verify(mSettingsFacade).putString(mMockContext,
-                Settings.Global.NETWORK_RECOMMENDATIONS_PACKAGE, defaultPackage);
+        assertFalse(mNetworkScorerAppManager.setActiveScorer(null));
+        verify(mSettingsFacade, never()).putString(any(),
+                eq(Settings.Global.NETWORK_RECOMMENDATIONS_PACKAGE), any());
     }
 
     @Test
@@ -242,29 +258,82 @@
         verify(mSettingsFacade, never()).putString(any(), any(), any());
     }
 
-
     @Test
-    public void testRevertToDefaultIfNoActive_notActive() throws Exception {
-        String defaultPackage = "defaultPackage";
-        setDefaultNetworkRecommendationPackage(defaultPackage);
+    public void testUpdateState_recommendationsForcedOff() throws Exception {
+        setRecommendationsEnabledSetting(NetworkScoreManager.RECOMMENDATIONS_ENABLED_FORCED_OFF);
 
-        mNetworkScorerAppManager.revertToDefaultIfNoActive();
+        mNetworkScorerAppManager.updateState();
 
-        verify(mSettingsFacade).putString(mMockContext,
-                Settings.Global.NETWORK_RECOMMENDATIONS_PACKAGE, defaultPackage);
+        verify(mSettingsFacade, never()).getString(any(),
+                eq(Settings.Global.NETWORK_RECOMMENDATIONS_PACKAGE));
+        verify(mSettingsFacade, never()).putInt(any(),
+                eq(Settings.Global.NETWORK_RECOMMENDATIONS_ENABLED), anyInt());
     }
 
     @Test
-    public void testRevertToDefaultIfNoActive_active() throws Exception {
+    public void testUpdateState_currentPackageValid() throws Exception {
         String packageName = "package";
         setNetworkRecoPackageSetting(packageName);
         final ComponentName recoComponent = new ComponentName(packageName, "class1");
         mockScoreNetworksGranted(recoComponent.getPackageName());
         mockRecommendationServiceAvailable(recoComponent, 924 /* packageUid */, null);
 
-        mNetworkScorerAppManager.revertToDefaultIfNoActive();
+        mNetworkScorerAppManager.updateState();
 
-        verify(mSettingsFacade, never()).putString(any(), any(), any());
+        verify(mSettingsFacade, never()).putString(any(),
+                eq(Settings.Global.NETWORK_RECOMMENDATIONS_PACKAGE), any());
+        verify(mSettingsFacade).putInt(mMockContext,
+                Settings.Global.NETWORK_RECOMMENDATIONS_ENABLED,
+                NetworkScoreManager.RECOMMENDATIONS_ENABLED_ON);
+    }
+
+    @Test
+    public void testUpdateState_currentPackageNotValid_validDefault() throws Exception {
+        String defaultPackage = "defaultPackage";
+        setDefaultNetworkRecommendationPackage(defaultPackage);
+        final ComponentName recoComponent = new ComponentName(defaultPackage, "class1");
+        mockScoreNetworksGranted(recoComponent.getPackageName());
+        mockRecommendationServiceAvailable(recoComponent, 924 /* packageUid */, null);
+
+        mNetworkScorerAppManager.updateState();
+
+        verify(mSettingsFacade).putString(mMockContext,
+                Settings.Global.NETWORK_RECOMMENDATIONS_PACKAGE, defaultPackage);
+        verify(mSettingsFacade).putInt(mMockContext,
+                Settings.Global.NETWORK_RECOMMENDATIONS_ENABLED,
+                NetworkScoreManager.RECOMMENDATIONS_ENABLED_ON);
+    }
+
+    @Test
+    public void testUpdateState_currentPackageNotValid_invalidDefault() throws Exception {
+        String defaultPackage = "defaultPackage";
+        setDefaultNetworkRecommendationPackage(defaultPackage);
+        setNetworkRecoPackageSetting("currentPackage");
+
+        mNetworkScorerAppManager.updateState();
+
+        verify(mSettingsFacade).putString(mMockContext,
+                Settings.Global.NETWORK_RECOMMENDATIONS_PACKAGE, defaultPackage);
+        verify(mSettingsFacade).putInt(mMockContext,
+                Settings.Global.NETWORK_RECOMMENDATIONS_ENABLED,
+                NetworkScoreManager.RECOMMENDATIONS_ENABLED_OFF);
+    }
+
+    @Test
+    public void testUpdateState_currentPackageNotValid_sameAsDefault() throws Exception {
+        String defaultPackage = "defaultPackage";
+        setDefaultNetworkRecommendationPackage(defaultPackage);
+        setNetworkRecoPackageSetting(defaultPackage);
+
+        mNetworkScorerAppManager.updateState();
+
+        verify(mSettingsFacade, never()).putString(any(),
+                eq(Settings.Global.NETWORK_RECOMMENDATIONS_PACKAGE), any());
+    }
+
+    private void setRecommendationsEnabledSetting(int value) {
+        when(mSettingsFacade.getInt(eq(mMockContext),
+                eq(Settings.Global.NETWORK_RECOMMENDATIONS_ENABLED), anyInt())).thenReturn(value);
     }
 
     private void setNetworkRecoPackageSetting(String packageName) {
diff --git a/services/tests/servicestests/src/com/android/server/storage/AppCollectorTest.java b/services/tests/servicestests/src/com/android/server/storage/AppCollectorTest.java
index 29185e9..8cf7c8a 100644
--- a/services/tests/servicestests/src/com/android/server/storage/AppCollectorTest.java
+++ b/services/tests/servicestests/src/com/android/server/storage/AppCollectorTest.java
@@ -16,12 +16,15 @@
 
 package com.android.server.storage;
 
+import android.app.usage.StorageStats;
+import android.app.usage.StorageStatsManager;
 import android.content.pm.UserInfo;
 import android.content.Context;
 import android.content.pm.ApplicationInfo;
 import android.content.pm.IPackageStatsObserver;
 import android.content.pm.PackageManager;
 import android.content.pm.PackageStats;
+import android.os.UserHandle;
 import android.os.UserManager;
 import android.os.storage.VolumeInfo;
 import android.test.AndroidTestCase;
@@ -53,6 +56,7 @@
     @Mock private Context mContext;
     @Mock private PackageManager mPm;
     @Mock private UserManager mUm;
+    @Mock private StorageStatsManager mSsm;
     private List<ApplicationInfo> mApps;
     private List<UserInfo> mUsers;
 
@@ -63,6 +67,7 @@
         mApps = new ArrayList<>();
         when(mContext.getPackageManager()).thenReturn(mPm);
         when(mContext.getSystemService(Context.USER_SERVICE)).thenReturn(mUm);
+        when(mContext.getSystemService(Context.STORAGE_STATS_SERVICE)).thenReturn(mSsm);
 
         // Set up the app list.
         when(mPm.getInstalledApplications(anyInt())).thenReturn(mApps);
@@ -100,39 +105,9 @@
         AppCollector collector = new AppCollector(mContext, volume);
         PackageStats stats = new PackageStats("com.test.app");
 
-        // Set up this to handle the asynchronous call to the PackageManager. This returns the
-        // package info for the specified package.
-        doAnswer(new Answer<Void>() {
-             @Override
-             public Void answer(InvocationOnMock invocation) {
-                 try {
-                     ((IPackageStatsObserver.Stub) invocation.getArguments()[2])
-                             .onGetStatsCompleted(stats, true);
-                 } catch (Exception e) {
-                     // We fail instead of just letting the exception fly because throwing
-                     // out of the callback like this on the background thread causes the test
-                     // runner to crash, rather than reporting the failure.
-                     fail();
-                 }
-                 return null;
-             }
-        }).when(mPm).getPackageSizeInfoAsUser(eq("com.test.app"), eq(0), any());
-
-
-        // Because getPackageStats is a blocking call, we block execution of the test until the
-        // call finishes. In order to finish the call, we need the above answer to execute.
-        List<PackageStats> myStats = new ArrayList<>();
-        CountDownLatch latch = new CountDownLatch(1);
-        new Thread(new Runnable() {
-            @Override
-            public void run() {
-                myStats.addAll(collector.getPackageStats(TIMEOUT));
-                latch.countDown();
-            }
-        }).start();
-        latch.await();
-
-        assertThat(myStats).containsExactly(stats);
+        when(mSsm.queryStatsForPackage(eq("testuuid"),
+                eq("com.test.app"), eq(UserHandle.of(0)))).thenReturn(new StorageStats());
+        assertThat(collector.getPackageStats(TIMEOUT)).containsExactly(stats);
     }
 
     @Test
@@ -151,43 +126,11 @@
         PackageStats otherStats = new PackageStats("com.test.app");
         otherStats.userHandle = 1;
 
-        // Set up this to handle the asynchronous call to the PackageManager. This returns the
-        // package info for our packages.
-        doAnswer(new Answer<Void>() {
-             @Override
-             public Void answer(InvocationOnMock invocation) {
-                 try {
-                     ((IPackageStatsObserver.Stub) invocation.getArguments()[2])
-                             .onGetStatsCompleted(stats, true);
-
-                     // Now callback for the other uid.
-                     ((IPackageStatsObserver.Stub) invocation.getArguments()[2])
-                             .onGetStatsCompleted(otherStats, true);
-                 } catch (Exception e) {
-                     // We fail instead of just letting the exception fly because throwing
-                     // out of the callback like this on the background thread causes the test
-                     // runner to crash, rather than reporting the failure.
-                     fail();
-                 }
-                 return null;
-             }
-        }).when(mPm).getPackageSizeInfoAsUser(eq("com.test.app"), eq(0), any());
-
-
-        // Because getPackageStats is a blocking call, we block execution of the test until the
-        // call finishes. In order to finish the call, we need the above answer to execute.
-        List<PackageStats> myStats = new ArrayList<>();
-        CountDownLatch latch = new CountDownLatch(1);
-        new Thread(new Runnable() {
-            @Override
-            public void run() {
-                myStats.addAll(collector.getPackageStats(TIMEOUT));
-                latch.countDown();
-            }
-        }).start();
-        latch.await();
-
-        assertThat(myStats).containsAllOf(stats, otherStats);
+        when(mSsm.queryStatsForPackage(eq("testuuid"),
+                eq("com.test.app"), eq(UserHandle.of(0)))).thenReturn(new StorageStats());
+        when(mSsm.queryStatsForPackage(eq("testuuid"),
+                eq("com.test.app"), eq(UserHandle.of(1)))).thenReturn(new StorageStats());
+        assertThat(collector.getPackageStats(TIMEOUT)).containsExactly(stats, otherStats);
     }
 
     @Test(expected=NullPointerException.class)
diff --git a/services/usb/java/com/android/server/usb/UsbProfileGroupSettingsManager.java b/services/usb/java/com/android/server/usb/UsbProfileGroupSettingsManager.java
index caf9ec6..7b8ebd4 100644
--- a/services/usb/java/com/android/server/usb/UsbProfileGroupSettingsManager.java
+++ b/services/usb/java/com/android/server/usb/UsbProfileGroupSettingsManager.java
@@ -602,7 +602,8 @@
                 new MtpNotificationManager.OnOpenInAppListener() {
                     @Override
                     public void onOpenInApp(UsbDevice device) {
-                        resolveActivity(createDeviceAttachedIntent(device), device);
+                        resolveActivity(createDeviceAttachedIntent(device),
+                                device, false /* showMtpNotification */);
                     }
                 });
     }
@@ -958,31 +959,27 @@
         // Send broadcast to running activities with registered intent
         mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
 
-        if (MtpNotificationManager.shouldShowNotification(mPackageManager, device)) {
-            // Show notification if the device is MTP storage.
-            mMtpNotificationManager.showNotification(device);
-        } else {
-            resolveActivity(intent, device);
-        }
+        resolveActivity(intent, device, true /* showMtpNotification */);
     }
 
-    private void resolveActivity(Intent intent, UsbDevice device) {
-        ArrayList<ResolveInfo> matches;
-        String defaultPackage = null;
-        UserHandle user = null;
+    private void resolveActivity(Intent intent, UsbDevice device, boolean showMtpNotification) {
+        final ArrayList<ResolveInfo> matches;
+        final ActivityInfo defaultActivity;
         synchronized (mLock) {
             matches = getDeviceMatchesLocked(device, intent);
-            // Launch our default activity directly, if we have one.
-            // Otherwise we will start the UsbResolverActivity to allow the user to choose.
-            UserPackage userPackage = mDevicePreferenceMap.get(new DeviceFilter(device));
-            if (userPackage != null) {
-                defaultPackage = userPackage.packageName;
-                user = userPackage.user;
-            }
+            defaultActivity = getDefaultActivityLocked(
+                    matches, mDevicePreferenceMap.get(new DeviceFilter(device)));
+        }
+
+        if (showMtpNotification && MtpNotificationManager.shouldShowNotification(
+                mPackageManager, device) && defaultActivity == null) {
+            // Show notification if the device is MTP storage.
+            mMtpNotificationManager.showNotification(device);
+            return;
         }
 
         // Start activity with registered intent
-        resolveActivity(intent, matches, defaultPackage, user, device, null);
+        resolveActivity(intent, matches, defaultActivity, device, null);
     }
 
     public void deviceAttachedForFixedHandler(UsbDevice device, ComponentName component) {
@@ -1027,21 +1024,15 @@
                 Intent.FLAG_ACTIVITY_NEW_TASK |
                 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
 
-        ArrayList<ResolveInfo> matches;
-        String defaultPackage = null;
-        UserHandle user = null;
+        final ArrayList<ResolveInfo> matches;
+        final ActivityInfo defaultActivity;
         synchronized (mLock) {
             matches = getAccessoryMatchesLocked(accessory, intent);
-            // Launch our default activity directly, if we have one.
-            // Otherwise we will start the UsbResolverActivity to allow the user to choose.
-            UserPackage userPackage = mAccessoryPreferenceMap.get(new AccessoryFilter(accessory));
-            if (userPackage != null) {
-                defaultPackage = userPackage.packageName;
-                user = userPackage.user;
-            }
+            defaultActivity = getDefaultActivityLocked(
+                    matches, mAccessoryPreferenceMap.get(new AccessoryFilter(accessory)));
         }
 
-        resolveActivity(intent, matches, defaultPackage, user, null, accessory);
+        resolveActivity(intent, matches, defaultActivity, null, accessory);
     }
 
     /**
@@ -1049,14 +1040,13 @@
      *
      * @param intent The intent to start the package
      * @param matches The available resolutions of the intent
-     * @param defaultPackage The default package for the device (if set)
-     * @param defaultUser The user of the default package (if package is set)
+     * @param defaultActivity The default activity for the device (if set)
      * @param device The device if a device was attached
      * @param accessory The accessory if a device was attached
      */
     private void resolveActivity(@NonNull Intent intent, @NonNull ArrayList<ResolveInfo> matches,
-            @Nullable String defaultPackage, @Nullable UserHandle defaultUser,
-            @Nullable UsbDevice device, @Nullable UsbAccessory accessory) {
+            @Nullable ActivityInfo defaultActivity, @Nullable UsbDevice device,
+            @Nullable UsbAccessory accessory) {
         int count = matches.size();
 
         // don't show the resolver activity if there are no choices available
@@ -1083,62 +1073,25 @@
             return;
         }
 
-        ResolveInfo defaultRI = null;
-        if (count == 1 && defaultPackage == null) {
-            // Check to see if our single choice is on the system partition.
-            // If so, treat it as our default without calling UsbResolverActivity
-            ResolveInfo rInfo = matches.get(0);
-            if (rInfo.activityInfo != null &&
-                    rInfo.activityInfo.applicationInfo != null &&
-                    (rInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
-                defaultRI = rInfo;
-            }
-
-            if (mDisablePermissionDialogs) {
-                // bypass dialog and launch the only matching activity
-                rInfo = matches.get(0);
-                if (rInfo.activityInfo != null) {
-                    defaultPackage = rInfo.activityInfo.packageName;
-                    defaultUser = UserHandle.getUserHandleForUid(
-                            rInfo.activityInfo.applicationInfo.uid);
-                }
-            }
-        }
-
-        if (defaultRI == null && defaultPackage != null) {
-            // look for default activity
-            for (int i = 0; i < count; i++) {
-                ResolveInfo rInfo = matches.get(i);
-                if (rInfo.activityInfo != null &&
-                        defaultPackage.equals(rInfo.activityInfo.packageName) &&
-                        defaultUser.getIdentifier() ==
-                                UserHandle.getUserId(rInfo.activityInfo.applicationInfo.uid)) {
-                    defaultRI = rInfo;
-                    break;
-                }
-            }
-        }
-
-        if (defaultRI != null) {
+        if (defaultActivity != null) {
             UsbUserSettingsManager defaultRIUserSettings = mSettingsManager.getSettingsForUser(
-                    UserHandle.getUserId(defaultRI.activityInfo.applicationInfo.uid));
+                    UserHandle.getUserId(defaultActivity.applicationInfo.uid));
             // grant permission for default activity
             if (device != null) {
                 defaultRIUserSettings.
-                        grantDevicePermission(device, defaultRI.activityInfo.applicationInfo.uid);
+                        grantDevicePermission(device, defaultActivity.applicationInfo.uid);
             } else if (accessory != null) {
                 defaultRIUserSettings.grantAccessoryPermission(accessory,
-                                defaultRI.activityInfo.applicationInfo.uid);
+                        defaultActivity.applicationInfo.uid);
             }
 
             // start default activity directly
             try {
                 intent.setComponent(
-                        new ComponentName(defaultRI.activityInfo.packageName,
-                                defaultRI.activityInfo.name));
+                        new ComponentName(defaultActivity.packageName, defaultActivity.name));
 
                 UserHandle user = UserHandle.getUserHandleForUid(
-                        defaultRI.activityInfo.applicationInfo.uid);
+                        defaultActivity.applicationInfo.uid);
                 mContext.startActivityAsUser(intent, user);
             } catch (ActivityNotFoundException e) {
                 Slog.e(TAG, "startActivity failed", e);
@@ -1179,6 +1132,46 @@
         }
     }
 
+    /**
+     * Returns a default activity for matched ResolveInfo.
+     * @param matches Resolved activities matched with connected device/accesary.
+     * @param userPackage Default activity choosed by a user before. Should be null if no activity
+     *     is choosed by a user.
+     * @return Default activity
+     */
+    private @Nullable ActivityInfo getDefaultActivityLocked(
+            @NonNull ArrayList<ResolveInfo> matches,
+            @Nullable UserPackage userPackage) {
+        if (userPackage != null) {
+            // look for default activity
+            for (final ResolveInfo info : matches) {
+                if (info.activityInfo != null
+                        && userPackage.packageName.equals(info.activityInfo.packageName)
+                        && userPackage.user.getIdentifier()
+                                == UserHandle.getUserId(info.activityInfo.applicationInfo.uid)) {
+                    return info.activityInfo;
+                }
+            }
+        }
+
+        if (matches.size() == 1) {
+            final ActivityInfo activityInfo = matches.get(0).activityInfo;
+            if (activityInfo != null) {
+                // bypass dialog and launch the only matching activity
+                if (mDisablePermissionDialogs) {
+                    return activityInfo;
+                }
+                if (activityInfo.applicationInfo != null
+                        && (activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
+                                != 0) {
+                    return activityInfo;
+                }
+            }
+        }
+
+        return null;
+    }
+
     private boolean clearCompatibleMatchesLocked(String packageName, DeviceFilter filter) {
         boolean changed = false;
         for (DeviceFilter test : mDevicePreferenceMap.keySet()) {
diff --git a/telephony/java/android/telephony/VisualVoicemailService.java b/telephony/java/android/telephony/VisualVoicemailService.java
index 84833e3..e211f76 100644
--- a/telephony/java/android/telephony/VisualVoicemailService.java
+++ b/telephony/java/android/telephony/VisualVoicemailService.java
@@ -41,6 +41,10 @@
  * the SMS filtering chain and may intercept the visual voicemail SMS before it reaches this
  * service.
  * <p>
+ * To extend this class, The service must be declared in the manifest file with
+ * the {@link android.Manifest.permission#BIND_VISUAL_VOICEMAIL_SERVICE} permission and include an
+ * intent filter with the {@link #SERVICE_INTERFACE} action.
+ * <p>
  * Below is an example manifest registration for a {@code VisualVoicemailService}.
  * <pre>
  * {@code
@@ -260,6 +264,9 @@
      * @param port The destination port for data SMS, or 0 for text SMS.
      * @param text The message content. For data sms, it will be encoded as a UTF-8 byte stream.
      * @param sentIntent The sent intent passed to the {@link SmsManager}
+     *
+     * @throws SecurityException if the caller is not the current default dialer
+     *
      * @see SmsManager#sendDataMessage(String, String, short, byte[], PendingIntent, PendingIntent)
      * @see SmsManager#sendTextMessage(String, String, String, PendingIntent, PendingIntent)
      */
diff --git a/telephony/java/com/android/internal/telephony/ITelephony.aidl b/telephony/java/com/android/internal/telephony/ITelephony.aidl
index e3816b6..220ea14 100644
--- a/telephony/java/com/android/internal/telephony/ITelephony.aidl
+++ b/telephony/java/com/android/internal/telephony/ITelephony.aidl
@@ -527,7 +527,7 @@
      * Send a visual voicemail SMS. Internal use only.
      * Requires caller to be the default dialer and have SEND_SMS permission
      */
-    oneway void sendVisualVoicemailSmsForSubscriber(in String callingPackage, in int subId,
+    void sendVisualVoicemailSmsForSubscriber(in String callingPackage, in int subId,
             in String number, in int port, in String text, in PendingIntent sentIntent);
 
     // Send the special dialer code. The IPC caller must be the current default dialer.
diff --git a/tests/FeatureSplit/base/Android.mk b/tests/FeatureSplit/base/Android.mk
index 7c0fc04..93f6d7a 100644
--- a/tests/FeatureSplit/base/Android.mk
+++ b/tests/FeatureSplit/base/Android.mk
@@ -19,6 +19,7 @@
 
 LOCAL_SRC_FILES := $(call all-subdir-java-files)
 LOCAL_PACKAGE_NAME := FeatureSplitBase
+LOCAL_EXPORT_PACKAGE_RESOURCES := true
 
 LOCAL_MODULE_TAGS := tests
 
diff --git a/tests/FeatureSplit/feature1/Android.mk b/tests/FeatureSplit/feature1/Android.mk
index aa222dd..e6ba5c2 100644
--- a/tests/FeatureSplit/feature1/Android.mk
+++ b/tests/FeatureSplit/feature1/Android.mk
@@ -17,17 +17,15 @@
 LOCAL_PATH:= $(call my-dir)
 include $(CLEAR_VARS)
 
+LOCAL_USE_AAPT2 := true
 LOCAL_SRC_FILES := $(call all-subdir-java-files)
 LOCAL_PACKAGE_NAME := FeatureSplit1
 LOCAL_MODULE_TAGS := tests
 
-featureOf := FeatureSplitBase
+LOCAL_APK_LIBRARIES := FeatureSplitBase
+LOCAL_RES_LIBRARIES := FeatureSplitBase
 
-LOCAL_APK_LIBRARIES := $(featureOf)
-featureOfApk := $(call intermediates-dir-for,APPS,$(featureOf))/package.apk
-localRStamp := $(call intermediates-dir-for,APPS,$(LOCAL_PACKAGE_NAME),,COMMON)/src/R.stamp
-$(localRStamp): $(featureOfApk)
-
-LOCAL_AAPT_FLAGS := --feature-of $(featureOfApk) --custom-package com.android.test.split.feature.one
+LOCAL_AAPT_FLAGS += --package-id 0x80
+LOCAL_AAPT_FLAGS += --custom-package com.android.test.split.feature.one
 
 include $(BUILD_PACKAGE)
diff --git a/tests/FeatureSplit/feature2/Android.mk b/tests/FeatureSplit/feature2/Android.mk
index 1a0322b..c8e8609 100644
--- a/tests/FeatureSplit/feature2/Android.mk
+++ b/tests/FeatureSplit/feature2/Android.mk
@@ -17,22 +17,15 @@
 LOCAL_PATH:= $(call my-dir)
 include $(CLEAR_VARS)
 
+LOCAL_USE_AAPT2 := true
 LOCAL_SRC_FILES := $(call all-subdir-java-files)
 LOCAL_PACKAGE_NAME := FeatureSplit2
 LOCAL_MODULE_TAGS := tests
 
-featureOf := FeatureSplitBase
-featureAfter := FeatureSplit1
+LOCAL_APK_LIBRARIES := FeatureSplitBase
+LOCAL_RES_LIBRARIES := FeatureSplitBase
 
-LOCAL_APK_LIBRARIES := $(featureOf)
-
-featureOfApk := $(call intermediates-dir-for,APPS,$(featureOf))/package.apk
-featureAfterApk := $(call intermediates-dir-for,APPS,$(featureAfter))/package.apk
-localRStamp := $(call intermediates-dir-for,APPS,$(LOCAL_PACKAGE_NAME),,COMMON)/src/R.stamp
-$(localRStamp): $(featureOfApk) $(featureAfterApk)
-
-LOCAL_AAPT_FLAGS := --feature-of $(featureOfApk)
-LOCAL_AAPT_FLAGS += --feature-after $(featureAfterApk)
+LOCAL_AAPT_FLAGS += --package-id 0x81
 LOCAL_AAPT_FLAGS += --custom-package com.android.test.split.feature.two
 
 include $(BUILD_PACKAGE)
diff --git a/tests/HwAccelerationTest/src/com/android/test/hwui/ListActivity.java b/tests/HwAccelerationTest/src/com/android/test/hwui/ListActivity.java
index db6421e..0defe92 100644
--- a/tests/HwAccelerationTest/src/com/android/test/hwui/ListActivity.java
+++ b/tests/HwAccelerationTest/src/com/android/test/hwui/ListActivity.java
@@ -42,7 +42,7 @@
             "Burkina Faso", "Burundi", "Cote d'Ivoire", "Cambodia", "Cameroon", "Canada", "Cape Verde",
             "Cayman Islands", "Central African Republic", "Chad", "Chile", "China",
             "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo",
-            "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic",
+            "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czechia",
             "Democratic Republic of the Congo", "Denmark", "Djibouti", "Dominica", "Dominican Republic",
             "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea",
             "Estonia", "Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji", "Finland",
diff --git a/tests/HwAccelerationTest/src/com/android/test/hwui/TransparentListActivity.java b/tests/HwAccelerationTest/src/com/android/test/hwui/TransparentListActivity.java
index 535f865..ffb8689 100644
--- a/tests/HwAccelerationTest/src/com/android/test/hwui/TransparentListActivity.java
+++ b/tests/HwAccelerationTest/src/com/android/test/hwui/TransparentListActivity.java
@@ -42,7 +42,7 @@
             "Burkina Faso", "Burundi", "Cote d'Ivoire", "Cambodia", "Cameroon", "Canada", "Cape Verde",
             "Cayman Islands", "Central African Republic", "Chad", "Chile", "China",
             "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo",
-            "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic",
+            "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czechia",
             "Democratic Republic of the Congo", "Denmark", "Djibouti", "Dominica", "Dominican Republic",
             "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea",
             "Estonia", "Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji", "Finland",
diff --git a/tests/HwAccelerationTest/src/com/android/test/hwui/ViewLayersActivity.java b/tests/HwAccelerationTest/src/com/android/test/hwui/ViewLayersActivity.java
index 0ddd7fd..7168478 100644
--- a/tests/HwAccelerationTest/src/com/android/test/hwui/ViewLayersActivity.java
+++ b/tests/HwAccelerationTest/src/com/android/test/hwui/ViewLayersActivity.java
@@ -126,7 +126,7 @@
             "Burkina Faso", "Burundi", "Cote d'Ivoire", "Cambodia", "Cameroon", "Canada", "Cape Verde",
             "Cayman Islands", "Central African Republic", "Chad", "Chile", "China",
             "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo",
-            "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic",
+            "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czechia",
             "Democratic Republic of the Congo", "Denmark", "Djibouti", "Dominica", "Dominican Republic",
             "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea",
             "Estonia", "Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji", "Finland",
diff --git a/tests/HwAccelerationTest/src/com/android/test/hwui/ViewLayersActivity2.java b/tests/HwAccelerationTest/src/com/android/test/hwui/ViewLayersActivity2.java
index e795f02..a037d70 100644
--- a/tests/HwAccelerationTest/src/com/android/test/hwui/ViewLayersActivity2.java
+++ b/tests/HwAccelerationTest/src/com/android/test/hwui/ViewLayersActivity2.java
@@ -76,7 +76,7 @@
             "Burkina Faso", "Burundi", "Cote d'Ivoire", "Cambodia", "Cameroon", "Canada", "Cape Verde",
             "Cayman Islands", "Central African Republic", "Chad", "Chile", "China",
             "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo",
-            "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic",
+            "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czechia",
             "Democratic Republic of the Congo", "Denmark", "Djibouti", "Dominica", "Dominican Republic",
             "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea",
             "Estonia", "Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji", "Finland",
diff --git a/tests/HwAccelerationTest/src/com/android/test/hwui/ViewLayersActivity3.java b/tests/HwAccelerationTest/src/com/android/test/hwui/ViewLayersActivity3.java
index c8ae75b..e65dd63 100644
--- a/tests/HwAccelerationTest/src/com/android/test/hwui/ViewLayersActivity3.java
+++ b/tests/HwAccelerationTest/src/com/android/test/hwui/ViewLayersActivity3.java
@@ -73,7 +73,7 @@
             "Burkina Faso", "Burundi", "Cote d'Ivoire", "Cambodia", "Cameroon", "Canada", "Cape Verde",
             "Cayman Islands", "Central African Republic", "Chad", "Chile", "China",
             "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo",
-            "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic",
+            "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czechia",
             "Democratic Republic of the Congo", "Denmark", "Djibouti", "Dominica", "Dominican Republic",
             "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea",
             "Estonia", "Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji", "Finland",
diff --git a/tests/HwAccelerationTest/src/com/android/test/hwui/ViewLayersActivity4.java b/tests/HwAccelerationTest/src/com/android/test/hwui/ViewLayersActivity4.java
index 6072c6e..17f78af 100644
--- a/tests/HwAccelerationTest/src/com/android/test/hwui/ViewLayersActivity4.java
+++ b/tests/HwAccelerationTest/src/com/android/test/hwui/ViewLayersActivity4.java
@@ -80,7 +80,7 @@
             "Burkina Faso", "Burundi", "Cote d'Ivoire", "Cambodia", "Cameroon", "Canada", "Cape Verde",
             "Cayman Islands", "Central African Republic", "Chad", "Chile", "China",
             "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo",
-            "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic",
+            "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czechia",
             "Democratic Republic of the Congo", "Denmark", "Djibouti", "Dominica", "Dominican Republic",
             "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea",
             "Estonia", "Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji", "Finland",
diff --git a/tests/HwAccelerationTest/src/com/android/test/hwui/ViewLayersActivity5.java b/tests/HwAccelerationTest/src/com/android/test/hwui/ViewLayersActivity5.java
index cbbb7ef..2dd7b6a 100644
--- a/tests/HwAccelerationTest/src/com/android/test/hwui/ViewLayersActivity5.java
+++ b/tests/HwAccelerationTest/src/com/android/test/hwui/ViewLayersActivity5.java
@@ -145,7 +145,7 @@
             "Burkina Faso", "Burundi", "Cote d'Ivoire", "Cambodia", "Cameroon", "Canada", "Cape Verde",
             "Cayman Islands", "Central African Republic", "Chad", "Chile", "China",
             "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo",
-            "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic",
+            "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czechia",
             "Democratic Republic of the Congo", "Denmark", "Djibouti", "Dominica", "Dominican Republic",
             "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea",
             "Estonia", "Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji", "Finland",
diff --git a/tests/ImfTest/src/com/android/imftest/samples/AutoCompleteTextViewActivityLandscape.java b/tests/ImfTest/src/com/android/imftest/samples/AutoCompleteTextViewActivityLandscape.java
index 7a4fddf..292bbd2 100644
--- a/tests/ImfTest/src/com/android/imftest/samples/AutoCompleteTextViewActivityLandscape.java
+++ b/tests/ImfTest/src/com/android/imftest/samples/AutoCompleteTextViewActivityLandscape.java
@@ -65,7 +65,7 @@
    "Cote d'Ivoire", "Cambodia", "Cameroon", "Canada", "Cape Verde",
    "Cayman Islands", "Central African Republic", "Chad", "Chile", "China",
    "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo",
-   "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic",
+   "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czechia",
    "Democratic Republic of the Congo", "Denmark", "Djibouti", "Dominica", "Dominican Republic",
    "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea",
    "Estonia", "Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji", "Finland",
diff --git a/tests/ImfTest/src/com/android/imftest/samples/AutoCompleteTextViewActivityPortrait.java b/tests/ImfTest/src/com/android/imftest/samples/AutoCompleteTextViewActivityPortrait.java
index 5bfe456..570cb6b 100644
--- a/tests/ImfTest/src/com/android/imftest/samples/AutoCompleteTextViewActivityPortrait.java
+++ b/tests/ImfTest/src/com/android/imftest/samples/AutoCompleteTextViewActivityPortrait.java
@@ -60,7 +60,7 @@
    "Cote d'Ivoire", "Cambodia", "Cameroon", "Canada", "Cape Verde",
    "Cayman Islands", "Central African Republic", "Chad", "Chile", "China",
    "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo",
-   "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic",
+   "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czechia",
    "Democratic Republic of the Congo", "Denmark", "Djibouti", "Dominica", "Dominican Republic",
    "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea",
    "Estonia", "Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji", "Finland",
diff --git a/tests/TtsTests/Android.mk b/tests/TtsTests/Android.mk
index ed63e12..3c3cd77 100644
--- a/tests/TtsTests/Android.mk
+++ b/tests/TtsTests/Android.mk
@@ -20,7 +20,7 @@
 
 LOCAL_SRC_FILES := $(call all-subdir-java-files)
 
-LOCAL_STATIC_JAVA_LIBRARIES := littlemock junit legacy-android-test
+LOCAL_STATIC_JAVA_LIBRARIES := mockito-target legacy-android-test
 LOCAL_JAVA_LIBRARIES := android.test.runner
 
 LOCAL_PACKAGE_NAME := TtsTests
diff --git a/tests/TtsTests/src/com/android/speech/tts/TextToSpeechTests.java b/tests/TtsTests/src/com/android/speech/tts/TextToSpeechTests.java
index faf6827..918873b 100644
--- a/tests/TtsTests/src/com/android/speech/tts/TextToSpeechTests.java
+++ b/tests/TtsTests/src/com/android/speech/tts/TextToSpeechTests.java
@@ -22,9 +22,12 @@
 import android.test.InstrumentationTestCase;
 
 import com.android.speech.tts.MockableTextToSpeechService.IDelegate;
-import com.google.testing.littlemock.ArgumentCaptor;
-import com.google.testing.littlemock.Behaviour;
-import com.google.testing.littlemock.LittleMock;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mockito;
+import org.mockito.internal.stubbing.StubberImpl;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+import org.mockito.stubbing.Stubber;
 import junit.framework.Assert;
 
 import java.util.Locale;
@@ -40,16 +43,16 @@
 
     @Override
     public void setUp() throws Exception {
-        IDelegate passThrough = LittleMock.mock(IDelegate.class);
+        IDelegate passThrough = Mockito.mock(IDelegate.class);
         MockableTextToSpeechService.setMocker(passThrough);
 
         // For the default voice selection
-        LittleMock.doReturn(TextToSpeech.LANG_COUNTRY_AVAILABLE).when(passThrough)
+        Mockito.doReturn(TextToSpeech.LANG_COUNTRY_AVAILABLE).when(passThrough)
             .onIsLanguageAvailable(
-                    LittleMock.anyString(), LittleMock.anyString(), LittleMock.anyString());
-        LittleMock.doReturn(TextToSpeech.LANG_COUNTRY_AVAILABLE).when(passThrough)
+                    Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
+        Mockito.doReturn(TextToSpeech.LANG_COUNTRY_AVAILABLE).when(passThrough)
             .onLoadLanguage(
-                    LittleMock.anyString(), LittleMock.anyString(), LittleMock.anyString());
+                    Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
 
         blockingInitAndVerify(MOCK_ENGINE, TextToSpeech.SUCCESS);
         assertEquals(MOCK_ENGINE, mTts.getCurrentEngine());
@@ -71,42 +74,42 @@
     }
 
     public void testSetLanguage_delegation() {
-        IDelegate delegate = LittleMock.mock(IDelegate.class);
+        IDelegate delegate = Mockito.mock(IDelegate.class);
         MockableTextToSpeechService.setMocker(delegate);
 
-        LittleMock.doReturn(TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE).when(delegate).onIsLanguageAvailable(
+        Mockito.doReturn(TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE).when(delegate).onIsLanguageAvailable(
                 "eng", "USA", "variant");
-        LittleMock.doReturn(TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE).when(delegate).onLoadLanguage(
+        Mockito.doReturn(TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE).when(delegate).onLoadLanguage(
                 "eng", "USA", "variant");
 
         // Test 1 :Tests that calls to onLoadLanguage( ) are delegated through to the
         // service without any caching or intermediate steps.
         assertEquals(TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE, mTts.setLanguage(new Locale("eng", "USA", "variant")));
-        LittleMock.verify(delegate, LittleMock.anyTimes()).onIsLanguageAvailable(
+        Mockito.verify(delegate, Mockito.atLeast(0)).onIsLanguageAvailable(
             "eng", "USA", "variant");
-        LittleMock.verify(delegate, LittleMock.anyTimes()).onLoadLanguage(
+        Mockito.verify(delegate, Mockito.atLeast(0)).onLoadLanguage(
             "eng", "USA", "variant");
     }
 
     public void testSetLanguage_availableLanguage() throws Exception {
-        IDelegate delegate = LittleMock.mock(IDelegate.class);
+        IDelegate delegate = Mockito.mock(IDelegate.class);
         MockableTextToSpeechService.setMocker(delegate);
 
         // ---------------------------------------------------------
         // Test 2 : Tests that when the language is successfully set
         // like above (returns LANG_COUNTRY_AVAILABLE). That the
         // request language changes from that point on.
-        LittleMock.doReturn(TextToSpeech.LANG_COUNTRY_AVAILABLE).when(delegate).onIsLanguageAvailable(
+        Mockito.doReturn(TextToSpeech.LANG_COUNTRY_AVAILABLE).when(delegate).onIsLanguageAvailable(
                 "eng", "USA", "variant");
-        LittleMock.doReturn(TextToSpeech.LANG_COUNTRY_AVAILABLE).when(delegate).onIsLanguageAvailable(
+        Mockito.doReturn(TextToSpeech.LANG_COUNTRY_AVAILABLE).when(delegate).onIsLanguageAvailable(
                 "eng", "USA", "");
-        LittleMock.doReturn(TextToSpeech.LANG_COUNTRY_AVAILABLE).when(delegate).onLoadLanguage(
+        Mockito.doReturn(TextToSpeech.LANG_COUNTRY_AVAILABLE).when(delegate).onLoadLanguage(
                 "eng", "USA", "");
         mTts.setLanguage(new Locale("eng", "USA", "variant"));
         blockingCallSpeak("foo bar", delegate);
-        ArgumentCaptor<SynthesisRequest> req = LittleMock.createCaptor();
-        LittleMock.verify(delegate, LittleMock.times(1)).onSynthesizeText(req.capture(),
-                LittleMock.<SynthesisCallback>anyObject());
+        ArgumentCaptor<SynthesisRequest> req = ArgumentCaptor.forClass(SynthesisRequest.class);
+        Mockito.verify(delegate, Mockito.times(1)).onSynthesizeText(req.capture(),
+                Mockito.<SynthesisCallback>anyObject());
 
         assertEquals("eng", req.getValue().getLanguage());
         assertEquals("USA", req.getValue().getCountry());
@@ -115,21 +118,21 @@
     }
 
     public void testSetLanguage_unavailableLanguage() throws Exception {
-        IDelegate delegate = LittleMock.mock(IDelegate.class);
+        IDelegate delegate = Mockito.mock(IDelegate.class);
         MockableTextToSpeechService.setMocker(delegate);
 
         // ---------------------------------------------------------
         // TEST 3 : Tests that the language that is set does not change when the
         // engine reports it could not load the specified language.
-        LittleMock.doReturn(TextToSpeech.LANG_NOT_SUPPORTED).when(
+        Mockito.doReturn(TextToSpeech.LANG_NOT_SUPPORTED).when(
                 delegate).onIsLanguageAvailable("fra", "FRA", "");
-        LittleMock.doReturn(TextToSpeech.LANG_NOT_SUPPORTED).when(
+        Mockito.doReturn(TextToSpeech.LANG_NOT_SUPPORTED).when(
                 delegate).onLoadLanguage("fra", "FRA", "");
         mTts.setLanguage(Locale.FRANCE);
         blockingCallSpeak("le fou barre", delegate);
-        ArgumentCaptor<SynthesisRequest> req2 = LittleMock.createCaptor();
-        LittleMock.verify(delegate, LittleMock.times(1)).onSynthesizeText(req2.capture(),
-                        LittleMock.<SynthesisCallback>anyObject());
+        ArgumentCaptor<SynthesisRequest> req2 = ArgumentCaptor.forClass(SynthesisRequest.class);
+        Mockito.verify(delegate, Mockito.times(1)).onSynthesizeText(req2.capture(),
+                        Mockito.<SynthesisCallback>anyObject());
 
         // The params are basically unchanged.
         assertEquals("eng", req2.getValue().getLanguage());
@@ -139,41 +142,41 @@
     }
 
     public void testIsLanguageAvailable() {
-        IDelegate delegate = LittleMock.mock(IDelegate.class);
+        IDelegate delegate = Mockito.mock(IDelegate.class);
         MockableTextToSpeechService.setMocker(delegate);
 
         // Test1: Simple end to end test.
-        LittleMock.doReturn(TextToSpeech.LANG_COUNTRY_AVAILABLE).when(
+        Mockito.doReturn(TextToSpeech.LANG_COUNTRY_AVAILABLE).when(
                 delegate).onIsLanguageAvailable("eng", "USA", "");
 
         assertEquals(TextToSpeech.LANG_COUNTRY_AVAILABLE, mTts.isLanguageAvailable(Locale.US));
-        LittleMock.verify(delegate, LittleMock.times(1)).onIsLanguageAvailable(
+        Mockito.verify(delegate, Mockito.times(1)).onIsLanguageAvailable(
                 "eng", "USA", "");
     }
 
     public void testDefaultLanguage_setsVoiceName() throws Exception {
-        IDelegate delegate = LittleMock.mock(IDelegate.class);
+        IDelegate delegate = Mockito.mock(IDelegate.class);
         MockableTextToSpeechService.setMocker(delegate);
         Locale defaultLocale = Locale.getDefault();
 
         // ---------------------------------------------------------
         // Test that default language also sets the default voice
         // name
-        LittleMock.doReturn(TextToSpeech.LANG_COUNTRY_AVAILABLE).
+        Mockito.doReturn(TextToSpeech.LANG_COUNTRY_AVAILABLE).
             when(delegate).onIsLanguageAvailable(
                 defaultLocale.getISO3Language(),
                 defaultLocale.getISO3Country().toUpperCase(),
                 defaultLocale.getVariant());
-        LittleMock.doReturn(TextToSpeech.LANG_COUNTRY_AVAILABLE).
+        Mockito.doReturn(TextToSpeech.LANG_COUNTRY_AVAILABLE).
             when(delegate).onLoadLanguage(
                 defaultLocale.getISO3Language(),
                 defaultLocale.getISO3Country(),
                 defaultLocale.getVariant());
 
         blockingCallSpeak("foo bar", delegate);
-        ArgumentCaptor<SynthesisRequest> req = LittleMock.createCaptor();
-        LittleMock.verify(delegate, LittleMock.times(1)).onSynthesizeText(req.capture(),
-                LittleMock.<SynthesisCallback>anyObject());
+        ArgumentCaptor<SynthesisRequest> req = ArgumentCaptor.forClass(SynthesisRequest.class);
+        Mockito.verify(delegate, Mockito.times(1)).onSynthesizeText(req.capture(),
+                Mockito.<SynthesisCallback>anyObject());
 
         assertEquals(defaultLocale.getISO3Language(), req.getValue().getLanguage());
         assertEquals(defaultLocale.getISO3Country(), req.getValue().getCountry());
@@ -185,8 +188,8 @@
     private void blockingCallSpeak(String speech, IDelegate mock) throws
             InterruptedException {
         final CountDownLatch latch = new CountDownLatch(1);
-        doCountDown(latch).when(mock).onSynthesizeText(LittleMock.<SynthesisRequest>anyObject(),
-                LittleMock.<SynthesisCallback>anyObject());
+        doCountDown(latch).when(mock).onSynthesizeText(Mockito.<SynthesisRequest>anyObject(),
+                Mockito.<SynthesisCallback>anyObject());
         mTts.speak(speech, TextToSpeech.QUEUE_ADD, null);
 
         awaitCountDown(latch, 5, TimeUnit.SECONDS);
@@ -194,7 +197,7 @@
 
     private void blockingInitAndVerify(final String engine, int errorCode) throws
             InterruptedException {
-        TextToSpeech.OnInitListener listener = LittleMock.mock(
+        TextToSpeech.OnInitListener listener = Mockito.mock(
                 TextToSpeech.OnInitListener.class);
 
         final CountDownLatch latch = new CountDownLatch(1);
@@ -206,18 +209,18 @@
         awaitCountDown(latch, 5, TimeUnit.SECONDS);
     }
 
-    public interface CountDownBehaviour extends Behaviour {
+    public static abstract class CountDownBehaviour extends StubberImpl {
         /** Used to mock methods that return a result. */
-        Behaviour andReturn(Object result);
+        public abstract Stubber andReturn(Object result);
     }
 
     public static CountDownBehaviour doCountDown(final CountDownLatch latch) {
         return new CountDownBehaviour() {
             @Override
             public <T> T when(T mock) {
-                return LittleMock.doAnswer(new Callable<Void>() {
+                return Mockito.doAnswer(new Answer<Void>() {
                     @Override
-                    public Void call() throws Exception {
+                    public Void answer(InvocationOnMock invocation) throws Exception {
                         latch.countDown();
                         return null;
                     }
@@ -225,13 +228,13 @@
             }
 
             @Override
-            public Behaviour andReturn(final Object result) {
-                return new Behaviour() {
+            public Stubber andReturn(final Object result) {
+                return new StubberImpl() {
                     @Override
                     public <T> T when(T mock) {
-                        return LittleMock.doAnswer(new Callable<Object>() {
+                        return Mockito.doAnswer(new Answer<Object>() {
                             @Override
-                            public Object call() throws Exception {
+                            public Object answer(InvocationOnMock invocation) throws Exception {
                                 latch.countDown();
                                 return result;
                             }
diff --git a/tests/net/Android.mk b/tests/net/Android.mk
index 8aa27a9..79f6e4d 100644
--- a/tests/net/Android.mk
+++ b/tests/net/Android.mk
@@ -40,7 +40,19 @@
     libnetdaidl \
     libui \
     libunwind \
-    libutils
+    libutils \
+    libcrypto \
+    libhidl-gen-utils \
+    libhidlbase \
+    libhidltransport \
+    libpackagelistparser \
+    libpcre2 \
+    libselinux \
+    libtinyxml2 \
+    libvintf \
+    libhwbinder \
+    android.hidl.base@1.0 \
+    android.hidl.token@1.0
 
 LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 
diff --git a/tools/aapt2/Main.cpp b/tools/aapt2/Main.cpp
index 38d9ef8..456f686 100644
--- a/tools/aapt2/Main.cpp
+++ b/tools/aapt2/Main.cpp
@@ -25,7 +25,7 @@
 static const char* sMajorVersion = "2";
 
 // Update minor version whenever a feature or flag is added.
-static const char* sMinorVersion = "9";
+static const char* sMinorVersion = "10";
 
 int PrintVersion() {
   std::cerr << "Android Asset Packaging Tool (aapt) " << sMajorVersion << "."
diff --git a/tools/aapt2/diff/Diff.cpp b/tools/aapt2/diff/Diff.cpp
index c877468..dacf8d9 100644
--- a/tools/aapt2/diff/Diff.cpp
+++ b/tools/aapt2/diff/Diff.cpp
@@ -331,7 +331,7 @@
 
   void Visit(Reference* ref) override {
     if (ref->name && ref->id) {
-      if (ref->id.value().package_id() == 0x7f) {
+      if (ref->id.value().package_id() == kAppPackageId) {
         ref->id = {};
       }
     }
diff --git a/tools/aapt2/flatten/XmlFlattener_test.cpp b/tools/aapt2/flatten/XmlFlattener_test.cpp
index ec3d75e..494d9d2 100644
--- a/tools/aapt2/flatten/XmlFlattener_test.cpp
+++ b/tools/aapt2/flatten/XmlFlattener_test.cpp
@@ -30,23 +30,20 @@
 class XmlFlattenerTest : public ::testing::Test {
  public:
   void SetUp() override {
-    context_ =
-        test::ContextBuilder()
-            .SetCompilationPackage("com.app.test")
-            .SetNameManglerPolicy(NameManglerPolicy{"com.app.test"})
-            .AddSymbolSource(
-                test::StaticSymbolSourceBuilder()
-                    .AddSymbol("android:attr/id", ResourceId(0x010100d0),
-                               test::AttributeBuilder().Build())
-                    .AddSymbol("com.app.test:id/id", ResourceId(0x7f020000))
-                    .AddSymbol("android:attr/paddingStart",
-                               ResourceId(0x010103b3),
-                               test::AttributeBuilder().Build())
-                    .AddSymbol("android:attr/colorAccent",
-                               ResourceId(0x01010435),
-                               test::AttributeBuilder().Build())
-                    .Build())
-            .Build();
+    context_ = test::ContextBuilder()
+                   .SetCompilationPackage("com.app.test")
+                   .SetNameManglerPolicy(NameManglerPolicy{"com.app.test"})
+                   .AddSymbolSource(
+                       test::StaticSymbolSourceBuilder()
+                           .AddSymbol("android:attr/id", ResourceId(0x010100d0),
+                                      test::AttributeBuilder().Build())
+                           .AddSymbol("com.app.test:id/id", ResourceId(0x7f020000))
+                           .AddPublicSymbol("android:attr/paddingStart", ResourceId(0x010103b3),
+                                            test::AttributeBuilder().Build())
+                           .AddPublicSymbol("android:attr/colorAccent", ResourceId(0x01010435),
+                                            test::AttributeBuilder().Build())
+                           .Build())
+                   .Build();
   }
 
   ::testing::AssertionResult Flatten(xml::XmlResource* doc,
diff --git a/tools/aapt2/link/Link.cpp b/tools/aapt2/link/Link.cpp
index dd8e14b..c8f0217 100644
--- a/tools/aapt2/link/Link.cpp
+++ b/tools/aapt2/link/Link.cpp
@@ -23,6 +23,7 @@
 
 #include "android-base/errors.h"
 #include "android-base/file.h"
+#include "android-base/stringprintf.h"
 #include "androidfw/StringPiece.h"
 #include "google/protobuf/io/coded_stream.h"
 
@@ -57,6 +58,7 @@
 #include "xml/XmlDom.h"
 
 using android::StringPiece;
+using android::base::StringPrintf;
 using ::google::protobuf::io::CopyingOutputStreamAdaptor;
 
 namespace aapt {
@@ -705,11 +707,17 @@
         }
 
         // If we are using --no-static-lib-packages, we need to rename the
-        // package of this
-        // table to our compilation package.
+        // package of this table to our compilation package.
         if (options_.no_static_lib_packages) {
-          if (ResourceTablePackage* pkg = include_static->FindPackageById(0x7f)) {
+          // Since package names can differ, and multiple packages can exist in a ResourceTable,
+          // we place the requirement that all static libraries are built with the package
+          // ID 0x7f. So if one is not found, this is an error.
+          if (ResourceTablePackage* pkg = include_static->FindPackageById(kAppPackageId)) {
             pkg->name = context_->GetCompilationPackage();
+          } else {
+            context_->GetDiagnostics()->Error(DiagMessage(path)
+                                              << "no package with ID 0x7f found in static library");
+            return false;
           }
         }
 
@@ -733,7 +741,7 @@
     // Capture the shared libraries so that the final resource table can be properly flattened
     // with support for shared libraries.
     for (auto& entry : asset_source->GetAssignedPackageIds()) {
-      if (entry.first > 0x01 && entry.first < 0x7f) {
+      if (entry.first > kFrameworkPackageId && entry.first < kAppPackageId) {
         final_table_.included_packages_[entry.first] = entry.second;
       }
     }
@@ -860,10 +868,9 @@
     for (const auto& package : final_table_.packages) {
       for (const auto& type : package->types) {
         if (type->id) {
-          context_->GetDiagnostics()->Error(
-              DiagMessage() << "type " << type->type << " has ID " << std::hex
-                            << (int)type->id.value() << std::dec
-                            << " assigned");
+          context_->GetDiagnostics()->Error(DiagMessage() << "type " << type->type << " has ID "
+                                                          << StringPrintf("%02x", type->id.value())
+                                                          << " assigned");
           return false;
         }
 
@@ -871,9 +878,8 @@
           if (entry->id) {
             ResourceNameRef res_name(package->name, type->type, entry->name);
             context_->GetDiagnostics()->Error(
-                DiagMessage() << "entry " << res_name << " has ID " << std::hex
-                              << (int)entry->id.value() << std::dec
-                              << " assigned");
+                DiagMessage() << "entry " << res_name << " has ID "
+                              << StringPrintf("%02x", entry->id.value()) << " assigned");
             return false;
           }
         }
@@ -1103,7 +1109,7 @@
       return false;
     }
 
-    ResourceTablePackage* pkg = table->FindPackageById(0x7f);
+    ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId);
     if (!pkg) {
       context_->GetDiagnostics()->Error(DiagMessage(input) << "static library has no package");
       return false;
@@ -1490,12 +1496,17 @@
 
     context_->SetNameManglerPolicy(
         NameManglerPolicy{context_->GetCompilationPackage()});
-    if (options_.package_type == PackageType::kSharedLib) {
-      context_->SetPackageId(0x00);
-    } else if (context_->GetCompilationPackage() == "android") {
+
+    // Override the package ID when it is "android".
+    if (context_->GetCompilationPackage() == "android") {
       context_->SetPackageId(0x01);
-    } else {
-      context_->SetPackageId(0x7f);
+
+      // Verify we're building a regular app.
+      if (options_.package_type != PackageType::kApp) {
+        context_->GetDiagnostics()->Error(
+            DiagMessage() << "package 'android' can only be built as a regular app");
+        return 1;
+      }
     }
 
     if (!LoadSymbolsFromIncludePaths()) {
@@ -1509,10 +1520,9 @@
 
     if (context_->IsVerbose()) {
       context_->GetDiagnostics()->Note(DiagMessage()
-                                       << "linking package '"
-                                       << context_->GetCompilationPackage()
-                                       << "' with package ID " << std::hex
-                                       << (int)context_->GetPackageId());
+                                       << StringPrintf("linking package '%s' using package ID %02x",
+                                                       context_->GetCompilationPackage().data(),
+                                                       context_->GetPackageId()));
     }
 
     for (const std::string& input : input_files) {
@@ -1889,6 +1899,7 @@
   LinkOptions options;
   std::vector<std::string> overlay_arg_list;
   std::vector<std::string> extra_java_packages;
+  Maybe<std::string> package_id;
   Maybe<std::string> configs;
   Maybe<std::string> preferred_density;
   Maybe<std::string> product_list;
@@ -1909,6 +1920,10 @@
                             "Compilation unit to link, using `overlay` semantics.\n"
                             "The last conflicting resource given takes precedence.",
                             &overlay_arg_list)
+          .OptionalFlag("--package-id",
+                        "Specify the package ID to use for this app. Must be greater or equal to\n"
+                        "0x7f and can't be used with --static-lib or --shared-lib.",
+                        &package_id)
           .OptionalFlag("--java", "Directory in which to generate R.java",
                         &options.generate_java_class_path)
           .OptionalFlag("--proguard", "Output file for generated Proguard rules",
@@ -2062,6 +2077,47 @@
     context.SetVerbose(verbose);
   }
 
+  if (shared_lib && static_lib) {
+    context.GetDiagnostics()->Error(DiagMessage()
+                                    << "only one of --shared-lib and --static-lib can be defined");
+    return 1;
+  }
+
+  if (shared_lib) {
+    options.package_type = PackageType::kSharedLib;
+    context.SetPackageId(0x00);
+  } else if (static_lib) {
+    options.package_type = PackageType::kStaticLib;
+    context.SetPackageId(kAppPackageId);
+  } else {
+    options.package_type = PackageType::kApp;
+    context.SetPackageId(kAppPackageId);
+  }
+
+  if (package_id) {
+    if (options.package_type != PackageType::kApp) {
+      context.GetDiagnostics()->Error(
+          DiagMessage() << "can't specify --package-id when not building a regular app");
+      return 1;
+    }
+
+    const Maybe<uint32_t> maybe_package_id_int = ResourceUtils::ParseInt(package_id.value());
+    if (!maybe_package_id_int) {
+      context.GetDiagnostics()->Error(DiagMessage() << "package ID '" << package_id.value()
+                                                    << "' is not a valid integer");
+      return 1;
+    }
+
+    const uint32_t package_id_int = maybe_package_id_int.value();
+    if (package_id_int < kAppPackageId || package_id_int > std::numeric_limits<uint8_t>::max()) {
+      context.GetDiagnostics()->Error(
+          DiagMessage() << StringPrintf(
+              "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
+      return 1;
+    }
+    context.SetPackageId(static_cast<uint8_t>(package_id_int));
+  }
+
   // Populate the set of extra packages for which to generate R.java.
   for (std::string& extra_package : extra_java_packages) {
     // A given package can actually be a colon separated list of packages.
@@ -2128,18 +2184,6 @@
     options.table_splitter_options.preferred_densities.push_back(preferred_density_config.density);
   }
 
-  if (shared_lib && static_lib) {
-    context.GetDiagnostics()->Error(DiagMessage()
-                                    << "only one of --shared-lib and --static-lib can be defined");
-    return 1;
-  }
-
-  if (shared_lib) {
-    options.package_type = PackageType::kSharedLib;
-  } else if (static_lib) {
-    options.package_type = PackageType::kStaticLib;
-  }
-
   if (options.package_type != PackageType::kStaticLib && stable_id_file_path) {
     if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path.value(),
                          &options.stable_id_map)) {
diff --git a/tools/aapt2/link/ReferenceLinker.cpp b/tools/aapt2/link/ReferenceLinker.cpp
index 0331313..833ae69 100644
--- a/tools/aapt2/link/ReferenceLinker.cpp
+++ b/tools/aapt2/link/ReferenceLinker.cpp
@@ -51,18 +51,16 @@
  public:
   using ValueVisitor::Visit;
 
-  ReferenceLinkerVisitor(IAaptContext* context, SymbolTable* symbols,
-                         StringPool* string_pool, xml::IPackageDeclStack* decl,
-                         CallSite* callsite)
-      : context_(context),
+  ReferenceLinkerVisitor(const CallSite& callsite, IAaptContext* context, SymbolTable* symbols,
+                         StringPool* string_pool, xml::IPackageDeclStack* decl)
+      : callsite_(callsite),
+        context_(context),
         symbols_(symbols),
         package_decls_(decl),
-        string_pool_(string_pool),
-        callsite_(callsite) {}
+        string_pool_(string_pool) {}
 
   void Visit(Reference* ref) override {
-    if (!ReferenceLinker::LinkReference(ref, context_, symbols_, package_decls_,
-                                        callsite_)) {
+    if (!ReferenceLinker::LinkReference(callsite_, ref, context_, symbols_, package_decls_)) {
       error_ = true;
     }
   }
@@ -97,7 +95,7 @@
       // Find the attribute in the symbol table and check if it is visible from
       // this callsite.
       const SymbolTable::Symbol* symbol = ReferenceLinker::ResolveAttributeCheckVisibility(
-          transformed_reference, symbols_, callsite_, &err_str);
+          transformed_reference, callsite_, symbols_, &err_str);
       if (symbol) {
         // Assign our style key the correct ID.
         // The ID may not exist.
@@ -105,8 +103,7 @@
 
         // Try to convert the value to a more specific, typed value based on the
         // attribute it is set to.
-        entry.value = ParseValueWithAttribute(std::move(entry.value),
-                                              symbol->attribute.get());
+        entry.value = ParseValueWithAttribute(std::move(entry.value), symbol->attribute.get());
 
         // Link/resolve the final value (mostly if it's a reference).
         entry.value->Accept(this);
@@ -131,8 +128,7 @@
       } else {
         DiagMessage msg(entry.key.GetSource());
         msg << "style attribute '";
-        ReferenceLinker::WriteResourceName(&msg, entry.key,
-                                           transformed_reference);
+        ReferenceLinker::WriteResourceName(&msg, entry.key, transformed_reference);
         msg << "' " << err_str;
         context_->GetDiagnostics()->Error(msg);
         error_ = true;
@@ -158,28 +154,26 @@
           ResourceUtils::TryParseItemForAttribute(*raw_string->value, attr);
 
       // If we could not parse as any specific type, try a basic STRING.
-      if (!transformed &&
-          (attr->type_mask & android::ResTable_map::TYPE_STRING)) {
+      if (!transformed && (attr->type_mask & android::ResTable_map::TYPE_STRING)) {
         util::StringBuilder string_builder;
         string_builder.Append(*raw_string->value);
         if (string_builder) {
-          transformed = util::make_unique<String>(
-              string_pool_->MakeRef(string_builder.ToString()));
+          transformed = util::make_unique<String>(string_pool_->MakeRef(string_builder.ToString()));
         }
       }
 
       if (transformed) {
         return transformed;
       }
-    };
+    }
     return value;
   }
 
+  const CallSite& callsite_;
   IAaptContext* context_;
   SymbolTable* symbols_;
   xml::IPackageDeclStack* package_decls_;
   StringPool* string_pool_;
-  CallSite* callsite_;
   bool error_ = false;
 };
 
@@ -234,8 +228,8 @@
 }
 
 const SymbolTable::Symbol* ReferenceLinker::ResolveSymbolCheckVisibility(const Reference& reference,
+                                                                         const CallSite& callsite,
                                                                          SymbolTable* symbols,
-                                                                         CallSite* callsite,
                                                                          std::string* out_error) {
   const SymbolTable::Symbol* symbol = ResolveSymbol(reference, symbols);
   if (!symbol) {
@@ -243,7 +237,7 @@
     return nullptr;
   }
 
-  if (!IsSymbolVisible(*symbol, reference, *callsite)) {
+  if (!IsSymbolVisible(*symbol, reference, callsite)) {
     if (out_error) *out_error = "is private";
     return nullptr;
   }
@@ -251,9 +245,10 @@
 }
 
 const SymbolTable::Symbol* ReferenceLinker::ResolveAttributeCheckVisibility(
-    const Reference& reference, SymbolTable* symbols, CallSite* callsite, std::string* out_error) {
+    const Reference& reference, const CallSite& callsite, SymbolTable* symbols,
+    std::string* out_error) {
   const SymbolTable::Symbol* symbol =
-      ResolveSymbolCheckVisibility(reference, symbols, callsite, out_error);
+      ResolveSymbolCheckVisibility(reference, callsite, symbols, out_error);
   if (!symbol) {
     return nullptr;
   }
@@ -266,12 +261,12 @@
 }
 
 Maybe<xml::AaptAttribute> ReferenceLinker::CompileXmlAttribute(const Reference& reference,
+                                                               const CallSite& callsite,
                                                                SymbolTable* symbols,
-                                                               CallSite* callsite,
                                                                std::string* out_error) {
-  const SymbolTable::Symbol* symbol = ResolveSymbol(reference, symbols);
+  const SymbolTable::Symbol* symbol =
+      ResolveAttributeCheckVisibility(reference, callsite, symbols, out_error);
   if (!symbol) {
-    if (out_error) *out_error = "not found";
     return {};
   }
 
@@ -297,10 +292,9 @@
   }
 }
 
-bool ReferenceLinker::LinkReference(Reference* reference, IAaptContext* context,
-                                    SymbolTable* symbols,
-                                    xml::IPackageDeclStack* decls,
-                                    CallSite* callsite) {
+bool ReferenceLinker::LinkReference(const CallSite& callsite, Reference* reference,
+                                    IAaptContext* context, SymbolTable* symbols,
+                                    xml::IPackageDeclStack* decls) {
   CHECK(reference != nullptr);
   CHECK(reference->name || reference->id);
 
@@ -309,7 +303,7 @@
 
   std::string err_str;
   const SymbolTable::Symbol* s =
-      ResolveSymbolCheckVisibility(transformed_reference, symbols, callsite, &err_str);
+      ResolveSymbolCheckVisibility(transformed_reference, callsite, symbols, &err_str);
   if (s) {
     // The ID may not exist. This is fine because of the possibility of building
     // against libraries without assigned IDs.
@@ -344,11 +338,9 @@
           error = true;
         }
 
-        CallSite callsite = {
-            ResourceNameRef(package->name, type->type, entry->name)};
-        ReferenceLinkerVisitor visitor(context, context->GetExternalSymbols(),
-                                       &table->string_pool, &decl_stack,
-                                       &callsite);
+        CallSite callsite = {ResourceNameRef(package->name, type->type, entry->name)};
+        ReferenceLinkerVisitor visitor(callsite, context, context->GetExternalSymbols(),
+                                       &table->string_pool, &decl_stack);
 
         for (auto& config_value : entry->values) {
           config_value->value->Accept(&visitor);
diff --git a/tools/aapt2/link/ReferenceLinker.h b/tools/aapt2/link/ReferenceLinker.h
index 2d18c49..b3d0196 100644
--- a/tools/aapt2/link/ReferenceLinker.h
+++ b/tools/aapt2/link/ReferenceLinker.h
@@ -59,8 +59,8 @@
    * returned. out_error holds the error message.
    */
   static const SymbolTable::Symbol* ResolveSymbolCheckVisibility(const Reference& reference,
+                                                                 const CallSite& callsite,
                                                                  SymbolTable* symbols,
-                                                                 CallSite* callsite,
                                                                  std::string* out_error);
 
   /**
@@ -70,8 +70,8 @@
    * ISymbolTable::Symbol::attribute.
    */
   static const SymbolTable::Symbol* ResolveAttributeCheckVisibility(const Reference& reference,
+                                                                    const CallSite& callsite,
                                                                     SymbolTable* symbols,
-                                                                    CallSite* callsite,
                                                                     std::string* out_error);
 
   /**
@@ -80,7 +80,8 @@
    * If resolution fails, outError holds the error message.
    */
   static Maybe<xml::AaptAttribute> CompileXmlAttribute(const Reference& reference,
-                                                       SymbolTable* symbols, CallSite* callsite,
+                                                       const CallSite& callsite,
+                                                       SymbolTable* symbols,
                                                        std::string* out_error);
 
   /**
@@ -99,9 +100,8 @@
    * Returns false on failure, and an error message is logged to the
    * IDiagnostics in the context.
    */
-  static bool LinkReference(Reference* reference, IAaptContext* context,
-                            SymbolTable* symbols, xml::IPackageDeclStack* decls,
-                            CallSite* callsite);
+  static bool LinkReference(const CallSite& callsite, Reference* reference, IAaptContext* context,
+                            SymbolTable* symbols, xml::IPackageDeclStack* decls);
 
   /**
    * Links all references in the ResourceTable.
diff --git a/tools/aapt2/link/ReferenceLinker_test.cpp b/tools/aapt2/link/ReferenceLinker_test.cpp
index 4ca36a9..d8e33a4 100644
--- a/tools/aapt2/link/ReferenceLinker_test.cpp
+++ b/tools/aapt2/link/ReferenceLinker_test.cpp
@@ -53,21 +53,20 @@
   ReferenceLinker linker;
   ASSERT_TRUE(linker.Consume(context.get(), table.get()));
 
-  Reference* ref =
-      test::GetValue<Reference>(table.get(), "com.app.test:string/foo");
-  ASSERT_NE(ref, nullptr);
+  Reference* ref = test::GetValue<Reference>(table.get(), "com.app.test:string/foo");
+  ASSERT_NE(nullptr, ref);
   AAPT_ASSERT_TRUE(ref->id);
-  EXPECT_EQ(ref->id.value(), ResourceId(0x7f020001));
+  EXPECT_EQ(ResourceId(0x7f020001), ref->id.value());
 
   ref = test::GetValue<Reference>(table.get(), "com.app.test:string/bar");
-  ASSERT_NE(ref, nullptr);
+  ASSERT_NE(nullptr, ref);
   AAPT_ASSERT_TRUE(ref->id);
-  EXPECT_EQ(ref->id.value(), ResourceId(0x7f020002));
+  EXPECT_EQ(ResourceId(0x7f020002), ref->id.value());
 
   ref = test::GetValue<Reference>(table.get(), "com.app.test:string/baz");
-  ASSERT_NE(ref, nullptr);
+  ASSERT_NE(nullptr, ref);
   AAPT_ASSERT_TRUE(ref->id);
-  EXPECT_EQ(ref->id.value(), ResourceId(0x01040034));
+  EXPECT_EQ(ResourceId(0x01040034), ref->id.value());
 }
 
 TEST(ReferenceLinkerTest, LinkStyleAttributes) {
@@ -87,9 +86,8 @@
     // We need to fill in the value for the attribute android:attr/bar after we
     // build the
     // table, because we need access to the string pool.
-    Style* style =
-        test::GetValue<Style>(table.get(), "com.app.test:style/Theme");
-    ASSERT_NE(style, nullptr);
+    Style* style = test::GetValue<Style>(table.get(), "com.app.test:style/Theme");
+    ASSERT_NE(nullptr, style);
     style->entries.back().value =
         util::make_unique<RawString>(table->string_pool.MakeRef("one|two"));
   }
@@ -120,20 +118,20 @@
   ASSERT_TRUE(linker.Consume(context.get(), table.get()));
 
   Style* style = test::GetValue<Style>(table.get(), "com.app.test:style/Theme");
-  ASSERT_NE(style, nullptr);
+  ASSERT_NE(nullptr, style);
   AAPT_ASSERT_TRUE(style->parent);
   AAPT_ASSERT_TRUE(style->parent.value().id);
-  EXPECT_EQ(style->parent.value().id.value(), ResourceId(0x01060000));
+  EXPECT_EQ(ResourceId(0x01060000), style->parent.value().id.value());
 
   ASSERT_EQ(2u, style->entries.size());
 
   AAPT_ASSERT_TRUE(style->entries[0].key.id);
-  EXPECT_EQ(style->entries[0].key.id.value(), ResourceId(0x01010001));
-  ASSERT_NE(ValueCast<BinaryPrimitive>(style->entries[0].value.get()), nullptr);
+  EXPECT_EQ(ResourceId(0x01010001), style->entries[0].key.id.value());
+  ASSERT_NE(nullptr, ValueCast<BinaryPrimitive>(style->entries[0].value.get()));
 
   AAPT_ASSERT_TRUE(style->entries[1].key.id);
-  EXPECT_EQ(style->entries[1].key.id.value(), ResourceId(0x01010002));
-  ASSERT_NE(ValueCast<BinaryPrimitive>(style->entries[1].value.get()), nullptr);
+  EXPECT_EQ(ResourceId(0x01010002), style->entries[1].key.id.value());
+  ASSERT_NE(nullptr, ValueCast<BinaryPrimitive>(style->entries[1].value.get()));
 }
 
 TEST(ReferenceLinkerTest, LinkMangledReferencesAndAttributes) {
@@ -167,10 +165,10 @@
   ASSERT_TRUE(linker.Consume(context.get(), table.get()));
 
   Style* style = test::GetValue<Style>(table.get(), "com.app.test:style/Theme");
-  ASSERT_NE(style, nullptr);
+  ASSERT_NE(nullptr, style);
   ASSERT_EQ(1u, style->entries.size());
   AAPT_ASSERT_TRUE(style->entries.front().key.id);
-  EXPECT_EQ(style->entries.front().key.id.value(), ResourceId(0x7f010000));
+  EXPECT_EQ(ResourceId(0x7f010000), style->entries.front().key.id.value());
 }
 
 TEST(ReferenceLinkerTest, FailToLinkPrivateSymbols) {
@@ -257,4 +255,42 @@
   ASSERT_FALSE(linker.Consume(context.get(), table.get()));
 }
 
+TEST(ReferenceLinkerTest, AppsWithSamePackageButDifferentIdAreVisibleNonPublic) {
+  NameMangler mangler(NameManglerPolicy{"com.app.test"});
+  SymbolTable table(&mangler);
+  table.AppendSource(test::StaticSymbolSourceBuilder()
+                         .AddSymbol("com.app.test:string/foo", ResourceId(0x7f010000))
+                         .Build());
+
+  std::string error;
+  const CallSite call_site{ResourceNameRef("com.app.test", ResourceType::kString, "foo")};
+  const SymbolTable::Symbol* symbol = ReferenceLinker::ResolveSymbolCheckVisibility(
+      *test::BuildReference("com.app.test:string/foo"), call_site, &table, &error);
+  ASSERT_NE(nullptr, symbol);
+  EXPECT_TRUE(error.empty());
+}
+
+TEST(ReferenceLinkerTest, AppsWithDifferentPackageCanNotUseEachOthersAttribute) {
+  NameMangler mangler(NameManglerPolicy{"com.app.ext"});
+  SymbolTable table(&mangler);
+  table.AppendSource(test::StaticSymbolSourceBuilder()
+                         .AddSymbol("com.app.test:attr/foo", ResourceId(0x7f010000),
+                                    test::AttributeBuilder().Build())
+                         .AddPublicSymbol("com.app.test:attr/public_foo", ResourceId(0x7f010001),
+                                          test::AttributeBuilder().Build())
+                         .Build());
+
+  std::string error;
+  const CallSite call_site{ResourceNameRef("com.app.ext", ResourceType::kLayout, "foo")};
+
+  AAPT_EXPECT_FALSE(ReferenceLinker::CompileXmlAttribute(
+      *test::BuildReference("com.app.test:attr/foo"), call_site, &table, &error));
+  EXPECT_FALSE(error.empty());
+
+  error = "";
+  AAPT_ASSERT_TRUE(ReferenceLinker::CompileXmlAttribute(
+      *test::BuildReference("com.app.test:attr/public_foo"), call_site, &table, &error));
+  EXPECT_TRUE(error.empty());
+}
+
 }  // namespace aapt
diff --git a/tools/aapt2/link/XmlReferenceLinker.cpp b/tools/aapt2/link/XmlReferenceLinker.cpp
index b839862..94bdccd 100644
--- a/tools/aapt2/link/XmlReferenceLinker.cpp
+++ b/tools/aapt2/link/XmlReferenceLinker.cpp
@@ -42,12 +42,12 @@
  public:
   using ValueVisitor::Visit;
 
-  ReferenceVisitor(IAaptContext* context, SymbolTable* symbols, xml::IPackageDeclStack* decls,
-                   CallSite* callsite)
-      : context_(context), symbols_(symbols), decls_(decls), callsite_(callsite), error_(false) {}
+  ReferenceVisitor(const CallSite& callsite, IAaptContext* context, SymbolTable* symbols,
+                   xml::IPackageDeclStack* decls)
+      : callsite_(callsite), context_(context), symbols_(symbols), decls_(decls), error_(false) {}
 
   void Visit(Reference* ref) override {
-    if (!ReferenceLinker::LinkReference(ref, context_, symbols_, decls_, callsite_)) {
+    if (!ReferenceLinker::LinkReference(callsite_, ref, context_, symbols_, decls_)) {
       error_ = true;
     }
   }
@@ -57,10 +57,10 @@
  private:
   DISALLOW_COPY_AND_ASSIGN(ReferenceVisitor);
 
+  const CallSite& callsite_;
   IAaptContext* context_;
   SymbolTable* symbols_;
   xml::IPackageDeclStack* decls_;
-  CallSite* callsite_;
   bool error_;
 };
 
@@ -71,14 +71,14 @@
  public:
   using xml::PackageAwareVisitor::Visit;
 
-  XmlVisitor(IAaptContext* context, SymbolTable* symbols, const Source& source,
-             std::set<int>* sdk_levels_found, CallSite* callsite)
-      : context_(context),
-        symbols_(symbols),
-        source_(source),
-        sdk_levels_found_(sdk_levels_found),
+  XmlVisitor(const Source& source, const CallSite& callsite, IAaptContext* context,
+             SymbolTable* symbols, std::set<int>* sdk_levels_found)
+      : source_(source),
         callsite_(callsite),
-        reference_visitor_(context, symbols, this, callsite) {}
+        context_(context),
+        symbols_(symbols),
+        sdk_levels_found_(sdk_levels_found),
+        reference_visitor_(callsite, context, symbols, this) {}
 
   void Visit(xml::Element* el) override {
     // The default Attribute allows everything except enums or flags.
@@ -108,7 +108,7 @@
 
         std::string err_str;
         attr.compiled_attribute =
-            ReferenceLinker::CompileXmlAttribute(attr_ref, symbols_, callsite_, &err_str);
+            ReferenceLinker::CompileXmlAttribute(attr_ref, callsite_, symbols_, &err_str);
 
         if (!attr.compiled_attribute) {
           context_->GetDiagnostics()->Error(DiagMessage(source) << "attribute '"
@@ -159,11 +159,12 @@
  private:
   DISALLOW_COPY_AND_ASSIGN(XmlVisitor);
 
+  Source source_;
+  const CallSite& callsite_;
   IAaptContext* context_;
   SymbolTable* symbols_;
-  Source source_;
+
   std::set<int>* sdk_levels_found_;
-  CallSite* callsite_;
   ReferenceVisitor reference_visitor_;
   bool error_ = false;
 };
@@ -172,9 +173,9 @@
 
 bool XmlReferenceLinker::Consume(IAaptContext* context, xml::XmlResource* resource) {
   sdk_levels_found_.clear();
-  CallSite callsite = {resource->file.name};
-  XmlVisitor visitor(context, context->GetExternalSymbols(), resource->file.source,
-                     &sdk_levels_found_, &callsite);
+  const CallSite callsite = {resource->file.name};
+  XmlVisitor visitor(resource->file.source, callsite, context, context->GetExternalSymbols(),
+                     &sdk_levels_found_);
   if (resource->root) {
     resource->root->Accept(&visitor);
     return !visitor.HasError();
diff --git a/tools/aapt2/process/SymbolTable_test.cpp b/tools/aapt2/process/SymbolTable_test.cpp
index bba316f..fd8a508 100644
--- a/tools/aapt2/process/SymbolTable_test.cpp
+++ b/tools/aapt2/process/SymbolTable_test.cpp
@@ -30,10 +30,8 @@
           .Build();
 
   ResourceTableSymbolSource symbol_source(table.get());
-  EXPECT_NE(nullptr,
-            symbol_source.FindByName(test::ParseNameOrDie("android:id/foo")));
-  EXPECT_NE(nullptr,
-            symbol_source.FindByName(test::ParseNameOrDie("android:id/bar")));
+  EXPECT_NE(nullptr, symbol_source.FindByName(test::ParseNameOrDie("android:id/foo")));
+  EXPECT_NE(nullptr, symbol_source.FindByName(test::ParseNameOrDie("android:id/bar")));
 
   std::unique_ptr<SymbolTable::Symbol> s =
       symbol_source.FindByName(test::ParseNameOrDie("android:attr/foo"));
diff --git a/tools/aapt2/readme.md b/tools/aapt2/readme.md
index fedd65c..1c9a75d 100644
--- a/tools/aapt2/readme.md
+++ b/tools/aapt2/readme.md
@@ -1,5 +1,13 @@
 # Android Asset Packaging Tool 2.0 (AAPT2) release notes
 
+## Version 2.10
+### `aapt2 link ...`
+- Add ability to specify package ID to compile with for regular apps (not shared or static libs).
+  This package ID is limited to the range 0x7f-0xff inclusive. Specified with the --package-id
+  flag.
+- Fixed issue with <plurals> resources being stripped for locales and other configuration.
+- Fixed issue with escaping strings in XML resources.
+
 ## Version 2.9
 ### `aapt2 link ...`
 - Added sparse resource type encoding, which encodes resource entries that are sparse with
diff --git a/tools/layoutlib/bridge/src/android/graphics/Bitmap_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/Bitmap_Delegate.java
index 8c6740c..43c95f4 100644
--- a/tools/layoutlib/bridge/src/android/graphics/Bitmap_Delegate.java
+++ b/tools/layoutlib/bridge/src/android/graphics/Bitmap_Delegate.java
@@ -650,6 +650,20 @@
         return null;
     }
 
+    @LayoutlibDelegate
+    /*package*/ static boolean nativeIsSRGB(long nativeBitmap) {
+        Bridge.getLog().error(LayoutLog.TAG_UNSUPPORTED,
+                "Color spaces are not supported", null /*data*/);
+        return false;
+    }
+
+    @LayoutlibDelegate
+    /*package*/ static boolean nativeGetColorSpace(long nativePtr, float[] xyz, float[] params) {
+        Bridge.getLog().error(LayoutLog.TAG_UNSUPPORTED,
+                "Color spaces are not supported", null /*data*/);
+        return false;
+    }
+
     // ---- Private delegate/helper methods ----
 
     private Bitmap_Delegate(BufferedImage image, Config config) {
diff --git a/tools/layoutlib/bridge/src/android/text/Hyphenator_Delegate.java b/tools/layoutlib/bridge/src/android/text/Hyphenator_Delegate.java
index fcd63ea..499e58a 100644
--- a/tools/layoutlib/bridge/src/android/text/Hyphenator_Delegate.java
+++ b/tools/layoutlib/bridge/src/android/text/Hyphenator_Delegate.java
@@ -40,7 +40,7 @@
     }
 
     /*package*/ @SuppressWarnings("UnusedParameters")  // TODO implement this.
-    static long loadHyphenator(ByteBuffer buffer, int offset) {
+    static long loadHyphenator(ByteBuffer buffer, int offset, int minPrefix, int minSuffix) {
         return sDelegateManager.addNewDelegate(new Hyphenator_Delegate());
     }
 }
diff --git a/tools/layoutlib/bridge/src/android/text/StaticLayout_Delegate.java b/tools/layoutlib/bridge/src/android/text/StaticLayout_Delegate.java
index 970c7d5..1b99015 100644
--- a/tools/layoutlib/bridge/src/android/text/StaticLayout_Delegate.java
+++ b/tools/layoutlib/bridge/src/android/text/StaticLayout_Delegate.java
@@ -53,8 +53,9 @@
     }
 
     @LayoutlibDelegate
-    /*package*/ static long nLoadHyphenator(ByteBuffer buf, int offset) {
-        return Hyphenator_Delegate.loadHyphenator(buf, offset);
+    /*package*/ static long nLoadHyphenator(ByteBuffer buf, int offset, int minPrefix,
+            int minSuffix) {
+        return Hyphenator_Delegate.loadHyphenator(buf, offset, minPrefix, minSuffix);
     }
 
     @LayoutlibDelegate
diff --git a/wifi/java/android/net/wifi/aware/DiscoverySession.java b/wifi/java/android/net/wifi/aware/DiscoverySession.java
index 59fe1ee..156c3fd 100644
--- a/wifi/java/android/net/wifi/aware/DiscoverySession.java
+++ b/wifi/java/android/net/wifi/aware/DiscoverySession.java
@@ -116,6 +116,7 @@
             Log.w(TAG, "terminate: already terminated.");
             return;
         }
+
         mTerminated = true;
         mMgr.clear();
         mCloseGuard.close();
@@ -172,15 +173,15 @@
         if (mTerminated) {
             Log.w(TAG, "sendMessage: called on terminated session");
             return;
-        } else {
-            WifiAwareManager mgr = mMgr.get();
-            if (mgr == null) {
-                Log.w(TAG, "sendMessage: called post GC on WifiAwareManager");
-                return;
-            }
-
-            mgr.sendMessage(mClientId, mSessionId, peerHandle, message, messageId, retryCount);
         }
+
+        WifiAwareManager mgr = mMgr.get();
+        if (mgr == null) {
+            Log.w(TAG, "sendMessage: called post GC on WifiAwareManager");
+            return;
+        }
+
+        mgr.sendMessage(mClientId, mSessionId, peerHandle, message, messageId, retryCount);
     }
 
     /**
@@ -235,15 +236,15 @@
         if (mTerminated) {
             Log.w(TAG, "startRanging: called on terminated session");
             return;
-        } else {
-            WifiAwareManager mgr = mMgr.get();
-            if (mgr == null) {
-                Log.w(TAG, "startRanging: called post GC on WifiAwareManager");
-                return;
-            }
-
-            mgr.startRanging(mClientId, mSessionId, params, listener);
         }
+
+        WifiAwareManager mgr = mMgr.get();
+        if (mgr == null) {
+            Log.w(TAG, "startRanging: called post GC on WifiAwareManager");
+            return;
+        }
+
+        mgr.startRanging(mClientId, mSessionId, params, listener);
     }
 
     /**
@@ -261,6 +262,9 @@
      * <p>
      * Note: per the Wi-Fi Aware specification the roles are fixed - a Subscriber is an INITIATOR
      * and a Publisher is a RESPONDER.
+     * <p>
+     * To set up an encrypted link use the {@link #createNetworkSpecifierPmk(PeerHandle, byte[])}
+     * or {@link #createNetworkSpecifierPassphrase(PeerHandle, String)} APIs.
      *
      * @param peerHandle The peer's handle obtained through
      * {@link DiscoverySessionCallback#onServiceDiscovered(PeerHandle, byte[], java.util.List)}
@@ -282,19 +286,19 @@
         if (mTerminated) {
             Log.w(TAG, "createNetworkSpecifierOpen: called on terminated session");
             return null;
-        } else {
-            WifiAwareManager mgr = mMgr.get();
-            if (mgr == null) {
-                Log.w(TAG, "createNetworkSpecifierOpen: called post GC on WifiAwareManager");
-                return null;
-            }
-
-            int role = this instanceof SubscribeDiscoverySession
-                    ? WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_INITIATOR
-                    : WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_RESPONDER;
-
-            return mgr.createNetworkSpecifier(mClientId, role, mSessionId, peerHandle, null);
         }
+
+        WifiAwareManager mgr = mMgr.get();
+        if (mgr == null) {
+            Log.w(TAG, "createNetworkSpecifierOpen: called post GC on WifiAwareManager");
+            return null;
+        }
+
+        int role = this instanceof SubscribeDiscoverySession
+                ? WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_INITIATOR
+                : WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_RESPONDER;
+
+        return mgr.createNetworkSpecifier(mClientId, role, mSessionId, peerHandle, null, null);
     }
 
     /**
@@ -307,8 +311,70 @@
      * discovery or communication (in such scenarios the MAC address of the peer is shielded by
      * an opaque peer ID handle). If a Aware connection is needed to a peer discovered using other
      * OOB (out-of-band) mechanism then use the alternative
-     * {@link WifiAwareSession#createNetworkSpecifierPmk(int, byte[], byte[])} method - which uses the
-     * peer's MAC address.
+     * {@link WifiAwareSession#createNetworkSpecifierPassphrase(int, byte[], String)} method -
+     * which uses the peer's MAC address.
+     * <p>
+     * Note: per the Wi-Fi Aware specification the roles are fixed - a Subscriber is an INITIATOR
+     * and a Publisher is a RESPONDER.
+     *
+     * @param peerHandle The peer's handle obtained through
+     * {@link DiscoverySessionCallback#onServiceDiscovered(PeerHandle,
+     * byte[], java.util.List)} or
+     * {@link DiscoverySessionCallback#onMessageReceived(PeerHandle,
+     * byte[])}. On a RESPONDER this value is used to gate the acceptance of a connection request
+     *                   from only that peer. A RESPONDER may specify a null - indicating that
+     *                   it will accept connection requests from any device.
+     * @param passphrase The passphrase to be used to encrypt the link. The PMK is generated from
+     *                   the passphrase. Use the
+     *                   {@link #createNetworkSpecifierPmk(PeerHandle, byte[])} to specify the
+     *                   PMK directly or {@link #createNetworkSpecifierOpen(PeerHandle)} to
+     *                   specify an open (unencrypted) link.
+     *
+     * @return A string to be used to construct
+     * {@link android.net.NetworkRequest.Builder#setNetworkSpecifier(String)} to pass to
+     * {@link android.net.ConnectivityManager#requestNetwork(android.net.NetworkRequest,
+     * android.net.ConnectivityManager.NetworkCallback)}
+     * [or other varieties of that API].
+     *
+     * * @hide
+     */
+    public String createNetworkSpecifierPassphrase(@Nullable PeerHandle peerHandle,
+            @NonNull String passphrase) {
+        if (passphrase == null || passphrase.length() == 0) {
+            throw new IllegalArgumentException("Passphrase must not be null or empty");
+        }
+
+        if (mTerminated) {
+            Log.w(TAG, "createNetworkSpecifierPassphrase: called on terminated session");
+            return null;
+        }
+
+        WifiAwareManager mgr = mMgr.get();
+        if (mgr == null) {
+            Log.w(TAG, "createNetworkSpecifierPassphrase: called post GC on WifiAwareManager");
+            return null;
+        }
+
+        int role = this instanceof SubscribeDiscoverySession
+                ? WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_INITIATOR
+                : WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_RESPONDER;
+
+        return mgr.createNetworkSpecifier(mClientId, role, mSessionId, peerHandle, null,
+                passphrase);
+    }
+
+    /**
+     * Create a {@link android.net.NetworkRequest.Builder#setNetworkSpecifier(String)} for an
+     * encrypted WiFi Aware connection (link) to the specified peer. The
+     * {@link android.net.NetworkRequest.Builder#addTransportType(int)} should be set to
+     * {@link android.net.NetworkCapabilities#TRANSPORT_WIFI_AWARE}.
+     * <p>
+     * This method should be used when setting up a connection with a peer discovered through Aware
+     * discovery or communication (in such scenarios the MAC address of the peer is shielded by
+     * an opaque peer ID handle). If a Aware connection is needed to a peer discovered using other
+     * OOB (out-of-band) mechanism then use the alternative
+     * {@link WifiAwareSession#createNetworkSpecifierPmk(int, byte[], byte[])} method - which uses
+     * the peer's MAC address.
      * <p>
      * Note: per the Wi-Fi Aware specification the roles are fixed - a Subscriber is an INITIATOR
      * and a Publisher is a RESPONDER.
@@ -322,8 +388,9 @@
      *                   it will accept connection requests from any device.
      * @param pmk A PMK (pairwise master key, see IEEE 802.11i) specifying the key to use for
      *            encrypting the data-path. Use the
-     *            {@link #createNetworkSpecifierOpen(PeerHandle)} to specify an open (unencrypted)
-     *            link.
+     *            {@link #createNetworkSpecifierPassphrase(PeerHandle, String)} to specify a
+     *            Passphrase or {@link #createNetworkSpecifierOpen(PeerHandle)} to specify an
+     *            open (unencrypted) link.
      *
      * @return A string to be used to construct
      * {@link android.net.NetworkRequest.Builder#setNetworkSpecifier(String)} to pass to
@@ -342,19 +409,19 @@
         if (mTerminated) {
             Log.w(TAG, "createNetworkSpecifierPmk: called on terminated session");
             return null;
-        } else {
-            WifiAwareManager mgr = mMgr.get();
-            if (mgr == null) {
-                Log.w(TAG, "createNetworkSpecifierPmk: called post GC on WifiAwareManager");
-                return null;
-            }
-
-            int role = this instanceof SubscribeDiscoverySession
-                    ? WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_INITIATOR
-                    : WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_RESPONDER;
-
-            return mgr.createNetworkSpecifier(mClientId, role, mSessionId, peerHandle, pmk);
         }
+
+        WifiAwareManager mgr = mMgr.get();
+        if (mgr == null) {
+            Log.w(TAG, "createNetworkSpecifierPmk: called post GC on WifiAwareManager");
+            return null;
+        }
+
+        int role = this instanceof SubscribeDiscoverySession
+                ? WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_INITIATOR
+                : WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_RESPONDER;
+
+        return mgr.createNetworkSpecifier(mClientId, role, mSessionId, peerHandle, pmk, null);
     }
 
     /**
diff --git a/wifi/java/android/net/wifi/aware/WifiAwareManager.java b/wifi/java/android/net/wifi/aware/WifiAwareManager.java
index 3d784ba..7b6805c 100644
--- a/wifi/java/android/net/wifi/aware/WifiAwareManager.java
+++ b/wifi/java/android/net/wifi/aware/WifiAwareManager.java
@@ -130,26 +130,26 @@
      */
 
     /**
-     * TYPE: in band, specific peer: role, client_id, session_id, peer_id, pmk optional
+     * TYPE: in band, specific peer: role, client_id, session_id, peer_id, pmk/passphrase optional
      * @hide
      */
     public static final int NETWORK_SPECIFIER_TYPE_IB = 0;
 
     /**
-     * TYPE: in band, any peer: role, client_id, session_id, pmk optional
+     * TYPE: in band, any peer: role, client_id, session_id, pmk/passphrase optional
      * [only permitted for RESPONDER]
      * @hide
      */
     public static final int NETWORK_SPECIFIER_TYPE_IB_ANY_PEER = 1;
 
     /**
-     * TYPE: out-of-band: role, client_id, peer_mac, pmk optional
+     * TYPE: out-of-band: role, client_id, peer_mac, pmk/passphrase optional
      * @hide
      */
     public static final int NETWORK_SPECIFIER_TYPE_OOB = 2;
 
     /**
-     * TYPE: out-of-band, any peer: role, client_id, pmk optional
+     * TYPE: out-of-band, any peer: role, client_id, pmk/passphrase optional
      * [only permitted for RESPONDER]
      * @hide
      */
@@ -180,6 +180,9 @@
     /** @hide */
     public static final String NETWORK_SPECIFIER_KEY_PMK = "pmk";
 
+    /** @hide */
+    public static final String NETWORK_SPECIFIER_KEY_PASSPHRASE = "passphrase";
+
     /**
      * Broadcast intent action to indicate that the state of Wi-Fi Aware availability has changed.
      * Use the {@link #isAvailable()} to query the current status.
@@ -473,11 +476,12 @@
 
     /** @hide */
     public String createNetworkSpecifier(int clientId, int role, int sessionId,
-            PeerHandle peerHandle, @Nullable byte[] pmk) {
+            PeerHandle peerHandle, @Nullable byte[] pmk, @Nullable String passphrase) {
         if (VDBG) {
             Log.v(TAG, "createNetworkSpecifier: role=" + role + ", sessionId=" + sessionId
                     + ", peerHandle=" + ((peerHandle == null) ? peerHandle : peerHandle.peerId)
-                    + ", pmk=" + ((pmk == null) ? "null" : "non-null"));
+                    + ", pmk=" + ((pmk == null) ? "null" : "non-null")
+                    + ", passphrase=" + ((passphrase == null) ? "null" : "non-null"));
         }
 
         int type = (peerHandle == null) ? NETWORK_SPECIFIER_TYPE_IB_ANY_PEER
@@ -512,6 +516,11 @@
             }
             json.put(NETWORK_SPECIFIER_KEY_PMK,
                     Base64.encodeToString(pmk, 0, pmk.length, Base64.DEFAULT));
+            if (passphrase == null) {
+                passphrase = new String();
+            }
+            json.put(NETWORK_SPECIFIER_KEY_PASSPHRASE, passphrase);
+
         } catch (JSONException e) {
             return "";
         }
@@ -521,10 +530,11 @@
 
     /** @hide */
     public String createNetworkSpecifier(int clientId, @DataPathRole int role,
-            @Nullable byte[] peer, @Nullable byte[] pmk) {
+            @Nullable byte[] peer, @Nullable byte[] pmk, @Nullable String passphrase) {
         if (VDBG) {
             Log.v(TAG, "createNetworkSpecifier: role=" + role
-                    + ", pmk=" + ((pmk == null) ? "null" : "non-null"));
+                    + ", pmk=" + ((pmk == null) ? "null" : "non-null")
+                    + ", passphrase=" + ((passphrase == null) ? "null" : "non-null"));
         }
 
         int type = (peer == null) ?
@@ -560,6 +570,10 @@
             }
             json.put(NETWORK_SPECIFIER_KEY_PMK,
                     Base64.encodeToString(pmk, 0, pmk.length, Base64.DEFAULT));
+            if (passphrase == null) {
+                passphrase = new String();
+            }
+            json.put(NETWORK_SPECIFIER_KEY_PASSPHRASE, passphrase);
         } catch (JSONException e) {
             return "";
         }
diff --git a/wifi/java/android/net/wifi/aware/WifiAwareSession.java b/wifi/java/android/net/wifi/aware/WifiAwareSession.java
index 856066e..f48f641 100644
--- a/wifi/java/android/net/wifi/aware/WifiAwareSession.java
+++ b/wifi/java/android/net/wifi/aware/WifiAwareSession.java
@@ -192,6 +192,9 @@
      *     (out-of-band) discovery. Aware discovery does not provide the MAC address of the peer -
      *     when using Aware discovery use the alternative network specifier method -
      *     {@link DiscoverySession#createNetworkSpecifierOpen(PeerHandle)}.
+     * <p>
+     * To set up an encrypted link use the {@link #createNetworkSpecifierPmk(int, byte[], byte[])}
+     * or {@link #createNetworkSpecifierPassphrase(int, byte[], String)} APIs.
      *
      * @param role  The role of this device:
      *              {@link WifiAwareManager#WIFI_AWARE_DATA_PATH_ROLE_INITIATOR} or
@@ -220,7 +223,7 @@
             Log.e(TAG, "createNetworkSpecifierOpen: called after termination");
             return "";
         }
-        return mgr.createNetworkSpecifier(mClientId, role, peer, null);
+        return mgr.createNetworkSpecifier(mClientId, role, peer, null, null);
     }
 
     /**
@@ -232,7 +235,56 @@
      *     This API is targeted for applications which can obtain the peer MAC address using OOB
      *     (out-of-band) discovery. Aware discovery does not provide the MAC address of the peer -
      *     when using Aware discovery use the alternative network specifier method -
-     *     {@link DiscoverySession#createNetworkSpecifierPmk(PeerHandle, byte[])}}.
+     *     {@link DiscoverySession#createNetworkSpecifierPassphrase(PeerHandle, String)}.
+     *
+     * @param role  The role of this device:
+     *              {@link WifiAwareManager#WIFI_AWARE_DATA_PATH_ROLE_INITIATOR} or
+     *              {@link WifiAwareManager#WIFI_AWARE_DATA_PATH_ROLE_RESPONDER}
+     * @param peer  The MAC address of the peer's Aware discovery interface. On a RESPONDER this
+     *              value is used to gate the acceptance of a connection request from only that
+     *              peer. A RESPONDER may specify a null - indicating that it will accept
+     *              connection requests from any device.
+     * @param passphrase The passphrase to be used to encrypt the link. The PMK is generated from
+     *                   the passphrase. Use the
+     *                   {@link #createNetworkSpecifierPmk(int, byte[], byte[])} to specify the
+     *                   PMK directly or {@link #createNetworkSpecifierOpen(int, byte[])} to
+     *                   specify an open (unencrypted) link.
+     *
+     * @return A string to be used to construct
+     * {@link android.net.NetworkRequest.Builder#setNetworkSpecifier(String)} to pass to
+     * {@link android.net.ConnectivityManager#requestNetwork(android.net.NetworkRequest,
+     * android.net.ConnectivityManager.NetworkCallback)}
+     * [or other varieties of that API].
+     *
+     * @hide
+     */
+    public String createNetworkSpecifierPassphrase(@WifiAwareManager.DataPathRole int role,
+            @Nullable byte[] peer, @NonNull String passphrase) {
+        WifiAwareManager mgr = mMgr.get();
+        if (mgr == null) {
+            Log.e(TAG, "createNetworkSpecifierPassphrase: called post GC on WifiAwareManager");
+            return "";
+        }
+        if (mTerminated) {
+            Log.e(TAG, "createNetworkSpecifierPassphrase: called after termination");
+            return "";
+        }
+        if (passphrase == null || passphrase.length() == 0) {
+            throw new IllegalArgumentException("Passphrase must not be null or empty");
+        }
+        return mgr.createNetworkSpecifier(mClientId, role, peer, null, passphrase);
+    }
+
+    /**
+     * Create a {@link android.net.NetworkRequest.Builder#setNetworkSpecifier(String)} for an
+     * encrypted WiFi Aware connection (link) to the specified peer. The
+     * {@link android.net.NetworkRequest.Builder#addTransportType(int)} should be set to
+     * {@link android.net.NetworkCapabilities#TRANSPORT_WIFI_AWARE}.
+     * <p>
+     *     This API is targeted for applications which can obtain the peer MAC address using OOB
+     *     (out-of-band) discovery. Aware discovery does not provide the MAC address of the peer -
+     *     when using Aware discovery use the alternative network specifier method -
+     *     {@link DiscoverySession#createNetworkSpecifierPassphrase(PeerHandle, String)}.
      *
      * @param role  The role of this device:
      *              {@link WifiAwareManager#WIFI_AWARE_DATA_PATH_ROLE_INITIATOR} or
@@ -242,8 +294,10 @@
      *              peer. A RESPONDER may specify a null - indicating that it will accept
      *              connection requests from any device.
      * @param pmk A PMK (pairwise master key, see IEEE 802.11i) specifying the key to use for
-     *            encrypting the data-path. Use the {@link #createNetworkSpecifierOpen(int, byte[])}
-     *            to specify an open (unencrypted) link.
+     *            encrypting the data-path. Use the
+     *            {@link #createNetworkSpecifierPassphrase(int, byte[], String)} to specify a
+     *            Passphrase or {@link #createNetworkSpecifierOpen(int, byte[])} to specify an
+     *            open (unencrypted) link.
      *
      * @return A string to be used to construct
      * {@link android.net.NetworkRequest.Builder#setNetworkSpecifier(String)} to pass to
@@ -267,7 +321,7 @@
         if (pmk == null || pmk.length == 0) {
             throw new IllegalArgumentException("PMK must not be null or empty");
         }
-        return mgr.createNetworkSpecifier(mClientId, role, peer, pmk);
+        return mgr.createNetworkSpecifier(mClientId, role, peer, pmk, null);
     }
 
     /**
diff --git a/wifi/tests/src/android/net/wifi/aware/WifiAwareManagerTest.java b/wifi/tests/src/android/net/wifi/aware/WifiAwareManagerTest.java
index 992958b..eceb365 100644
--- a/wifi/tests/src/android/net/wifi/aware/WifiAwareManagerTest.java
+++ b/wifi/tests/src/android/net/wifi/aware/WifiAwareManagerTest.java
@@ -974,6 +974,7 @@
         final PeerHandle peerHandle = new PeerHandle(123412);
         final int role = WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_RESPONDER;
         final byte[] pmk = "Some arbitrary byte array".getBytes();
+        final String passphrase = "A really bad password";
         final ConfigRequest configRequest = new ConfigRequest.Builder().build();
         final PublishConfig publishConfig = new PublishConfig.Builder().build();
 
@@ -1038,6 +1039,23 @@
         collector.checkThat("pmk", pmkB64 ,
                 equalTo(jsonObject.getString(WifiAwareManager.NETWORK_SPECIFIER_KEY_PMK)));
 
+        // (5) request an encrypted (Passphrase) network specifier from the session
+        networkSpecifier = publishSession.getValue().createNetworkSpecifierPassphrase(peerHandle,
+                passphrase);
+
+        // validate format
+        jsonObject = new JSONObject(networkSpecifier);
+        collector.checkThat("role", role,
+                equalTo(jsonObject.getInt(WifiAwareManager.NETWORK_SPECIFIER_KEY_ROLE)));
+        collector.checkThat("client_id", clientId,
+                equalTo(jsonObject.getInt(WifiAwareManager.NETWORK_SPECIFIER_KEY_CLIENT_ID)));
+        collector.checkThat("session_id", sessionId,
+                equalTo(jsonObject.getInt(WifiAwareManager.NETWORK_SPECIFIER_KEY_SESSION_ID)));
+        collector.checkThat("peer_id", peerHandle.peerId,
+                equalTo(jsonObject.getInt(WifiAwareManager.NETWORK_SPECIFIER_KEY_PEER_ID)));
+        collector.checkThat("passphrase", passphrase,
+                equalTo(jsonObject.getString(WifiAwareManager.NETWORK_SPECIFIER_KEY_PASSPHRASE)));
+
         verifyNoMoreInteractions(mockCallback, mockSessionCallback, mockAwareService,
                 mockPublishSession, mockRttListener);
     }
@@ -1053,6 +1071,7 @@
         final byte[] someMac = HexEncoding.decode("000102030405".toCharArray(), false);
         final int role = WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_INITIATOR;
         final byte[] pmk = "Some arbitrary pmk data".getBytes();
+        final String passphrase = "A really bad password";
 
         String pmkB64 = Base64.encodeToString(pmk, Base64.DEFAULT);
 
@@ -1101,6 +1120,21 @@
         collector.checkThat("pmk", pmkB64,
                 equalTo(jsonObject.getString(WifiAwareManager.NETWORK_SPECIFIER_KEY_PMK)));
 
+        // (4) request an encrypted (Passphrase) direct network specifier
+        networkSpecifier = session.createNetworkSpecifierPassphrase(role, someMac, passphrase);
+
+        // validate format
+        jsonObject = new JSONObject(networkSpecifier);
+        collector.checkThat("role", role,
+                equalTo(jsonObject.getInt(WifiAwareManager.NETWORK_SPECIFIER_KEY_ROLE)));
+        collector.checkThat("client_id", clientId,
+                equalTo(jsonObject.getInt(WifiAwareManager.NETWORK_SPECIFIER_KEY_CLIENT_ID)));
+        collector.checkThat("peer_mac", someMac, equalTo(HexEncoding.decode(
+                jsonObject.getString(WifiAwareManager.NETWORK_SPECIFIER_KEY_PEER_MAC).toCharArray(),
+                false)));
+        collector.checkThat("passphrase", passphrase,
+                equalTo(jsonObject.getString(WifiAwareManager.NETWORK_SPECIFIER_KEY_PASSPHRASE)));
+
         verifyNoMoreInteractions(mockCallback, mockSessionCallback, mockAwareService,
                 mockPublishSession, mockRttListener);
     }